text
stringlengths
70
351k
source
stringclasses
4 values
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/nmi/transformers.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/connector/nmi/transformers.rs" role="context" start="1033" end="1053"> fn try_from( item: types::ResponseRouterData<F, SyncResponse, T, types::PaymentsResponseData>, ) -> Result<Self, Self::Error> { match item.response.transaction { Some(trn) => Ok(Self { status: enums::AttemptStatus::from(NmiStatus::from(trn.condition)), response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(trn.transaction_id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..item.data }), None => Ok(Self { ..item.data }), //when there is empty connector response i.e. response we get in psync when payment status is in authentication_pending } } <file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="1032" end="1032"> use common_utils::{errors::CustomResult, ext_traits::XmlExt, pii::Email, types::FloatMajorUnit}; use crate::{ connector::utils::{ self, AddressDetailsData, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, RouterData, }, core::errors, services, types::{self, api, domain, storage::enums, transformers::ForeignFrom, ConnectorAuthType}, }; type Error = Report<errors::ConnectorError>; <file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="1069" end="1075"> fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> { let query_response = String::from_utf8(bytes) .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; query_response .parse_xml::<Self>() .change_context(errors::ConnectorError::ResponseDeserializationFailed) } <file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="1058" end="1064"> fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> { let query_response = String::from_utf8(bytes) .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; query_response .parse_xml::<Self>() .change_context(errors::ConnectorError::ResponseDeserializationFailed) } <file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="976" end="1013"> fn try_from( item: types::ResponseRouterData< api::Void, StandardResponse, T, types::PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let (response, status) = match item.response.response { Response::Approved => ( Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId( item.response.transactionid.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.orderid), incremental_authorization_allowed: None, charges: None, }), enums::AttemptStatus::VoidInitiated, ), Response::Declined | Response::Error => ( Err(types::ErrorResponse::foreign_from(( item.response, item.http_code, ))), enums::AttemptStatus::VoidFailed, ), }; Ok(Self { status, response, ..item.data }) } <file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="925" end="968"> fn try_from( item: types::ResponseRouterData< api::Authorize, StandardResponse, types::PaymentsAuthorizeData, types::PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let (response, status) = match item.response.response { Response::Approved => ( Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId( item.response.transactionid.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.orderid), incremental_authorization_allowed: None, charges: None, }), if let Some(diesel_models::enums::CaptureMethod::Automatic) = item.data.request.capture_method { enums::AttemptStatus::CaptureInitiated } else { enums::AttemptStatus::Authorized }, ), Response::Declined | Response::Error => ( Err(types::ErrorResponse::foreign_from(( item.response, item.http_code, ))), enums::AttemptStatus::Failure, ), }; Ok(Self { status, response, ..item.data }) } <file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="435" end="449"> pub fn new(metadata: &serde_json::Value) -> Self { let metadata_as_string = metadata.to_string(); let hash_map: std::collections::BTreeMap<String, serde_json::Value> = serde_json::from_str(&metadata_as_string).unwrap_or(std::collections::BTreeMap::new()); let inner = hash_map .into_iter() .enumerate() .map(|(index, (hs_key, hs_value))| { let nmi_key = format!("merchant_defined_field_{}", index + 1); let nmi_value = format!("{hs_key}={hs_value}"); (nmi_key, Secret::new(nmi_value)) }) .collect(); Self { inner } } <file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="1210" end="1222"> fn from(value: String) -> Self { match value.as_str() { "abandoned" => Self::Abandoned, "canceled" => Self::Cancelled, "in_progress" => Self::InProgress, "pendingsettlement" => Self::Pendingsettlement, "complete" => Self::Complete, "failed" => Self::Failed, "unknown" => Self::Unknown, // Other than above values only pending is possible, since value is a string handling this as default _ => Self::Pending, } } <file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="19" end="19"> type Error = Report<errors::ConnectorError>; <file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="1232" end="1234"> pub struct SyncResponse { pub transaction: Option<SyncTransactionResponse>, } <file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="1018" end="1027"> pub enum NmiStatus { Abandoned, Cancelled, Pendingsettlement, Pending, Failed, Complete, InProgress, Unknown, } <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/stripe/transformers.rs<|crate|> router anchor=serialize kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="3033" end="3049"> fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { match *self { Self::CashappHandleRedirectOrDisplayQrCode(ref i) => { Serialize::serialize(i, serializer) } Self::RedirectToUrl(ref i) => Serialize::serialize(i, serializer), Self::AlipayHandleRedirect(ref i) => Serialize::serialize(i, serializer), Self::VerifyWithMicrodeposits(ref i) => Serialize::serialize(i, serializer), Self::WechatPayDisplayQrCode(ref i) => Serialize::serialize(i, serializer), Self::DisplayBankTransferInstructions(ref i) => Serialize::serialize(i, serializer), Self::MultibancoDisplayDetails(ref i) => Serialize::serialize(i, serializer), Self::NoNextActionBody => Serialize::serialize("NoNextActionBody", serializer), } } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="3032" end="3032"> use api_models::{self, enums as api_enums, payments}; use common_utils::{ errors::CustomResult, ext_traits::{ByteSliceExt, Encode}, pii::{self, Email}, request::RequestContent, types::MinorUnit, }; use serde::{Deserialize, Serialize}; pub use self::connect::*; use crate::{ collect_missing_value_keys, connector::utils::{self as connector_util, ApplePay, ApplePayDecrypt, RouterData}, consts, core::errors, headers, services, types::{ self, api, domain, storage::enums, transformers::{ForeignFrom, ForeignTryFrom}, }, utils::OptionExt, }; <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="3199" end="3237"> fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { let amount = item.request.minor_refund_amount; match item.request.split_refunds.as_ref() { None => Err(errors::ConnectorError::MissingRequiredField { field_name: "split_refunds", } .into()), Some(split_refunds) => match split_refunds { types::SplitRefundsRequest::StripeSplitRefund(stripe_refund) => { let (refund_application_fee, reverse_transfer) = match &stripe_refund.options { types::ChargeRefundsOptions::Direct(types::DirectChargeRefund { revert_platform_fee, }) => (Some(*revert_platform_fee), None), types::ChargeRefundsOptions::Destination( types::DestinationChargeRefund { revert_platform_fee, revert_transfer, }, ) => (Some(*revert_platform_fee), Some(*revert_transfer)), }; Ok(Self { charge: stripe_refund.charge_id.clone(), refund_application_fee, reverse_transfer, amount: Some(amount), meta_data: StripeMetadata { order_id: Some(item.request.refund_id.clone()), is_refund_id_as_reference: Some("true".to_string()), }, }) } _ => Err(errors::ConnectorError::MissingRequiredField { field_name: "stripe_split_refund", })?, }, } } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="3172" end="3184"> fn try_from( (item, refund_amount): (&types::RefundsRouterData<F>, MinorUnit), ) -> Result<Self, Self::Error> { let payment_intent = item.request.connector_transaction_id.clone(); Ok(Self { amount: Some(refund_amount), payment_intent, meta_data: StripeMetadata { order_id: Some(item.request.refund_id.clone()), is_refund_id_as_reference: Some("true".to_string()), }, }) } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="3010" end="3029"> fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { #[derive(Deserialize)] struct Wrapper { #[serde(rename = "type")] _ignore: String, #[serde(flatten, with = "StripeNextActionResponse")] inner: StripeNextActionResponse, } // There is some exception in the stripe next action, it usually sends : // "next_action": { // "redirect_to_url": { "return_url": "...", "url": "..." }, // "type": "redirect_to_url" // }, // But there is a case where it only sends the type and not other field named as it's type let stripe_next_action_response = Wrapper::deserialize(deserializer).map_or(Self::NoNextActionBody, |w| w.inner); Ok(stripe_next_action_response) } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="2985" end="2999"> fn get_url(&self) -> Option<Url> { match self { Self::RedirectToUrl(redirect_to_url) | Self::AlipayHandleRedirect(redirect_to_url) => { Some(redirect_to_url.url.to_owned()) } Self::WechatPayDisplayQrCode(_) => None, Self::VerifyWithMicrodeposits(verify_with_microdeposits) => { Some(verify_with_microdeposits.hosted_verification_url.to_owned()) } Self::CashappHandleRedirectOrDisplayQrCode(_) => None, Self::DisplayBankTransferInstructions(_) => None, Self::MultibancoDisplayDetails(_) => None, Self::NoNextActionBody => None, } } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="46" end="46"> type Error = error_stack::Report<errors::ConnectorError>; <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/stripe/transformers.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/connector/stripe/transformers.rs" role="context" start="2083" end="2112"> fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> { //Only cards supported for mandates let pm_type = StripePaymentMethodType::Card; let payment_data = StripePaymentMethodData::try_from((item, item.auth_type, pm_type))?; let meta_data = Some(get_transaction_metadata( item.request.metadata.clone(), item.connector_request_reference_id.clone(), )); let browser_info = item .request .browser_info .clone() .map(StripeBrowserInformation::from); Ok(Self { confirm: true, payment_data, return_url: item.request.router_return_url.clone(), off_session: item.request.off_session, usage: item.request.setup_future_usage, payment_method_options: None, customer: item.connector_customer.to_owned().map(Secret::new), meta_data, payment_method_types: Some(pm_type), expand: Some(ExpandableObjects::LatestAttempt), browser_info, }) } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="2082" end="2082"> use common_utils::{ errors::CustomResult, ext_traits::{ByteSliceExt, Encode}, pii::{self, Email}, request::RequestContent, types::MinorUnit, }; use hyperswitch_domain_models::mandates::AcceptanceType; use masking::{ExposeInterface, ExposeOptionInterface, Mask, PeekInterface, Secret}; use crate::{ collect_missing_value_keys, connector::utils::{self as connector_util, ApplePay, ApplePayDecrypt, RouterData}, consts, core::errors, headers, services, types::{ self, api, domain, storage::enums, transformers::{ForeignFrom, ForeignTryFrom}, }, utils::OptionExt, }; <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="2148" end="2156"> fn try_from(item: &types::ConnectorCustomerRouterData) -> Result<Self, Self::Error> { Ok(Self { description: item.request.description.to_owned(), email: item.request.email.to_owned(), phone: item.request.phone.to_owned(), name: item.request.name.to_owned(), source: item.request.preprocessing_id.to_owned().map(Secret::new), }) } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="2117" end="2143"> fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> { // Card flow for tokenization is handled seperately because of API contact difference let request_payment_data = match &item.request.payment_method_data { domain::PaymentMethodData::Card(card_details) => { StripePaymentMethodData::CardToken(StripeCardToken { token_card_number: card_details.card_number.clone(), token_card_exp_month: card_details.card_exp_month.clone(), token_card_exp_year: card_details.card_exp_year.clone(), token_card_cvc: card_details.card_cvc.clone(), }) } _ => { create_stripe_payment_method( &item.request.payment_method_data, item.auth_type, item.payment_method_token.clone(), None, StripeBillingAddress::default(), )? .0 } }; Ok(Self { token_data: request_payment_data, }) } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="2073" end="2078"> fn from(item: types::BrowserInformation) -> Self { Self { ip_address: item.ip_address.map(|ip| Secret::new(ip.to_string())), user_agent: item.user_agent, } } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="2039" end="2070"> fn get_payment_method_type_for_saved_payment_method_payment( item: &types::PaymentsAuthorizeRouterData, ) -> Result<Option<StripePaymentMethodType>, error_stack::Report<errors::ConnectorError>> { if item.payment_method == api_enums::PaymentMethod::Card { Ok(Some(StripePaymentMethodType::Card)) //stripe takes ["Card"] as default } else { let stripe_payment_method_type = match item.recurring_mandate_payment_data.clone() { Some(recurring_payment_method_data) => { match recurring_payment_method_data.payment_method_type { Some(payment_method_type) => { StripePaymentMethodType::try_from(payment_method_type) } None => Err(errors::ConnectorError::MissingRequiredField { field_name: "payment_method_type", } .into()), } } None => Err(errors::ConnectorError::MissingRequiredField { field_name: "recurring_mandate_payment_data", } .into()), }?; match stripe_payment_method_type { //Stripe converts Ideal, Bancontact & Sofort Bank redirect methods to Sepa direct debit and attaches to the customer for future usage StripePaymentMethodType::Ideal | StripePaymentMethodType::Bancontact | StripePaymentMethodType::Sofort => Ok(Some(StripePaymentMethodType::Sepa)), _ => Ok(Some(stripe_payment_method_type)), } } } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="4116" end="4164"> fn try_from(item: &types::SubmitEvidenceRouterData) -> Result<Self, Self::Error> { let submit_evidence_request_data = item.request.clone(); Ok(Self { access_activity_log: submit_evidence_request_data.access_activity_log, billing_address: submit_evidence_request_data .billing_address .map(Secret::new), cancellation_policy: submit_evidence_request_data.cancellation_policy_provider_file_id, cancellation_policy_disclosure: submit_evidence_request_data .cancellation_policy_disclosure, cancellation_rebuttal: submit_evidence_request_data.cancellation_rebuttal, customer_communication: submit_evidence_request_data .customer_communication_provider_file_id, customer_email_address: submit_evidence_request_data .customer_email_address .map(Secret::new), customer_name: submit_evidence_request_data.customer_name.map(Secret::new), customer_purchase_ip: submit_evidence_request_data .customer_purchase_ip .map(Secret::new), customer_signature: submit_evidence_request_data .customer_signature_provider_file_id .map(Secret::new), product_description: submit_evidence_request_data.product_description, receipt: submit_evidence_request_data .receipt_provider_file_id .map(Secret::new), refund_policy: submit_evidence_request_data.refund_policy_provider_file_id, refund_policy_disclosure: submit_evidence_request_data.refund_policy_disclosure, refund_refusal_explanation: submit_evidence_request_data.refund_refusal_explanation, service_date: submit_evidence_request_data.service_date, service_documentation: submit_evidence_request_data .service_documentation_provider_file_id, shipping_address: submit_evidence_request_data .shipping_address .map(Secret::new), shipping_carrier: submit_evidence_request_data.shipping_carrier, shipping_date: submit_evidence_request_data.shipping_date, shipping_documentation: submit_evidence_request_data .shipping_documentation_provider_file_id .map(Secret::new), shipping_tracking_number: submit_evidence_request_data .shipping_tracking_number .map(Secret::new), uncategorized_file: submit_evidence_request_data.uncategorized_file_provider_file_id, uncategorized_text: submit_evidence_request_data.uncategorized_text, submit: true, }) } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="4174" end="4192"> fn get_transaction_metadata( merchant_metadata: Option<Secret<Value>>, order_id: String, ) -> HashMap<String, String> { let mut meta_data = HashMap::from([("metadata[order_id]".to_string(), order_id)]); let mut request_hash_map = HashMap::new(); if let Some(metadata) = merchant_metadata { let hashmap: HashMap<String, Value> = serde_json::from_str(&metadata.peek().to_string()).unwrap_or(HashMap::new()); for (key, value) in hashmap { request_hash_map.insert(format!("metadata[{}]", key), value.to_string()); } meta_data.extend(request_hash_map) }; meta_data } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="46" end="46"> type Error = error_stack::Report<errors::ConnectorError>; <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="3484" end="3487"> pub enum LatestAttempt { PaymentIntentAttempt(Box<LatestPaymentAttempt>), SetupAttempt(String), } <file_sep path="hyperswitch/crates/router/src/connector/payone/transformers.rs" role="context" start="117" end="121"> pub struct Card { card_holder_name: Secret<String>, card_number: CardNumber, expiry_date: Secret<String>, } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1075" end="1083"> pub struct Card { pub card_number: CardNumber, pub name_on_card: Option<masking::Secret<String>>, pub card_exp_month: masking::Secret<String>, pub card_exp_year: masking::Secret<String>, pub card_brand: Option<String>, pub card_isin: Option<String>, pub nick_name: Option<String>, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/routes/payment_methods.rs<|crate|> router anchor=list_countries_currencies_for_connector_payment_method kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/routes/payment_methods.rs" role="context" start="796" end="830"> pub async fn list_countries_currencies_for_connector_payment_method( state: web::Data<AppState>, req: HttpRequest, query_payload: web::Query<payment_methods::ListCountriesCurrenciesRequest>, ) -> HttpResponse { let flow = Flow::ListCountriesCurrencies; let payload = query_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { cards::list_countries_currencies_for_connector_payment_method( state, req, auth.profile_id, ) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { permission: Permission::ProfileConnectorWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::ProfileConnectorWrite, }, api_locking::LockAction::NotApplicable, )) .await } <file_sep path="hyperswitch/crates/router/src/routes/payment_methods.rs" role="context" start="795" end="795"> use actix_web::{web, HttpRequest, HttpResponse}; use router_env::{instrument, logger, tracing, Flow}; use super::app::{AppState, SessionState}; use crate::{ core::{ api_locking, errors::{self, utils::StorageErrorExt}, payment_methods::{self as payment_methods_routes, cards}, }, services::{self, api, authentication as auth, authorization::permissions::Permission}, types::{ api::payment_methods::{self, PaymentMethodId}, domain, storage::payment_method::PaymentTokenData, }, }; use crate::{ core::{ customers, payment_methods::{migration, tokenize}, }, types::api::customers::CustomerRequest, }; <file_sep path="hyperswitch/crates/router/src/routes/payment_methods.rs" role="context" start="887" end="892"> fn test_custom_list_deserialization_multi_amount() { let dummy_data = "amount=120&recurring_enabled=true&amount=1000"; let de_query: Result<web::Query<PaymentMethodListRequest>, _> = web::Query::from_query(dummy_data); assert!(de_query.is_err()) } <file_sep path="hyperswitch/crates/router/src/routes/payment_methods.rs" role="context" start="834" end="868"> pub async fn default_payment_method_set_api( state: web::Data<AppState>, req: HttpRequest, path: web::Path<payment_methods::DefaultPaymentMethod>, ) -> HttpResponse { let flow = Flow::DefaultPaymentMethodsSet; let payload = path.into_inner(); let pc = payload.clone(); let customer_id = &pc.customer_id; let ephemeral_auth = match auth::is_ephemeral_auth(req.headers()) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(err), }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, default_payment_method, _| async move { cards::set_default_payment_method( &state, auth.merchant_account.get_id(), auth.key_store, customer_id, default_payment_method.payment_method_id, auth.merchant_account.storage_scheme, ) .await }, &*ephemeral_auth, api_locking::LockAction::NotApplicable, )) .await } <file_sep path="hyperswitch/crates/router/src/routes/payment_methods.rs" role="context" start="766" end="792"> pub async fn payment_method_delete_api( state: web::Data<AppState>, req: HttpRequest, payment_method_id: web::Path<(String,)>, ) -> HttpResponse { let flow = Flow::PaymentMethodsDelete; let pm = PaymentMethodId { payment_method_id: payment_method_id.into_inner().0, }; let ephemeral_auth = match auth::is_ephemeral_auth(req.headers()) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(err), }; Box::pin(api::server_wrap( flow, state, &req, pm, |state, auth: auth::AuthenticationData, req, _| { cards::delete_payment_method(state, auth.merchant_account, req, auth.key_store) }, &*ephemeral_auth, api_locking::LockAction::NotApplicable, )) .await } <file_sep path="hyperswitch/crates/router/src/routes/payment_methods.rs" role="context" start="726" end="759"> pub async fn payment_method_update_api( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, json_payload: web::Json<payment_methods::PaymentMethodUpdate>, ) -> HttpResponse { let flow = Flow::PaymentMethodsUpdate; let payment_method_id = path.into_inner(); let payload = json_payload.into_inner(); let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload) { Ok((auth, _auth_flow)) => (auth, _auth_flow), Err(e) => return api::log_and_return_error_response(e), }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { cards::update_customer_payment_method( state, auth.merchant_account, req, &payment_method_id, auth.key_store, ) }, &*auth, api_locking::LockAction::NotApplicable, )) .await } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2311" end="2314"> pub struct ListCountriesCurrenciesRequest { pub connector: api_enums::Connector, pub payment_method_type: api_enums::PaymentMethodType, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/nmi/transformers.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/connector/nmi/transformers.rs" role="context" start="865" end="902"> fn try_from( item: types::ResponseRouterData< api::SetupMandate, StandardResponse, T, types::PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let (response, status) = match item.response.response { Response::Approved => ( Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId( item.response.transactionid.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.orderid), incremental_authorization_allowed: None, charges: None, }), enums::AttemptStatus::Charged, ), Response::Declined | Response::Error => ( Err(types::ErrorResponse::foreign_from(( item.response, item.http_code, ))), enums::AttemptStatus::Failure, ), }; Ok(Self { status, response, ..item.data }) } <file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="864" end="864"> use common_utils::{errors::CustomResult, ext_traits::XmlExt, pii::Email, types::FloatMajorUnit}; use crate::{ connector::utils::{ self, AddressDetailsData, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, RouterData, }, core::errors, services, types::{self, api, domain, storage::enums, transformers::ForeignFrom, ConnectorAuthType}, }; type Error = Report<errors::ConnectorError>; <file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="925" end="968"> fn try_from( item: types::ResponseRouterData< api::Authorize, StandardResponse, types::PaymentsAuthorizeData, types::PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let (response, status) = match item.response.response { Response::Approved => ( Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId( item.response.transactionid.clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.orderid), incremental_authorization_allowed: None, charges: None, }), if let Some(diesel_models::enums::CaptureMethod::Automatic) = item.data.request.capture_method { enums::AttemptStatus::CaptureInitiated } else { enums::AttemptStatus::Authorized }, ), Response::Declined | Response::Error => ( Err(types::ErrorResponse::foreign_from(( item.response, item.http_code, ))), enums::AttemptStatus::Failure, ), }; Ok(Self { status, response, ..item.data }) } <file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="906" end="918"> fn foreign_from((response, http_code): (StandardResponse, u16)) -> Self { Self { code: response.response_code, message: response.responsetext.to_owned(), reason: Some(response.responsetext), status_code: http_code, attempt_status: None, connector_transaction_id: Some(response.transactionid), network_advice_code: None, network_decline_code: None, network_error_message: None, } } <file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="808" end="829"> fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> { let auth = NmiAuthType::try_from(&item.connector_auth_type)?; match &item.request.cancellation_reason { Some(cancellation_reason) => { let void_reason: NmiVoidReason = serde_json::from_str(&format!("\"{}\"", cancellation_reason)) .map_err(|_| errors::ConnectorError::NotSupported { message: format!("Json deserialise error: unknown variant `{}` expected to be one of `fraud`, `user_cancel`, `icc_rejected`, `icc_card_removed`, `icc_no_confirmation`, `pos_timeout`. This cancellation_reason", cancellation_reason), connector: "nmi" })?; Ok(Self { transaction_type: TransactionType::Void, security_key: auth.api_key, transactionid: item.request.connector_transaction_id.clone(), void_reason, }) } None => Err(errors::ConnectorError::MissingRequiredField { field_name: "cancellation_reason", } .into()), } } <file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="746" end="783"> fn try_from( item: types::ResponseRouterData< api::Capture, StandardResponse, types::PaymentsCaptureData, types::PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let (response, status) = match item.response.response { Response::Approved => ( Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId( item.response.transactionid.to_owned(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.orderid), incremental_authorization_allowed: None, charges: None, }), enums::AttemptStatus::CaptureInitiated, ), Response::Declined | Response::Error => ( Err(types::ErrorResponse::foreign_from(( item.response, item.http_code, ))), enums::AttemptStatus::CaptureFailed, ), }; Ok(Self { status, response, ..item.data }) } <file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="1314" end="1332"> fn foreign_from(status: NmiWebhookEventType) -> Self { match status { NmiWebhookEventType::SaleSuccess => Self::PaymentIntentSuccess, NmiWebhookEventType::SaleFailure => Self::PaymentIntentFailure, NmiWebhookEventType::RefundSuccess => Self::RefundSuccess, NmiWebhookEventType::RefundFailure => Self::RefundFailure, NmiWebhookEventType::VoidSuccess => Self::PaymentIntentCancelled, NmiWebhookEventType::AuthSuccess => Self::PaymentIntentAuthorizationSuccess, NmiWebhookEventType::CaptureSuccess => Self::PaymentIntentCaptureSuccess, NmiWebhookEventType::AuthFailure => Self::PaymentIntentAuthorizationFailure, NmiWebhookEventType::CaptureFailure => Self::PaymentIntentCaptureFailure, NmiWebhookEventType::VoidFailure => Self::PaymentIntentCancelFailure, NmiWebhookEventType::SaleUnknown | NmiWebhookEventType::RefundUnknown | NmiWebhookEventType::AuthUnknown | NmiWebhookEventType::VoidUnknown | NmiWebhookEventType::CaptureUnknown => Self::EventNotSupported, } } <file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="435" end="449"> pub fn new(metadata: &serde_json::Value) -> Self { let metadata_as_string = metadata.to_string(); let hash_map: std::collections::BTreeMap<String, serde_json::Value> = serde_json::from_str(&metadata_as_string).unwrap_or(std::collections::BTreeMap::new()); let inner = hash_map .into_iter() .enumerate() .map(|(index, (hs_key, hs_value))| { let nmi_key = format!("merchant_defined_field_{}", index + 1); let nmi_value = format!("{hs_key}={hs_value}"); (nmi_key, Secret::new(nmi_value)) }) .collect(); Self { inner } } <file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="19" end="19"> type Error = Report<errors::ConnectorError>; <file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="843" end="852"> pub struct StandardResponse { pub response: Response, pub responsetext: String, pub authcode: Option<String>, pub transactionid: String, pub avsresponse: Option<String>, pub cvvresponse: Option<String>, pub orderid: String, pub response_code: String, } <file_sep path="hyperswitch/crates/router/src/middleware.rs" role="context" start="22" end="22"> type Response = actix_web::dev::ServiceResponse<B>; <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/types/transformers.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/transformers.rs" role="context" start="1988" end="2020"> fn try_from(item: domain::Event) -> Result<Self, Self::Error> { use crate::utils::OptionExt; // We only allow retrieving events with all required fields in `EventListItemResponse`, and // `request` and `response` populated. // We cannot retrieve events with only some of these fields populated. let event_information = api_models::webhook_events::EventListItemResponse::try_from(item.clone())?; let request = item .request .get_required_value("request") .change_context(errors::ApiErrorResponse::InternalServerError)? .peek() .parse_struct("OutgoingWebhookRequestContent") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse webhook event request information")?; let response = item .response .get_required_value("response") .change_context(errors::ApiErrorResponse::InternalServerError)? .peek() .parse_struct("OutgoingWebhookResponseContent") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse webhook event response information")?; Ok(Self { event_information, request, response, delivery_attempt: item.delivery_attempt, }) } <file_sep path="hyperswitch/crates/router/src/types/transformers.rs" role="context" start="1987" end="1987"> use actix_web::http::header::HeaderMap; use api_models::{ cards_info as card_info_types, enums as api_enums, gsm as gsm_api_types, payment_methods, payments, routing::ConnectorSelection, }; use common_utils::{ consts::X_HS_LATENCY, crypto::Encryptable, ext_traits::{Encode, StringExt, ValueExt}, fp_utils::when, pii, types::ConnectorTransactionIdTrait, }; use diesel_models::enums as storage_enums; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::payments::payment_intent::CustomerData; use masking::{ExposeInterface, PeekInterface, Secret}; use super::domain; use crate::{ core::errors, headers::{ ACCEPT_LANGUAGE, BROWSER_NAME, X_APP_ID, X_CLIENT_PLATFORM, X_CLIENT_SOURCE, X_CLIENT_VERSION, X_MERCHANT_DOMAIN, X_PAYMENT_CONFIRM_SOURCE, X_REDIRECT_URI, }, services::authentication::get_header_value_by_key, types::{ self as router_types, api::{self as api_types, routing as routing_types}, storage, }, }; <file_sep path="hyperswitch/crates/router/src/types/transformers.rs" role="context" start="2038" end="2044"> fn foreign_from(item: diesel_models::business_profile::AuthenticationConnectorDetails) -> Self { Self { authentication_connectors: item.authentication_connectors, three_ds_requestor_url: item.three_ds_requestor_url, three_ds_requestor_app_url: item.three_ds_requestor_app_url, } } <file_sep path="hyperswitch/crates/router/src/types/transformers.rs" role="context" start="2026" end="2032"> fn foreign_from(item: api_models::admin::AuthenticationConnectorDetails) -> Self { Self { authentication_connectors: item.authentication_connectors, three_ds_requestor_url: item.three_ds_requestor_url, three_ds_requestor_app_url: item.three_ds_requestor_app_url, } } <file_sep path="hyperswitch/crates/router/src/types/transformers.rs" role="context" start="1951" end="1981"> fn try_from(item: domain::Event) -> Result<Self, Self::Error> { use crate::utils::OptionExt; // We only allow retrieving events with merchant_id, business_profile_id // and initial_attempt_id populated. // We cannot retrieve events with only some of these fields populated. let merchant_id = item .merchant_id .get_required_value("merchant_id") .change_context(errors::ApiErrorResponse::InternalServerError)?; let profile_id = item .business_profile_id .get_required_value("business_profile_id") .change_context(errors::ApiErrorResponse::InternalServerError)?; let initial_attempt_id = item .initial_attempt_id .get_required_value("initial_attempt_id") .change_context(errors::ApiErrorResponse::InternalServerError)?; Ok(Self { event_id: item.event_id, merchant_id, profile_id, object_id: item.primary_object_id, event_type: item.event_type, event_class: item.event_class, is_delivery_successful: item.is_overall_delivery_successful, initial_attempt_id, created: item.created_at, }) } <file_sep path="hyperswitch/crates/router/src/types/transformers.rs" role="context" start="1917" end="1944"> fn foreign_try_from( item: api_types::webhook_events::EventListConstraints, ) -> Result<Self, Self::Error> { if item.object_id.is_some() && (item.created_after.is_some() || item.created_before.is_some() || item.limit.is_some() || item.offset.is_some()) { return Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "Either only `object_id` must be specified, or one or more of \ `created_after`, `created_before`, `limit` and `offset` must be specified" .to_string() })); } match item.object_id { Some(object_id) => Ok(Self::ObjectIdFilter { object_id }), None => Ok(Self::GenericFilter { created_after: item.created_after, created_before: item.created_before, limit: item.limit.map(i64::from), offset: item.offset.map(i64::from), is_delivered: item.is_delivered, }), } } <file_sep path="hyperswitch/crates/router/src/types/transformers.rs" role="context" start="68" end="68"> type Error = <T as ForeignTryFrom<F>>::Error; <file_sep path="hyperswitch/crates/router/src/types/domain/event.rs" role="context" start="21" end="74"> pub struct Event { /// A string that uniquely identifies the event. pub event_id: String, /// Represents the type of event for the webhook. pub event_type: EventType, /// Represents the class of event for the webhook. pub event_class: EventClass, /// Indicates whether the current webhook delivery was successful. pub is_webhook_notified: bool, /// Reference to the object for which the webhook was created. pub primary_object_id: String, /// Type of the object type for which the webhook was created. pub primary_object_type: EventObjectType, /// The timestamp when the webhook was created. pub created_at: time::PrimitiveDateTime, /// Merchant Account identifier to which the object is associated with. pub merchant_id: Option<common_utils::id_type::MerchantId>, /// Business Profile identifier to which the object is associated with. pub business_profile_id: Option<common_utils::id_type::ProfileId>, /// The timestamp when the primary object was created. pub primary_object_created_at: Option<time::PrimitiveDateTime>, /// This allows the event to be uniquely identified to prevent multiple processing. pub idempotent_event_id: Option<String>, /// Links to the initial attempt of the event. pub initial_attempt_id: Option<String>, /// This field contains the encrypted request data sent as part of the event. #[encrypt] pub request: Option<Encryptable<Secret<String>>>, /// This field contains the encrypted response data received as part of the event. #[encrypt] pub response: Option<Encryptable<Secret<String>>>, /// Represents the event delivery type. pub delivery_attempt: Option<WebhookDeliveryAttempt>, /// Holds any additional data related to the event. pub metadata: Option<EventMetadata>, /// Indicates whether the event was ultimately delivered. pub is_overall_delivery_successful: Option<bool>, } <file_sep path="hyperswitch/migrations/2022-09-29-084920_create_initial_tables/up.sql" role="context" start="279" end="295"> phone_country_code VARCHAR(255), description VARCHAR(255), address JSON, created_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP, metadata JSON, PRIMARY KEY (customer_id, merchant_id) ); CREATE TABLE events ( id SERIAL PRIMARY KEY, event_id VARCHAR(255) NOT NULL, event_type "EventType" NOT NULL, event_class "EventClass" NOT NULL, is_webhook_notified BOOLEAN NOT NULL DEFAULT FALSE, intent_reference_id VARCHAR(255), primary_object_id VARCHAR(255) NOT NULL, primary_object_type "EventObjectType" 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/connector/stripe/transformers.rs<|crate|> router anchor=get_payment_method_type_for_saved_payment_method_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="2039" end="2070"> fn get_payment_method_type_for_saved_payment_method_payment( item: &types::PaymentsAuthorizeRouterData, ) -> Result<Option<StripePaymentMethodType>, error_stack::Report<errors::ConnectorError>> { if item.payment_method == api_enums::PaymentMethod::Card { Ok(Some(StripePaymentMethodType::Card)) //stripe takes ["Card"] as default } else { let stripe_payment_method_type = match item.recurring_mandate_payment_data.clone() { Some(recurring_payment_method_data) => { match recurring_payment_method_data.payment_method_type { Some(payment_method_type) => { StripePaymentMethodType::try_from(payment_method_type) } None => Err(errors::ConnectorError::MissingRequiredField { field_name: "payment_method_type", } .into()), } } None => Err(errors::ConnectorError::MissingRequiredField { field_name: "recurring_mandate_payment_data", } .into()), }?; match stripe_payment_method_type { //Stripe converts Ideal, Bancontact & Sofort Bank redirect methods to Sepa direct debit and attaches to the customer for future usage StripePaymentMethodType::Ideal | StripePaymentMethodType::Bancontact | StripePaymentMethodType::Sofort => Ok(Some(StripePaymentMethodType::Sepa)), _ => Ok(Some(stripe_payment_method_type)), } } } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="2038" end="2038"> use api_models::{self, enums as api_enums, payments}; use common_utils::{ errors::CustomResult, ext_traits::{ByteSliceExt, Encode}, pii::{self, Email}, request::RequestContent, types::MinorUnit, }; use error_stack::ResultExt; use crate::{ collect_missing_value_keys, connector::utils::{self as connector_util, ApplePay, ApplePayDecrypt, RouterData}, consts, core::errors, headers, services, types::{ self, api, domain, storage::enums, transformers::{ForeignFrom, ForeignTryFrom}, }, utils::OptionExt, }; <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="2083" end="2112"> fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> { //Only cards supported for mandates let pm_type = StripePaymentMethodType::Card; let payment_data = StripePaymentMethodData::try_from((item, item.auth_type, pm_type))?; let meta_data = Some(get_transaction_metadata( item.request.metadata.clone(), item.connector_request_reference_id.clone(), )); let browser_info = item .request .browser_info .clone() .map(StripeBrowserInformation::from); Ok(Self { confirm: true, payment_data, return_url: item.request.router_return_url.clone(), off_session: item.request.off_session, usage: item.request.setup_future_usage, payment_method_options: None, customer: item.connector_customer.to_owned().map(Secret::new), meta_data, payment_method_types: Some(pm_type), expand: Some(ExpandableObjects::LatestAttempt), browser_info, }) } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="2073" end="2078"> fn from(item: types::BrowserInformation) -> Self { Self { ip_address: item.ip_address.map(|ip| Secret::new(ip.to_string())), user_agent: item.user_agent, } } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="1674" end="2036"> fn try_from( data: (&types::PaymentsAuthorizeRouterData, MinorUnit), ) -> Result<Self, Self::Error> { let item = data.0; let amount = data.1; let order_id = item.connector_request_reference_id.clone(); let shipping_address = match item.get_optional_shipping() { Some(shipping_details) => { let shipping_address = shipping_details.address.as_ref(); shipping_address.and_then(|shipping_detail| { shipping_detail .first_name .as_ref() .map(|first_name| StripeShippingAddress { city: shipping_address.and_then(|a| a.city.clone()), country: shipping_address.and_then(|a| a.country), line1: shipping_address.and_then(|a| a.line1.clone()), line2: shipping_address.and_then(|a| a.line2.clone()), zip: shipping_address.and_then(|a| a.zip.clone()), state: shipping_address.and_then(|a| a.state.clone()), name: format!( "{} {}", first_name.clone().expose(), shipping_detail .last_name .clone() .expose_option() .unwrap_or_default() ) .into(), phone: shipping_details.phone.as_ref().map(|p| { format!( "{}{}", p.country_code.clone().unwrap_or_default(), p.number.clone().expose_option().unwrap_or_default() ) .into() }), }) }) } None => None, }; let billing_address = match item.get_optional_billing() { Some(billing_details) => { let billing_address = billing_details.address.as_ref(); StripeBillingAddress { city: billing_address.and_then(|a| a.city.clone()), country: billing_address.and_then(|a| a.country), address_line1: billing_address.and_then(|a| a.line1.clone()), address_line2: billing_address.and_then(|a| a.line2.clone()), zip_code: billing_address.and_then(|a| a.zip.clone()), state: billing_address.and_then(|a| a.state.clone()), name: billing_address.and_then(|a| { a.first_name.as_ref().map(|first_name| { format!( "{} {}", first_name.clone().expose(), a.last_name.clone().expose_option().unwrap_or_default() ) .into() }) }), email: billing_details.email.clone(), phone: billing_details.phone.as_ref().map(|p| { format!( "{}{}", p.country_code.clone().unwrap_or_default(), p.number.clone().expose_option().unwrap_or_default() ) .into() }), } } None => StripeBillingAddress::default(), }; let mut payment_method_options = None; let ( mut payment_data, payment_method, billing_address, payment_method_types, setup_future_usage, ) = { match item .request .mandate_id .clone() .and_then(|mandate_ids| mandate_ids.mandate_reference_id) { Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => ( None, connector_mandate_ids.get_connector_mandate_id(), StripeBillingAddress::default(), get_payment_method_type_for_saved_payment_method_payment(item)?, None, ), Some(payments::MandateReferenceId::NetworkMandateId(network_transaction_id)) => { payment_method_options = Some(StripePaymentMethodOptions::Card { mandate_options: None, network_transaction_id: None, mit_exemption: Some(MitExemption { network_transaction_id: Secret::new(network_transaction_id), }), }); let payment_data = match item.request.payment_method_data { domain::payments::PaymentMethodData::CardDetailsForNetworkTransactionId( ref card_details_for_network_transaction_id, ) => StripePaymentMethodData::Card(StripeCardData { payment_method_data_type: StripePaymentMethodType::Card, payment_method_data_card_number: card_details_for_network_transaction_id.card_number.clone(), payment_method_data_card_exp_month: card_details_for_network_transaction_id .card_exp_month .clone(), payment_method_data_card_exp_year: card_details_for_network_transaction_id .card_exp_year .clone(), payment_method_data_card_cvc: None, payment_method_auth_type: None, payment_method_data_card_preferred_network: card_details_for_network_transaction_id .card_network .clone() .and_then(get_stripe_card_network), }), domain::payments::PaymentMethodData::CardRedirect(_) | domain::payments::PaymentMethodData::Wallet(_) | domain::payments::PaymentMethodData::PayLater(_) | domain::payments::PaymentMethodData::BankRedirect(_) | domain::payments::PaymentMethodData::BankDebit(_) | domain::payments::PaymentMethodData::BankTransfer(_) | domain::payments::PaymentMethodData::Crypto(_) | domain::payments::PaymentMethodData::MandatePayment | domain::payments::PaymentMethodData::Reward | domain::payments::PaymentMethodData::RealTimePayment(_) | domain::payments::PaymentMethodData::MobilePayment(_) | domain::payments::PaymentMethodData::Upi(_) | domain::payments::PaymentMethodData::Voucher(_) | domain::payments::PaymentMethodData::GiftCard(_) | domain::payments::PaymentMethodData::OpenBanking(_) | domain::payments::PaymentMethodData::CardToken(_) | domain::PaymentMethodData::NetworkToken(_) | domain::PaymentMethodData::Card(_) => { Err(errors::ConnectorError::NotSupported { message: "Network tokenization for payment method".to_string(), connector: "Stripe", })? } }; ( Some(payment_data), None, StripeBillingAddress::default(), None, None, ) } Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) | None => { let (payment_method_data, payment_method_type, billing_address) = create_stripe_payment_method( &item.request.payment_method_data, item.auth_type, item.payment_method_token.clone(), Some(connector_util::PaymentsAuthorizeRequestData::is_customer_initiated_mandate_payment( &item.request, )), billing_address )?; validate_shipping_address_against_payment_method( &shipping_address, payment_method_type.as_ref(), )?; ( Some(payment_method_data), None, billing_address, payment_method_type, item.request.setup_future_usage, ) } } }; payment_data = match item.request.payment_method_data { domain::PaymentMethodData::Wallet(domain::WalletData::ApplePay(_)) => { let payment_method_token = item .payment_method_token .to_owned() .get_required_value("payment_token") .change_context(errors::ConnectorError::InvalidWalletToken { wallet_name: "Apple Pay".to_string(), })?; let payment_method_token = match payment_method_token { types::PaymentMethodToken::Token(payment_method_token) => payment_method_token, types::PaymentMethodToken::ApplePayDecrypt(_) => { Err(errors::ConnectorError::InvalidWalletToken { wallet_name: "Apple Pay".to_string(), })? } types::PaymentMethodToken::PazeDecrypt(_) => { Err(crate::unimplemented_payment_method!("Paze", "Stripe"))? } types::PaymentMethodToken::GooglePayDecrypt(_) => { Err(crate::unimplemented_payment_method!("Google Pay", "Stripe"))? } }; Some(StripePaymentMethodData::Wallet( StripeWallet::ApplepayPayment(ApplepayPayment { token: payment_method_token, payment_method_types: StripePaymentMethodType::Card, }), )) } _ => payment_data, }; let setup_mandate_details = item .request .setup_mandate_details .as_ref() .and_then(|mandate_details| { mandate_details .customer_acceptance .as_ref() .map(|customer_acceptance| { Ok::<_, error_stack::Report<errors::ConnectorError>>( match customer_acceptance.acceptance_type { AcceptanceType::Online => { let online_mandate = customer_acceptance .online .clone() .get_required_value("online") .change_context( errors::ConnectorError::MissingRequiredField { field_name: "online", }, )?; StripeMandateRequest { mandate_type: StripeMandateType::Online { ip_address: online_mandate .ip_address .get_required_value("ip_address") .change_context( errors::ConnectorError::MissingRequiredField { field_name: "ip_address", }, )?, user_agent: online_mandate.user_agent, }, } } AcceptanceType::Offline => StripeMandateRequest { mandate_type: StripeMandateType::Offline, }, }, ) }) }) .transpose()? .or_else(|| { //stripe requires us to send mandate_data while making recurring payment through saved bank debit if payment_method.is_some() { //check if payment is done through saved payment method match &payment_method_types { //check if payment method is bank debit Some( StripePaymentMethodType::Ach | StripePaymentMethodType::Sepa | StripePaymentMethodType::Becs | StripePaymentMethodType::Bacs, ) => Some(StripeMandateRequest { mandate_type: StripeMandateType::Offline, }), _ => None, } } else { None } }); let meta_data = get_transaction_metadata(item.request.metadata.clone().map(Into::into), order_id); // We pass browser_info only when payment_data exists. // Hence, we're pass Null during recurring payments as payment_method_data[type] is not passed let browser_info = if payment_data.is_some() { item.request .browser_info .clone() .map(StripeBrowserInformation::from) } else { None }; let (charges, customer) = match &item.request.split_payments { Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment( stripe_split_payment, )) => { let charges = match &stripe_split_payment.charge_type { api_models::enums::PaymentChargeType::Stripe(charge_type) => { match charge_type { api_models::enums::StripeChargeType::Direct => Some(IntentCharges { application_fee_amount: stripe_split_payment.application_fees, destination_account_id: None, }), api_models::enums::StripeChargeType::Destination => { Some(IntentCharges { application_fee_amount: stripe_split_payment.application_fees, destination_account_id: Some( stripe_split_payment.transfer_account_id.clone(), ), }) } } } }; (charges, None) } Some(common_types::payments::SplitPaymentsRequest::AdyenSplitPayment(_)) | Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment(_)) | None => (None, item.connector_customer.to_owned().map(Secret::new)), }; Ok(Self { amount, //hopefully we don't loose some cents here currency: item.request.currency.to_string(), //we need to copy the value and not transfer ownership statement_descriptor_suffix: item.request.statement_descriptor_suffix.clone(), statement_descriptor: item.request.statement_descriptor.clone(), meta_data, return_url: item .request .router_return_url .clone() .unwrap_or_else(|| "https://juspay.in/".to_string()), confirm: true, // Stripe requires confirm to be true if return URL is present description: item.description.clone(), shipping: shipping_address, billing: billing_address, capture_method: StripeCaptureMethod::from(item.request.capture_method), payment_data, payment_method_options, payment_method, customer, setup_mandate_details, off_session: item.request.off_session, setup_future_usage, payment_method_types, expand: Some(ExpandableObjects::LatestCharge), browser_info, charges, }) } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="1654" end="1669"> fn try_from(gpay_data: &domain::GooglePayWalletData) -> Result<Self, Self::Error> { Ok(Self::Wallet(StripeWallet::GooglepayToken(GooglePayToken { token: Secret::new( gpay_data .tokenization_data .token .as_bytes() .parse_struct::<StripeGpayToken>("StripeGpayToken") .change_context(errors::ConnectorError::InvalidWalletToken { wallet_name: "Google Pay".to_string(), })? .id, ), payment_type: StripePaymentMethodType::Card, }))) } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="4116" end="4164"> fn try_from(item: &types::SubmitEvidenceRouterData) -> Result<Self, Self::Error> { let submit_evidence_request_data = item.request.clone(); Ok(Self { access_activity_log: submit_evidence_request_data.access_activity_log, billing_address: submit_evidence_request_data .billing_address .map(Secret::new), cancellation_policy: submit_evidence_request_data.cancellation_policy_provider_file_id, cancellation_policy_disclosure: submit_evidence_request_data .cancellation_policy_disclosure, cancellation_rebuttal: submit_evidence_request_data.cancellation_rebuttal, customer_communication: submit_evidence_request_data .customer_communication_provider_file_id, customer_email_address: submit_evidence_request_data .customer_email_address .map(Secret::new), customer_name: submit_evidence_request_data.customer_name.map(Secret::new), customer_purchase_ip: submit_evidence_request_data .customer_purchase_ip .map(Secret::new), customer_signature: submit_evidence_request_data .customer_signature_provider_file_id .map(Secret::new), product_description: submit_evidence_request_data.product_description, receipt: submit_evidence_request_data .receipt_provider_file_id .map(Secret::new), refund_policy: submit_evidence_request_data.refund_policy_provider_file_id, refund_policy_disclosure: submit_evidence_request_data.refund_policy_disclosure, refund_refusal_explanation: submit_evidence_request_data.refund_refusal_explanation, service_date: submit_evidence_request_data.service_date, service_documentation: submit_evidence_request_data .service_documentation_provider_file_id, shipping_address: submit_evidence_request_data .shipping_address .map(Secret::new), shipping_carrier: submit_evidence_request_data.shipping_carrier, shipping_date: submit_evidence_request_data.shipping_date, shipping_documentation: submit_evidence_request_data .shipping_documentation_provider_file_id .map(Secret::new), shipping_tracking_number: submit_evidence_request_data .shipping_tracking_number .map(Secret::new), uncategorized_file: submit_evidence_request_data.uncategorized_file_provider_file_id, uncategorized_text: submit_evidence_request_data.uncategorized_text, submit: true, }) } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="647" end="676"> pub enum StripePaymentMethodType { Affirm, AfterpayClearpay, Alipay, #[serde(rename = "amazon_pay")] AmazonPay, #[serde(rename = "au_becs_debit")] Becs, #[serde(rename = "bacs_debit")] Bacs, Bancontact, Blik, Card, CustomerBalance, Eps, Giropay, Ideal, Klarna, #[serde(rename = "p24")] Przelewy24, #[serde(rename = "sepa_debit")] Sepa, Sofort, #[serde(rename = "us_bank_account")] Ach, #[serde(rename = "wechat_pay")] Wechatpay, #[serde(rename = "cashapp")] Cashapp, } <file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="54" end="70"> 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 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); <file_sep path="hyperswitch/crates/api_models/src/payouts.rs" role="context" start="262" end="267"> pub enum Bank { Ach(AchBankTransfer), Bacs(BacsBankTransfer), Sepa(SepaBankTransfer), Pix(PixBankTransfer), }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/stripe/transformers.rs<|crate|> router anchor=get_bank_debit_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="1135" end="1180"> fn get_bank_debit_data( bank_debit_data: &domain::BankDebitData, ) -> (StripePaymentMethodType, BankDebitData) { match bank_debit_data { domain::BankDebitData::AchBankDebit { account_number, routing_number, .. } => { let ach_data = BankDebitData::Ach { account_holder_type: "individual".to_string(), account_number: account_number.to_owned(), routing_number: routing_number.to_owned(), }; (StripePaymentMethodType::Ach, ach_data) } domain::BankDebitData::SepaBankDebit { iban, .. } => { let sepa_data: BankDebitData = BankDebitData::Sepa { iban: iban.to_owned(), }; (StripePaymentMethodType::Sepa, sepa_data) } domain::BankDebitData::BecsBankDebit { account_number, bsb_number, .. } => { let becs_data = BankDebitData::Becs { account_number: account_number.to_owned(), bsb_number: bsb_number.to_owned(), }; (StripePaymentMethodType::Becs, becs_data) } domain::BankDebitData::BacsBankDebit { account_number, sort_code, .. } => { let bacs_data = BankDebitData::Bacs { account_number: account_number.to_owned(), sort_code: Secret::new(sort_code.clone().expose().replace('-', "")), }; (StripePaymentMethodType::Bacs, bacs_data) } } } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="1134" end="1134"> use masking::{ExposeInterface, ExposeOptionInterface, Mask, PeekInterface, Secret}; use crate::{ collect_missing_value_keys, connector::utils::{self as connector_util, ApplePay, ApplePayDecrypt, RouterData}, consts, core::errors, headers, services, types::{ self, api, domain, storage::enums, transformers::{ForeignFrom, ForeignTryFrom}, }, utils::OptionExt, }; <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="1407" end="1421"> fn get_stripe_card_network(card_network: common_enums::CardNetwork) -> Option<StripeCardNetwork> { match card_network { common_enums::CardNetwork::Visa => Some(StripeCardNetwork::Visa), common_enums::CardNetwork::Mastercard => Some(StripeCardNetwork::Mastercard), common_enums::CardNetwork::CartesBancaires => Some(StripeCardNetwork::CartesBancaires), common_enums::CardNetwork::AmericanExpress | common_enums::CardNetwork::JCB | common_enums::CardNetwork::DinersClub | common_enums::CardNetwork::Discover | common_enums::CardNetwork::UnionPay | common_enums::CardNetwork::Interac | common_enums::CardNetwork::RuPay | common_enums::CardNetwork::Maestro => None, } } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="1182" end="1405"> fn create_stripe_payment_method( payment_method_data: &domain::PaymentMethodData, auth_type: enums::AuthenticationType, payment_method_token: Option<types::PaymentMethodToken>, is_customer_initiated_mandate_payment: Option<bool>, billing_address: StripeBillingAddress, ) -> Result< ( StripePaymentMethodData, Option<StripePaymentMethodType>, StripeBillingAddress, ), error_stack::Report<errors::ConnectorError>, > { match payment_method_data { domain::PaymentMethodData::Card(card_details) => { let payment_method_auth_type = match auth_type { enums::AuthenticationType::ThreeDs => Auth3ds::Any, enums::AuthenticationType::NoThreeDs => Auth3ds::Automatic, }; Ok(( StripePaymentMethodData::try_from((card_details, payment_method_auth_type))?, Some(StripePaymentMethodType::Card), billing_address, )) } domain::PaymentMethodData::PayLater(pay_later_data) => { let stripe_pm_type = StripePaymentMethodType::try_from(pay_later_data)?; Ok(( StripePaymentMethodData::PayLater(StripePayLaterData { payment_method_data_type: stripe_pm_type, }), Some(stripe_pm_type), billing_address, )) } domain::PaymentMethodData::BankRedirect(bank_redirect_data) => { let billing_address = if is_customer_initiated_mandate_payment == Some(true) { mandatory_parameters_for_sepa_bank_debit_mandates( &Some(billing_address.to_owned()), is_customer_initiated_mandate_payment, )? } else { billing_address }; let pm_type = StripePaymentMethodType::try_from(bank_redirect_data)?; let bank_redirect_data = StripePaymentMethodData::try_from(( bank_redirect_data, Some(billing_address.to_owned()), ))?; Ok((bank_redirect_data, Some(pm_type), billing_address)) } domain::PaymentMethodData::Wallet(wallet_data) => { let pm_type = ForeignTryFrom::foreign_try_from(wallet_data)?; let wallet_specific_data = StripePaymentMethodData::try_from((wallet_data, payment_method_token))?; Ok(( wallet_specific_data, pm_type, StripeBillingAddress::default(), )) } domain::PaymentMethodData::BankDebit(bank_debit_data) => { let (pm_type, bank_debit_data) = get_bank_debit_data(bank_debit_data); let pm_data = StripePaymentMethodData::BankDebit(StripeBankDebitData { bank_specific_data: bank_debit_data, }); Ok((pm_data, Some(pm_type), billing_address)) } domain::PaymentMethodData::BankTransfer(bank_transfer_data) => { match bank_transfer_data.deref() { domain::BankTransferData::AchBankTransfer {} => Ok(( StripePaymentMethodData::BankTransfer(StripeBankTransferData::AchBankTransfer( Box::new(AchTransferData { payment_method_data_type: StripePaymentMethodType::CustomerBalance, bank_transfer_type: StripeCreditTransferTypes::AchCreditTransfer, payment_method_type: StripePaymentMethodType::CustomerBalance, balance_funding_type: BankTransferType::BankTransfers, }), )), None, StripeBillingAddress::default(), )), domain::BankTransferData::MultibancoBankTransfer {} => Ok(( StripePaymentMethodData::BankTransfer( StripeBankTransferData::MultibancoBankTransfers(Box::new( MultibancoTransferData { payment_method_data_type: StripeCreditTransferTypes::Multibanco, payment_method_type: StripeCreditTransferTypes::Multibanco, email: billing_address.email.ok_or( errors::ConnectorError::MissingRequiredField { field_name: "billing_address.email", }, )?, }, )), ), None, StripeBillingAddress::default(), )), domain::BankTransferData::SepaBankTransfer {} => Ok(( StripePaymentMethodData::BankTransfer( StripeBankTransferData::SepaBankTransfer(Box::new(SepaBankTransferData { payment_method_data_type: StripePaymentMethodType::CustomerBalance, bank_transfer_type: BankTransferType::EuBankTransfer, balance_funding_type: BankTransferType::BankTransfers, payment_method_type: StripePaymentMethodType::CustomerBalance, country: billing_address.country.ok_or( errors::ConnectorError::MissingRequiredField { field_name: "billing_address.country", }, )?, })), ), Some(StripePaymentMethodType::CustomerBalance), billing_address, )), domain::BankTransferData::BacsBankTransfer {} => Ok(( StripePaymentMethodData::BankTransfer( StripeBankTransferData::BacsBankTransfers(Box::new(BacsBankTransferData { payment_method_data_type: StripePaymentMethodType::CustomerBalance, bank_transfer_type: BankTransferType::GbBankTransfer, balance_funding_type: BankTransferType::BankTransfers, payment_method_type: StripePaymentMethodType::CustomerBalance, })), ), Some(StripePaymentMethodType::CustomerBalance), billing_address, )), domain::BankTransferData::Pix { .. } => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) .into()) } domain::BankTransferData::Pse {} | domain::BankTransferData::LocalBankTransfer { .. } | domain::BankTransferData::InstantBankTransfer {} | domain::BankTransferData::PermataBankTransfer { .. } | domain::BankTransferData::BcaBankTransfer { .. } | domain::BankTransferData::BniVaBankTransfer { .. } | domain::BankTransferData::BriVaBankTransfer { .. } | domain::BankTransferData::CimbVaBankTransfer { .. } | domain::BankTransferData::DanamonVaBankTransfer { .. } | domain::BankTransferData::MandiriVaBankTransfer { .. } => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) .into()) } } } domain::PaymentMethodData::Crypto(_) => Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) .into()), domain::PaymentMethodData::GiftCard(giftcard_data) => match giftcard_data.deref() { domain::GiftCardData::Givex(_) | domain::GiftCardData::PaySafeCard {} => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) .into()) } }, domain::PaymentMethodData::CardRedirect(cardredirect_data) => match cardredirect_data { domain::CardRedirectData::Knet {} | domain::CardRedirectData::Benefit {} | domain::CardRedirectData::MomoAtm {} | domain::CardRedirectData::CardRedirect {} => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) .into()) } }, domain::PaymentMethodData::Reward => Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) .into()), domain::PaymentMethodData::Voucher(voucher_data) => match voucher_data { domain::VoucherData::Boleto(_) | domain::VoucherData::Oxxo => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) .into()) } domain::VoucherData::Alfamart(_) | domain::VoucherData::Efecty | domain::VoucherData::PagoEfectivo | domain::VoucherData::RedCompra | domain::VoucherData::RedPagos | domain::VoucherData::Indomaret(_) | domain::VoucherData::SevenEleven(_) | domain::VoucherData::Lawson(_) | domain::VoucherData::MiniStop(_) | domain::VoucherData::FamilyMart(_) | domain::VoucherData::Seicomart(_) | domain::VoucherData::PayEasy(_) => Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) .into()), }, domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::RealTimePayment(_) | domain::PaymentMethodData::MobilePayment(_) | domain::PaymentMethodData::MandatePayment | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) | domain::PaymentMethodData::NetworkToken(_) | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) .into()) } } } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="1125" end="1132"> fn from(bank_debit_data: &domain::BankDebitData) -> Self { match bank_debit_data { domain::BankDebitData::AchBankDebit { .. } => Self::Ach, domain::BankDebitData::SepaBankDebit { .. } => Self::Sepa, domain::BankDebitData::BecsBankDebit { .. } => Self::Becs, domain::BankDebitData::BacsBankDebit { .. } => Self::Bacs, } } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="1081" end="1121"> fn foreign_try_from(wallet_data: &domain::WalletData) -> Result<Self, Self::Error> { match wallet_data { domain::WalletData::AliPayRedirect(_) => Ok(Some(StripePaymentMethodType::Alipay)), domain::WalletData::ApplePay(_) => Ok(None), domain::WalletData::GooglePay(_) => Ok(Some(StripePaymentMethodType::Card)), domain::WalletData::WeChatPayQr(_) => Ok(Some(StripePaymentMethodType::Wechatpay)), domain::WalletData::CashappQr(_) => Ok(Some(StripePaymentMethodType::Cashapp)), domain::WalletData::AmazonPayRedirect(_) => { Ok(Some(StripePaymentMethodType::AmazonPay)) } domain::WalletData::MobilePayRedirect(_) => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), )) } domain::WalletData::PaypalRedirect(_) | domain::WalletData::AliPayQr(_) | domain::WalletData::AliPayHkRedirect(_) | domain::WalletData::MomoRedirect(_) | domain::WalletData::KakaoPayRedirect(_) | domain::WalletData::GoPayRedirect(_) | domain::WalletData::GcashRedirect(_) | domain::WalletData::ApplePayRedirect(_) | domain::WalletData::ApplePayThirdPartySdk(_) | domain::WalletData::DanaRedirect {} | domain::WalletData::GooglePayRedirect(_) | domain::WalletData::GooglePayThirdPartySdk(_) | domain::WalletData::MbWayRedirect(_) | domain::WalletData::PaypalSdk(_) | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} | domain::WalletData::TouchNGoRedirect(_) | domain::WalletData::SwishQr(_) | domain::WalletData::WeChatPayRedirect(_) | domain::WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), )), } } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="3876" end="3980"> fn try_from( (item, auth_type, pm_type): ( &types::SetupMandateRouterData, enums::AuthenticationType, StripePaymentMethodType, ), ) -> Result<Self, Self::Error> { let pm_data = &item.request.payment_method_data; match pm_data { domain::PaymentMethodData::Card(ref ccard) => { let payment_method_auth_type = match auth_type { enums::AuthenticationType::ThreeDs => Auth3ds::Any, enums::AuthenticationType::NoThreeDs => Auth3ds::Automatic, }; Ok(Self::try_from((ccard, payment_method_auth_type))?) } domain::PaymentMethodData::PayLater(_) => Ok(Self::PayLater(StripePayLaterData { payment_method_data_type: pm_type, })), domain::PaymentMethodData::BankRedirect(ref bank_redirect_data) => { Ok(Self::try_from((bank_redirect_data, None))?) } domain::PaymentMethodData::Wallet(ref wallet_data) => { Ok(Self::try_from((wallet_data, None))?) } domain::PaymentMethodData::BankDebit(bank_debit_data) => { let (_pm_type, bank_data) = get_bank_debit_data(bank_debit_data); Ok(Self::BankDebit(StripeBankDebitData { bank_specific_data: bank_data, })) } domain::PaymentMethodData::BankTransfer(bank_transfer_data) => match bank_transfer_data .deref() { domain::BankTransferData::AchBankTransfer {} => Ok(Self::BankTransfer( StripeBankTransferData::AchBankTransfer(Box::new(AchTransferData { payment_method_data_type: StripePaymentMethodType::CustomerBalance, bank_transfer_type: StripeCreditTransferTypes::AchCreditTransfer, payment_method_type: StripePaymentMethodType::CustomerBalance, balance_funding_type: BankTransferType::BankTransfers, })), )), domain::BankTransferData::MultibancoBankTransfer {} => Ok(Self::BankTransfer( StripeBankTransferData::MultibancoBankTransfers(Box::new( MultibancoTransferData { payment_method_data_type: StripeCreditTransferTypes::Multibanco, payment_method_type: StripeCreditTransferTypes::Multibanco, email: item.get_billing_email()?, }, )), )), domain::BankTransferData::SepaBankTransfer {} => Ok(Self::BankTransfer( StripeBankTransferData::SepaBankTransfer(Box::new(SepaBankTransferData { payment_method_data_type: StripePaymentMethodType::CustomerBalance, bank_transfer_type: BankTransferType::EuBankTransfer, balance_funding_type: BankTransferType::BankTransfers, payment_method_type: StripePaymentMethodType::CustomerBalance, country: item.get_billing_country()?, })), )), domain::BankTransferData::BacsBankTransfer { .. } => Ok(Self::BankTransfer( StripeBankTransferData::BacsBankTransfers(Box::new(BacsBankTransferData { payment_method_data_type: StripePaymentMethodType::CustomerBalance, bank_transfer_type: BankTransferType::GbBankTransfer, balance_funding_type: BankTransferType::BankTransfers, payment_method_type: StripePaymentMethodType::CustomerBalance, })), )), domain::BankTransferData::Pix { .. } | domain::BankTransferData::Pse {} | domain::BankTransferData::PermataBankTransfer { .. } | domain::BankTransferData::BcaBankTransfer { .. } | domain::BankTransferData::BniVaBankTransfer { .. } | domain::BankTransferData::BriVaBankTransfer { .. } | domain::BankTransferData::CimbVaBankTransfer { .. } | domain::BankTransferData::DanamonVaBankTransfer { .. } | domain::BankTransferData::LocalBankTransfer { .. } | domain::BankTransferData::InstantBankTransfer {} | domain::BankTransferData::MandiriVaBankTransfer { .. } => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) .into()) } }, domain::PaymentMethodData::MandatePayment | domain::PaymentMethodData::Crypto(_) | domain::PaymentMethodData::Reward | domain::PaymentMethodData::RealTimePayment(_) | domain::PaymentMethodData::MobilePayment(_) | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::CardRedirect(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) | domain::PaymentMethodData::NetworkToken(_) | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ))? } } } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="647" end="676"> pub enum StripePaymentMethodType { Affirm, AfterpayClearpay, Alipay, #[serde(rename = "amazon_pay")] AmazonPay, #[serde(rename = "au_becs_debit")] Becs, #[serde(rename = "bacs_debit")] Bacs, Bancontact, Blik, Card, CustomerBalance, Eps, Giropay, Ideal, Klarna, #[serde(rename = "p24")] Przelewy24, #[serde(rename = "sepa_debit")] Sepa, Sofort, #[serde(rename = "us_bank_account")] Ach, #[serde(rename = "wechat_pay")] Wechatpay, #[serde(rename = "cashapp")] Cashapp, } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="498" end="527"> pub enum BankDebitData { #[serde(rename = "us_bank_account")] Ach { #[serde(rename = "payment_method_data[us_bank_account][account_holder_type]")] account_holder_type: String, #[serde(rename = "payment_method_data[us_bank_account][account_number]")] account_number: Secret<String>, #[serde(rename = "payment_method_data[us_bank_account][routing_number]")] routing_number: Secret<String>, }, #[serde(rename = "sepa_debit")] Sepa { #[serde(rename = "payment_method_data[sepa_debit][iban]")] iban: Secret<String>, }, #[serde(rename = "au_becs_debit")] Becs { #[serde(rename = "payment_method_data[au_becs_debit][account_number]")] account_number: Secret<String>, #[serde(rename = "payment_method_data[au_becs_debit][bsb_number]")] bsb_number: Secret<String>, }, #[serde(rename = "bacs_debit")] Bacs { #[serde(rename = "payment_method_data[bacs_debit][account_number]")] account_number: Secret<String>, #[serde(rename = "payment_method_data[bacs_debit][sort_code]")] sort_code: Secret<String>, }, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/stripe/transformers.rs<|crate|> router anchor=get_bank_debit_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="1135" end="1180"> fn get_bank_debit_data( bank_debit_data: &domain::BankDebitData, ) -> (StripePaymentMethodType, BankDebitData) { match bank_debit_data { domain::BankDebitData::AchBankDebit { account_number, routing_number, .. } => { let ach_data = BankDebitData::Ach { account_holder_type: "individual".to_string(), account_number: account_number.to_owned(), routing_number: routing_number.to_owned(), }; (StripePaymentMethodType::Ach, ach_data) } domain::BankDebitData::SepaBankDebit { iban, .. } => { let sepa_data: BankDebitData = BankDebitData::Sepa { iban: iban.to_owned(), }; (StripePaymentMethodType::Sepa, sepa_data) } domain::BankDebitData::BecsBankDebit { account_number, bsb_number, .. } => { let becs_data = BankDebitData::Becs { account_number: account_number.to_owned(), bsb_number: bsb_number.to_owned(), }; (StripePaymentMethodType::Becs, becs_data) } domain::BankDebitData::BacsBankDebit { account_number, sort_code, .. } => { let bacs_data = BankDebitData::Bacs { account_number: account_number.to_owned(), sort_code: Secret::new(sort_code.clone().expose().replace('-', "")), }; (StripePaymentMethodType::Bacs, bacs_data) } } } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="1134" end="1134"> use masking::{ExposeInterface, ExposeOptionInterface, Mask, PeekInterface, Secret}; use crate::{ collect_missing_value_keys, connector::utils::{self as connector_util, ApplePay, ApplePayDecrypt, RouterData}, consts, core::errors, headers, services, types::{ self, api, domain, storage::enums, transformers::{ForeignFrom, ForeignTryFrom}, }, utils::OptionExt, }; <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="1407" end="1421"> fn get_stripe_card_network(card_network: common_enums::CardNetwork) -> Option<StripeCardNetwork> { match card_network { common_enums::CardNetwork::Visa => Some(StripeCardNetwork::Visa), common_enums::CardNetwork::Mastercard => Some(StripeCardNetwork::Mastercard), common_enums::CardNetwork::CartesBancaires => Some(StripeCardNetwork::CartesBancaires), common_enums::CardNetwork::AmericanExpress | common_enums::CardNetwork::JCB | common_enums::CardNetwork::DinersClub | common_enums::CardNetwork::Discover | common_enums::CardNetwork::UnionPay | common_enums::CardNetwork::Interac | common_enums::CardNetwork::RuPay | common_enums::CardNetwork::Maestro => None, } } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="1182" end="1405"> fn create_stripe_payment_method( payment_method_data: &domain::PaymentMethodData, auth_type: enums::AuthenticationType, payment_method_token: Option<types::PaymentMethodToken>, is_customer_initiated_mandate_payment: Option<bool>, billing_address: StripeBillingAddress, ) -> Result< ( StripePaymentMethodData, Option<StripePaymentMethodType>, StripeBillingAddress, ), error_stack::Report<errors::ConnectorError>, > { match payment_method_data { domain::PaymentMethodData::Card(card_details) => { let payment_method_auth_type = match auth_type { enums::AuthenticationType::ThreeDs => Auth3ds::Any, enums::AuthenticationType::NoThreeDs => Auth3ds::Automatic, }; Ok(( StripePaymentMethodData::try_from((card_details, payment_method_auth_type))?, Some(StripePaymentMethodType::Card), billing_address, )) } domain::PaymentMethodData::PayLater(pay_later_data) => { let stripe_pm_type = StripePaymentMethodType::try_from(pay_later_data)?; Ok(( StripePaymentMethodData::PayLater(StripePayLaterData { payment_method_data_type: stripe_pm_type, }), Some(stripe_pm_type), billing_address, )) } domain::PaymentMethodData::BankRedirect(bank_redirect_data) => { let billing_address = if is_customer_initiated_mandate_payment == Some(true) { mandatory_parameters_for_sepa_bank_debit_mandates( &Some(billing_address.to_owned()), is_customer_initiated_mandate_payment, )? } else { billing_address }; let pm_type = StripePaymentMethodType::try_from(bank_redirect_data)?; let bank_redirect_data = StripePaymentMethodData::try_from(( bank_redirect_data, Some(billing_address.to_owned()), ))?; Ok((bank_redirect_data, Some(pm_type), billing_address)) } domain::PaymentMethodData::Wallet(wallet_data) => { let pm_type = ForeignTryFrom::foreign_try_from(wallet_data)?; let wallet_specific_data = StripePaymentMethodData::try_from((wallet_data, payment_method_token))?; Ok(( wallet_specific_data, pm_type, StripeBillingAddress::default(), )) } domain::PaymentMethodData::BankDebit(bank_debit_data) => { let (pm_type, bank_debit_data) = get_bank_debit_data(bank_debit_data); let pm_data = StripePaymentMethodData::BankDebit(StripeBankDebitData { bank_specific_data: bank_debit_data, }); Ok((pm_data, Some(pm_type), billing_address)) } domain::PaymentMethodData::BankTransfer(bank_transfer_data) => { match bank_transfer_data.deref() { domain::BankTransferData::AchBankTransfer {} => Ok(( StripePaymentMethodData::BankTransfer(StripeBankTransferData::AchBankTransfer( Box::new(AchTransferData { payment_method_data_type: StripePaymentMethodType::CustomerBalance, bank_transfer_type: StripeCreditTransferTypes::AchCreditTransfer, payment_method_type: StripePaymentMethodType::CustomerBalance, balance_funding_type: BankTransferType::BankTransfers, }), )), None, StripeBillingAddress::default(), )), domain::BankTransferData::MultibancoBankTransfer {} => Ok(( StripePaymentMethodData::BankTransfer( StripeBankTransferData::MultibancoBankTransfers(Box::new( MultibancoTransferData { payment_method_data_type: StripeCreditTransferTypes::Multibanco, payment_method_type: StripeCreditTransferTypes::Multibanco, email: billing_address.email.ok_or( errors::ConnectorError::MissingRequiredField { field_name: "billing_address.email", }, )?, }, )), ), None, StripeBillingAddress::default(), )), domain::BankTransferData::SepaBankTransfer {} => Ok(( StripePaymentMethodData::BankTransfer( StripeBankTransferData::SepaBankTransfer(Box::new(SepaBankTransferData { payment_method_data_type: StripePaymentMethodType::CustomerBalance, bank_transfer_type: BankTransferType::EuBankTransfer, balance_funding_type: BankTransferType::BankTransfers, payment_method_type: StripePaymentMethodType::CustomerBalance, country: billing_address.country.ok_or( errors::ConnectorError::MissingRequiredField { field_name: "billing_address.country", }, )?, })), ), Some(StripePaymentMethodType::CustomerBalance), billing_address, )), domain::BankTransferData::BacsBankTransfer {} => Ok(( StripePaymentMethodData::BankTransfer( StripeBankTransferData::BacsBankTransfers(Box::new(BacsBankTransferData { payment_method_data_type: StripePaymentMethodType::CustomerBalance, bank_transfer_type: BankTransferType::GbBankTransfer, balance_funding_type: BankTransferType::BankTransfers, payment_method_type: StripePaymentMethodType::CustomerBalance, })), ), Some(StripePaymentMethodType::CustomerBalance), billing_address, )), domain::BankTransferData::Pix { .. } => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) .into()) } domain::BankTransferData::Pse {} | domain::BankTransferData::LocalBankTransfer { .. } | domain::BankTransferData::InstantBankTransfer {} | domain::BankTransferData::PermataBankTransfer { .. } | domain::BankTransferData::BcaBankTransfer { .. } | domain::BankTransferData::BniVaBankTransfer { .. } | domain::BankTransferData::BriVaBankTransfer { .. } | domain::BankTransferData::CimbVaBankTransfer { .. } | domain::BankTransferData::DanamonVaBankTransfer { .. } | domain::BankTransferData::MandiriVaBankTransfer { .. } => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) .into()) } } } domain::PaymentMethodData::Crypto(_) => Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) .into()), domain::PaymentMethodData::GiftCard(giftcard_data) => match giftcard_data.deref() { domain::GiftCardData::Givex(_) | domain::GiftCardData::PaySafeCard {} => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) .into()) } }, domain::PaymentMethodData::CardRedirect(cardredirect_data) => match cardredirect_data { domain::CardRedirectData::Knet {} | domain::CardRedirectData::Benefit {} | domain::CardRedirectData::MomoAtm {} | domain::CardRedirectData::CardRedirect {} => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) .into()) } }, domain::PaymentMethodData::Reward => Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) .into()), domain::PaymentMethodData::Voucher(voucher_data) => match voucher_data { domain::VoucherData::Boleto(_) | domain::VoucherData::Oxxo => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) .into()) } domain::VoucherData::Alfamart(_) | domain::VoucherData::Efecty | domain::VoucherData::PagoEfectivo | domain::VoucherData::RedCompra | domain::VoucherData::RedPagos | domain::VoucherData::Indomaret(_) | domain::VoucherData::SevenEleven(_) | domain::VoucherData::Lawson(_) | domain::VoucherData::MiniStop(_) | domain::VoucherData::FamilyMart(_) | domain::VoucherData::Seicomart(_) | domain::VoucherData::PayEasy(_) => Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) .into()), }, domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::RealTimePayment(_) | domain::PaymentMethodData::MobilePayment(_) | domain::PaymentMethodData::MandatePayment | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) | domain::PaymentMethodData::NetworkToken(_) | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) .into()) } } } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="1125" end="1132"> fn from(bank_debit_data: &domain::BankDebitData) -> Self { match bank_debit_data { domain::BankDebitData::AchBankDebit { .. } => Self::Ach, domain::BankDebitData::SepaBankDebit { .. } => Self::Sepa, domain::BankDebitData::BecsBankDebit { .. } => Self::Becs, domain::BankDebitData::BacsBankDebit { .. } => Self::Bacs, } } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="1081" end="1121"> fn foreign_try_from(wallet_data: &domain::WalletData) -> Result<Self, Self::Error> { match wallet_data { domain::WalletData::AliPayRedirect(_) => Ok(Some(StripePaymentMethodType::Alipay)), domain::WalletData::ApplePay(_) => Ok(None), domain::WalletData::GooglePay(_) => Ok(Some(StripePaymentMethodType::Card)), domain::WalletData::WeChatPayQr(_) => Ok(Some(StripePaymentMethodType::Wechatpay)), domain::WalletData::CashappQr(_) => Ok(Some(StripePaymentMethodType::Cashapp)), domain::WalletData::AmazonPayRedirect(_) => { Ok(Some(StripePaymentMethodType::AmazonPay)) } domain::WalletData::MobilePayRedirect(_) => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), )) } domain::WalletData::PaypalRedirect(_) | domain::WalletData::AliPayQr(_) | domain::WalletData::AliPayHkRedirect(_) | domain::WalletData::MomoRedirect(_) | domain::WalletData::KakaoPayRedirect(_) | domain::WalletData::GoPayRedirect(_) | domain::WalletData::GcashRedirect(_) | domain::WalletData::ApplePayRedirect(_) | domain::WalletData::ApplePayThirdPartySdk(_) | domain::WalletData::DanaRedirect {} | domain::WalletData::GooglePayRedirect(_) | domain::WalletData::GooglePayThirdPartySdk(_) | domain::WalletData::MbWayRedirect(_) | domain::WalletData::PaypalSdk(_) | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} | domain::WalletData::TouchNGoRedirect(_) | domain::WalletData::SwishQr(_) | domain::WalletData::WeChatPayRedirect(_) | domain::WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), )), } } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="3876" end="3980"> fn try_from( (item, auth_type, pm_type): ( &types::SetupMandateRouterData, enums::AuthenticationType, StripePaymentMethodType, ), ) -> Result<Self, Self::Error> { let pm_data = &item.request.payment_method_data; match pm_data { domain::PaymentMethodData::Card(ref ccard) => { let payment_method_auth_type = match auth_type { enums::AuthenticationType::ThreeDs => Auth3ds::Any, enums::AuthenticationType::NoThreeDs => Auth3ds::Automatic, }; Ok(Self::try_from((ccard, payment_method_auth_type))?) } domain::PaymentMethodData::PayLater(_) => Ok(Self::PayLater(StripePayLaterData { payment_method_data_type: pm_type, })), domain::PaymentMethodData::BankRedirect(ref bank_redirect_data) => { Ok(Self::try_from((bank_redirect_data, None))?) } domain::PaymentMethodData::Wallet(ref wallet_data) => { Ok(Self::try_from((wallet_data, None))?) } domain::PaymentMethodData::BankDebit(bank_debit_data) => { let (_pm_type, bank_data) = get_bank_debit_data(bank_debit_data); Ok(Self::BankDebit(StripeBankDebitData { bank_specific_data: bank_data, })) } domain::PaymentMethodData::BankTransfer(bank_transfer_data) => match bank_transfer_data .deref() { domain::BankTransferData::AchBankTransfer {} => Ok(Self::BankTransfer( StripeBankTransferData::AchBankTransfer(Box::new(AchTransferData { payment_method_data_type: StripePaymentMethodType::CustomerBalance, bank_transfer_type: StripeCreditTransferTypes::AchCreditTransfer, payment_method_type: StripePaymentMethodType::CustomerBalance, balance_funding_type: BankTransferType::BankTransfers, })), )), domain::BankTransferData::MultibancoBankTransfer {} => Ok(Self::BankTransfer( StripeBankTransferData::MultibancoBankTransfers(Box::new( MultibancoTransferData { payment_method_data_type: StripeCreditTransferTypes::Multibanco, payment_method_type: StripeCreditTransferTypes::Multibanco, email: item.get_billing_email()?, }, )), )), domain::BankTransferData::SepaBankTransfer {} => Ok(Self::BankTransfer( StripeBankTransferData::SepaBankTransfer(Box::new(SepaBankTransferData { payment_method_data_type: StripePaymentMethodType::CustomerBalance, bank_transfer_type: BankTransferType::EuBankTransfer, balance_funding_type: BankTransferType::BankTransfers, payment_method_type: StripePaymentMethodType::CustomerBalance, country: item.get_billing_country()?, })), )), domain::BankTransferData::BacsBankTransfer { .. } => Ok(Self::BankTransfer( StripeBankTransferData::BacsBankTransfers(Box::new(BacsBankTransferData { payment_method_data_type: StripePaymentMethodType::CustomerBalance, bank_transfer_type: BankTransferType::GbBankTransfer, balance_funding_type: BankTransferType::BankTransfers, payment_method_type: StripePaymentMethodType::CustomerBalance, })), )), domain::BankTransferData::Pix { .. } | domain::BankTransferData::Pse {} | domain::BankTransferData::PermataBankTransfer { .. } | domain::BankTransferData::BcaBankTransfer { .. } | domain::BankTransferData::BniVaBankTransfer { .. } | domain::BankTransferData::BriVaBankTransfer { .. } | domain::BankTransferData::CimbVaBankTransfer { .. } | domain::BankTransferData::DanamonVaBankTransfer { .. } | domain::BankTransferData::LocalBankTransfer { .. } | domain::BankTransferData::InstantBankTransfer {} | domain::BankTransferData::MandiriVaBankTransfer { .. } => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) .into()) } }, domain::PaymentMethodData::MandatePayment | domain::PaymentMethodData::Crypto(_) | domain::PaymentMethodData::Reward | domain::PaymentMethodData::RealTimePayment(_) | domain::PaymentMethodData::MobilePayment(_) | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::CardRedirect(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) | domain::PaymentMethodData::NetworkToken(_) | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ))? } } } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="647" end="676"> pub enum StripePaymentMethodType { Affirm, AfterpayClearpay, Alipay, #[serde(rename = "amazon_pay")] AmazonPay, #[serde(rename = "au_becs_debit")] Becs, #[serde(rename = "bacs_debit")] Bacs, Bancontact, Blik, Card, CustomerBalance, Eps, Giropay, Ideal, Klarna, #[serde(rename = "p24")] Przelewy24, #[serde(rename = "sepa_debit")] Sepa, Sofort, #[serde(rename = "us_bank_account")] Ach, #[serde(rename = "wechat_pay")] Wechatpay, #[serde(rename = "cashapp")] Cashapp, } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="498" end="527"> pub enum BankDebitData { #[serde(rename = "us_bank_account")] Ach { #[serde(rename = "payment_method_data[us_bank_account][account_holder_type]")] account_holder_type: String, #[serde(rename = "payment_method_data[us_bank_account][account_number]")] account_number: Secret<String>, #[serde(rename = "payment_method_data[us_bank_account][routing_number]")] routing_number: Secret<String>, }, #[serde(rename = "sepa_debit")] Sepa { #[serde(rename = "payment_method_data[sepa_debit][iban]")] iban: Secret<String>, }, #[serde(rename = "au_becs_debit")] Becs { #[serde(rename = "payment_method_data[au_becs_debit][account_number]")] account_number: Secret<String>, #[serde(rename = "payment_method_data[au_becs_debit][bsb_number]")] bsb_number: Secret<String>, }, #[serde(rename = "bacs_debit")] Bacs { #[serde(rename = "payment_method_data[bacs_debit][account_number]")] account_number: Secret<String>, #[serde(rename = "payment_method_data[bacs_debit][sort_code]")] sort_code: Secret<String>, }, } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2217" end="2280"> pub enum BankDebitData { /// Payment Method data for Ach bank debit AchBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for ach bank debit payment #[schema(value_type = String, example = "000123456789")] account_number: Secret<String>, /// Routing number for ach bank debit payment #[schema(value_type = String, example = "110000000")] routing_number: Secret<String>, #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "John Doe")] bank_account_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "ACH")] bank_name: Option<common_enums::BankNames>, #[schema(value_type = String, example = "Checking")] bank_type: Option<common_enums::BankType>, #[schema(value_type = String, example = "Personal")] bank_holder_type: Option<common_enums::BankHolderType>, }, SepaBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// International bank account number (iban) for SEPA #[schema(value_type = String, example = "DE89370400440532013000")] iban: Secret<String>, /// Owner name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BecsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Becs payment method #[schema(value_type = String, example = "000123456")] account_number: Secret<String>, /// Bank-State-Branch (bsb) number #[schema(value_type = String, example = "000000")] bsb_number: Secret<String>, /// Owner name for bank debit #[schema(value_type = Option<String>, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BacsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Bacs payment method #[schema(value_type = String, example = "00012345")] account_number: Secret<String>, /// Sort code for Bacs payment method #[schema(value_type = String, example = "108800")] sort_code: Secret<String>, /// holder name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/wise/transformers.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/connector/wise/transformers.rs" role="context" start="368" end="411"> fn try_from( item_data: &WiseRouterData<&types::PayoutsRouterData<F>>, ) -> Result<Self, Self::Error> { let item = item_data.router_data; let request = item.request.to_owned(); let customer_details = request.customer_details.to_owned(); let payout_method_data = item.get_payout_method_data()?; let bank_details = get_payout_bank_details( payout_method_data.to_owned(), item.get_optional_billing(), item.request.entity_type, )?; let source_id = match item.connector_auth_type.to_owned() { types::ConnectorAuthType::BodyKey { api_key: _, key1 } => Ok(key1), _ => Err(errors::ConnectorError::MissingRequiredField { field_name: "source_id for PayoutRecipient creation", }), }?; let payout_type = request.get_payout_type()?; match payout_type { storage_enums::PayoutType::Card | storage_enums::PayoutType::Wallet => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Wise"), ))? } storage_enums::PayoutType::Bank => { let account_holder_name = customer_details .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "customer_details for PayoutRecipient creation", })? .name .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "customer_details.name for PayoutRecipient creation", })?; Ok(Self { profile: source_id, currency: request.destination_currency.to_string(), recipient_type: RecipientType::try_from(payout_method_data)?, account_holder_name, details: bank_details, }) } } } <file_sep path="hyperswitch/crates/router/src/connector/wise/transformers.rs" role="context" start="367" end="367"> use common_utils::types::MinorUnit; type Error = error_stack::Report<errors::ConnectorError>; use crate::{ connector::utils::{self, PayoutsData, RouterData}, types::{ api::payouts, storage::enums::{self as storage_enums, PayoutEntityType}, }, }; use crate::{core::errors, types}; <file_sep path="hyperswitch/crates/router/src/connector/wise/transformers.rs" role="context" start="443" end="463"> fn try_from( item_data: &WiseRouterData<&types::PayoutsRouterData<F>>, ) -> Result<Self, Self::Error> { let item = item_data.router_data; let request = item.request.to_owned(); let payout_type = request.get_payout_type()?; match payout_type { storage_enums::PayoutType::Bank => Ok(Self { source_amount: Some(item_data.amount), source_currency: request.source_currency.to_string(), target_amount: None, target_currency: request.destination_currency.to_string(), pay_out: WisePayOutOption::default(), }), storage_enums::PayoutType::Card | storage_enums::PayoutType::Wallet => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Wise"), ))? } } } <file_sep path="hyperswitch/crates/router/src/connector/wise/transformers.rs" role="context" start="420" end="436"> fn try_from( item: types::PayoutsResponseRouterData<F, WiseRecipientCreateResponse>, ) -> Result<Self, Self::Error> { let response: WiseRecipientCreateResponse = item.response; Ok(Self { response: Ok(types::PayoutsResponseData { status: Some(storage_enums::PayoutStatus::RequiresCreation), connector_payout_id: Some(response.id.to_string()), payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: None, error_message: None, }), ..item.data }) } <file_sep path="hyperswitch/crates/router/src/connector/wise/transformers.rs" role="context" start="324" end="362"> fn get_payout_bank_details( payout_method_data: PayoutMethodData, address: Option<&hyperswitch_domain_models::address::Address>, entity_type: PayoutEntityType, ) -> Result<WiseBankDetails, errors::ConnectorError> { let wise_address_details = match get_payout_address_details(address) { Some(a) => Ok(a), None => Err(errors::ConnectorError::MissingRequiredField { field_name: "address", }), }?; match payout_method_data { PayoutMethodData::Bank(payouts::BankPayout::Ach(b)) => Ok(WiseBankDetails { legal_type: LegalType::from(entity_type), address: Some(wise_address_details), account_number: Some(b.bank_account_number.to_owned()), abartn: Some(b.bank_routing_number), account_type: Some(AccountType::Checking), ..WiseBankDetails::default() }), PayoutMethodData::Bank(payouts::BankPayout::Bacs(b)) => Ok(WiseBankDetails { legal_type: LegalType::from(entity_type), address: Some(wise_address_details), account_number: Some(b.bank_account_number.to_owned()), sort_code: Some(b.bank_sort_code), ..WiseBankDetails::default() }), PayoutMethodData::Bank(payouts::BankPayout::Sepa(b)) => Ok(WiseBankDetails { legal_type: LegalType::from(entity_type), address: Some(wise_address_details), iban: Some(b.iban.to_owned()), bic: b.bic, ..WiseBankDetails::default() }), _ => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Wise"), ))?, } } <file_sep path="hyperswitch/crates/router/src/connector/wise/transformers.rs" role="context" start="308" end="321"> fn get_payout_address_details( address: Option<&hyperswitch_domain_models::address::Address>, ) -> Option<WiseAddressDetails> { address.and_then(|add| { add.address.as_ref().map(|a| WiseAddressDetails { country: a.country, country_code: a.country, first_line: a.line1.clone(), post_code: a.zip.clone(), city: a.city.clone(), state: a.state.clone(), }) }) } <file_sep path="hyperswitch/crates/router/src/connector/wise/transformers.rs" role="context" start="639" end="649"> fn try_from(payout_method_type: PayoutMethodData) -> Result<Self, Self::Error> { match payout_method_type { PayoutMethodData::Bank(api_models::payouts::Bank::Ach(_)) => Ok(Self::Aba), PayoutMethodData::Bank(api_models::payouts::Bank::Bacs(_)) => Ok(Self::SortCode), PayoutMethodData::Bank(api_models::payouts::Bank::Sepa(_)) => Ok(Self::Iban), _ => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Wise"), ) .into()), } } <file_sep path="hyperswitch/crates/router/src/connector/wise/transformers.rs" role="context" start="9" end="9"> type Error = error_stack::Report<errors::ConnectorError>; <file_sep path="hyperswitch/crates/router/src/connector/wise/transformers.rs" role="context" start="91" end="96"> pub enum RecipientType { Aba, Iban, SortCode, SwiftCode, } <file_sep path="hyperswitch/crates/router/src/connector/payone/transformers.rs" role="context" start="117" end="121"> pub struct Card { card_holder_name: Secret<String>, card_number: CardNumber, expiry_date: Secret<String>, } <file_sep path="hyperswitch/crates/api_models/src/payouts.rs" role="context" start="262" end="267"> pub enum Bank { Ach(AchBankTransfer), Bacs(BacsBankTransfer), Sepa(SepaBankTransfer), Pix(PixBankTransfer), }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/pm_auth.rs<|crate|> router anchor=get_bank_account_creds kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/pm_auth.rs" role="context" start="655" end="709"> pub async fn get_bank_account_creds( connector: PaymentAuthConnectorData, merchant_account: &domain::MerchantAccount, connector_name: &str, access_token: &Secret<String>, auth_type: pm_auth_types::ConnectorAuthType, state: &SessionState, bank_account_id: Option<Secret<String>>, ) -> RouterResult<pm_auth_types::BankAccountCredentialsResponse> { let connector_integration_bank_details: BoxedConnectorIntegration< '_, BankAccountCredentials, pm_auth_types::BankAccountCredentialsRequest, pm_auth_types::BankAccountCredentialsResponse, > = connector.connector.get_connector_integration(); let router_data_bank_details = pm_auth_types::BankDetailsRouterData { flow: std::marker::PhantomData, merchant_id: Some(merchant_account.get_id().clone()), connector: Some(connector_name.to_string()), request: pm_auth_types::BankAccountCredentialsRequest { access_token: access_token.clone(), optional_ids: bank_account_id .map(|id| pm_auth_types::BankAccountOptionalIDs { ids: vec![id] }), }, response: Ok(pm_auth_types::BankAccountCredentialsResponse { credentials: Vec::new(), }), connector_http_status_code: None, connector_auth_type: auth_type, }; let bank_details_resp = pm_auth_services::execute_connector_processing_step( state, connector_integration_bank_details, &router_data_bank_details, &connector.connector_name, ) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed while calling bank account details connector api")?; let bank_account_details_resp = bank_details_resp .response .map_err(|err| ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: connector.connector_name.to_string(), status_code: err.status_code, reason: err.reason, })?; Ok(bank_account_details_resp) } <file_sep path="hyperswitch/crates/router/src/core/pm_auth.rs" role="context" start="654" end="654"> use std::{collections::HashMap, str::FromStr}; use masking::{ExposeInterface, PeekInterface, Secret}; use pm_auth::{ connector::plaid::transformers::PlaidAuthType, types::{ self as pm_auth_types, api::{ auth_service::{BankAccountCredentials, ExchangeToken, LinkToken}, BoxedConnectorIntegration, PaymentAuthConnectorData, }, }, }; use crate::{ core::{ errors::{self, ApiErrorResponse, RouterResponse, RouterResult, StorageErrorExt}, payment_methods::cards, payments::helpers as oss_helpers, pm_auth::helpers as pm_auth_helpers, }, db::StorageInterface, logger, routes::SessionState, services::{pm_auth as pm_auth_services, ApplicationResponse}, types::{self, domain, storage, transformers::ForeignTryFrom}, }; <file_sep path="hyperswitch/crates/router/src/core/pm_auth.rs" role="context" start="763" end="810"> async fn get_selected_config_from_redis( db: &dyn StorageInterface, payload: &api_models::pm_auth::ExchangeTokenCreateRequest, ) -> RouterResult<api_models::pm_auth::PaymentMethodAuthConnectorChoice> { let redis_conn = db .get_redis_conn() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let pm_auth_key = payload.payment_id.get_pm_auth_key(); redis_conn .exists::<Vec<u8>>(&pm_auth_key.as_str().into()) .await .change_context(ApiErrorResponse::InvalidRequestData { message: "Incorrect payment_id provided in request".to_string(), }) .attach_printable("Corresponding pm_auth_key does not exist in redis")? .then_some(()) .ok_or(ApiErrorResponse::InvalidRequestData { message: "Incorrect payment_id provided in request".to_string(), }) .attach_printable("Corresponding pm_auth_key does not exist in redis")?; let pm_auth_configs = redis_conn .get_and_deserialize_key::<Vec<api_models::pm_auth::PaymentMethodAuthConnectorChoice>>( &pm_auth_key.as_str().into(), "Vec<PaymentMethodAuthConnectorChoice>", ) .await .change_context(ApiErrorResponse::GenericNotFoundError { message: "payment method auth connector name not found".to_string(), }) .attach_printable("Failed to get payment method auth choices from redis")?; let selected_config = pm_auth_configs .iter() .find(|conf| { conf.payment_method == payload.payment_method && conf.payment_method_type == payload.payment_method_type }) .ok_or(ApiErrorResponse::GenericNotFoundError { message: "payment method auth connector name not found".to_string(), })? .clone(); Ok(selected_config) } <file_sep path="hyperswitch/crates/router/src/core/pm_auth.rs" role="context" start="711" end="761"> async fn get_access_token_from_exchange_api( connector: &PaymentAuthConnectorData, connector_name: &str, payload: &api_models::pm_auth::ExchangeTokenCreateRequest, auth_type: &pm_auth_types::ConnectorAuthType, state: &SessionState, ) -> RouterResult<Secret<String>> { let connector_integration: BoxedConnectorIntegration< '_, ExchangeToken, pm_auth_types::ExchangeTokenRequest, pm_auth_types::ExchangeTokenResponse, > = connector.connector.get_connector_integration(); let router_data = pm_auth_types::ExchangeTokenRouterData { flow: std::marker::PhantomData, merchant_id: None, connector: Some(connector_name.to_string()), request: pm_auth_types::ExchangeTokenRequest { public_token: payload.public_token.clone(), }, response: Ok(pm_auth_types::ExchangeTokenResponse { access_token: "".to_string(), }), connector_http_status_code: None, connector_auth_type: auth_type.clone(), }; let resp = pm_auth_services::execute_connector_processing_step( state, connector_integration, &router_data, &connector.connector_name, ) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed while calling exchange token connector api")?; let exchange_token_resp = resp.response .map_err(|err| ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: connector.connector_name.to_string(), status_code: err.status_code, reason: err.reason, })?; let access_token = exchange_token_resp.access_token; Ok(Secret::new(access_token)) } <file_sep path="hyperswitch/crates/router/src/core/pm_auth.rs" role="context" start="616" end="653"> async fn store_in_db( state: &SessionState, key_store: &domain::MerchantKeyStore, update_entries: Vec<(domain::PaymentMethod, storage::PaymentMethodUpdate)>, new_entries: Vec<domain::PaymentMethod>, db: &dyn StorageInterface, storage_scheme: MerchantStorageScheme, ) -> RouterResult<()> { let key_manager_state = &(state.into()); let update_entries_futures = update_entries .into_iter() .map(|(pm, pm_update)| { db.update_payment_method(key_manager_state, key_store, pm, pm_update, storage_scheme) }) .collect::<Vec<_>>(); let new_entries_futures = new_entries .into_iter() .map(|pm_new| { db.insert_payment_method(key_manager_state, key_store, pm_new, storage_scheme) }) .collect::<Vec<_>>(); let update_futures = futures::future::join_all(update_entries_futures); let new_futures = futures::future::join_all(new_entries_futures); let (update, new) = tokio::join!(update_futures, new_futures); let _ = update .into_iter() .map(|res| res.map_err(|err| logger::error!("Payment method storage failed {err:?}"))); let _ = new .into_iter() .map(|res| res.map_err(|err| logger::error!("Payment method storage failed {err:?}"))); Ok(()) } <file_sep path="hyperswitch/crates/router/src/core/pm_auth.rs" role="context" start="604" end="614"> async fn store_bank_details_in_payment_methods( _key_store: domain::MerchantKeyStore, _payload: api_models::pm_auth::ExchangeTokenCreateRequest, _merchant_account: domain::MerchantAccount, _state: SessionState, _bank_account_details_resp: pm_auth_types::BankAccountCredentialsResponse, _connector_details: (&str, Secret<String>), _mca_id: common_utils::id_type::MerchantConnectorAccountId, ) -> RouterResult<()> { todo!() } <file_sep path="hyperswitch/crates/router/src/core/pm_auth.rs" role="context" start="240" end="310"> pub async fn exchange_token_core( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, payload: api_models::pm_auth::ExchangeTokenCreateRequest, ) -> RouterResponse<()> { let db = &*state.store; let config = get_selected_config_from_redis(db, &payload).await?; let connector_name = config.connector_name.as_str(); let connector = PaymentAuthConnectorData::get_connector_by_name(connector_name)?; #[cfg(feature = "v1")] let merchant_connector_account = state .store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( &(&state).into(), merchant_account.get_id(), &config.mca_id, &key_store, ) .await .change_context(ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_account.get_id().get_string_repr().to_owned(), })?; #[cfg(feature = "v2")] let merchant_connector_account: domain::MerchantConnectorAccount = { let _ = merchant_account; let _ = connector; let _ = key_store; todo!() }; let auth_type = helpers::get_connector_auth_type(merchant_connector_account.clone())?; let access_token = get_access_token_from_exchange_api( &connector, connector_name, &payload, &auth_type, &state, ) .await?; let bank_account_details_resp = get_bank_account_creds( connector, &merchant_account, connector_name, &access_token, auth_type, &state, None, ) .await?; Box::pin(store_bank_details_in_payment_methods( key_store, payload, merchant_account, state, bank_account_details_resp, (connector_name, access_token), merchant_connector_account.get_id(), )) .await?; Ok(ApplicationResponse::StatusOk) } <file_sep path="hyperswitch/crates/router/src/core/pm_auth.rs" role="context" start="824" end="943"> pub async fn retrieve_payment_method_from_auth_service( state: &SessionState, key_store: &domain::MerchantKeyStore, auth_token: &payment_methods::BankAccountTokenData, payment_intent: &PaymentIntent, _customer: &Option<domain::Customer>, ) -> RouterResult<Option<(domain::PaymentMethodData, enums::PaymentMethod)>> { let db = state.store.as_ref(); let connector = PaymentAuthConnectorData::get_connector_by_name( auth_token.connector_details.connector.as_str(), )?; let key_manager_state = &state.into(); let merchant_account = db .find_merchant_account_by_merchant_id( key_manager_state, &payment_intent.merchant_id, key_store, ) .await .to_not_found_response(ApiErrorResponse::MerchantAccountNotFound)?; #[cfg(feature = "v1")] let mca = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, &payment_intent.merchant_id, &auth_token.connector_details.mca_id, key_store, ) .await .to_not_found_response(ApiErrorResponse::MerchantConnectorAccountNotFound { id: auth_token .connector_details .mca_id .get_string_repr() .to_string() .clone(), }) .attach_printable( "error while fetching merchant_connector_account from merchant_id and connector name", )?; let auth_type = pm_auth_helpers::get_connector_auth_type(mca)?; let BankAccountAccessCreds::AccessToken(access_token) = &auth_token.connector_details.access_token; let bank_account_creds = get_bank_account_creds( connector, &merchant_account, &auth_token.connector_details.connector, access_token, auth_type, state, Some(auth_token.connector_details.account_id.clone()), ) .await?; let bank_account = bank_account_creds .credentials .iter() .find(|acc| { acc.payment_method_type == auth_token.payment_method_type && acc.payment_method == auth_token.payment_method }) .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("Bank account details not found")?; if let (Some(balance), Some(currency)) = (bank_account.balance, payment_intent.currency) { let required_conversion = util_types::FloatMajorUnitForConnector; let converted_amount = required_conversion .convert_back(balance, currency) .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Could not convert FloatMajorUnit to MinorUnit")?; if converted_amount < payment_intent.amount { return Err((ApiErrorResponse::PreconditionFailed { message: "selected bank account has insufficient balance".to_string(), }) .into()); } } let mut bank_type = None; if let Some(account_type) = bank_account.account_type.clone() { bank_type = common_enums::BankType::from_str(account_type.as_str()) .map_err(|error| logger::error!(%error,"unable to parse account_type {account_type:?}")) .ok(); } let payment_method_data = match &bank_account.account_details { pm_auth_types::PaymentMethodTypeDetails::Ach(ach) => { domain::PaymentMethodData::BankDebit(domain::BankDebitData::AchBankDebit { account_number: ach.account_number.clone(), routing_number: ach.routing_number.clone(), bank_name: None, bank_type, bank_holder_type: None, card_holder_name: None, bank_account_holder_name: None, }) } pm_auth_types::PaymentMethodTypeDetails::Bacs(bacs) => { domain::PaymentMethodData::BankDebit(domain::BankDebitData::BacsBankDebit { account_number: bacs.account_number.clone(), sort_code: bacs.sort_code.clone(), bank_account_holder_name: None, }) } pm_auth_types::PaymentMethodTypeDetails::Sepa(sepa) => { domain::PaymentMethodData::BankDebit(domain::BankDebitData::SepaBankDebit { iban: sepa.iban.clone(), bank_account_holder_name: None, }) } }; Ok(Some((payment_method_data, enums::PaymentMethod::BankDebit))) } <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/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.rs<|crate|> router anchor=set_eligible_connector_for_nti_in_payment_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="6186" end="6242"> pub async fn set_eligible_connector_for_nti_in_payment_data<F, D>( state: &SessionState, business_profile: &domain::Profile, key_store: &domain::MerchantKeyStore, payment_data: &mut D, connector_choice: api::ConnectorChoice, ) -> RouterResult<api::ConnectorData> where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { let (mandate_reference_id, card_details_for_network_transaction_id, eligible_connector_data) = match connector_choice { api::ConnectorChoice::StraightThrough(straight_through) => { get_eligible_connector_for_nti( state, key_store, payment_data, core_routing::StraightThroughAlgorithmTypeSingle(straight_through), business_profile, ) .await? } api::ConnectorChoice::Decide => { get_eligible_connector_for_nti( state, key_store, payment_data, core_routing::DecideConnector, business_profile, ) .await? } api::ConnectorChoice::SessionMultiple(_) => { Err(errors::ApiErrorResponse::InternalServerError).attach_printable( "Invalid routing rule configured for nti and card details based mit flow", )? } }; // Set the eligible connector in the attempt payment_data .set_connector_in_payment_attempt(Some(eligible_connector_data.connector_name.to_string())); // Set `NetworkMandateId` as the MandateId payment_data.set_mandate_id(payments_api::MandateIds { mandate_id: None, mandate_reference_id: Some(mandate_reference_id), }); // Set the card details received in the recurring details within the payment method data. payment_data.set_payment_method_data(Some( hyperswitch_domain_models::payment_method_data::PaymentMethodData::CardDetailsForNetworkTransactionId(card_details_for_network_transaction_id), )); Ok(eligible_connector_data) } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="6185" end="6185"> .first() .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) .attach_printable( "No eligible connector found for the network transaction id based mit flow", )?; Ok(( mandate_reference_id, card_details_for_network_transaction_id, eligible_connector_data.clone(), )) } pub async fn set_eligible_connector_for_nti_in_payment_data<F, D>( state: &SessionState, business_profile: &domain::Profile, key_store: &domain::MerchantKeyStore, payment_data: &mut D, connector_choice: api::ConnectorChoice, ) -> RouterResult<api::ConnectorData> where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { let (mandate_reference_id, card_details_for_network_transaction_id, eligible_connector_data) = match connector_choice { <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="6319" end="6335"> pub async fn decide_connector<F, D>( state: SessionState, merchant_account: &domain::MerchantAccount, business_profile: &domain::Profile, key_store: &domain::MerchantKeyStore, payment_data: &mut D, request_straight_through: Option<api::routing::StraightThroughAlgorithm>, routing_data: &mut storage::RoutingData, eligible_connectors: Option<Vec<enums::RoutableConnectors>>, mandate_type: Option<api::MandateTransactionType>, ) -> RouterResult<ConnectorCallType> where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { todo!() } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="6246" end="6315"> pub async fn connector_selection<F, D>( state: &SessionState, merchant_account: &domain::MerchantAccount, business_profile: &domain::Profile, key_store: &domain::MerchantKeyStore, payment_data: &mut D, request_straight_through: Option<serde_json::Value>, eligible_connectors: Option<Vec<enums::RoutableConnectors>>, mandate_type: Option<api::MandateTransactionType>, ) -> RouterResult<ConnectorCallType> where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { let request_straight_through: Option<api::routing::StraightThroughAlgorithm> = request_straight_through .map(|val| val.parse_value("RoutingAlgorithm")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid straight through routing rules format")?; let mut routing_data = storage::RoutingData { routed_through: payment_data.get_payment_attempt().connector.clone(), merchant_connector_id: payment_data .get_payment_attempt() .merchant_connector_id .clone(), algorithm: request_straight_through.clone(), routing_info: payment_data .get_payment_attempt() .straight_through_algorithm .clone() .map(|val| val.parse_value("PaymentRoutingInfo")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid straight through algorithm format found in payment attempt")? .unwrap_or(storage::PaymentRoutingInfo { algorithm: None, pre_routing_results: None, }), }; let decided_connector = decide_connector( state.clone(), merchant_account, business_profile, key_store, payment_data, request_straight_through, &mut routing_data, eligible_connectors, mandate_type, ) .await?; let encoded_info = routing_data .routing_info .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error serializing payment routing info to serde value")?; payment_data.set_connector_in_payment_attempt(routing_data.routed_through); payment_data.set_merchant_connector_id_in_attempt(routing_data.merchant_connector_id); payment_data.set_straight_through_algorithm_in_payment_attempt(encoded_info); Ok(decided_connector) } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="6121" end="6184"> async fn get_eligible_connector_for_nti<T: core_routing::GetRoutableConnectorsForChoice, F, D>( state: &SessionState, key_store: &domain::MerchantKeyStore, payment_data: &D, connector_choice: T, business_profile: &domain::Profile, ) -> RouterResult<( api_models::payments::MandateReferenceId, hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId, api::ConnectorData, )> where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { // Since this flow will only be used in the MIT flow, recurring details are mandatory. let recurring_payment_details = payment_data .get_recurring_details() .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) .attach_printable("Failed to fetch recurring details for mit")?; let (mandate_reference_id, card_details_for_network_transaction_id)= hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId::get_nti_and_card_details_for_mit_flow(recurring_payment_details.clone()).get_required_value("network transaction id and card details").attach_printable("Failed to fetch network transaction id and card details for mit")?; helpers::validate_card_expiry( &card_details_for_network_transaction_id.card_exp_month, &card_details_for_network_transaction_id.card_exp_year, )?; let network_transaction_id_supported_connectors = &state .conf .network_transaction_id_supported_connectors .connector_list .iter() .map(|value| value.to_string()) .collect::<HashSet<_>>(); let eligible_connector_data_list = connector_choice .get_routable_connectors(&*state.store, business_profile) .await? .filter_network_transaction_id_flow_supported_connectors( network_transaction_id_supported_connectors.to_owned(), ) .construct_dsl_and_perform_eligibility_analysis( state, key_store, payment_data, business_profile.get_id(), ) .await .attach_printable("Failed to fetch eligible connector data")?; let eligible_connector_data = eligible_connector_data_list .first() .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) .attach_printable( "No eligible connector found for the network transaction id based mit flow", )?; Ok(( mandate_reference_id, card_details_for_network_transaction_id, eligible_connector_data.clone(), )) } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="6040" end="6119"> pub async fn get_connector_choice<F, Req, D>( operation: &BoxedOperation<'_, F, Req, D>, state: &SessionState, req: &Req, merchant_account: &domain::MerchantAccount, business_profile: &domain::Profile, key_store: &domain::MerchantKeyStore, payment_data: &mut D, eligible_connectors: Option<Vec<enums::RoutableConnectors>>, mandate_type: Option<api::MandateTransactionType>, ) -> RouterResult<Option<ConnectorCallType>> where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { let connector_choice = operation .to_domain()? .get_connector( merchant_account, &state.clone(), req, payment_data.get_payment_intent(), key_store, ) .await?; let connector = if should_call_connector(operation, payment_data) { Some(match connector_choice { api::ConnectorChoice::SessionMultiple(connectors) => { let routing_output = perform_session_token_routing( state.clone(), merchant_account, business_profile, key_store, payment_data, connectors, ) .await?; ConnectorCallType::SessionMultiple(routing_output) } api::ConnectorChoice::StraightThrough(straight_through) => { connector_selection( state, merchant_account, business_profile, key_store, payment_data, Some(straight_through), eligible_connectors, mandate_type, ) .await? } api::ConnectorChoice::Decide => { connector_selection( state, merchant_account, business_profile, key_store, payment_data, None, eligible_connectors, mandate_type, ) .await? } }) } else if let api::ConnectorChoice::StraightThrough(algorithm) = connector_choice { update_straight_through_routing(payment_data, algorithm) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update straight through routing algorithm")?; None } else { None }; Ok(connector) } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="900" end="1094"> pub async fn proxy_for_payments_operation_core<F, Req, Op, FData, D>( state: &SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, profile_id_from_auth_layer: Option<id_type::ProfileId>, key_store: domain::MerchantKeyStore, operation: Op, req: Req, call_connector_action: CallConnectorAction, auth_flow: services::AuthFlow, header_payload: HeaderPayload, platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResult<(D, Req, Option<domain::Customer>, Option<u16>, Option<u128>)> where F: Send + Clone + Sync, Req: Authenticate + Clone, Op: Operation<F, Req, Data = D> + Send + Sync, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, // To create connector flow specific interface data D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>, RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>, // To perform router related operation for PaymentResponse PaymentResponse: Operation<F, FData, Data = D>, FData: Send + Sync + Clone, { let operation: BoxedOperation<'_, F, Req, D> = Box::new(operation); tracing::Span::current().record("merchant_id", merchant_account.get_id().get_string_repr()); let (operation, validate_result) = operation .to_validate_request()? .validate_request(&req, &merchant_account)?; tracing::Span::current().record("payment_id", format!("{}", validate_result.payment_id)); let operations::GetTrackerResponse { operation, customer_details: _, mut payment_data, business_profile, mandate_type: _, } = operation .to_get_tracker()? .get_trackers( state, &validate_result.payment_id, &req, &merchant_account, &key_store, auth_flow, &header_payload, platform_merchant_account.as_ref(), ) .await?; core_utils::validate_profile_id_from_auth_layer( profile_id_from_auth_layer, &payment_data.get_payment_intent().clone(), )?; common_utils::fp_utils::when(!should_call_connector(&operation, &payment_data), || { Err(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration).attach_printable(format!( "Nti and card details based mit flow is not support for this {operation:?} payment operation" )) })?; let connector_choice = operation .to_domain()? .get_connector( &merchant_account, &state.clone(), &req, payment_data.get_payment_intent(), &key_store, ) .await?; let connector = set_eligible_connector_for_nti_in_payment_data( state, &business_profile, &key_store, &mut payment_data, connector_choice, ) .await?; let should_add_task_to_process_tracker = should_add_task_to_process_tracker(&payment_data); let locale = header_payload.locale.clone(); let schedule_time = if should_add_task_to_process_tracker { payment_sync::get_sync_process_schedule_time( &*state.store, connector.connector.id(), merchant_account.get_id(), 0, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while getting process schedule time")? } else { None }; let (router_data, mca) = proxy_for_call_connector_service( state, req_state.clone(), &merchant_account, &key_store, connector.clone(), &operation, &mut payment_data, &None, call_connector_action.clone(), &validate_result, schedule_time, header_payload.clone(), &business_profile, ) .await?; let op_ref = &operation; let should_trigger_post_processing_flows = is_operation_confirm(&operation); let operation = Box::new(PaymentResponse); let connector_http_status_code = router_data.connector_http_status_code; let external_latency = router_data.external_latency; add_connector_http_status_code_metrics(connector_http_status_code); #[cfg(all(feature = "dynamic_routing", feature = "v1"))] let routable_connectors = convert_connector_data_to_routable_connectors(&[connector.clone()]) .map_err(|e| logger::error!(routable_connector_error=?e)) .unwrap_or_default(); let mut payment_data = operation .to_post_update_tracker()? .update_tracker( state, payment_data, router_data, &key_store, merchant_account.storage_scheme, &locale, #[cfg(all(feature = "dynamic_routing", feature = "v1"))] routable_connectors, #[cfg(all(feature = "dynamic_routing", feature = "v1"))] &business_profile, ) .await?; if should_trigger_post_processing_flows { complete_postprocessing_steps_if_required( state, &merchant_account, &key_store, &None, &mca, &connector, &mut payment_data, op_ref, Some(header_payload.clone()), ) .await?; } let cloned_payment_data = payment_data.clone(); utils::trigger_payments_webhook( merchant_account, business_profile, &key_store, cloned_payment_data, None, state, operation, ) .await .map_err(|error| logger::warn!(payments_outgoing_webhook_error=?error)) .ok(); Ok(( payment_data, req, None, connector_http_status_code, external_latency, )) } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="8054" end="8097"> pub trait OperationSessionSetters<F> { // Setter functions for PaymentData fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent); fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt); fn set_payment_method_data(&mut self, payment_method_data: Option<domain::PaymentMethodData>); fn set_email_if_not_present(&mut self, email: pii::Email); fn set_payment_method_id_in_attempt(&mut self, payment_method_id: Option<String>); fn set_pm_token(&mut self, token: String); fn set_connector_customer_id(&mut self, customer_id: Option<String>); fn push_sessions_token(&mut self, token: api::SessionToken); fn set_surcharge_details(&mut self, surcharge_details: Option<types::SurchargeDetails>); fn set_merchant_connector_id_in_attempt( &mut self, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, ); #[cfg(feature = "v1")] fn set_capture_method_in_attempt(&mut self, capture_method: enums::CaptureMethod); fn set_frm_message(&mut self, frm_message: FraudCheck); fn set_payment_intent_status(&mut self, status: storage_enums::IntentStatus); fn set_authentication_type_in_attempt( &mut self, authentication_type: Option<enums::AuthenticationType>, ); fn set_recurring_mandate_payment_data( &mut self, recurring_mandate_payment_data: hyperswitch_domain_models::router_data::RecurringMandatePaymentData, ); fn set_mandate_id(&mut self, mandate_id: api_models::payments::MandateIds); fn set_setup_future_usage_in_payment_intent( &mut self, setup_future_usage: storage_enums::FutureUsage, ); #[cfg(feature = "v1")] fn set_straight_through_algorithm_in_payment_attempt( &mut self, straight_through_algorithm: serde_json::Value, ); fn set_connector_in_payment_attempt(&mut self, connector: Option<String>); #[cfg(feature = "v1")] fn set_vault_operation(&mut self, vault_operation: domain_payments::VaultOperation); } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="8013" end="8052"> pub trait OperationSessionGetters<F> { fn get_payment_attempt(&self) -> &storage::PaymentAttempt; fn get_payment_intent(&self) -> &storage::PaymentIntent; fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod>; fn get_mandate_id(&self) -> Option<&payments_api::MandateIds>; fn get_address(&self) -> &PaymentAddress; fn get_creds_identifier(&self) -> Option<&str>; fn get_token(&self) -> Option<&str>; fn get_multiple_capture_data(&self) -> Option<&types::MultipleCaptureData>; fn get_payment_link_data(&self) -> Option<api_models::payments::PaymentLinkResponse>; fn get_ephemeral_key(&self) -> Option<ephemeral_key::EphemeralKey>; fn get_setup_mandate(&self) -> Option<&MandateData>; fn get_poll_config(&self) -> Option<router_types::PollConfig>; fn get_authentication(&self) -> Option<&storage::Authentication>; fn get_frm_message(&self) -> Option<FraudCheck>; fn get_refunds(&self) -> Vec<storage::Refund>; fn get_disputes(&self) -> Vec<storage::Dispute>; fn get_authorizations(&self) -> Vec<diesel_models::authorization::Authorization>; fn get_attempts(&self) -> Option<Vec<storage::PaymentAttempt>>; fn get_recurring_details(&self) -> Option<&RecurringDetails>; // TODO: this should be a mandatory field, should we throw an error instead of returning an Option? fn get_payment_intent_profile_id(&self) -> Option<&id_type::ProfileId>; fn get_currency(&self) -> storage_enums::Currency; fn get_amount(&self) -> api::Amount; fn get_payment_attempt_connector(&self) -> Option<&str>; fn get_billing_address(&self) -> Option<hyperswitch_domain_models::address::Address>; fn get_payment_method_data(&self) -> Option<&domain::PaymentMethodData>; fn get_sessions_token(&self) -> Vec<api::SessionToken>; fn get_token_data(&self) -> Option<&storage::PaymentTokenData>; fn get_mandate_connector(&self) -> Option<&MandateConnectorDetails>; fn get_force_sync(&self) -> Option<bool>; fn get_capture_method(&self) -> Option<enums::CaptureMethod>; fn get_merchant_connector_id_in_attempt(&self) -> Option<id_type::MerchantConnectorAccountId>; #[cfg(feature = "v1")] fn get_vault_operation(&self) -> Option<&domain_payments::VaultOperation>; #[cfg(feature = "v2")] fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt>; } <file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207"> pub struct PaymentMethodData { pub id: Option<String>, pub object: &'static str, pub card: Option<CardDetails>, pub created: Option<time::PrimitiveDateTime>, } <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/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/helpers.rs<|crate|> router anchor=fetch_card_details_from_locker 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="2260" end="2312"> pub async fn fetch_card_details_from_locker( state: &SessionState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, locker_id: &str, card_token_data: Option<&domain::CardToken>, ) -> RouterResult<domain::Card> { let card = cards::get_card_from_locker(state, customer_id, merchant_id, locker_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to fetch card information from the permanent locker")?; // The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked // from payment_method_data.card_token object let name_on_card = if let Some(name) = card.name_on_card.clone() { if name.clone().expose().is_empty() { card_token_data .and_then(|token_data| token_data.card_holder_name.clone()) .or(Some(name)) } else { card.name_on_card } } else { card_token_data.and_then(|token_data| token_data.card_holder_name.clone()) }; let api_card = api::Card { card_number: card.card_number, card_holder_name: name_on_card, card_exp_month: card.card_exp_month, card_exp_year: card.card_exp_year, card_cvc: card_token_data .cloned() .unwrap_or_default() .card_cvc .unwrap_or_default(), card_issuer: None, nick_name: card.nick_name.map(masking::Secret::new), card_network: card .card_brand .map(|card_brand| enums::CardNetwork::from_str(&card_brand)) .transpose() .map_err(|e| { logger::error!("Failed to parse card network {e:?}"); }) .ok() .flatten(), card_type: None, card_issuing_country: None, bank_code: None, }; Ok(api_card.into()) } <file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="2259" end="2259"> card_token_data, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to fetch card information from the permanent locker")?, )) } #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") ))] pub async fn fetch_card_details_from_locker( state: &SessionState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, locker_id: &str, card_token_data: Option<&domain::CardToken>, ) -> RouterResult<domain::Card> { let card = cards::get_card_from_locker(state, customer_id, merchant_id, locker_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to fetch card information from the permanent locker")?; // The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked <file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="2370" end="2411"> pub async fn fetch_card_details_for_network_transaction_flow_from_locker( state: &SessionState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, locker_id: &str, ) -> RouterResult<domain::PaymentMethodData> { let card_details_from_locker = cards::get_card_from_locker(state, customer_id, merchant_id, locker_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to fetch card details from locker")?; let card_network = card_details_from_locker .card_brand .map(|card_brand| enums::CardNetwork::from_str(&card_brand)) .transpose() .map_err(|e| { logger::error!("Failed to parse card network {e:?}"); }) .ok() .flatten(); let card_details_for_network_transaction_id = hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId { card_number: card_details_from_locker.card_number, card_exp_month: card_details_from_locker.card_exp_month, card_exp_year: card_details_from_locker.card_exp_year, card_issuer: None, card_network, card_type: None, card_issuing_country: None, bank_code: None, nick_name: card_details_from_locker.nick_name.map(masking::Secret::new), card_holder_name: card_details_from_locker.name_on_card.clone(), }; Ok( domain::PaymentMethodData::CardDetailsForNetworkTransactionId( card_details_for_network_transaction_id, ), ) } <file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="2318" end="2364"> pub async fn fetch_network_token_details_from_locker( state: &SessionState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, network_token_locker_id: &str, network_transaction_data: api_models::payments::NetworkTokenWithNTIRef, ) -> RouterResult<domain::NetworkTokenData> { let mut token_data = cards::get_card_from_locker(state, customer_id, merchant_id, network_token_locker_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "failed to fetch network token information from the permanent locker", )?; let expiry = network_transaction_data .token_exp_month .zip(network_transaction_data.token_exp_year); if let Some((exp_month, exp_year)) = expiry { token_data.card_exp_month = exp_month; token_data.card_exp_year = exp_year; } let card_network = token_data .card_brand .map(|card_brand| enums::CardNetwork::from_str(&card_brand)) .transpose() .map_err(|e| { logger::error!("Failed to parse card network {e:?}"); }) .ok() .flatten(); let network_token_data = domain::NetworkTokenData { token_number: token_data.card_number, token_cryptogram: None, token_exp_month: token_data.card_exp_month, token_exp_year: token_data.card_exp_year, nick_name: token_data.nick_name.map(masking::Secret::new), card_issuer: None, card_network, card_type: None, card_issuing_country: None, bank_code: None, eci: None, }; Ok(network_token_data) } <file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="2227" end="2254"> pub async fn retrieve_card_with_permanent_token_for_external_authentication( state: &SessionState, locker_id: &str, payment_intent: &PaymentIntent, card_token_data: Option<&domain::CardToken>, _merchant_key_store: &domain::MerchantKeyStore, _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<domain::PaymentMethodData> { let customer_id = payment_intent .customer_id .as_ref() .get_required_value("customer_id") .change_context(errors::ApiErrorResponse::UnprocessableEntity { message: "no customer id provided for the payment".to_string(), })?; Ok(domain::PaymentMethodData::Card( fetch_card_details_from_locker( state, customer_id, &payment_intent.merchant_id, locker_id, card_token_data, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to fetch card information from the permanent locker")?, )) } <file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="2074" end="2220"> pub async fn retrieve_payment_method_data_with_permanent_token( state: &SessionState, locker_id: &str, _payment_method_id: &str, payment_intent: &PaymentIntent, card_token_data: Option<&domain::CardToken>, _merchant_key_store: &domain::MerchantKeyStore, _storage_scheme: enums::MerchantStorageScheme, mandate_id: Option<api_models::payments::MandateIds>, payment_method_info: domain::PaymentMethod, business_profile: &domain::Profile, connector: Option<String>, should_retry_with_pan: bool, vault_data: Option<&domain_payments::VaultData>, ) -> RouterResult<domain::PaymentMethodData> { let customer_id = payment_intent .customer_id .as_ref() .get_required_value("customer_id") .change_context(errors::ApiErrorResponse::UnprocessableEntity { message: "no customer id provided for the payment".to_string(), })?; let network_tokenization_supported_connectors = &state .conf .network_tokenization_supported_connectors .connector_list; let connector_variant = connector .as_ref() .map(|conn| { api_enums::Connector::from_str(conn.as_str()) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "connector", }) .attach_printable_lazy(|| format!("unable to parse connector name {connector:?}")) }) .transpose()?; let vault_fetch_action = decide_payment_method_retrieval_action( business_profile.is_network_tokenization_enabled, mandate_id, connector_variant, network_tokenization_supported_connectors, should_retry_with_pan, payment_method_info .network_token_requestor_reference_id .clone(), ); match vault_fetch_action { VaultFetchAction::FetchCardDetailsFromLocker => { let card = vault_data .and_then(|vault_data| vault_data.get_card_vault_data()) .map(Ok) .async_unwrap_or_else(|| async { fetch_card_details_from_locker( state, customer_id, &payment_intent.merchant_id, locker_id, card_token_data, ) .await }) .await?; Ok(domain::PaymentMethodData::Card(card)) } VaultFetchAction::FetchCardDetailsForNetworkTransactionIdFlowFromLocker => { fetch_card_details_for_network_transaction_flow_from_locker( state, customer_id, &payment_intent.merchant_id, locker_id, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to fetch card information from the permanent locker") } VaultFetchAction::FetchNetworkTokenDataFromTokenizationService( network_token_requestor_ref_id, ) => { logger::info!("Fetching network token data from tokenization service"); match network_tokenization::get_token_from_tokenization_service( state, network_token_requestor_ref_id, &payment_method_info, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to fetch network token data from tokenization service") { Ok(network_token_data) => { Ok(domain::PaymentMethodData::NetworkToken(network_token_data)) } Err(err) => { logger::info!( "Failed to fetch network token data from tokenization service {err:?}" ); logger::info!("Falling back to fetch card details from locker"); Ok(domain::PaymentMethodData::Card( vault_data .and_then(|vault_data| vault_data.get_card_vault_data()) .map(Ok) .async_unwrap_or_else(|| async { fetch_card_details_from_locker( state, customer_id, &payment_intent.merchant_id, locker_id, card_token_data, ) .await }) .await?, )) } } } VaultFetchAction::FetchNetworkTokenDetailsFromLocker(nt_data) => { if let Some(network_token_locker_id) = payment_method_info.network_token_locker_id.as_ref() { let network_token_data = vault_data .and_then(|vault_data| vault_data.get_network_token_data()) .map(Ok) .async_unwrap_or_else(|| async { fetch_network_token_details_from_locker( state, customer_id, &payment_intent.merchant_id, network_token_locker_id, nt_data, ) .await }) .await?; Ok(domain::PaymentMethodData::NetworkToken(network_token_data)) } else { Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Network token locker id is not present") } } VaultFetchAction::NoFetchAction => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Payment method data is not present"), } } <file_sep path="hyperswitch/crates/router/src/connector/payone/transformers.rs" role="context" start="117" end="121"> pub struct Card { card_holder_name: Secret<String>, card_number: CardNumber, expiry_date: Secret<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/payment_methods/cards.rs<|crate|> router anchor=insert_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="1988" end="2044"> pub async fn insert_payment_method( state: &routes::SessionState, resp: &api::PaymentMethodResponse, req: &api::PaymentMethodCreate, key_store: &domain::MerchantKeyStore, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, pm_metadata: Option<serde_json::Value>, customer_acceptance: Option<serde_json::Value>, locker_id: Option<String>, connector_mandate_details: Option<serde_json::Value>, network_transaction_id: Option<String>, storage_scheme: MerchantStorageScheme, payment_method_billing_address: crypto::OptionalEncryptableValue, network_token_requestor_reference_id: Option<String>, network_token_locker_id: Option<String>, network_token_payment_method_data: crypto::OptionalEncryptableValue, ) -> errors::RouterResult<domain::PaymentMethod> { let pm_card_details = resp .card .clone() .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))); let key_manager_state = state.into(); let pm_data_encrypted: crypto::OptionalEncryptableValue = pm_card_details .clone() .async_map(|pm_card| create_encrypted_data(&key_manager_state, key_store, pm_card)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt payment method data")?; create_payment_method( state, req, customer_id, &resp.payment_method_id, locker_id, merchant_id, pm_metadata, customer_acceptance, pm_data_encrypted, key_store, connector_mandate_details, None, network_transaction_id, storage_scheme, payment_method_billing_address, resp.card.clone().and_then(|card| { card.card_network .map(|card_network| card_network.to_string()) }), network_token_requestor_reference_id, network_token_locker_id, network_token_payment_method_data, ) .await } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="1987" end="1987"> .and_then(|val| (!val.0.is_empty()).then_some(false)) }), ); Ok(services::ApplicationResponse::Json(resp)) } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[allow(clippy::too_many_arguments)] pub async fn insert_payment_method( state: &routes::SessionState, resp: &api::PaymentMethodResponse, req: &api::PaymentMethodCreate, key_store: &domain::MerchantKeyStore, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, pm_metadata: Option<serde_json::Value>, customer_acceptance: Option<serde_json::Value>, locker_id: Option<String>, connector_mandate_details: Option<serde_json::Value>, network_transaction_id: Option<String>, storage_scheme: MerchantStorageScheme, <file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2071" end="2293"> pub async fn update_customer_payment_method( state: routes::SessionState, merchant_account: domain::MerchantAccount, req: api::PaymentMethodUpdate, payment_method_id: &str, key_store: domain::MerchantKeyStore, ) -> errors::RouterResponse<api::PaymentMethodResponse> { // Currently update is supported only for cards if let Some(card_update) = req.card.clone() { let db = state.store.as_ref(); let pm = db .find_payment_method( &((&state).into()), &key_store, payment_method_id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; if let Some(cs) = &req.client_secret { let is_client_secret_expired = authenticate_pm_client_secret_and_check_expiry(cs, &pm)?; if is_client_secret_expired { return Err((errors::ApiErrorResponse::ClientSecretExpired).into()); }; }; if pm.status == enums::PaymentMethodStatus::AwaitingData { return Err(report!(errors::ApiErrorResponse::NotSupported { message: "Payment method is awaiting data so it cannot be updated".into() })); } if pm.payment_method_data.is_none() { return Err(report!(errors::ApiErrorResponse::GenericNotFoundError { message: "payment_method_data not found".to_string() })); } // Fetch the existing payment method data from db let existing_card_data = pm.payment_method_data .clone() .map(|x| x.into_inner().expose()) .map( |value| -> Result< PaymentMethodsData, error_stack::Report<errors::ApiErrorResponse>, > { value .parse_value::<PaymentMethodsData>("PaymentMethodsData") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to deserialize payment methods data") }, ) .transpose()? .and_then(|pmd| match pmd { PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)), _ => None, }) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to obtain decrypted card object from db")?; let is_card_updation_required = validate_payment_method_update(card_update.clone(), existing_card_data.clone()); let response = if is_card_updation_required { // Fetch the existing card data from locker for getting card number let card_data_from_locker = get_card_from_locker( &state, &pm.customer_id, &pm.merchant_id, pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error getting card from locker")?; if card_update.card_exp_month.is_some() || card_update.card_exp_year.is_some() { helpers::validate_card_expiry( card_update .card_exp_month .as_ref() .unwrap_or(&card_data_from_locker.card_exp_month), card_update .card_exp_year .as_ref() .unwrap_or(&card_data_from_locker.card_exp_year), )?; } let updated_card_details = card_update.apply(card_data_from_locker.clone()); // Construct new payment method object from request let new_pm = api::PaymentMethodCreate { payment_method: pm.get_payment_method_type(), payment_method_type: pm.get_payment_method_subtype(), payment_method_issuer: pm.payment_method_issuer.clone(), payment_method_issuer_code: pm.payment_method_issuer_code, #[cfg(feature = "payouts")] bank_transfer: None, card: Some(updated_card_details.clone()), #[cfg(feature = "payouts")] wallet: None, metadata: None, customer_id: Some(pm.customer_id.clone()), client_secret: pm.client_secret.clone(), payment_method_data: None, card_network: None, billing: None, connector_mandate_details: None, network_transaction_id: None, }; new_pm.validate()?; // Delete old payment method from locker delete_card_from_locker( &state, &pm.customer_id, &pm.merchant_id, pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id), ) .await?; // Add the updated payment method data to locker let (mut add_card_resp, _) = Box::pin(add_card_to_locker( &state, new_pm.clone(), &updated_card_details, &pm.customer_id, &merchant_account, Some(pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id)), )) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add updated payment method to locker")?; // Construct new updated card object. Consider a field if passed in request or else populate it with the existing value from existing_card_data let updated_card = Some(api::CardDetailFromLocker { scheme: existing_card_data.scheme, last4_digits: Some(card_data_from_locker.card_number.get_last4()), issuer_country: existing_card_data.issuer_country, card_number: existing_card_data.card_number, expiry_month: card_update .card_exp_month .or(existing_card_data.expiry_month), expiry_year: card_update.card_exp_year.or(existing_card_data.expiry_year), card_token: existing_card_data.card_token, card_fingerprint: existing_card_data.card_fingerprint, card_holder_name: card_update .card_holder_name .or(existing_card_data.card_holder_name), nick_name: card_update.nick_name.or(existing_card_data.nick_name), card_network: existing_card_data.card_network, card_isin: existing_card_data.card_isin, card_issuer: existing_card_data.card_issuer, card_type: existing_card_data.card_type, saved_to_locker: true, }); let updated_pmd = updated_card .as_ref() .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))); let key_manager_state = (&state).into(); let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = updated_pmd .async_map(|updated_pmd| { create_encrypted_data(&key_manager_state, &key_store, updated_pmd) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt payment method data")?; let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate { payment_method_data: pm_data_encrypted.map(Into::into), }; add_card_resp .payment_method_id .clone_from(&pm.payment_method_id); db.update_payment_method( &((&state).into()), &key_store, pm, pm_update, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update payment method in db")?; add_card_resp } else { // Return existing payment method data as response without any changes api::PaymentMethodResponse { merchant_id: pm.merchant_id.to_owned(), customer_id: Some(pm.customer_id.clone()), payment_method_id: pm.payment_method_id.clone(), payment_method: pm.get_payment_method_type(), payment_method_type: pm.get_payment_method_subtype(), #[cfg(feature = "payouts")] bank_transfer: None, card: Some(existing_card_data), metadata: pm.metadata, created: Some(pm.created_at), recurring_enabled: false, installment_payment_enabled: false, payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), last_used_at: Some(common_utils::date_time::now()), client_secret: pm.client_secret.clone(), } }; Ok(services::ApplicationResponse::Json(response)) } else { Err(report!(errors::ApiErrorResponse::NotSupported { message: "Payment method update for the given payment method is not supported".into() })) } } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2048" end="2064"> pub async fn insert_payment_method( state: &routes::SessionState, resp: &api::PaymentMethodResponse, req: &api::PaymentMethodCreate, key_store: &domain::MerchantKeyStore, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, pm_metadata: Option<serde_json::Value>, customer_acceptance: Option<serde_json::Value>, locker_id: Option<String>, connector_mandate_details: Option<serde_json::Value>, network_transaction_id: Option<String>, storage_scheme: MerchantStorageScheme, payment_method_billing_address: Option<Encryption>, ) -> errors::RouterResult<domain::PaymentMethod> { todo!() } <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/src/core/payment_methods/cards.rs" role="context" start="5907" end="5937"> pub async fn create_encrypted_data<T>( key_manager_state: &KeyManagerState, key_store: &domain::MerchantKeyStore, data: T, ) -> Result<Encryptable<Secret<serde_json::Value>>, error_stack::Report<errors::StorageError>> where T: Debug + serde::Serialize, { let key = key_store.key.get_inner().peek(); let identifier = Identifier::Merchant(key_store.merchant_id.clone()); let encoded_data = Encode::encode_to_value(&data) .change_context(errors::StorageError::SerializationFailed) .attach_printable("Unable to encode data")?; let secret_data = Secret::<_, masking::WithType>::new(encoded_data); let encrypted_data = domain::types::crypto_operation( key_manager_state, type_name!(payment_method::PaymentMethod), domain::types::CryptoOperation::Encrypt(secret_data), identifier.clone(), key, ) .await .and_then(|val| val.try_into_operation()) .change_context(errors::StorageError::EncryptionError) .attach_printable("Unable to encrypt data")?; Ok(encrypted_data) } <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/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="54" end="70"> 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 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/webhooks/recovery_incoming.rs<|crate|> router anchor=handle_billing_connector_payment_sync_call kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/webhooks/recovery_incoming.rs" role="context" start="658" end="715"> async fn handle_billing_connector_payment_sync_call( state: &SessionState, merchant_account: &domain::MerchantAccount, merchant_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, connector_name: &str, id: &str, ) -> CustomResult<Self, errors::RevenueRecoveryError> { let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, connector_name, api::GetToken::Connector, None, ) .change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed) .attach_printable("invalid connector name received in payment attempt")?; let connector_integration: services::BoxedBillingConnectorPaymentsSyncIntegrationInterface< router_flow_types::BillingConnectorPaymentsSync, revenue_recovery_request::BillingConnectorPaymentsSyncRequest, revenue_recovery_response::BillingConnectorPaymentsSyncResponse, > = connector_data.connector.get_connector_integration(); let router_data = BillingConnectorPaymentsSyncFlowRouterData::construct_router_data_for_billing_connector_payment_sync_call( state, connector_name, merchant_connector_account, merchant_account, id, ) .await .change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed) .attach_printable( "Failed while constructing router data for billing connector psync call", )? .inner(); let response = services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, ) .await .change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed) .attach_printable("Failed while fetching billing connector payment details")?; let additional_recovery_details = match response.response { Ok(response) => Ok(response), error @ Err(_) => { router_env::logger::error!(?error); Err(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed) .attach_printable("Failed while fetching billing connector payment details") } }?; Ok(Self(additional_recovery_details)) } <file_sep path="hyperswitch/crates/router/src/core/webhooks/recovery_incoming.rs" role="context" start="657" end="657"> use std::{marker::PhantomData, str::FromStr}; use api_models::{payments as api_payments, webhooks}; use hyperswitch_domain_models::{ errors::api_error_response, revenue_recovery, router_data_v2::flow_common_types, router_flow_types, router_request_types::revenue_recovery as revenue_recovery_request, router_response_types::revenue_recovery as revenue_recovery_response, types as router_types, }; use router_env::{instrument, tracing}; use crate::{ core::{ errors::{self, CustomResult}, payments::{self, helpers}, }, db::{errors::RevenueRecoveryError, StorageInterface}, routes::{app::ReqState, metrics, SessionState}, services::{ self, connector_integration_interface::{self, RouterDataConversion}, }, types::{self, api, domain, storage::revenue_recovery as storage_churn_recovery}, workflows::revenue_recovery as revenue_recovery_flow, }; <file_sep path="hyperswitch/crates/router/src/core/webhooks/recovery_incoming.rs" role="context" start="754" end="756"> fn inner(self) -> revenue_recovery_response::BillingConnectorPaymentsSyncResponse { self.0 } <file_sep path="hyperswitch/crates/router/src/core/webhooks/recovery_incoming.rs" role="context" start="717" end="752"> async fn get_billing_connector_payment_details( should_billing_connector_payment_api_called: bool, state: &SessionState, merchant_account: &domain::MerchantAccount, billing_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, connector_name: &str, object_ref_id: &webhooks::ObjectReferenceId, ) -> CustomResult< Option<revenue_recovery_response::BillingConnectorPaymentsSyncResponse>, errors::RevenueRecoveryError, > { let response_data = match should_billing_connector_payment_api_called { true => { let billing_connector_transaction_id = object_ref_id .clone() .get_connector_transaction_id_as_string() .change_context( errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed, ) .attach_printable("Billing connector Payments api call failed")?; let billing_connector_payment_details = Self::handle_billing_connector_payment_sync_call( state, merchant_account, billing_connector_account, connector_name, &billing_connector_transaction_id, ) .await?; Some(billing_connector_payment_details.inner()) } false => None, }; Ok(response_data) } <file_sep path="hyperswitch/crates/router/src/core/webhooks/recovery_incoming.rs" role="context" start="574" end="647"> async fn insert_execute_pcr_task( db: &dyn StorageInterface, merchant_id: id_type::MerchantId, payment_intent: revenue_recovery::RecoveryPaymentIntent, profile_id: id_type::ProfileId, payment_attempt_id: Option<id_type::GlobalAttemptId>, runner: storage::ProcessTrackerRunner, ) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> { let task = "EXECUTE_WORKFLOW"; let payment_id = payment_intent.payment_id.clone(); let process_tracker_id = format!("{runner}_{task}_{}", payment_id.get_string_repr()); let total_retry_count = payment_intent .feature_metadata .and_then(|feature_metadata| feature_metadata.get_retry_count()) .unwrap_or(0); let schedule_time = revenue_recovery_flow::get_schedule_time_to_retry_mit_payments( db, &merchant_id, (total_retry_count + 1).into(), ) .await .map_or_else( || { Err( report!(errors::RevenueRecoveryError::ScheduleTimeFetchFailed) .attach_printable("Failed to get schedule time for pcr workflow"), ) }, Ok, // Simply returns `time` wrapped in `Ok` )?; let payment_attempt_id = payment_attempt_id .ok_or(report!( errors::RevenueRecoveryError::PaymentAttemptIdNotFound )) .attach_printable("payment attempt id is required for pcr workflow tracking")?; let execute_workflow_tracking_data = storage_churn_recovery::PcrWorkflowTrackingData { global_payment_id: payment_id.clone(), merchant_id, profile_id, payment_attempt_id, }; let tag = ["PCR"]; let process_tracker_entry = storage::ProcessTrackerNew::new( process_tracker_id, task, runner, tag, execute_workflow_tracking_data, Some(total_retry_count.into()), schedule_time, common_enums::ApiVersion::V2, ) .change_context(errors::RevenueRecoveryError::ProcessTrackerCreationError) .attach_printable("Failed to construct process tracker entry")?; db.insert_process(process_tracker_entry) .await .change_context(errors::RevenueRecoveryError::ProcessTrackerResponseError) .attach_printable("Failed to enter process_tracker_entry in DB")?; metrics::TASKS_ADDED_COUNT.add(1, router_env::metric_attributes!(("flow", "ExecutePCR"))); Ok(webhooks::WebhookResponseTracker::Payment { payment_id, status: payment_intent.status, }) } <file_sep path="hyperswitch/crates/router/src/core/webhooks/recovery_incoming.rs" role="context" start="505" end="572"> async fn get_recovery_payment_attempt( is_recovery_transaction_event: bool, billing_connector_account: &domain::MerchantConnectorAccount, state: &SessionState, key_store: &domain::MerchantKeyStore, connector_enum: &connector_integration_interface::ConnectorEnum, req_state: &ReqState, billing_connector_payment_details: Option< &revenue_recovery_response::BillingConnectorPaymentsSyncResponse, >, request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>, merchant_account: &domain::MerchantAccount, business_profile: &domain::Profile, payment_intent: &revenue_recovery::RecoveryPaymentIntent, ) -> CustomResult<Option<revenue_recovery::RecoveryPaymentAttempt>, errors::RevenueRecoveryError> { let recovery_payment_attempt = match is_recovery_transaction_event { true => { // Checks whether we have data in recovery_details , If its there then it will use the data and convert it into required from or else fetches from Incoming webhook let invoice_transaction_details = Self::get_recovery_invoice_transaction_details( connector_enum, request_details, billing_connector_payment_details, )?; // Find the payment merchant connector ID at the top level to avoid multiple DB calls. let payment_merchant_connector_account = invoice_transaction_details .find_payment_merchant_connector_account( state, key_store, billing_connector_account, ) .await?; Some( invoice_transaction_details .get_payment_attempt( state, req_state, merchant_account, business_profile, key_store, payment_intent.payment_id.clone(), ) .await .transpose() .async_unwrap_or_else(|| async { invoice_transaction_details .record_payment_attempt( state, req_state, merchant_account, business_profile, key_store, payment_intent.payment_id.clone(), &billing_connector_account.id, payment_merchant_connector_account, ) .await }) .await?, ) } false => None, }; Ok(recovery_payment_attempt) } <file_sep path="hyperswitch/crates/router/src/core/webhooks/recovery_incoming.rs" role="context" start="760" end="795"> async fn construct_router_data_for_billing_connector_payment_sync_call( state: &SessionState, connector_name: &str, merchant_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, merchant_account: &domain::MerchantAccount, billing_connector_psync_id: &str, ) -> CustomResult<Self, errors::RevenueRecoveryError> { let auth_type: types::ConnectorAuthType = helpers::MerchantConnectorAccountType::DbVal( Box::new(merchant_connector_account.clone()), ) .get_connector_account_details() .parse_value("ConnectorAuthType") .change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)?; let router_data = types::RouterDataV2 { flow: PhantomData::<router_flow_types::BillingConnectorPaymentsSync>, tenant_id: state.tenant.tenant_id.clone(), resource_common_data: flow_common_types::BillingConnectorPaymentsSyncFlowData, connector_auth_type: auth_type, request: revenue_recovery_request::BillingConnectorPaymentsSyncRequest { billing_connector_psync_id: billing_connector_psync_id.to_string(), }, response: Err(types::ErrorResponse::default()), }; let old_router_data = flow_common_types::BillingConnectorPaymentsSyncFlowData::to_old_router_data( router_data, ) .change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed) .attach_printable( "Cannot construct router data for making the billing connector payments api call", )?; Ok(Self(old_router_data)) } <file_sep path="hyperswitch/crates/router/src/core/webhooks/recovery_incoming.rs" role="context" start="653" end="655"> pub struct BillingConnectorPaymentsSyncFlowRouterData( router_types::BillingConnectorPaymentsSyncRouterData, ); <file_sep path="hyperswitch/crates/router/src/types/api.rs" role="context" start="104" end="111"> pub enum GetToken { GpayMetadata, SamsungPayMetadata, ApplePayMetadata, PaypalSdkMetadata, PazeMetadata, Connector, } <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/webhooks/recovery_incoming.rs<|crate|> router anchor=get_recovery_payment_attempt kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/webhooks/recovery_incoming.rs" role="context" start="505" end="572"> async fn get_recovery_payment_attempt( is_recovery_transaction_event: bool, billing_connector_account: &domain::MerchantConnectorAccount, state: &SessionState, key_store: &domain::MerchantKeyStore, connector_enum: &connector_integration_interface::ConnectorEnum, req_state: &ReqState, billing_connector_payment_details: Option< &revenue_recovery_response::BillingConnectorPaymentsSyncResponse, >, request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>, merchant_account: &domain::MerchantAccount, business_profile: &domain::Profile, payment_intent: &revenue_recovery::RecoveryPaymentIntent, ) -> CustomResult<Option<revenue_recovery::RecoveryPaymentAttempt>, errors::RevenueRecoveryError> { let recovery_payment_attempt = match is_recovery_transaction_event { true => { // Checks whether we have data in recovery_details , If its there then it will use the data and convert it into required from or else fetches from Incoming webhook let invoice_transaction_details = Self::get_recovery_invoice_transaction_details( connector_enum, request_details, billing_connector_payment_details, )?; // Find the payment merchant connector ID at the top level to avoid multiple DB calls. let payment_merchant_connector_account = invoice_transaction_details .find_payment_merchant_connector_account( state, key_store, billing_connector_account, ) .await?; Some( invoice_transaction_details .get_payment_attempt( state, req_state, merchant_account, business_profile, key_store, payment_intent.payment_id.clone(), ) .await .transpose() .async_unwrap_or_else(|| async { invoice_transaction_details .record_payment_attempt( state, req_state, merchant_account, business_profile, key_store, payment_intent.payment_id.clone(), &billing_connector_account.id, payment_merchant_connector_account, ) .await }) .await?, ) } false => None, }; Ok(recovery_payment_attempt) } <file_sep path="hyperswitch/crates/router/src/core/webhooks/recovery_incoming.rs" role="context" start="504" end="504"> use std::{marker::PhantomData, str::FromStr}; use api_models::{payments as api_payments, webhooks}; use common_utils::{ ext_traits::{AsyncExt, ValueExt}, id_type, }; use diesel_models::{process_tracker as storage, schema::process_tracker::retry_count}; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ errors::api_error_response, revenue_recovery, router_data_v2::flow_common_types, router_flow_types, router_request_types::revenue_recovery as revenue_recovery_request, router_response_types::revenue_recovery as revenue_recovery_response, types as router_types, }; use hyperswitch_interfaces::webhooks as interface_webhooks; use router_env::{instrument, tracing}; use serde_with::rust::unwrap_or_skip; use crate::{ core::{ errors::{self, CustomResult}, payments::{self, helpers}, }, db::{errors::RevenueRecoveryError, StorageInterface}, routes::{app::ReqState, metrics, SessionState}, services::{ self, connector_integration_interface::{self, RouterDataConversion}, }, types::{self, api, domain, storage::revenue_recovery as storage_churn_recovery}, workflows::revenue_recovery as revenue_recovery_flow, }; <file_sep path="hyperswitch/crates/router/src/core/webhooks/recovery_incoming.rs" role="context" start="658" end="715"> async fn handle_billing_connector_payment_sync_call( state: &SessionState, merchant_account: &domain::MerchantAccount, merchant_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, connector_name: &str, id: &str, ) -> CustomResult<Self, errors::RevenueRecoveryError> { let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, connector_name, api::GetToken::Connector, None, ) .change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed) .attach_printable("invalid connector name received in payment attempt")?; let connector_integration: services::BoxedBillingConnectorPaymentsSyncIntegrationInterface< router_flow_types::BillingConnectorPaymentsSync, revenue_recovery_request::BillingConnectorPaymentsSyncRequest, revenue_recovery_response::BillingConnectorPaymentsSyncResponse, > = connector_data.connector.get_connector_integration(); let router_data = BillingConnectorPaymentsSyncFlowRouterData::construct_router_data_for_billing_connector_payment_sync_call( state, connector_name, merchant_connector_account, merchant_account, id, ) .await .change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed) .attach_printable( "Failed while constructing router data for billing connector psync call", )? .inner(); let response = services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, ) .await .change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed) .attach_printable("Failed while fetching billing connector payment details")?; let additional_recovery_details = match response.response { Ok(response) => Ok(response), error @ Err(_) => { router_env::logger::error!(?error); Err(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed) .attach_printable("Failed while fetching billing connector payment details") } }?; Ok(Self(additional_recovery_details)) } <file_sep path="hyperswitch/crates/router/src/core/webhooks/recovery_incoming.rs" role="context" start="574" end="647"> async fn insert_execute_pcr_task( db: &dyn StorageInterface, merchant_id: id_type::MerchantId, payment_intent: revenue_recovery::RecoveryPaymentIntent, profile_id: id_type::ProfileId, payment_attempt_id: Option<id_type::GlobalAttemptId>, runner: storage::ProcessTrackerRunner, ) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> { let task = "EXECUTE_WORKFLOW"; let payment_id = payment_intent.payment_id.clone(); let process_tracker_id = format!("{runner}_{task}_{}", payment_id.get_string_repr()); let total_retry_count = payment_intent .feature_metadata .and_then(|feature_metadata| feature_metadata.get_retry_count()) .unwrap_or(0); let schedule_time = revenue_recovery_flow::get_schedule_time_to_retry_mit_payments( db, &merchant_id, (total_retry_count + 1).into(), ) .await .map_or_else( || { Err( report!(errors::RevenueRecoveryError::ScheduleTimeFetchFailed) .attach_printable("Failed to get schedule time for pcr workflow"), ) }, Ok, // Simply returns `time` wrapped in `Ok` )?; let payment_attempt_id = payment_attempt_id .ok_or(report!( errors::RevenueRecoveryError::PaymentAttemptIdNotFound )) .attach_printable("payment attempt id is required for pcr workflow tracking")?; let execute_workflow_tracking_data = storage_churn_recovery::PcrWorkflowTrackingData { global_payment_id: payment_id.clone(), merchant_id, profile_id, payment_attempt_id, }; let tag = ["PCR"]; let process_tracker_entry = storage::ProcessTrackerNew::new( process_tracker_id, task, runner, tag, execute_workflow_tracking_data, Some(total_retry_count.into()), schedule_time, common_enums::ApiVersion::V2, ) .change_context(errors::RevenueRecoveryError::ProcessTrackerCreationError) .attach_printable("Failed to construct process tracker entry")?; db.insert_process(process_tracker_entry) .await .change_context(errors::RevenueRecoveryError::ProcessTrackerResponseError) .attach_printable("Failed to enter process_tracker_entry in DB")?; metrics::TASKS_ADDED_COUNT.add(1, router_env::metric_attributes!(("flow", "ExecutePCR"))); Ok(webhooks::WebhookResponseTracker::Payment { payment_id, status: payment_intent.status, }) } <file_sep path="hyperswitch/crates/router/src/core/webhooks/recovery_incoming.rs" role="context" start="477" end="502"> pub async fn find_payment_merchant_connector_account( &self, state: &SessionState, key_store: &domain::MerchantKeyStore, billing_connector_account: &domain::MerchantConnectorAccount, ) -> CustomResult<Option<domain::MerchantConnectorAccount>, errors::RevenueRecoveryError> { let payment_merchant_connector_account_id = billing_connector_account .get_payment_merchant_connector_account_id_using_account_reference_id( self.0.connector_account_reference_id.clone(), ); let db = &*state.store; let key_manager_state = &(state).into(); let payment_merchant_connector_account = payment_merchant_connector_account_id .as_ref() .async_map(|mca_id| async move { db.find_merchant_connector_account_by_id(key_manager_state, mca_id, key_store) .await }) .await .transpose() .change_context(errors::RevenueRecoveryError::PaymentMerchantConnectorAccountNotFound) .attach_printable( "failed to fetch payment merchant connector id using account reference id", )?; Ok(payment_merchant_connector_account) } <file_sep path="hyperswitch/crates/router/src/core/webhooks/recovery_incoming.rs" role="context" start="442" end="475"> pub fn create_payment_record_request( &self, billing_merchant_connector_account_id: &id_type::MerchantConnectorAccountId, payment_merchant_connector_account: Option<domain::MerchantConnectorAccount>, ) -> api_payments::PaymentsAttemptRecordRequest { let amount_details = api_payments::PaymentAttemptAmountDetails::from(&self.0); let feature_metadata = api_payments::PaymentAttemptFeatureMetadata { revenue_recovery: Some(api_payments::PaymentAttemptRevenueRecoveryData { // Since we are recording the external paymenmt attempt, this is hardcoded to External attempt_triggered_by: common_enums::TriggeredBy::External, }), }; let error = Option::<api_payments::RecordAttemptErrorDetails>::from(&self.0); api_payments::PaymentsAttemptRecordRequest { amount_details, status: self.0.status, billing: None, shipping: None, connector : payment_merchant_connector_account.as_ref().map(|account| account.connector_name), payment_merchant_connector_id: payment_merchant_connector_account.as_ref().map(|account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount| account.id.clone()), error, description: None, connector_transaction_id: self.0.connector_transaction_id.clone(), payment_method_type: self.0.payment_method_type, billing_connector_id: billing_merchant_connector_account_id.clone(), payment_method_subtype: self.0.payment_method_sub_type, payment_method_data: None, metadata: None, feature_metadata: Some(feature_metadata), transaction_created_at: self.0.transaction_created_at, processor_payment_method_token: self.0.processor_payment_method_token.clone(), connector_customer_id: self.0.connector_customer_id.clone(), } } <file_sep path="hyperswitch/crates/router/src/core/webhooks/recovery_incoming.rs" role="context" start="37" end="173"> pub async fn recovery_incoming_webhook_flow( state: SessionState, merchant_account: domain::MerchantAccount, business_profile: domain::Profile, key_store: domain::MerchantKeyStore, _webhook_details: api::IncomingWebhookDetails, source_verified: bool, connector_enum: &connector_integration_interface::ConnectorEnum, billing_connector_account: hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, connector_name: &str, request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>, event_type: webhooks::IncomingWebhookEvent, req_state: ReqState, object_ref_id: &webhooks::ObjectReferenceId, ) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> { // Source verification is necessary for revenue recovery webhooks flow since We don't have payment intent/attempt object created before in our system. common_utils::fp_utils::when(!source_verified, || { Err(report!( errors::RevenueRecoveryError::WebhookAuthenticationFailed )) })?; let connector = api_models::enums::Connector::from_str(connector_name) .change_context(errors::RevenueRecoveryError::InvoiceWebhookProcessingFailed) .attach_printable_lazy(|| format!("unable to parse connector name {connector_name:?}"))?; let billing_connectors_with_payment_sync_call = &state.conf.billing_connectors_payment_sync; let should_billing_connector_payment_api_called = billing_connectors_with_payment_sync_call .billing_connectors_which_require_payment_sync .contains(&connector); let billing_connector_payment_details = BillingConnectorPaymentsSyncResponseData::get_billing_connector_payment_details( should_billing_connector_payment_api_called, &state, &merchant_account, &billing_connector_account, connector_name, object_ref_id, ) .await?; // Checks whether we have data in recovery_details , If its there then it will use the data and convert it into required from or else fetches from Incoming webhook let invoice_details = RevenueRecoveryInvoice::get_recovery_invoice_details( connector_enum, request_details, billing_connector_payment_details.as_ref(), )?; // Fetch the intent using merchant reference id, if not found create new intent. let payment_intent = invoice_details .get_payment_intent( &state, &req_state, &merchant_account, &business_profile, &key_store, ) .await .transpose() .async_unwrap_or_else(|| async { invoice_details .create_payment_intent( &state, &req_state, &merchant_account, &business_profile, &key_store, ) .await }) .await?; let is_event_recovery_transaction_event = event_type.is_recovery_transaction_event(); let payment_attempt = RevenueRecoveryAttempt::get_recovery_payment_attempt( is_event_recovery_transaction_event, &billing_connector_account, &state, &key_store, connector_enum, &req_state, billing_connector_payment_details.as_ref(), request_details, &merchant_account, &business_profile, &payment_intent, ) .await?; let attempt_triggered_by = payment_attempt .as_ref() .and_then(revenue_recovery::RecoveryPaymentAttempt::get_attempt_triggered_by); let action = revenue_recovery::RecoveryAction::get_action(event_type, attempt_triggered_by); match action { revenue_recovery::RecoveryAction::CancelInvoice => todo!(), revenue_recovery::RecoveryAction::ScheduleFailedPayment => { Ok(RevenueRecoveryAttempt::insert_execute_pcr_task( &*state.store, merchant_account.get_id().to_owned(), payment_intent, business_profile.get_id().to_owned(), payment_attempt.map(|attempt| attempt.attempt_id.clone()), storage::ProcessTrackerRunner::PassiveRecoveryWorkflow, ) .await .change_context(errors::RevenueRecoveryError::InvoiceWebhookProcessingFailed)?) } revenue_recovery::RecoveryAction::SuccessPaymentExternal => { // Need to add recovery stop flow for this scenario router_env::logger::info!("Payment has been succeeded via external system"); Ok(webhooks::WebhookResponseTracker::NoEffect) } revenue_recovery::RecoveryAction::PendingPayment => { router_env::logger::info!( "Pending transactions are not consumed by the revenue recovery webhooks" ); Ok(webhooks::WebhookResponseTracker::NoEffect) } revenue_recovery::RecoveryAction::NoAction => { router_env::logger::info!( "No Recovery action is taken place for recovery event : {:?} and attempt triggered_by : {:?} ", event_type.clone(), attempt_triggered_by ); Ok(webhooks::WebhookResponseTracker::NoEffect) } revenue_recovery::RecoveryAction::InvalidAction => { router_env::logger::error!( "Invalid Revenue recovery action state has been received, event : {:?}, triggered_by : {:?}", event_type, attempt_triggered_by ); Ok(webhooks::WebhookResponseTracker::NoEffect) } } } <file_sep path="hyperswitch/crates/router/src/core/webhooks/recovery_incoming.rs" role="context" start="302" end="327"> fn get_recovery_invoice_transaction_details( connector_enum: &connector_integration_interface::ConnectorEnum, request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>, billing_connector_payment_details: Option< &revenue_recovery_response::BillingConnectorPaymentsSyncResponse, >, ) -> CustomResult<Self, errors::RevenueRecoveryError> { billing_connector_payment_details.map_or_else( || { interface_webhooks::IncomingWebhook::get_revenue_recovery_attempt_details( connector_enum, request_details, ) .change_context(errors::RevenueRecoveryError::TransactionWebhookProcessingFailed) .attach_printable( "Failed to get recovery attempt details from the billing connector", ) .map(RevenueRecoveryAttempt) }, |data| { Ok(Self(revenue_recovery::RevenueRecoveryAttemptData::from( data, ))) }, ) } <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 );
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/routing.rs<|crate|> router anchor=perform_dynamic_routing kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="1488" end="1556"> pub async fn perform_dynamic_routing( state: &SessionState, routable_connectors: Vec<api_routing::RoutableConnectorChoice>, profile: &domain::Profile, dynamic_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator, ) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> { let dynamic_routing_algo_ref: api_routing::DynamicRoutingAlgorithmRef = profile .dynamic_routing_algorithm .clone() .map(|val| val.parse_value("DynamicRoutingAlgorithmRef")) .transpose() .change_context(errors::RoutingError::DeserializationError { from: "JSON".to_string(), to: "DynamicRoutingAlgorithmRef".to_string(), }) .attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")? .ok_or(errors::RoutingError::GenericNotFoundError { field: "dynamic_routing_algorithm".to_string(), })?; logger::debug!( "performing dynamic_routing for profile {}", profile.get_id().get_string_repr() ); let connector_list = match dynamic_routing_algo_ref .success_based_algorithm .as_ref() .async_map(|algorithm| { perform_success_based_routing( state, routable_connectors.clone(), profile.get_id(), dynamic_routing_config_params_interpolator.clone(), algorithm.clone(), ) }) .await .transpose() .inspect_err(|e| logger::error!(dynamic_routing_error=?e)) .ok() .flatten() { Some(success_based_list) => success_based_list, None => { // Only run contract based if success based returns None dynamic_routing_algo_ref .contract_based_routing .as_ref() .async_map(|algorithm| { perform_contract_based_routing( state, routable_connectors.clone(), profile.get_id(), dynamic_routing_config_params_interpolator, algorithm.clone(), ) }) .await .transpose() .inspect_err(|e| logger::error!(dynamic_routing_error=?e)) .ok() .flatten() .unwrap_or(routable_connectors) } }; Ok(connector_list) } <file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="1487" end="1487"> use api_models::routing as api_routing; use api_models::{ admin as admin_api, enums::{self as api_enums, CountryAlpha2}, routing::ConnectorSelection, }; use external_services::grpc_client::dynamic_routing::{ contract_routing_client::ContractBasedDynamicRouting, success_rate_client::{CalSuccessRateResponse, SuccessBasedDynamicRouting}, DynamicRoutingError, }; use crate::{ core::{ errors, errors as oss_errors, routing::{self}, }, logger, types::{ api::{self, routing as routing_types}, domain, storage as oss_storage, transformers::{ForeignFrom, ForeignInto, ForeignTryFrom}, }, utils::{OptionExt, ValueExt}, SessionState, }; type RoutingResult<O> = oss_errors::CustomResult<O, errors::RoutingError>; <file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="1658" end="1805"> pub async fn perform_contract_based_routing( state: &SessionState, routable_connectors: Vec<api_routing::RoutableConnectorChoice>, profile_id: &common_utils::id_type::ProfileId, _dynamic_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator, contract_based_algo_ref: api_routing::ContractRoutingAlgorithm, ) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> { if contract_based_algo_ref.enabled_feature == api_routing::DynamicRoutingFeatures::DynamicConnectorSelection { logger::debug!( "performing contract_based_routing for profile {}", profile_id.get_string_repr() ); let client = state .grpc_client .dynamic_routing .contract_based_client .as_ref() .ok_or(errors::RoutingError::ContractRoutingClientInitializationError) .attach_printable("contract routing gRPC client not found")?; let contract_based_routing_configs = routing::helpers::fetch_dynamic_routing_configs::< api_routing::ContractBasedRoutingConfig, >( state, profile_id, contract_based_algo_ref .algorithm_id_with_timestamp .algorithm_id .ok_or(errors::RoutingError::GenericNotFoundError { field: "contract_based_routing_algorithm_id".to_string(), }) .attach_printable("contract_based_routing_algorithm_id not found in profile_id")?, ) .await .change_context(errors::RoutingError::ContractBasedRoutingConfigError) .attach_printable("unable to fetch contract based dynamic routing configs")?; let label_info = contract_based_routing_configs .label_info .clone() .ok_or(errors::RoutingError::ContractBasedRoutingConfigError) .attach_printable("Label information not found in contract routing configs")?; let contract_based_connectors = routable_connectors .clone() .into_iter() .filter(|conn| { label_info .iter() .any(|info| Some(info.mca_id.clone()) == conn.merchant_connector_id.clone()) }) .collect::<Vec<_>>(); let mut other_connectors = routable_connectors .into_iter() .filter(|conn| { label_info .iter() .all(|info| Some(info.mca_id.clone()) != conn.merchant_connector_id.clone()) }) .collect::<Vec<_>>(); let contract_based_connectors_result = client .calculate_contract_score( profile_id.get_string_repr().into(), contract_based_routing_configs.clone(), "".to_string(), contract_based_connectors, state.get_grpc_headers(), ) .await .attach_printable( "unable to calculate/fetch contract score from dynamic routing service", ); let contract_based_connectors = match contract_based_connectors_result { Ok(resp) => resp, Err(err) => match err.current_context() { DynamicRoutingError::ContractNotFound => { client .update_contracts( profile_id.get_string_repr().into(), label_info, "".to_string(), vec![], u64::default(), state.get_grpc_headers(), ) .await .change_context(errors::RoutingError::ContractScoreUpdationError) .attach_printable( "unable to update contract based routing window in dynamic routing service", )?; return Err((errors::RoutingError::ContractScoreCalculationError { err: err.to_string(), }) .into()); } _ => { return Err((errors::RoutingError::ContractScoreCalculationError { err: err.to_string(), }) .into()) } }, }; let mut connectors = Vec::with_capacity(contract_based_connectors.labels_with_score.len()); for label_with_score in contract_based_connectors.labels_with_score { let (connector, merchant_connector_id) = label_with_score.label .split_once(':') .ok_or(errors::RoutingError::InvalidContractBasedConnectorLabel(label_with_score.label.to_string())) .attach_printable( "unable to split connector_name and mca_id from the label obtained by the dynamic routing service", )?; connectors.push(api_routing::RoutableConnectorChoice { choice_kind: api_routing::RoutableChoiceKind::FullStruct, connector: common_enums::RoutableConnectors::from_str(connector) .change_context(errors::RoutingError::GenericConversionError { from: "String".to_string(), to: "RoutableConnectors".to_string(), }) .attach_printable("unable to convert String to RoutableConnectors")?, merchant_connector_id: Some( common_utils::id_type::MerchantConnectorAccountId::wrap( merchant_connector_id.to_string(), ) .change_context(errors::RoutingError::GenericConversionError { from: "String".to_string(), to: "MerchantConnectorAccountId".to_string(), }) .attach_printable("unable to convert MerchantConnectorAccountId from string")?, ), }); } connectors.append(&mut other_connectors); logger::debug!(contract_based_routing_connectors=?connectors); Ok(connectors) } else { Ok(routable_connectors) } } <file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="1561" end="1655"> pub async fn perform_success_based_routing( state: &SessionState, routable_connectors: Vec<api_routing::RoutableConnectorChoice>, profile_id: &common_utils::id_type::ProfileId, success_based_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator, success_based_algo_ref: api_routing::SuccessBasedAlgorithm, ) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> { if success_based_algo_ref.enabled_feature == api_routing::DynamicRoutingFeatures::DynamicConnectorSelection { logger::debug!( "performing success_based_routing for profile {}", profile_id.get_string_repr() ); let client = state .grpc_client .dynamic_routing .success_rate_client .as_ref() .ok_or(errors::RoutingError::SuccessRateClientInitializationError) .attach_printable("success_rate gRPC client not found")?; let success_based_routing_configs = routing::helpers::fetch_dynamic_routing_configs::< api_routing::SuccessBasedRoutingConfig, >( state, profile_id, success_based_algo_ref .algorithm_id_with_timestamp .algorithm_id .ok_or(errors::RoutingError::GenericNotFoundError { field: "success_based_routing_algorithm_id".to_string(), }) .attach_printable("success_based_routing_algorithm_id not found in profile_id")?, ) .await .change_context(errors::RoutingError::SuccessBasedRoutingConfigError) .attach_printable("unable to fetch success_rate based dynamic routing configs")?; let success_based_routing_config_params = success_based_routing_config_params_interpolator .get_string_val( success_based_routing_configs .params .as_ref() .ok_or(errors::RoutingError::SuccessBasedRoutingParamsNotFoundError)?, ); let success_based_connectors: CalSuccessRateResponse = client .calculate_success_rate( profile_id.get_string_repr().into(), success_based_routing_configs, success_based_routing_config_params, routable_connectors, state.get_grpc_headers(), ) .await .change_context(errors::RoutingError::SuccessRateCalculationError) .attach_printable( "unable to calculate/fetch success rate from dynamic routing service", )?; let mut connectors = Vec::with_capacity(success_based_connectors.labels_with_score.len()); for label_with_score in success_based_connectors.labels_with_score { let (connector, merchant_connector_id) = label_with_score.label .split_once(':') .ok_or(errors::RoutingError::InvalidSuccessBasedConnectorLabel(label_with_score.label.to_string())) .attach_printable( "unable to split connector_name and mca_id from the label obtained by the dynamic routing service", )?; connectors.push(api_routing::RoutableConnectorChoice { choice_kind: api_routing::RoutableChoiceKind::FullStruct, connector: common_enums::RoutableConnectors::from_str(connector) .change_context(errors::RoutingError::GenericConversionError { from: "String".to_string(), to: "RoutableConnectors".to_string(), }) .attach_printable("unable to convert String to RoutableConnectors")?, merchant_connector_id: Some( common_utils::id_type::MerchantConnectorAccountId::wrap( merchant_connector_id.to_string(), ) .change_context(errors::RoutingError::GenericConversionError { from: "String".to_string(), to: "MerchantConnectorAccountId".to_string(), }) .attach_printable("unable to convert MerchantConnectorAccountId from string")?, ), }); } logger::debug!(success_based_routing_connectors=?connectors); Ok(connectors) } else { Ok(routable_connectors) } } <file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="1434" end="1485"> pub fn make_dsl_input_for_surcharge( payment_attempt: &oss_storage::PaymentAttempt, payment_intent: &oss_storage::PaymentIntent, billing_address: Option<Address>, ) -> RoutingResult<dsl_inputs::BackendInput> { let mandate_data = dsl_inputs::MandateData { mandate_acceptance_type: None, mandate_type: None, payment_type: None, }; let payment_input = dsl_inputs::PaymentInput { amount: payment_attempt.get_total_amount(), // currency is always populated in payment_attempt during payment create currency: payment_attempt .currency .get_required_value("currency") .change_context(errors::RoutingError::DslMissingRequiredField { field_name: "currency".to_string(), })?, authentication_type: payment_attempt.authentication_type, card_bin: None, capture_method: payment_attempt.capture_method, business_country: payment_intent .business_country .map(api_enums::Country::from_alpha2), billing_country: billing_address .and_then(|bic| bic.address) .and_then(|add| add.country) .map(api_enums::Country::from_alpha2), business_label: payment_intent.business_label.clone(), setup_future_usage: payment_intent.setup_future_usage, }; let metadata = payment_intent .parse_and_get_metadata("routing_parameters") .change_context(errors::RoutingError::MetadataParsingError) .attach_printable("Unable to parse routing_parameters from metadata of payment_intent") .unwrap_or(None); let payment_method_input = dsl_inputs::PaymentMethodInput { payment_method: None, payment_method_type: None, card_network: None, }; let backend_input = dsl_inputs::BackendInput { metadata, payment: payment_input, payment_method: payment_method_input, mandate: mandate_data, }; Ok(backend_input) } <file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="1425" end="1431"> pub fn make_dsl_input_for_surcharge( _payment_attempt: &oss_storage::PaymentAttempt, _payment_intent: &oss_storage::PaymentIntent, _billing_address: Option<Address>, ) -> RoutingResult<dsl_inputs::BackendInput> { todo!() } <file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="111" end="111"> type RoutingResult<O> = oss_errors::CustomResult<O, errors::RoutingError>; <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="173" end="179"> pub struct RoutableConnectorChoice { #[serde(skip)] pub choice_kind: RoutableChoiceKind, pub connector: RoutableConnectors, #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } <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.rs<|crate|> router anchor=should_call_connector kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="5504" end="5559"> pub fn should_call_connector<Op: Debug, F: Clone, D>(operation: &Op, payment_data: &D) -> bool where D: OperationSessionGetters<F> + Send + Sync + Clone, { match format!("{operation:?}").as_str() { "PaymentConfirm" => true, "PaymentStart" => { !matches!( payment_data.get_payment_intent().status, storage_enums::IntentStatus::Failed | storage_enums::IntentStatus::Succeeded ) && payment_data .get_payment_attempt() .authentication_data .is_none() } "PaymentStatus" => { matches!( payment_data.get_payment_intent().status, storage_enums::IntentStatus::Processing | storage_enums::IntentStatus::RequiresCustomerAction | storage_enums::IntentStatus::RequiresMerchantAction | storage_enums::IntentStatus::RequiresCapture | storage_enums::IntentStatus::PartiallyCapturedAndCapturable ) && payment_data.get_force_sync().unwrap_or(false) } "PaymentCancel" => matches!( payment_data.get_payment_intent().status, storage_enums::IntentStatus::RequiresCapture | storage_enums::IntentStatus::PartiallyCapturedAndCapturable ), "PaymentCapture" => { matches!( payment_data.get_payment_intent().status, storage_enums::IntentStatus::RequiresCapture | storage_enums::IntentStatus::PartiallyCapturedAndCapturable ) || (matches!( payment_data.get_payment_intent().status, storage_enums::IntentStatus::Processing ) && matches!( payment_data.get_capture_method(), Some(storage_enums::CaptureMethod::ManualMultiple) )) } "CompleteAuthorize" => true, "PaymentApprove" => true, "PaymentReject" => true, "PaymentSession" => true, "PaymentSessionUpdate" => true, "PaymentPostSessionTokens" => true, "PaymentIncrementalAuthorization" => matches!( payment_data.get_payment_intent().status, storage_enums::IntentStatus::RequiresCapture ), _ => false, } } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="5503" end="5503"> &'a PaymentConfirm: Operation<F, R, Data = PaymentData<F>>, Op: Operation<F, R, Data = PaymentData<F>> + Send + Sync, &'a Op: Operation<F, R, Data = PaymentData<F>>, { if confirm.unwrap_or(false) { Box::new(&PaymentConfirm) } else { Box::new(operation) } } #[cfg(feature = "v1")] pub fn should_call_connector<Op: Debug, F: Clone, D>(operation: &Op, payment_data: &D) -> bool where D: OperationSessionGetters<F> + Send + Sync + Clone, { match format!("{operation:?}").as_str() { "PaymentConfirm" => true, "PaymentStart" => { !matches!( payment_data.get_payment_intent().status, storage_enums::IntentStatus::Failed | storage_enums::IntentStatus::Succeeded ) && payment_data .get_payment_attempt() .authentication_data <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="5565" end="5567"> pub fn is_operation_complete_authorize<Op: Debug>(operation: &Op) -> bool { matches!(format!("{operation:?}").as_str(), "CompleteAuthorize") } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="5561" end="5563"> pub fn is_operation_confirm<Op: Debug>(operation: &Op) -> bool { matches!(format!("{operation:?}").as_str(), "PaymentConfirm") } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="5486" end="5501"> pub fn is_confirm<'a, F: Clone + Send, R, Op>( operation: &'a Op, confirm: Option<bool>, ) -> BoxedOperation<'a, F, R, PaymentData<F>> where PaymentConfirm: Operation<F, R, Data = PaymentData<F>>, &'a PaymentConfirm: Operation<F, R, Data = PaymentData<F>>, Op: Operation<F, R, Data = PaymentData<F>> + Send + Sync, &'a Op: Operation<F, R, Data = PaymentData<F>>, { if confirm.unwrap_or(false) { Box::new(&PaymentConfirm) } else { Box::new(operation) } } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="5461" end="5483"> pub fn if_not_create_change_operation<'a, Op, F>( status: storage_enums::IntentStatus, confirm: Option<bool>, current: &'a Op, ) -> BoxedOperation<'a, F, api::PaymentsRequest, PaymentData<F>> where F: Send + Clone + Sync, Op: Operation<F, api::PaymentsRequest, Data = PaymentData<F>> + Send + Sync, &'a Op: Operation<F, api::PaymentsRequest, Data = PaymentData<F>>, PaymentStatus: Operation<F, api::PaymentsRequest, Data = PaymentData<F>>, &'a PaymentStatus: Operation<F, api::PaymentsRequest, Data = PaymentData<F>>, { if confirm.unwrap_or(false) { Box::new(PaymentConfirm) } else { match status { storage_enums::IntentStatus::RequiresConfirmation | storage_enums::IntentStatus::RequiresCustomerAction | storage_enums::IntentStatus::RequiresPaymentMethod => Box::new(current), _ => Box::new(&PaymentStatus), } } } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="900" end="1094"> pub async fn proxy_for_payments_operation_core<F, Req, Op, FData, D>( state: &SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, profile_id_from_auth_layer: Option<id_type::ProfileId>, key_store: domain::MerchantKeyStore, operation: Op, req: Req, call_connector_action: CallConnectorAction, auth_flow: services::AuthFlow, header_payload: HeaderPayload, platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResult<(D, Req, Option<domain::Customer>, Option<u16>, Option<u128>)> where F: Send + Clone + Sync, Req: Authenticate + Clone, Op: Operation<F, Req, Data = D> + Send + Sync, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, // To create connector flow specific interface data D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>, RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>, // To perform router related operation for PaymentResponse PaymentResponse: Operation<F, FData, Data = D>, FData: Send + Sync + Clone, { let operation: BoxedOperation<'_, F, Req, D> = Box::new(operation); tracing::Span::current().record("merchant_id", merchant_account.get_id().get_string_repr()); let (operation, validate_result) = operation .to_validate_request()? .validate_request(&req, &merchant_account)?; tracing::Span::current().record("payment_id", format!("{}", validate_result.payment_id)); let operations::GetTrackerResponse { operation, customer_details: _, mut payment_data, business_profile, mandate_type: _, } = operation .to_get_tracker()? .get_trackers( state, &validate_result.payment_id, &req, &merchant_account, &key_store, auth_flow, &header_payload, platform_merchant_account.as_ref(), ) .await?; core_utils::validate_profile_id_from_auth_layer( profile_id_from_auth_layer, &payment_data.get_payment_intent().clone(), )?; common_utils::fp_utils::when(!should_call_connector(&operation, &payment_data), || { Err(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration).attach_printable(format!( "Nti and card details based mit flow is not support for this {operation:?} payment operation" )) })?; let connector_choice = operation .to_domain()? .get_connector( &merchant_account, &state.clone(), &req, payment_data.get_payment_intent(), &key_store, ) .await?; let connector = set_eligible_connector_for_nti_in_payment_data( state, &business_profile, &key_store, &mut payment_data, connector_choice, ) .await?; let should_add_task_to_process_tracker = should_add_task_to_process_tracker(&payment_data); let locale = header_payload.locale.clone(); let schedule_time = if should_add_task_to_process_tracker { payment_sync::get_sync_process_schedule_time( &*state.store, connector.connector.id(), merchant_account.get_id(), 0, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while getting process schedule time")? } else { None }; let (router_data, mca) = proxy_for_call_connector_service( state, req_state.clone(), &merchant_account, &key_store, connector.clone(), &operation, &mut payment_data, &None, call_connector_action.clone(), &validate_result, schedule_time, header_payload.clone(), &business_profile, ) .await?; let op_ref = &operation; let should_trigger_post_processing_flows = is_operation_confirm(&operation); let operation = Box::new(PaymentResponse); let connector_http_status_code = router_data.connector_http_status_code; let external_latency = router_data.external_latency; add_connector_http_status_code_metrics(connector_http_status_code); #[cfg(all(feature = "dynamic_routing", feature = "v1"))] let routable_connectors = convert_connector_data_to_routable_connectors(&[connector.clone()]) .map_err(|e| logger::error!(routable_connector_error=?e)) .unwrap_or_default(); let mut payment_data = operation .to_post_update_tracker()? .update_tracker( state, payment_data, router_data, &key_store, merchant_account.storage_scheme, &locale, #[cfg(all(feature = "dynamic_routing", feature = "v1"))] routable_connectors, #[cfg(all(feature = "dynamic_routing", feature = "v1"))] &business_profile, ) .await?; if should_trigger_post_processing_flows { complete_postprocessing_steps_if_required( state, &merchant_account, &key_store, &None, &mca, &connector, &mut payment_data, op_ref, Some(header_payload.clone()), ) .await?; } let cloned_payment_data = payment_data.clone(); utils::trigger_payments_webhook( merchant_account, business_profile, &key_store, cloned_payment_data, None, state, operation, ) .await .map_err(|error| logger::warn!(payments_outgoing_webhook_error=?error)) .ok(); Ok(( payment_data, req, None, connector_http_status_code, external_latency, )) } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="6040" end="6119"> pub async fn get_connector_choice<F, Req, D>( operation: &BoxedOperation<'_, F, Req, D>, state: &SessionState, req: &Req, merchant_account: &domain::MerchantAccount, business_profile: &domain::Profile, key_store: &domain::MerchantKeyStore, payment_data: &mut D, eligible_connectors: Option<Vec<enums::RoutableConnectors>>, mandate_type: Option<api::MandateTransactionType>, ) -> RouterResult<Option<ConnectorCallType>> where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { let connector_choice = operation .to_domain()? .get_connector( merchant_account, &state.clone(), req, payment_data.get_payment_intent(), key_store, ) .await?; let connector = if should_call_connector(operation, payment_data) { Some(match connector_choice { api::ConnectorChoice::SessionMultiple(connectors) => { let routing_output = perform_session_token_routing( state.clone(), merchant_account, business_profile, key_store, payment_data, connectors, ) .await?; ConnectorCallType::SessionMultiple(routing_output) } api::ConnectorChoice::StraightThrough(straight_through) => { connector_selection( state, merchant_account, business_profile, key_store, payment_data, Some(straight_through), eligible_connectors, mandate_type, ) .await? } api::ConnectorChoice::Decide => { connector_selection( state, merchant_account, business_profile, key_store, payment_data, None, eligible_connectors, mandate_type, ) .await? } }) } else if let api::ConnectorChoice::StraightThrough(algorithm) = connector_choice { update_straight_through_routing(payment_data, algorithm) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update straight through routing algorithm")?; None } else { None }; Ok(connector) } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="8013" end="8052"> pub trait OperationSessionGetters<F> { fn get_payment_attempt(&self) -> &storage::PaymentAttempt; fn get_payment_intent(&self) -> &storage::PaymentIntent; fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod>; fn get_mandate_id(&self) -> Option<&payments_api::MandateIds>; fn get_address(&self) -> &PaymentAddress; fn get_creds_identifier(&self) -> Option<&str>; fn get_token(&self) -> Option<&str>; fn get_multiple_capture_data(&self) -> Option<&types::MultipleCaptureData>; fn get_payment_link_data(&self) -> Option<api_models::payments::PaymentLinkResponse>; fn get_ephemeral_key(&self) -> Option<ephemeral_key::EphemeralKey>; fn get_setup_mandate(&self) -> Option<&MandateData>; fn get_poll_config(&self) -> Option<router_types::PollConfig>; fn get_authentication(&self) -> Option<&storage::Authentication>; fn get_frm_message(&self) -> Option<FraudCheck>; fn get_refunds(&self) -> Vec<storage::Refund>; fn get_disputes(&self) -> Vec<storage::Dispute>; fn get_authorizations(&self) -> Vec<diesel_models::authorization::Authorization>; fn get_attempts(&self) -> Option<Vec<storage::PaymentAttempt>>; fn get_recurring_details(&self) -> Option<&RecurringDetails>; // TODO: this should be a mandatory field, should we throw an error instead of returning an Option? fn get_payment_intent_profile_id(&self) -> Option<&id_type::ProfileId>; fn get_currency(&self) -> storage_enums::Currency; fn get_amount(&self) -> api::Amount; fn get_payment_attempt_connector(&self) -> Option<&str>; fn get_billing_address(&self) -> Option<hyperswitch_domain_models::address::Address>; fn get_payment_method_data(&self) -> Option<&domain::PaymentMethodData>; fn get_sessions_token(&self) -> Vec<api::SessionToken>; fn get_token_data(&self) -> Option<&storage::PaymentTokenData>; fn get_mandate_connector(&self) -> Option<&MandateConnectorDetails>; fn get_force_sync(&self) -> Option<bool>; fn get_capture_method(&self) -> Option<enums::CaptureMethod>; fn get_merchant_connector_id_in_attempt(&self) -> Option<id_type::MerchantConnectorAccountId>; #[cfg(feature = "v1")] fn get_vault_operation(&self) -> Option<&domain_payments::VaultOperation>; #[cfg(feature = "v2")] fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt>; } <file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_start.rs" role="context" start="27" end="27"> pub struct PaymentStart; <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/routing.rs<|crate|> router anchor=link_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="335" end="402"> pub async fn link_routing_config_under_profile( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, profile_id: common_utils::id_type::ProfileId, algorithm_id: common_utils::id_type::RoutingId, transaction_type: &enums::TransactionType, ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { metrics::ROUTING_LINK_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?; utils::when(routing_algorithm.0.profile_id != profile_id, || { Err(errors::ApiErrorResponse::PreconditionFailed { message: "Profile Id is invalid for the routing config".to_string(), }) })?; 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")?; utils::when( routing_algorithm.0.algorithm_for != *transaction_type, || { Err(errors::ApiErrorResponse::PreconditionFailed { message: format!( "Cannot use {}'s routing algorithm for {} operation", routing_algorithm.0.algorithm_for, transaction_type ), }) }, )?; utils::when( business_profile.routing_algorithm_id == Some(algorithm_id.clone()) || business_profile.payout_routing_algorithm_id == Some(algorithm_id.clone()), || { Err(errors::ApiErrorResponse::PreconditionFailed { message: "Algorithm is already active".to_string(), }) }, )?; 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_LINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json( routing_algorithm.0.foreign_into(), )) } <file_sep path="hyperswitch/crates/router/src/core/routing.rs" role="context" start="334" end="334"> let record = db .insert_routing_algorithm(algo) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; let new_record = record.foreign_into(); metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json(new_record)) } #[cfg(feature = "v2")] pub async fn link_routing_config_under_profile( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, profile_id: common_utils::id_type::ProfileId, algorithm_id: common_utils::id_type::RoutingId, transaction_type: &enums::TransactionType, ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { metrics::ROUTING_LINK_CONFIG.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let routing_algorithm = <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="405" end="593"> pub async fn link_routing_config( 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, transaction_type: &enums::TransactionType, ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { metrics::ROUTING_LINK_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 .change_context(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::ProfileNotFound { id: routing_algorithm.profile_id.get_string_repr().to_owned(), })?; core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?; match routing_algorithm.kind { diesel_models::enums::RoutingAlgorithmKind::Dynamic => { let mut dynamic_routing_ref: routing_types::DynamicRoutingAlgorithmRef = business_profile .dynamic_routing_algorithm .clone() .map(|val| val.parse_value("DynamicRoutingAlgorithmRef")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "unable to deserialize Dynamic routing algorithm ref from business profile", )? .unwrap_or_default(); utils::when( matches!( dynamic_routing_ref.success_based_algorithm, Some(routing::SuccessBasedAlgorithm { algorithm_id_with_timestamp: routing_types::DynamicAlgorithmWithTimestamp { algorithm_id: Some(ref id), timestamp: _ }, enabled_feature: _ }) if id == &algorithm_id ) || matches!( dynamic_routing_ref.elimination_routing_algorithm, Some(routing::EliminationRoutingAlgorithm { algorithm_id_with_timestamp: routing_types::DynamicAlgorithmWithTimestamp { algorithm_id: Some(ref id), timestamp: _ }, enabled_feature: _ }) if id == &algorithm_id ) || matches!( dynamic_routing_ref.contract_based_routing, Some(routing::ContractRoutingAlgorithm { algorithm_id_with_timestamp: routing_types::DynamicAlgorithmWithTimestamp { algorithm_id: Some(ref id), timestamp: _ }, enabled_feature: _ }) if id == &algorithm_id ), || { Err(errors::ApiErrorResponse::PreconditionFailed { message: "Algorithm is already active".to_string(), }) }, )?; if routing_algorithm.name == helpers::SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM { dynamic_routing_ref.update_algorithm_id( algorithm_id, dynamic_routing_ref .success_based_algorithm .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable( "missing success_based_algorithm in dynamic_algorithm_ref from business_profile table", )? .enabled_feature, routing_types::DynamicRoutingType::SuccessRateBasedRouting, ); } else if routing_algorithm.name == helpers::ELIMINATION_BASED_DYNAMIC_ROUTING_ALGORITHM { dynamic_routing_ref.update_algorithm_id( algorithm_id, dynamic_routing_ref .elimination_routing_algorithm .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable( "missing elimination_routing_algorithm in dynamic_algorithm_ref from business_profile table", )? .enabled_feature, routing_types::DynamicRoutingType::EliminationRouting, ); } else if routing_algorithm.name == helpers::CONTRACT_BASED_DYNAMIC_ROUTING_ALGORITHM { dynamic_routing_ref.update_algorithm_id( algorithm_id, dynamic_routing_ref .contract_based_routing .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable( "missing contract_based_routing in dynamic_algorithm_ref from business_profile table", )? .enabled_feature, routing_types::DynamicRoutingType::ContractBasedRouting, ); } helpers::update_business_profile_active_dynamic_algorithm_ref( db, key_manager_state, &key_store, business_profile, dynamic_routing_ref, ) .await?; } diesel_models::enums::RoutingAlgorithmKind::Single | diesel_models::enums::RoutingAlgorithmKind::Priority | diesel_models::enums::RoutingAlgorithmKind::Advanced | diesel_models::enums::RoutingAlgorithmKind::VolumeSplit => { let mut routing_ref: routing_types::RoutingAlgorithmRef = business_profile .routing_algorithm .clone() .map(|val| val.parse_value("RoutingAlgorithmRef")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "unable to deserialize routing algorithm ref from business profile", )? .unwrap_or_default(); utils::when(routing_algorithm.algorithm_for != *transaction_type, || { Err(errors::ApiErrorResponse::PreconditionFailed { message: format!( "Cannot use {}'s routing algorithm for {} operation", routing_algorithm.algorithm_for, transaction_type ), }) })?; utils::when( routing_ref.algorithm_id == Some(algorithm_id.clone()), || { Err(errors::ApiErrorResponse::PreconditionFailed { message: "Algorithm is already active".to_string(), }) }, )?; routing_ref.update_algorithm_id(algorithm_id); helpers::update_profile_active_algorithm_ref( db, key_manager_state, &key_store, business_profile, routing_ref, transaction_type, ) .await?; } }; metrics::ROUTING_LINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json( routing_algorithm.foreign_into(), )) } <file_sep path="hyperswitch/crates/router/src/core/routing.rs" role="context" start="245" end="332"> pub async fn create_routing_algorithm_under_profile( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, authentication_profile_id: Option<common_utils::id_type::ProfileId>, request: routing_types::RoutingConfigRequest, transaction_type: enums::TransactionType, ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { metrics::ROUTING_CREATE_REQUEST_RECEIVED.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let name = request .name .get_required_value("name") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "name" }) .attach_printable("Name of config not given")?; let description = request .description .get_required_value("description") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "description", }) .attach_printable("Description of config not given")?; let algorithm = request .algorithm .get_required_value("algorithm") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "algorithm", }) .attach_printable("Algorithm of config not given")?; let algorithm_id = common_utils::generate_routing_id_of_default_length(); 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? .get_required_value("Profile")?; core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?; helpers::validate_connectors_in_routing_config( &state, &key_store, merchant_account.get_id(), &profile_id, &algorithm, ) .await?; let timestamp = common_utils::date_time::now(); let algo = RoutingAlgorithm { algorithm_id: algorithm_id.clone(), profile_id, merchant_id: merchant_account.get_id().to_owned(), name: name.clone(), description: Some(description.clone()), kind: algorithm.get_kind().foreign_into(), algorithm_data: serde_json::json!(algorithm), created_at: timestamp, modified_at: timestamp, algorithm_for: transaction_type.to_owned(), }; let record = db .insert_routing_algorithm(algo) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; let new_record = record.foreign_into(); metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json(new_record)) } <file_sep path="hyperswitch/crates/router/src/core/routing.rs" role="context" start="170" end="242"> pub async fn create_routing_algorithm_under_profile( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, authentication_profile_id: Option<common_utils::id_type::ProfileId>, request: routing_types::RoutingConfigRequest, transaction_type: enums::TransactionType, ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { metrics::ROUTING_CREATE_REQUEST_RECEIVED.add(1, &[]); let db = &*state.store; let key_manager_state = &(&state).into(); let business_profile = core_utils::validate_and_get_business_profile( db, key_manager_state, &key_store, Some(&request.profile_id), merchant_account.get_id(), ) .await? .get_required_value("Profile")?; let merchant_id = merchant_account.get_id(); core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?; let all_mcas = state .store .find_merchant_connector_account_by_merchant_id_and_disabled_list( key_manager_state, merchant_id, true, &key_store, ) .await .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_id.get_string_repr().to_owned(), })?; let name_mca_id_set = helpers::ConnectNameAndMCAIdForProfile( all_mcas.filter_by_profile(business_profile.get_id(), |mca| { (&mca.connector_name, mca.get_id()) }), ); let name_set = helpers::ConnectNameForProfile( all_mcas.filter_by_profile(business_profile.get_id(), |mca| &mca.connector_name), ); let algorithm_helper = helpers::RoutingAlgorithmHelpers { name_mca_id_set, name_set, routing_algorithm: &request.algorithm, }; algorithm_helper.validate_connectors_in_routing_config()?; let algo = RoutingAlgorithmUpdate::create_new_routing_algorithm( &request, merchant_account.get_id(), business_profile.get_id().to_owned(), transaction_type, ); let record = state .store .as_ref() .insert_routing_algorithm(algo.0) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; let new_record = record.foreign_into(); metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json(new_record)) } <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="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="97" end="97"> struct RoutingAlgorithmUpdate(RoutingAlgorithm); <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/retry.rs<|crate|> router anchor=do_retry kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payments/retry.rs" role="context" start="316" end="380"> pub async fn do_retry<F, ApiRequest, FData, D>( state: &routes::SessionState, req_state: ReqState, connector: &api::ConnectorData, operation: &operations::BoxedOperation<'_, F, ApiRequest, D>, customer: &Option<domain::Customer>, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, payment_data: &mut D, router_data: types::RouterData<F, FData, types::PaymentsResponseData>, validate_result: &operations::ValidateResult, schedule_time: Option<time::PrimitiveDateTime>, is_step_up: bool, frm_suggestion: Option<storage_enums::FrmSuggestion>, business_profile: &domain::Profile, should_retry_with_pan: bool, ) -> RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>> where F: Clone + Send + Sync, FData: Send + Sync, payments::PaymentResponse: operations::Operation<F, FData>, D: payments::OperationSessionGetters<F> + payments::OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, FData, types::PaymentsResponseData>, types::RouterData<F, FData, types::PaymentsResponseData>: Feature<F, FData>, dyn api::Connector: services::api::ConnectorIntegration<F, FData, types::PaymentsResponseData>, { metrics::AUTO_RETRY_PAYMENT_COUNT.add(1, &[]); modify_trackers( state, connector.connector_name.to_string(), payment_data, key_store, merchant_account.storage_scheme, router_data, is_step_up, ) .await?; let (router_data, _mca) = payments::call_connector_service( state, req_state, merchant_account, key_store, connector.clone(), operation, payment_data, customer, payments::CallConnectorAction::Trigger, validate_result, schedule_time, hyperswitch_domain_models::payments::HeaderPayload::default(), frm_suggestion, business_profile, true, should_retry_with_pan, ) .await?; Ok(router_data) } <file_sep path="hyperswitch/crates/router/src/core/payments/retry.rs" role="context" start="315" end="315"> use common_utils::{ext_traits::Encode, types::MinorUnit}; use diesel_models::enums as storage_enums; use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payments::{ self, flows::{ConstructFlowSpecificData, Feature}, operations, }, }, db::StorageInterface, routes::{ self, app::{self, ReqState}, metrics, }, services, types::{self, api, domain, storage}, }; <file_sep path="hyperswitch/crates/router/src/core/payments/retry.rs" role="context" start="403" end="608"> pub async fn modify_trackers<F, FData, D>( state: &routes::SessionState, connector: String, payment_data: &mut D, key_store: &domain::MerchantKeyStore, storage_scheme: storage_enums::MerchantStorageScheme, router_data: types::RouterData<F, FData, types::PaymentsResponseData>, is_step_up: bool, ) -> RouterResult<()> where F: Clone + Send, FData: Send, D: payments::OperationSessionGetters<F> + payments::OperationSessionSetters<F> + Send + Sync, { let new_attempt_count = payment_data.get_payment_intent().attempt_count + 1; let new_payment_attempt = make_new_payment_attempt( connector, payment_data.get_payment_attempt().clone(), new_attempt_count, is_step_up, ); let db = &*state.store; let key_manager_state = &state.into(); let additional_payment_method_data = payments::helpers::update_additional_payment_data_with_connector_response_pm_data( payment_data .get_payment_attempt() .payment_method_data .clone(), router_data .connector_response .clone() .and_then(|connector_response| connector_response.additional_payment_method_data), )?; match router_data.response { Ok(types::PaymentsResponseData::TransactionResponse { resource_id, connector_metadata, redirection_data, charges, .. }) => { let encoded_data = payment_data.get_payment_attempt().encoded_data.clone(); let authentication_data = (*redirection_data) .as_ref() .map(Encode::encode_to_value) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not parse the connector response")?; let payment_attempt_update = storage::PaymentAttemptUpdate::ResponseUpdate { status: router_data.status, connector: None, connector_transaction_id: match resource_id { types::ResponseId::NoResponseId => None, types::ResponseId::ConnectorTransactionId(id) | types::ResponseId::EncodedData(id) => Some(id), }, connector_response_reference_id: payment_data .get_payment_attempt() .connector_response_reference_id .clone(), authentication_type: None, payment_method_id: payment_data.get_payment_attempt().payment_method_id.clone(), mandate_id: payment_data .get_mandate_id() .and_then(|mandate| mandate.mandate_id.clone()), connector_metadata, payment_token: None, error_code: None, error_message: None, error_reason: None, amount_capturable: if router_data.status.is_terminal_status() { Some(MinorUnit::new(0)) } else { None }, updated_by: storage_scheme.to_string(), authentication_data, encoded_data, unified_code: None, unified_message: None, capture_before: None, extended_authorization_applied: None, payment_method_data: additional_payment_method_data, connector_mandate_detail: None, charges, }; #[cfg(feature = "v1")] db.update_payment_attempt_with_attempt_id( payment_data.get_payment_attempt().clone(), payment_attempt_update, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; #[cfg(feature = "v2")] db.update_payment_attempt_with_attempt_id( key_manager_state, key_store, payment_data.get_payment_attempt().clone(), payment_attempt_update, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; } Ok(_) => { logger::error!("unexpected response: this response was not expected in Retry flow"); return Ok(()); } Err(ref error_response) => { let option_gsm = get_gsm(state, &router_data).await?; let auth_update = if Some(router_data.auth_type) != payment_data.get_payment_attempt().authentication_type { Some(router_data.auth_type) } else { None }; let payment_attempt_update = storage::PaymentAttemptUpdate::ErrorUpdate { connector: None, error_code: Some(Some(error_response.code.clone())), error_message: Some(Some(error_response.message.clone())), status: storage_enums::AttemptStatus::Failure, error_reason: Some(error_response.reason.clone()), amount_capturable: Some(MinorUnit::new(0)), updated_by: storage_scheme.to_string(), unified_code: option_gsm.clone().map(|gsm| gsm.unified_code), unified_message: option_gsm.map(|gsm| gsm.unified_message), connector_transaction_id: error_response.connector_transaction_id.clone(), payment_method_data: additional_payment_method_data, authentication_type: auth_update, issuer_error_code: error_response.network_decline_code.clone(), issuer_error_message: error_response.network_error_message.clone(), }; #[cfg(feature = "v1")] db.update_payment_attempt_with_attempt_id( payment_data.get_payment_attempt().clone(), payment_attempt_update, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; #[cfg(feature = "v2")] db.update_payment_attempt_with_attempt_id( key_manager_state, key_store, payment_data.get_payment_attempt().clone(), payment_attempt_update, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; } } #[cfg(feature = "v1")] let payment_attempt = db .insert_payment_attempt(new_payment_attempt, storage_scheme) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error inserting payment attempt")?; #[cfg(feature = "v2")] let payment_attempt = db .insert_payment_attempt( key_manager_state, key_store, new_payment_attempt, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error inserting payment attempt")?; // update payment_attempt, connector_response and payment_intent in payment_data payment_data.set_payment_attempt(payment_attempt); let payment_intent = db .update_payment_intent( key_manager_state, payment_data.get_payment_intent().clone(), storage::PaymentIntentUpdate::PaymentAttemptAndAttemptCountUpdate { active_attempt_id: payment_data.get_payment_attempt().get_id().to_owned(), attempt_count: new_attempt_count, updated_by: storage_scheme.to_string(), }, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; payment_data.set_payment_intent(payment_intent); Ok(()) } <file_sep path="hyperswitch/crates/router/src/core/payments/retry.rs" role="context" start="384" end="399"> pub async fn modify_trackers<F, FData, D>( state: &routes::SessionState, connector: String, payment_data: &mut D, key_store: &domain::MerchantKeyStore, storage_scheme: storage_enums::MerchantStorageScheme, router_data: types::RouterData<F, FData, types::PaymentsResponseData>, is_step_up: bool, ) -> RouterResult<()> where F: Clone + Send, FData: Send, D: payments::OperationSessionGetters<F> + payments::OperationSessionSetters<F> + Send + Sync, { todo!() } <file_sep path="hyperswitch/crates/router/src/core/payments/retry.rs" role="context" start="303" end="311"> fn get_flow_name<F>() -> RouterResult<String> { Ok(std::any::type_name::<F>() .to_string() .rsplit("::") .next() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Flow stringify failed")? .to_string()) } <file_sep path="hyperswitch/crates/router/src/core/payments/retry.rs" role="context" start="281" end="300"> pub fn get_gsm_decision( option_gsm: Option<storage::gsm::GatewayStatusMap>, ) -> api_models::gsm::GsmDecision { let option_gsm_decision = option_gsm .and_then(|gsm| { api_models::gsm::GsmDecision::from_str(gsm.decision.as_str()) .map_err(|err| { let api_error = report!(err).change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("gsm decision parsing failed"); logger::warn!(get_gsm_decision_parse_error=?api_error, "error fetching gsm decision"); api_error }) .ok() }); if option_gsm_decision.is_some() { metrics::AUTO_RETRY_GSM_MATCH_COUNT.add(1, &[]); } option_gsm_decision.unwrap_or_default() } <file_sep path="hyperswitch/crates/router/src/core/payments/retry.rs" role="context" start="33" end="198"> pub async fn do_gsm_actions<F, ApiRequest, FData, D>( state: &app::SessionState, req_state: ReqState, payment_data: &mut D, mut connectors: IntoIter<api::ConnectorData>, original_connector_data: &api::ConnectorData, mut router_data: types::RouterData<F, FData, types::PaymentsResponseData>, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, operation: &operations::BoxedOperation<'_, F, ApiRequest, D>, customer: &Option<domain::Customer>, validate_result: &operations::ValidateResult, schedule_time: Option<time::PrimitiveDateTime>, frm_suggestion: Option<storage_enums::FrmSuggestion>, business_profile: &domain::Profile, ) -> RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>> where F: Clone + Send + Sync, FData: Send + Sync, payments::PaymentResponse: operations::Operation<F, FData>, D: payments::OperationSessionGetters<F> + payments::OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, FData, types::PaymentsResponseData>, types::RouterData<F, FData, types::PaymentsResponseData>: Feature<F, FData>, dyn api::Connector: services::api::ConnectorIntegration<F, FData, types::PaymentsResponseData>, { let mut retries = None; metrics::AUTO_RETRY_ELIGIBLE_REQUEST_COUNT.add(1, &[]); let mut initial_gsm = get_gsm(state, &router_data).await?; //Check if step-up to threeDS is possible and merchant has enabled let step_up_possible = initial_gsm .clone() .map(|gsm| gsm.step_up_possible) .unwrap_or(false); #[cfg(feature = "v1")] let is_no_three_ds_payment = matches!( payment_data.get_payment_attempt().authentication_type, Some(storage_enums::AuthenticationType::NoThreeDs) ); #[cfg(feature = "v2")] let is_no_three_ds_payment = matches!( payment_data.get_payment_attempt().authentication_type, storage_enums::AuthenticationType::NoThreeDs ); let should_step_up = if step_up_possible && is_no_three_ds_payment { is_step_up_enabled_for_merchant_connector( state, merchant_account.get_id(), original_connector_data.connector_name, ) .await } else { false }; if should_step_up { router_data = do_retry( &state.clone(), req_state.clone(), original_connector_data, operation, customer, merchant_account, key_store, payment_data, router_data, validate_result, schedule_time, true, frm_suggestion, business_profile, false, //should_retry_with_pan is not applicable for step-up ) .await?; } // Step up is not applicable so proceed with auto retries flow else { loop { // Use initial_gsm for first time alone let gsm = match initial_gsm.as_ref() { Some(gsm) => Some(gsm.clone()), None => get_gsm(state, &router_data).await?, }; match get_gsm_decision(gsm) { api_models::gsm::GsmDecision::Retry => { retries = get_retries(state, retries, merchant_account.get_id(), business_profile) .await; if retries.is_none() || retries == Some(0) { metrics::AUTO_RETRY_EXHAUSTED_COUNT.add(1, &[]); logger::info!("retries exhausted for auto_retry payment"); break; } if connectors.len() == 0 { logger::info!("connectors exhausted for auto_retry payment"); metrics::AUTO_RETRY_EXHAUSTED_COUNT.add(1, &[]); break; } let is_network_token = payment_data .get_payment_method_data() .map(|pmd| pmd.is_network_token_payment_method_data()) .unwrap_or(false); let should_retry_with_pan = is_network_token && initial_gsm .as_ref() .map(|gsm| gsm.clear_pan_possible) .unwrap_or(false) && business_profile.is_clear_pan_retries_enabled; let connector = if should_retry_with_pan { // If should_retry_with_pan is true, it indicates that we are retrying with PAN using the same connector. original_connector_data.clone() } else { super::get_connector_data(&mut connectors)? }; router_data = do_retry( &state.clone(), req_state.clone(), &connector, operation, customer, merchant_account, key_store, payment_data, router_data, validate_result, schedule_time, //this is an auto retry payment, but not step-up false, frm_suggestion, business_profile, should_retry_with_pan, ) .await?; retries = retries.map(|i| i - 1); } api_models::gsm::GsmDecision::Requeue => { Err(report!(errors::ApiErrorResponse::NotImplemented { message: errors::NotImplementedMessage::Reason( "Requeue not implemented".to_string(), ), }))? } api_models::gsm::GsmDecision::DoDefault => break, } initial_gsm = None; } } Ok(router_data) } <file_sep path="hyperswitch/crates/router/src/core/payments/flows.rs" role="context" start="86" end="193"> pub trait Feature<F, T> { 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> where Self: Sized, F: Clone, dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>; async fn add_access_token<'a>( &self, state: &SessionState, connector: &api::ConnectorData, merchant_account: &domain::MerchantAccount, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> where F: Clone, Self: Sized, dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>; async fn add_session_token<'a>( self, _state: &SessionState, _connector: &api::ConnectorData, ) -> RouterResult<Self> where F: Clone, Self: Sized, dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>, { Ok(self) } async fn add_payment_method_token<'a>( &mut self, _state: &SessionState, _connector: &api::ConnectorData, _tokenization_action: &payments::TokenizationAction, _should_continue_payment: bool, ) -> RouterResult<types::PaymentMethodTokenResult> where F: Clone, Self: Sized, dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>, { Ok(types::PaymentMethodTokenResult { payment_method_token_result: Ok(None), is_payment_method_tokenization_performed: false, connector_response: None, }) } async fn preprocessing_steps<'a>( self, _state: &SessionState, _connector: &api::ConnectorData, ) -> RouterResult<Self> where F: Clone, Self: Sized, dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>, { Ok(self) } async fn postprocessing_steps<'a>( self, _state: &SessionState, _connector: &api::ConnectorData, ) -> RouterResult<Self> where F: Clone, Self: Sized, dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>, { Ok(self) } async fn create_connector_customer<'a>( &self, _state: &SessionState, _connector: &api::ConnectorData, ) -> RouterResult<Option<String>> where F: Clone, Self: Sized, dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>, { Ok(None) } /// Returns the connector request and a bool which specifies whether to proceed with further async fn build_flow_specific_connector_request( &mut self, _state: &SessionState, _connector: &api::ConnectorData, _call_connector_action: payments::CallConnectorAction, ) -> RouterResult<(Option<services::Request>, bool)> { Ok((None, true)) } } <file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="1" end="11"> -- This file contains all new columns being added as part of v2 refactoring. -- The new columns added should work with both v1 and v2 applications. ALTER TABLE customers ADD COLUMN IF NOT EXISTS merchant_reference_id VARCHAR(64), ADD COLUMN IF NOT EXISTS default_billing_address BYTEA DEFAULT NULL, ADD COLUMN IF NOT EXISTS default_shipping_address BYTEA DEFAULT NULL, ADD COLUMN IF NOT EXISTS status "DeleteStatus"; CREATE TYPE "OrderFulfillmentTimeOrigin" AS ENUM ('create', 'confirm'); ALTER TABLE business_profile
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments.rs<|crate|> router anchor=complete_postprocessing_steps_if_required kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="4632" end="4695"> async fn complete_postprocessing_steps_if_required<F, Q, RouterDReq, D>( state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_conn_account: &helpers::MerchantConnectorAccountType, connector: &api::ConnectorData, payment_data: &mut D, _operation: &BoxedOperation<'_, F, Q, D>, header_payload: Option<HeaderPayload>, ) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>> where F: Send + Clone + Sync, RouterDReq: Send + Sync, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send, dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, { let mut router_data = payment_data .construct_router_data( state, connector.connector.id(), merchant_account, key_store, customer, merchant_conn_account, None, header_payload, ) .await?; match payment_data.get_payment_method_data() { Some(domain::PaymentMethodData::OpenBanking(domain::OpenBankingData::OpenBankingPIS { .. })) => { if connector.connector_name == router_types::Connector::Plaid { router_data = router_data.postprocessing_steps(state, connector).await?; let token = if let Ok(ref res) = router_data.response { match res { router_types::PaymentsResponseData::PostProcessingResponse { session_token, } => session_token .as_ref() .map(|token| api::SessionToken::OpenBanking(token.clone())), _ => None, } } else { None }; if let Some(t) = token { payment_data.push_sessions_token(t); } Ok(router_data) } else { Ok(router_data) } } _ => Ok(router_data), } } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="4631" end="4631"> (router_data, !is_error_in_response) } else { (router_data, should_continue_payment) } } }; Ok(router_data_and_should_continue_payment) } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] async fn complete_postprocessing_steps_if_required<F, Q, RouterDReq, D>( state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_conn_account: &helpers::MerchantConnectorAccountType, connector: &api::ConnectorData, payment_data: &mut D, _operation: &BoxedOperation<'_, F, Q, D>, header_payload: Option<HeaderPayload>, ) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>> where F: Send + Clone + Sync, <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="4703" end="4740"> pub async fn construct_profile_id_and_get_mca<'a, F, D>( state: &'a SessionState, merchant_account: &domain::MerchantAccount, payment_data: &D, connector_name: &str, merchant_connector_id: Option<&id_type::MerchantConnectorAccountId>, key_store: &domain::MerchantKeyStore, _should_validate: bool, ) -> RouterResult<helpers::MerchantConnectorAccountType> where F: Clone, D: OperationSessionGetters<F> + Send + Sync + Clone, { let profile_id = payment_data .get_payment_intent() .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("profile_id is not set in payment_intent")? .clone(); #[cfg(feature = "v2")] let profile_id = payment_data.get_payment_intent().profile_id.clone(); let merchant_connector_account = helpers::get_merchant_connector_account( state, merchant_account.get_id(), payment_data.get_creds_identifier(), key_store, &profile_id, connector_name, merchant_connector_id, ) .await?; Ok(merchant_connector_account) } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="4697" end="4699"> pub fn is_preprocessing_required_for_wallets(connector_name: String) -> bool { connector_name == *"trustpay" || connector_name == *"payme" } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="4464" end="4628"> async fn complete_preprocessing_steps_if_required<F, Req, Q, D>( state: &SessionState, connector: &api::ConnectorData, payment_data: &D, mut router_data: RouterData<F, Req, router_types::PaymentsResponseData>, operation: &BoxedOperation<'_, F, Q, D>, should_continue_payment: bool, ) -> RouterResult<(RouterData<F, Req, router_types::PaymentsResponseData>, bool)> where F: Send + Clone + Sync, D: OperationSessionGetters<F> + Send + Sync + Clone, Req: Send + Sync, RouterData<F, Req, router_types::PaymentsResponseData>: Feature<F, Req> + Send, dyn api::Connector: services::api::ConnectorIntegration<F, Req, router_types::PaymentsResponseData>, { if !is_operation_complete_authorize(&operation) && connector .connector_name .is_pre_processing_required_before_authorize() { router_data = router_data.preprocessing_steps(state, connector).await?; return Ok((router_data, should_continue_payment)); } //TODO: For ACH transfers, if preprocessing_step is not required for connectors encountered in future, add the check let router_data_and_should_continue_payment = match payment_data.get_payment_method_data() { Some(domain::PaymentMethodData::BankTransfer(_)) => (router_data, should_continue_payment), Some(domain::PaymentMethodData::Wallet(_)) => { if is_preprocessing_required_for_wallets(connector.connector_name.to_string()) { ( router_data.preprocessing_steps(state, connector).await?, false, ) } else { (router_data, should_continue_payment) } } Some(domain::PaymentMethodData::Card(_)) => { if connector.connector_name == router_types::Connector::Payme && !matches!(format!("{operation:?}").as_str(), "CompleteAuthorize") { router_data = router_data.preprocessing_steps(state, connector).await?; let is_error_in_response = router_data.response.is_err(); // If is_error_in_response is true, should_continue_payment should be false, we should throw the error (router_data, !is_error_in_response) } else if connector.connector_name == router_types::Connector::Nmi && !matches!(format!("{operation:?}").as_str(), "CompleteAuthorize") && router_data.auth_type == storage_enums::AuthenticationType::ThreeDs && !matches!( payment_data .get_payment_attempt() .external_three_ds_authentication_attempted, Some(true) ) { router_data = router_data.preprocessing_steps(state, connector).await?; (router_data, false) } else if connector.connector_name == router_types::Connector::Cybersource && is_operation_complete_authorize(&operation) && router_data.auth_type == storage_enums::AuthenticationType::ThreeDs { router_data = router_data.preprocessing_steps(state, connector).await?; // Should continue the flow only if no redirection_data is returned else a response with redirection form shall be returned let should_continue = matches!( router_data.response, Ok(router_types::PaymentsResponseData::TransactionResponse { ref redirection_data, .. }) if redirection_data.is_none() ) && router_data.status != common_enums::AttemptStatus::AuthenticationFailed; (router_data, should_continue) } else if router_data.auth_type == common_enums::AuthenticationType::ThreeDs && ((connector.connector_name == router_types::Connector::Nexixpay && is_operation_complete_authorize(&operation)) || ((connector.connector_name == router_types::Connector::Nuvei || connector.connector_name == router_types::Connector::Shift4) && !is_operation_complete_authorize(&operation))) { router_data = router_data.preprocessing_steps(state, connector).await?; (router_data, should_continue_payment) } else if connector.connector_name == router_types::Connector::Xendit && is_operation_confirm(&operation) { match payment_data.get_payment_intent().split_payments { Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment( common_types::payments::XenditSplitRequest::MultipleSplits(_), )) => { router_data = router_data.preprocessing_steps(state, connector).await?; let is_error_in_response = router_data.response.is_err(); (router_data, !is_error_in_response) } _ => (router_data, should_continue_payment), } } else if connector.connector_name == router_types::Connector::Redsys && router_data.auth_type == common_enums::AuthenticationType::ThreeDs && is_operation_confirm(&operation) { router_data = router_data.preprocessing_steps(state, connector).await?; let should_continue = match router_data.response { Ok(router_types::PaymentsResponseData::TransactionResponse { ref connector_metadata, .. }) => { let three_ds_invoke_data: Option< api_models::payments::PaymentsConnectorThreeDsInvokeData, > = connector_metadata.clone().and_then(|metadata| { metadata .parse_value("PaymentsConnectorThreeDsInvokeData") .ok() // "ThreeDsInvokeData was not found; proceeding with the payment flow without triggering the ThreeDS invoke action" }); three_ds_invoke_data.is_none() } _ => false, }; (router_data, should_continue) } else { (router_data, should_continue_payment) } } Some(domain::PaymentMethodData::GiftCard(gift_card_data)) => { if connector.connector_name == router_types::Connector::Adyen && matches!(gift_card_data.deref(), domain::GiftCardData::Givex(..)) { router_data = router_data.preprocessing_steps(state, connector).await?; let is_error_in_response = router_data.response.is_err(); // If is_error_in_response is true, should_continue_payment should be false, we should throw the error (router_data, !is_error_in_response) } else { (router_data, should_continue_payment) } } Some(domain::PaymentMethodData::BankDebit(_)) => { if connector.connector_name == router_types::Connector::Gocardless { router_data = router_data.preprocessing_steps(state, connector).await?; let is_error_in_response = router_data.response.is_err(); // If is_error_in_response is true, should_continue_payment should be false, we should throw the error (router_data, !is_error_in_response) } else { (router_data, should_continue_payment) } } _ => { // 3DS validation for paypal cards after verification (authorize call) if connector.connector_name == router_types::Connector::Paypal && payment_data.get_payment_attempt().get_payment_method() == Some(storage_enums::PaymentMethod::Card) && matches!(format!("{operation:?}").as_str(), "CompleteAuthorize") { router_data = router_data.preprocessing_steps(state, connector).await?; let is_error_in_response = router_data.response.is_err(); // If is_error_in_response is true, should_continue_payment should be false, we should throw the error (router_data, !is_error_in_response) } else { (router_data, should_continue_payment) } } }; Ok(router_data_and_should_continue_payment) } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="4382" end="4462"> pub async fn call_create_connector_customer_if_required<F, Req, D>( state: &SessionState, customer: &Option<domain::Customer>, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, merchant_connector_account: &domain::MerchantConnectorAccount, payment_data: &mut D, ) -> RouterResult<Option<storage::CustomerUpdate>> where F: Send + Clone + Sync, Req: Send + Sync, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, Req, router_types::PaymentsResponseData>, RouterData<F, Req, router_types::PaymentsResponseData>: Feature<F, Req> + Send, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, Req, router_types::PaymentsResponseData>, { let connector_name = payment_data.get_payment_attempt().connector.clone(); match connector_name { Some(connector_name) => { let connector = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &connector_name, api::GetToken::Connector, Some(merchant_connector_account.get_id()), )?; let merchant_connector_id = merchant_connector_account.get_id(); let (should_call_connector, existing_connector_customer_id) = customers::should_call_connector_create_customer( state, &connector, customer, &merchant_connector_id, ); if should_call_connector { // Create customer at connector and update the customer table to store this data let router_data = payment_data .construct_router_data( state, connector.connector.id(), merchant_account, key_store, customer, merchant_connector_account, None, None, ) .await?; let connector_customer_id = router_data .create_connector_customer(state, &connector) .await?; let customer_update = customers::update_connector_customer_in_customers( merchant_connector_id, customer.as_ref(), connector_customer_id.clone(), ) .await; payment_data.set_connector_customer_id(connector_customer_id); Ok(customer_update) } else { // Customer already created in previous calls use the same value, no need to update payment_data.set_connector_customer_id( existing_connector_customer_id.map(ToOwned::to_owned), ); Ok(None) } } None => Ok(None), } } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="258" end="893"> pub async fn payments_operation_core<F, Req, Op, FData, D>( state: &SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, profile_id_from_auth_layer: Option<id_type::ProfileId>, key_store: domain::MerchantKeyStore, operation: Op, req: Req, call_connector_action: CallConnectorAction, auth_flow: services::AuthFlow, eligible_connectors: Option<Vec<common_enums::RoutableConnectors>>, header_payload: HeaderPayload, platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResult<(D, Req, Option<domain::Customer>, Option<u16>, Option<u128>)> where F: Send + Clone + Sync, Req: Authenticate + Clone, Op: Operation<F, Req, Data = D> + Send + Sync, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, // To create connector flow specific interface data D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>, RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>, // To perform router related operation for PaymentResponse PaymentResponse: Operation<F, FData, Data = D>, FData: Send + Sync + Clone, { let operation: BoxedOperation<'_, F, Req, D> = Box::new(operation); tracing::Span::current().record("merchant_id", merchant_account.get_id().get_string_repr()); let (operation, validate_result) = operation .to_validate_request()? .validate_request(&req, &merchant_account)?; tracing::Span::current().record("payment_id", format!("{}", validate_result.payment_id)); // get profile from headers let operations::GetTrackerResponse { operation, customer_details, mut payment_data, business_profile, mandate_type, } = operation .to_get_tracker()? .get_trackers( state, &validate_result.payment_id, &req, &merchant_account, &key_store, auth_flow, &header_payload, platform_merchant_account.as_ref(), ) .await?; operation .to_get_tracker()? .validate_request_with_state(state, &req, &mut payment_data, &business_profile) .await?; core_utils::validate_profile_id_from_auth_layer( profile_id_from_auth_layer, &payment_data.get_payment_intent().clone(), )?; let (operation, customer) = operation .to_domain()? // get_customer_details .get_or_create_customer_details( state, &mut payment_data, customer_details, &key_store, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound) .attach_printable("Failed while fetching/creating customer")?; let authentication_type = call_decision_manager(state, &merchant_account, &business_profile, &payment_data).await?; payment_data.set_authentication_type_in_attempt(authentication_type); let connector = get_connector_choice( &operation, state, &req, &merchant_account, &business_profile, &key_store, &mut payment_data, eligible_connectors, mandate_type, ) .await?; let should_add_task_to_process_tracker = should_add_task_to_process_tracker(&payment_data); let locale = header_payload.locale.clone(); payment_data = tokenize_in_router_when_confirm_false_or_external_authentication( state, &operation, &mut payment_data, &validate_result, &key_store, &customer, &business_profile, ) .await?; let mut connector_http_status_code = None; let mut external_latency = None; if let Some(connector_details) = connector { // Fetch and check FRM configs #[cfg(feature = "frm")] let mut frm_info = None; #[allow(unused_variables, unused_mut)] let mut should_continue_transaction: bool = true; #[cfg(feature = "frm")] let mut should_continue_capture: bool = true; #[cfg(feature = "frm")] let frm_configs = if state.conf.frm.enabled { Box::pin(frm_core::call_frm_before_connector_call( &operation, &merchant_account, &mut payment_data, state, &mut frm_info, &customer, &mut should_continue_transaction, &mut should_continue_capture, key_store.clone(), )) .await? } else { None }; #[cfg(feature = "frm")] logger::debug!( "frm_configs: {:?}\nshould_continue_transaction: {:?}\nshould_continue_capture: {:?}", frm_configs, should_continue_transaction, should_continue_capture, ); let is_eligible_for_uas = helpers::is_merchant_eligible_authentication_service(merchant_account.get_id(), state) .await?; if is_eligible_for_uas { let should_do_uas_confirmation_call = false; operation .to_domain()? .call_unified_authentication_service_if_eligible( state, &mut payment_data, &mut should_continue_transaction, &connector_details, &business_profile, &key_store, mandate_type, &should_do_uas_confirmation_call, ) .await?; } else { logger::info!( "skipping authentication service call since the merchant is not eligible." ); operation .to_domain()? .call_external_three_ds_authentication_if_eligible( state, &mut payment_data, &mut should_continue_transaction, &connector_details, &business_profile, &key_store, mandate_type, ) .await?; }; operation .to_domain()? .payments_dynamic_tax_calculation( state, &mut payment_data, &connector_details, &business_profile, &key_store, &merchant_account, ) .await?; if should_continue_transaction { #[cfg(feature = "frm")] match ( should_continue_capture, payment_data.get_payment_attempt().capture_method, ) { ( false, Some(storage_enums::CaptureMethod::Automatic) | Some(storage_enums::CaptureMethod::SequentialAutomatic), ) | (false, Some(storage_enums::CaptureMethod::Scheduled)) => { if let Some(info) = &mut frm_info { if let Some(frm_data) = &mut info.frm_data { frm_data.fraud_check.payment_capture_method = payment_data.get_payment_attempt().capture_method; } } payment_data .set_capture_method_in_attempt(storage_enums::CaptureMethod::Manual); logger::debug!("payment_id : {:?} capture method has been changed to manual, since it has configured Post FRM flow",payment_data.get_payment_attempt().payment_id); } _ => (), }; payment_data = match connector_details { ConnectorCallType::PreDetermined(ref connector) => { #[cfg(all(feature = "dynamic_routing", feature = "v1"))] let routable_connectors = convert_connector_data_to_routable_connectors(&[connector.clone()]) .map_err(|e| logger::error!(routable_connector_error=?e)) .unwrap_or_default(); let schedule_time = if should_add_task_to_process_tracker { payment_sync::get_sync_process_schedule_time( &*state.store, connector.connector.id(), merchant_account.get_id(), 0, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while getting process schedule time")? } else { None }; let (router_data, mca) = call_connector_service( state, req_state.clone(), &merchant_account, &key_store, connector.clone(), &operation, &mut payment_data, &customer, call_connector_action.clone(), &validate_result, schedule_time, header_payload.clone(), #[cfg(feature = "frm")] frm_info.as_ref().and_then(|fi| fi.suggested_action), #[cfg(not(feature = "frm"))] None, &business_profile, false, false, ) .await?; if is_eligible_for_uas { let should_do_uas_confirmation_call = true; operation .to_domain()? .call_unified_authentication_service_if_eligible( state, &mut payment_data, &mut should_continue_transaction, &connector_details, &business_profile, &key_store, mandate_type, &should_do_uas_confirmation_call, ) .await?; } let op_ref = &operation; let should_trigger_post_processing_flows = is_operation_confirm(&operation); let operation = Box::new(PaymentResponse); connector_http_status_code = router_data.connector_http_status_code; external_latency = router_data.external_latency; //add connector http status code metrics add_connector_http_status_code_metrics(connector_http_status_code); operation .to_post_update_tracker()? .save_pm_and_mandate( state, &router_data, &merchant_account, &key_store, &mut payment_data, &business_profile, ) .await?; let mut payment_data = operation .to_post_update_tracker()? .update_tracker( state, payment_data, router_data, &key_store, merchant_account.storage_scheme, &locale, #[cfg(all(feature = "dynamic_routing", feature = "v1"))] routable_connectors, #[cfg(all(feature = "dynamic_routing", feature = "v1"))] &business_profile, ) .await?; if should_trigger_post_processing_flows { complete_postprocessing_steps_if_required( state, &merchant_account, &key_store, &customer, &mca, connector, &mut payment_data, op_ref, Some(header_payload.clone()), ) .await?; } payment_data } ConnectorCallType::Retryable(ref connectors) => { #[cfg(all(feature = "dynamic_routing", feature = "v1"))] let routable_connectors = convert_connector_data_to_routable_connectors(connectors) .map_err(|e| logger::error!(routable_connector_error=?e)) .unwrap_or_default(); let mut connectors = connectors.clone().into_iter(); let connector_data = get_connector_data(&mut connectors)?; let schedule_time = if should_add_task_to_process_tracker { payment_sync::get_sync_process_schedule_time( &*state.store, connector_data.connector.id(), merchant_account.get_id(), 0, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while getting process schedule time")? } else { None }; let (router_data, mca) = call_connector_service( state, req_state.clone(), &merchant_account, &key_store, connector_data.clone(), &operation, &mut payment_data, &customer, call_connector_action.clone(), &validate_result, schedule_time, header_payload.clone(), #[cfg(feature = "frm")] frm_info.as_ref().and_then(|fi| fi.suggested_action), #[cfg(not(feature = "frm"))] None, &business_profile, false, false, ) .await?; #[cfg(all(feature = "retry", feature = "v1"))] let mut router_data = router_data; #[cfg(all(feature = "retry", feature = "v1"))] { use crate::core::payments::retry::{self, GsmValidation}; let config_bool = retry::config_should_call_gsm( &*state.store, merchant_account.get_id(), &business_profile, ) .await; if config_bool && router_data.should_call_gsm() { router_data = retry::do_gsm_actions( state, req_state.clone(), &mut payment_data, connectors, &connector_data, router_data, &merchant_account, &key_store, &operation, &customer, &validate_result, schedule_time, #[cfg(feature = "frm")] frm_info.as_ref().and_then(|fi| fi.suggested_action), #[cfg(not(feature = "frm"))] None, &business_profile, ) .await?; }; } let op_ref = &operation; let should_trigger_post_processing_flows = is_operation_confirm(&operation); if is_eligible_for_uas { let should_do_uas_confirmation_call = true; operation .to_domain()? .call_unified_authentication_service_if_eligible( state, &mut payment_data, &mut should_continue_transaction, &connector_details, &business_profile, &key_store, mandate_type, &should_do_uas_confirmation_call, ) .await?; } let operation = Box::new(PaymentResponse); connector_http_status_code = router_data.connector_http_status_code; external_latency = router_data.external_latency; //add connector http status code metrics add_connector_http_status_code_metrics(connector_http_status_code); operation .to_post_update_tracker()? .save_pm_and_mandate( state, &router_data, &merchant_account, &key_store, &mut payment_data, &business_profile, ) .await?; let mut payment_data = operation .to_post_update_tracker()? .update_tracker( state, payment_data, router_data, &key_store, merchant_account.storage_scheme, &locale, #[cfg(all(feature = "dynamic_routing", feature = "v1"))] routable_connectors, #[cfg(all(feature = "dynamic_routing", feature = "v1"))] &business_profile, ) .await?; if should_trigger_post_processing_flows { complete_postprocessing_steps_if_required( state, &merchant_account, &key_store, &customer, &mca, &connector_data, &mut payment_data, op_ref, Some(header_payload.clone()), ) .await?; } payment_data } ConnectorCallType::SessionMultiple(connectors) => { let session_surcharge_details = call_surcharge_decision_management_for_session_flow( state, &merchant_account, &business_profile, payment_data.get_payment_attempt(), payment_data.get_payment_intent(), payment_data.get_billing_address(), &connectors, ) .await?; Box::pin(call_multiple_connectors_service( state, &merchant_account, &key_store, connectors, &operation, payment_data, &customer, session_surcharge_details, &business_profile, header_payload.clone(), )) .await? } }; #[cfg(feature = "frm")] if let Some(fraud_info) = &mut frm_info { #[cfg(feature = "v1")] Box::pin(frm_core::post_payment_frm_core( state, req_state, &merchant_account, &mut payment_data, fraud_info, frm_configs .clone() .ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "frm_configs", }) .attach_printable("Frm configs label not found")?, &customer, key_store.clone(), &mut should_continue_capture, platform_merchant_account.as_ref(), )) .await?; } } else { (_, payment_data) = operation .to_update_tracker()? .update_trackers( state, req_state, payment_data.clone(), customer.clone(), validate_result.storage_scheme, None, &key_store, #[cfg(feature = "frm")] frm_info.and_then(|info| info.suggested_action), #[cfg(not(feature = "frm"))] None, header_payload.clone(), ) .await?; } let payment_intent_status = payment_data.get_payment_intent().status; payment_data .get_payment_attempt() .payment_token .as_ref() .zip(payment_data.get_payment_attempt().payment_method) .map(ParentPaymentMethodToken::create_key_for_token) .async_map(|key_for_hyperswitch_token| async move { if key_for_hyperswitch_token .should_delete_payment_method_token(payment_intent_status) { let _ = key_for_hyperswitch_token.delete(state).await; } }) .await; } else { (_, payment_data) = operation .to_update_tracker()? .update_trackers( state, req_state, payment_data.clone(), customer.clone(), validate_result.storage_scheme, None, &key_store, None, header_payload.clone(), ) .await?; } let cloned_payment_data = payment_data.clone(); let cloned_customer = customer.clone(); #[cfg(feature = "v1")] operation .to_domain()? .store_extended_card_info_temporarily( state, payment_data.get_payment_intent().get_id(), &business_profile, payment_data.get_payment_method_data(), ) .await?; utils::trigger_payments_webhook( merchant_account, business_profile, &key_store, cloned_payment_data, cloned_customer, state, operation, ) .await .map_err(|error| logger::warn!(payments_outgoing_webhook_error=?error)) .ok(); Ok(( payment_data, req, customer, connector_http_status_code, external_latency, )) } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="900" end="1094"> pub async fn proxy_for_payments_operation_core<F, Req, Op, FData, D>( state: &SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, profile_id_from_auth_layer: Option<id_type::ProfileId>, key_store: domain::MerchantKeyStore, operation: Op, req: Req, call_connector_action: CallConnectorAction, auth_flow: services::AuthFlow, header_payload: HeaderPayload, platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResult<(D, Req, Option<domain::Customer>, Option<u16>, Option<u128>)> where F: Send + Clone + Sync, Req: Authenticate + Clone, Op: Operation<F, Req, Data = D> + Send + Sync, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, // To create connector flow specific interface data D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>, RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>, // To perform router related operation for PaymentResponse PaymentResponse: Operation<F, FData, Data = D>, FData: Send + Sync + Clone, { let operation: BoxedOperation<'_, F, Req, D> = Box::new(operation); tracing::Span::current().record("merchant_id", merchant_account.get_id().get_string_repr()); let (operation, validate_result) = operation .to_validate_request()? .validate_request(&req, &merchant_account)?; tracing::Span::current().record("payment_id", format!("{}", validate_result.payment_id)); let operations::GetTrackerResponse { operation, customer_details: _, mut payment_data, business_profile, mandate_type: _, } = operation .to_get_tracker()? .get_trackers( state, &validate_result.payment_id, &req, &merchant_account, &key_store, auth_flow, &header_payload, platform_merchant_account.as_ref(), ) .await?; core_utils::validate_profile_id_from_auth_layer( profile_id_from_auth_layer, &payment_data.get_payment_intent().clone(), )?; common_utils::fp_utils::when(!should_call_connector(&operation, &payment_data), || { Err(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration).attach_printable(format!( "Nti and card details based mit flow is not support for this {operation:?} payment operation" )) })?; let connector_choice = operation .to_domain()? .get_connector( &merchant_account, &state.clone(), &req, payment_data.get_payment_intent(), &key_store, ) .await?; let connector = set_eligible_connector_for_nti_in_payment_data( state, &business_profile, &key_store, &mut payment_data, connector_choice, ) .await?; let should_add_task_to_process_tracker = should_add_task_to_process_tracker(&payment_data); let locale = header_payload.locale.clone(); let schedule_time = if should_add_task_to_process_tracker { payment_sync::get_sync_process_schedule_time( &*state.store, connector.connector.id(), merchant_account.get_id(), 0, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while getting process schedule time")? } else { None }; let (router_data, mca) = proxy_for_call_connector_service( state, req_state.clone(), &merchant_account, &key_store, connector.clone(), &operation, &mut payment_data, &None, call_connector_action.clone(), &validate_result, schedule_time, header_payload.clone(), &business_profile, ) .await?; let op_ref = &operation; let should_trigger_post_processing_flows = is_operation_confirm(&operation); let operation = Box::new(PaymentResponse); let connector_http_status_code = router_data.connector_http_status_code; let external_latency = router_data.external_latency; add_connector_http_status_code_metrics(connector_http_status_code); #[cfg(all(feature = "dynamic_routing", feature = "v1"))] let routable_connectors = convert_connector_data_to_routable_connectors(&[connector.clone()]) .map_err(|e| logger::error!(routable_connector_error=?e)) .unwrap_or_default(); let mut payment_data = operation .to_post_update_tracker()? .update_tracker( state, payment_data, router_data, &key_store, merchant_account.storage_scheme, &locale, #[cfg(all(feature = "dynamic_routing", feature = "v1"))] routable_connectors, #[cfg(all(feature = "dynamic_routing", feature = "v1"))] &business_profile, ) .await?; if should_trigger_post_processing_flows { complete_postprocessing_steps_if_required( state, &merchant_account, &key_store, &None, &mca, &connector, &mut payment_data, op_ref, Some(header_payload.clone()), ) .await?; } let cloned_payment_data = payment_data.clone(); utils::trigger_payments_webhook( merchant_account, business_profile, &key_store, cloned_payment_data, None, state, operation, ) .await .map_err(|error| logger::warn!(payments_outgoing_webhook_error=?error)) .ok(); Ok(( payment_data, req, None, connector_http_status_code, external_latency, )) } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="8054" end="8097"> pub trait OperationSessionSetters<F> { // Setter functions for PaymentData fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent); fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt); fn set_payment_method_data(&mut self, payment_method_data: Option<domain::PaymentMethodData>); fn set_email_if_not_present(&mut self, email: pii::Email); fn set_payment_method_id_in_attempt(&mut self, payment_method_id: Option<String>); fn set_pm_token(&mut self, token: String); fn set_connector_customer_id(&mut self, customer_id: Option<String>); fn push_sessions_token(&mut self, token: api::SessionToken); fn set_surcharge_details(&mut self, surcharge_details: Option<types::SurchargeDetails>); fn set_merchant_connector_id_in_attempt( &mut self, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, ); #[cfg(feature = "v1")] fn set_capture_method_in_attempt(&mut self, capture_method: enums::CaptureMethod); fn set_frm_message(&mut self, frm_message: FraudCheck); fn set_payment_intent_status(&mut self, status: storage_enums::IntentStatus); fn set_authentication_type_in_attempt( &mut self, authentication_type: Option<enums::AuthenticationType>, ); fn set_recurring_mandate_payment_data( &mut self, recurring_mandate_payment_data: hyperswitch_domain_models::router_data::RecurringMandatePaymentData, ); fn set_mandate_id(&mut self, mandate_id: api_models::payments::MandateIds); fn set_setup_future_usage_in_payment_intent( &mut self, setup_future_usage: storage_enums::FutureUsage, ); #[cfg(feature = "v1")] fn set_straight_through_algorithm_in_payment_attempt( &mut self, straight_through_algorithm: serde_json::Value, ); fn set_connector_in_payment_attempt(&mut self, connector: Option<String>); #[cfg(feature = "v1")] fn set_vault_operation(&mut self, vault_operation: domain_payments::VaultOperation); } <file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207"> pub struct PaymentMethodData { pub id: Option<String>, pub object: &'static str, pub card: Option<CardDetails>, pub created: Option<time::PrimitiveDateTime>, } <file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="1" end="11"> -- This file contains all new columns being added as part of v2 refactoring. -- The new columns added should work with both v1 and v2 applications. ALTER TABLE customers ADD COLUMN IF NOT EXISTS merchant_reference_id VARCHAR(64), ADD COLUMN IF NOT EXISTS default_billing_address BYTEA DEFAULT NULL, ADD COLUMN IF NOT EXISTS default_shipping_address BYTEA DEFAULT NULL, ADD COLUMN IF NOT EXISTS status "DeleteStatus"; CREATE TYPE "OrderFulfillmentTimeOrigin" AS ENUM ('create', 'confirm'); ALTER TABLE business_profile
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payouts.rs<|crate|> router anchor=complete_create_payout kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="1584" end="1649"> pub async fn complete_create_payout( state: &SessionState, merchant_account: &domain::MerchantAccount, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, ) -> RouterResult<()> { if !payout_data.should_terminate && matches!( payout_data.payout_attempt.status, storage_enums::PayoutStatus::RequiresCreation | storage_enums::PayoutStatus::RequiresConfirmation | storage_enums::PayoutStatus::RequiresPayoutMethodData ) { if connector_data .connector_name .supports_instant_payout(payout_data.payouts.payout_type) { // create payout_object only in router let db = &*state.store; let payout_attempt = &payout_data.payout_attempt; let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_data.payout_attempt.connector_payout_id.clone(), status: storage::enums::PayoutStatus::RequiresFulfillment, error_code: None, error_message: None, is_eligible: None, unified_code: None, unified_message: None, }; payout_data.payout_attempt = db .update_payout_attempt( payout_attempt, updated_payout_attempt, &payout_data.payouts, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payout_attempt in db")?; payout_data.payouts = db .update_payout( &payout_data.payouts, storage::PayoutsUpdate::StatusUpdate { status: storage::enums::PayoutStatus::RequiresFulfillment, }, &payout_data.payout_attempt, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payouts in db")?; } else { // create payout_object in connector as well as router Box::pin(create_payout( state, merchant_account, connector_data, payout_data, )) .await .attach_printable("Payout creation failed for given Payout request")?; } } Ok(()) } <file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="1583" end="1583"> use api_models::payments as payment_enums; use api_models::{self, enums as api_enums, payouts::PayoutLinkResponse}; use diesel_models::{ enums as storage_enums, generic_link::{GenericLinkNew, PayoutLink}, CommonMandateReference, PayoutsMandateReference, PayoutsMandateReferenceRecord, }; use scheduler::utils as pt_utils; use crate::types::domain::behaviour::Conversion; use crate::{ core::{ errors::{ self, ConnectorErrorExt, CustomResult, RouterResponse, RouterResult, StorageErrorExt, }, payments::{self, customers, helpers as payment_helpers}, utils as core_utils, }, db::StorageInterface, routes::SessionState, services, types::{ self, api::{self, payments as payment_api_types, payouts}, domain, storage::{self, PaymentRoutingInfo}, transformers::ForeignFrom, }, utils::{self, OptionExt}, }; <file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="1799" end="1835"> async fn complete_payout_quote_steps_if_required<F>( state: &SessionState, connector_data: &api::ConnectorData, router_data: &mut types::RouterData<F, types::PayoutsData, types::PayoutsResponseData>, ) -> RouterResult<()> { if connector_data .connector_name .is_payout_quote_call_required() { let quote_router_data = types::PayoutsRouterData::foreign_from((router_data, router_data.request.clone())); let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< api::PoQuote, types::PayoutsData, types::PayoutsResponseData, > = connector_data.connector.get_connector_integration(); let router_data_resp = services::execute_connector_processing_step( state, connector_integration, &quote_router_data, payments::CallConnectorAction::Trigger, None, ) .await .to_payout_failed_response()?; match router_data_resp.response.to_owned() { Ok(resp) => { router_data.quote_id = resp.connector_payout_id; } Err(_err) => { router_data.response = router_data_resp.response; } }; } Ok(()) } <file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="1651" end="1797"> pub async fn create_payout( state: &SessionState, merchant_account: &domain::MerchantAccount, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, ) -> RouterResult<()> { // 1. Form Router data let mut router_data = core_utils::construct_payout_router_data( state, connector_data, merchant_account, payout_data, ) .await?; // 2. Get/Create access token access_token::create_access_token( state, connector_data, merchant_account, &mut router_data, payout_data.payouts.payout_type.to_owned(), ) .await?; // 3. Fetch connector integration details let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< api::PoCreate, types::PayoutsData, types::PayoutsResponseData, > = connector_data.connector.get_connector_integration(); // 4. Execute pretasks complete_payout_quote_steps_if_required(state, connector_data, &mut router_data).await?; // 5. Call connector service let router_data_resp = services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, ) .await .to_payout_failed_response()?; // 6. Process data returned by the connector let db = &*state.store; match router_data_resp.response { Ok(payout_response_data) => { let payout_attempt = &payout_data.payout_attempt; let status = payout_response_data .status .unwrap_or(payout_attempt.status.to_owned()); let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_response_data.connector_payout_id, status, error_code: None, error_message: None, is_eligible: payout_response_data.payout_eligible, unified_code: None, unified_message: None, }; payout_data.payout_attempt = db .update_payout_attempt( payout_attempt, updated_payout_attempt, &payout_data.payouts, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payout_attempt in db")?; payout_data.payouts = db .update_payout( &payout_data.payouts, storage::PayoutsUpdate::StatusUpdate { status }, &payout_data.payout_attempt, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payouts in db")?; if helpers::is_payout_err_state(status) { return Err(report!(errors::ApiErrorResponse::PayoutFailed { data: Some( serde_json::json!({"payout_status": status.to_string(), "error_message": payout_data.payout_attempt.error_message.as_ref(), "error_code": payout_data.payout_attempt.error_code.as_ref()}) ), })); } } Err(err) => { let status = storage_enums::PayoutStatus::Failed; let (error_code, error_message) = (Some(err.code), Some(err.message)); let (unified_code, unified_message) = helpers::get_gsm_record( state, error_code.clone(), error_message.clone(), payout_data.payout_attempt.connector.clone(), consts::PAYOUT_FLOW_STR, ) .await .map_or((None, None), |gsm| (gsm.unified_code, gsm.unified_message)); let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(), status, error_code, error_message, is_eligible: None, unified_code: unified_code .map(UnifiedCode::try_from) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "unified_code", })?, unified_message: unified_message .map(UnifiedMessage::try_from) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "unified_message", })?, }; payout_data.payout_attempt = db .update_payout_attempt( &payout_data.payout_attempt, updated_payout_attempt, &payout_data.payouts, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payout_attempt in db")?; payout_data.payouts = db .update_payout( &payout_data.payouts, storage::PayoutsUpdate::StatusUpdate { status }, &payout_data.payout_attempt, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payouts in db")?; } }; Ok(()) } <file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="1449" end="1582"> pub async fn check_payout_eligibility( state: &SessionState, merchant_account: &domain::MerchantAccount, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, ) -> RouterResult<()> { // 1. Form Router data let router_data = core_utils::construct_payout_router_data( state, connector_data, merchant_account, payout_data, ) .await?; // 2. Fetch connector integration details let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< api::PoEligibility, types::PayoutsData, types::PayoutsResponseData, > = connector_data.connector.get_connector_integration(); // 3. Call connector service let router_data_resp = services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, ) .await .to_payout_failed_response()?; // 4. Process data returned by the connector let db = &*state.store; match router_data_resp.response { Ok(payout_response_data) => { let payout_attempt = &payout_data.payout_attempt; let status = payout_response_data .status .unwrap_or(payout_attempt.status.to_owned()); let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_response_data.connector_payout_id, status, error_code: None, error_message: None, is_eligible: payout_response_data.payout_eligible, unified_code: None, unified_message: None, }; payout_data.payout_attempt = db .update_payout_attempt( payout_attempt, updated_payout_attempt, &payout_data.payouts, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payout_attempt in db")?; payout_data.payouts = db .update_payout( &payout_data.payouts, storage::PayoutsUpdate::StatusUpdate { status }, &payout_data.payout_attempt, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payouts in db")?; if helpers::is_payout_err_state(status) { return Err(report!(errors::ApiErrorResponse::PayoutFailed { data: Some( serde_json::json!({"payout_status": status.to_string(), "error_message": payout_data.payout_attempt.error_message.as_ref(), "error_code": payout_data.payout_attempt.error_code.as_ref()}) ), })); } } Err(err) => { let status = storage_enums::PayoutStatus::Failed; let (error_code, error_message) = (Some(err.code), Some(err.message)); let (unified_code, unified_message) = helpers::get_gsm_record( state, error_code.clone(), error_message.clone(), payout_data.payout_attempt.connector.clone(), consts::PAYOUT_FLOW_STR, ) .await .map_or((None, None), |gsm| (gsm.unified_code, gsm.unified_message)); let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(), status, error_code, error_message, is_eligible: Some(false), unified_code: unified_code .map(UnifiedCode::try_from) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "unified_code", })?, unified_message: unified_message .map(UnifiedMessage::try_from) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "unified_message", })?, }; payout_data.payout_attempt = db .update_payout_attempt( &payout_data.payout_attempt, updated_payout_attempt, &payout_data.payouts, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payout_attempt in db")?; payout_data.payouts = db .update_payout( &payout_data.payouts, storage::PayoutsUpdate::StatusUpdate { status }, &payout_data.payout_attempt, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payouts in db")?; } }; Ok(()) } <file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="1413" end="1447"> pub async fn complete_payout_eligibility( state: &SessionState, merchant_account: &domain::MerchantAccount, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, ) -> RouterResult<()> { let payout_attempt = &payout_data.payout_attempt.to_owned(); if !payout_data.should_terminate && payout_attempt.is_eligible.is_none() && connector_data .connector_name .supports_payout_eligibility(payout_data.payouts.payout_type) { check_payout_eligibility(state, merchant_account, connector_data, payout_data) .await .attach_printable("Eligibility failed for given Payout request")?; } utils::when( !payout_attempt .is_eligible .unwrap_or(state.conf.payouts.payout_eligibility), || { Err(report!(errors::ApiErrorResponse::PayoutFailed { data: Some(serde_json::json!({ "message": "Payout method data is invalid" })) }) .attach_printable("Payout data provided is invalid")) }, )?; Ok(()) } <file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="1048" end="1168"> pub async fn call_connector_payout( state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, ) -> RouterResult<()> { let payout_attempt = &payout_data.payout_attempt.to_owned(); let payouts = &payout_data.payouts.to_owned(); // fetch merchant connector account if not present if payout_data.merchant_connector_account.is_none() || payout_data.payout_attempt.merchant_connector_id.is_none() { let merchant_connector_account = get_mca_from_profile_id( state, merchant_account, &payout_data.profile_id, &connector_data.connector_name.to_string(), payout_attempt .merchant_connector_id .clone() .or(connector_data.merchant_connector_id.clone()) .as_ref(), key_store, ) .await?; payout_data.payout_attempt.merchant_connector_id = merchant_connector_account.get_mca_id(); payout_data.merchant_connector_account = Some(merchant_connector_account); } // update connector_name if payout_data.payout_attempt.connector.is_none() || payout_data.payout_attempt.connector != Some(connector_data.connector_name.to_string()) { payout_data.payout_attempt.connector = Some(connector_data.connector_name.to_string()); let updated_payout_attempt = storage::PayoutAttemptUpdate::UpdateRouting { connector: connector_data.connector_name.to_string(), routing_info: payout_data.payout_attempt.routing_info.clone(), merchant_connector_id: payout_data.payout_attempt.merchant_connector_id.clone(), }; let db = &*state.store; payout_data.payout_attempt = db .update_payout_attempt( &payout_data.payout_attempt, updated_payout_attempt, payouts, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating routing info in payout_attempt")?; }; // Fetch / store payout_method_data if payout_data.payout_method_data.is_none() || payout_attempt.payout_token.is_none() { let customer_id = payouts .customer_id .clone() .get_required_value("customer_id")?; payout_data.payout_method_data = Some( helpers::make_payout_method_data( state, payout_data.payout_method_data.to_owned().as_ref(), payout_attempt.payout_token.as_deref(), &customer_id, &payout_attempt.merchant_id, payouts.payout_type, key_store, Some(payout_data), merchant_account.storage_scheme, ) .await? .get_required_value("payout_method_data")?, ); } // Eligibility flow complete_payout_eligibility(state, merchant_account, connector_data, payout_data).await?; // Create customer flow Box::pin(complete_create_recipient( state, merchant_account, key_store, connector_data, payout_data, )) .await?; // Create customer's disbursement account flow Box::pin(complete_create_recipient_disburse_account( state, merchant_account, connector_data, payout_data, key_store, )) .await?; // Payout creation flow Box::pin(complete_create_payout( state, merchant_account, connector_data, payout_data, )) .await?; // Auto fulfillment flow let status = payout_data.payout_attempt.status; if payouts.auto_fulfill && status == storage_enums::PayoutStatus::RequiresFulfillment { Box::pin(fulfill_payout( state, merchant_account, key_store, connector_data, payout_data, )) .await .attach_printable("Payout fulfillment failed for given Payout request")?; } Ok(()) } <file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="68" end="81"> pub struct PayoutData { pub billing_address: Option<domain::Address>, pub business_profile: domain::Profile, pub customer_details: Option<domain::Customer>, pub merchant_connector_account: Option<payment_helpers::MerchantConnectorAccountType>, pub payouts: storage::Payouts, pub payout_attempt: storage::PayoutAttempt, pub payout_method_data: Option<payouts::PayoutMethodData>, pub profile_id: common_utils::id_type::ProfileId, pub should_terminate: bool, pub payout_link: Option<PayoutLink>, pub current_locale: String, pub payment_method: Option<PaymentMethod>, } <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/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, <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/payouts.rs<|crate|> router anchor=get_connector_choice kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="94" end="166"> pub async fn get_connector_choice( state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, connector: Option<String>, routing_algorithm: Option<serde_json::Value>, payout_data: &mut PayoutData, eligible_connectors: Option<Vec<api_enums::PayoutConnectors>>, ) -> RouterResult<api::ConnectorCallType> { let eligible_routable_connectors = eligible_connectors.map(|connectors| { connectors .into_iter() .map(api::enums::RoutableConnectors::from) .collect() }); let connector_choice = helpers::get_default_payout_connector(state, routing_algorithm).await?; match connector_choice { api::ConnectorChoice::SessionMultiple(_) => { Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector choice - SessionMultiple")? } api::ConnectorChoice::StraightThrough(straight_through) => { let request_straight_through: api::routing::StraightThroughAlgorithm = straight_through .clone() .parse_value("StraightThroughAlgorithm") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid straight through routing rules format")?; payout_data.payout_attempt.routing_info = Some(straight_through); let mut routing_data = storage::RoutingData { routed_through: connector, merchant_connector_id: None, algorithm: Some(request_straight_through.clone()), routing_info: PaymentRoutingInfo { algorithm: None, pre_routing_results: None, }, }; helpers::decide_payout_connector( state, merchant_account, key_store, Some(request_straight_through), &mut routing_data, payout_data, eligible_routable_connectors, ) .await } api::ConnectorChoice::Decide => { let mut routing_data = storage::RoutingData { routed_through: connector, merchant_connector_id: None, algorithm: None, routing_info: PaymentRoutingInfo { algorithm: None, pre_routing_results: None, }, }; helpers::decide_payout_connector( state, merchant_account, key_store, None, &mut routing_data, payout_data, eligible_routable_connectors, ) .await } } } <file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="93" end="93"> use api_models::{self, enums as api_enums, payouts::PayoutLinkResponse}; use diesel_models::{ enums as storage_enums, generic_link::{GenericLinkNew, PayoutLink}, CommonMandateReference, PayoutsMandateReference, PayoutsMandateReferenceRecord, }; use serde_json; use crate::types::domain::behaviour::Conversion; use crate::{ core::{ errors::{ self, ConnectorErrorExt, CustomResult, RouterResponse, RouterResult, StorageErrorExt, }, payments::{self, customers, helpers as payment_helpers}, utils as core_utils, }, db::StorageInterface, routes::SessionState, services, types::{ self, api::{self, payments as payment_api_types, payouts}, domain, storage::{self, PaymentRoutingInfo}, transformers::ForeignFrom, }, utils::{self, OptionExt}, }; <file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="274" end="305"> pub async fn payouts_core( state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, payout_data: &mut PayoutData, routing_algorithm: Option<serde_json::Value>, eligible_connectors: Option<Vec<api_enums::PayoutConnectors>>, ) -> RouterResult<()> { let payout_attempt = &payout_data.payout_attempt; // Form connector data let connector_call_type = get_connector_choice( state, merchant_account, key_store, payout_attempt.connector.clone(), routing_algorithm, payout_data, eligible_connectors, ) .await?; // Call connector steps Box::pin(make_connector_decision( state, merchant_account, key_store, connector_call_type, payout_data, )) .await } <file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="169" end="270"> pub async fn make_connector_decision( state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, connector_call_type: api::ConnectorCallType, payout_data: &mut PayoutData, ) -> RouterResult<()> { match connector_call_type { api::ConnectorCallType::PreDetermined(connector_data) => { Box::pin(call_connector_payout( state, merchant_account, key_store, &connector_data, payout_data, )) .await?; #[cfg(feature = "payout_retry")] { let config_bool = retry::config_should_call_gsm_payout( &*state.store, merchant_account.get_id(), PayoutRetryType::SingleConnector, ) .await; if config_bool && payout_data.should_call_gsm() { Box::pin(retry::do_gsm_single_connector_actions( state, connector_data, payout_data, merchant_account, key_store, )) .await?; } } Ok(()) } api::ConnectorCallType::Retryable(connectors) => { let mut connectors = connectors.into_iter(); let connector_data = get_next_connector(&mut connectors)?; Box::pin(call_connector_payout( state, merchant_account, key_store, &connector_data, payout_data, )) .await?; #[cfg(feature = "payout_retry")] { let config_multiple_connector_bool = retry::config_should_call_gsm_payout( &*state.store, merchant_account.get_id(), PayoutRetryType::MultiConnector, ) .await; if config_multiple_connector_bool && payout_data.should_call_gsm() { Box::pin(retry::do_gsm_multiple_connector_actions( state, connectors, connector_data.clone(), payout_data, merchant_account, key_store, )) .await?; } let config_single_connector_bool = retry::config_should_call_gsm_payout( &*state.store, merchant_account.get_id(), PayoutRetryType::SingleConnector, ) .await; if config_single_connector_bool && payout_data.should_call_gsm() { Box::pin(retry::do_gsm_single_connector_actions( state, connector_data, payout_data, merchant_account, key_store, )) .await?; } } Ok(()) } _ => Err(errors::ApiErrorResponse::InternalServerError).attach_printable({ "only PreDetermined and Retryable ConnectorCallTypes are supported".to_string() })?, } } <file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="84" end="91"> pub fn get_next_connector( connectors: &mut IntoIter<api::ConnectorData>, ) -> RouterResult<api::ConnectorData> { connectors .next() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Connector not found in connectors iterator") } <file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="540" end="582"> pub async fn payouts_retrieve_core( state: SessionState, merchant_account: domain::MerchantAccount, profile_id: Option<common_utils::id_type::ProfileId>, key_store: domain::MerchantKeyStore, req: payouts::PayoutRetrieveRequest, ) -> RouterResponse<payouts::PayoutCreateResponse> { let mut payout_data = make_payout_data( &state, &merchant_account, profile_id, &key_store, &payouts::PayoutRequest::PayoutRetrieveRequest(req.to_owned()), &state.locale, ) .await?; let payout_attempt = payout_data.payout_attempt.to_owned(); let status = payout_attempt.status; if matches!(req.force_sync, Some(true)) && helpers::should_call_retrieve(status) { // Form connector data let connector_call_type = get_connector_choice( &state, &merchant_account, &key_store, payout_attempt.connector.clone(), None, &mut payout_data, None, ) .await?; complete_payout_retrieve( &state, &merchant_account, connector_call_type, &mut payout_data, ) .await?; } response_handler(&state, &merchant_account, &payout_data).await } <file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="68" end="81"> pub struct PayoutData { pub billing_address: Option<domain::Address>, pub business_profile: domain::Profile, pub customer_details: Option<domain::Customer>, pub merchant_connector_account: Option<payment_helpers::MerchantConnectorAccountType>, pub payouts: storage::Payouts, pub payout_attempt: storage::PayoutAttempt, pub payout_method_data: Option<payouts::PayoutMethodData>, pub profile_id: common_utils::id_type::ProfileId, pub should_terminate: bool, pub payout_link: Option<PayoutLink>, pub current_locale: String, pub payment_method: Option<PaymentMethod>, } <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/cards.rs<|crate|> router anchor=execute_payment_method_tokenization 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="6103" end="6172"> pub async fn execute_payment_method_tokenization( executor: tokenize::CardNetworkTokenizeExecutor<'_, domain::TokenizePaymentMethodRequest>, builder: tokenize::NetworkTokenizationBuilder<'_, tokenize::TokenizeWithPmId>, req: &domain::TokenizePaymentMethodRequest, ) -> errors::RouterResult<api::CardNetworkTokenizeResponse> { // Fetch payment method let payment_method = executor .fetch_payment_method(&req.payment_method_id) .await?; let builder = builder.set_payment_method(&payment_method); // Validate payment method and customer let (locker_id, customer) = executor .validate_request_and_locker_reference_and_customer(&payment_method) .await?; let builder = builder.set_validate_result(&customer); // Fetch card from locker let card_details = get_card_from_locker( executor.state, &customer.id, executor.merchant_account.get_id(), &locker_id, ) .await?; // Perform BIN lookup and validate card network let optional_card_info = executor .fetch_bin_details_and_validate_card_network( card_details.card_number.clone(), None, None, None, None, ) .await?; let builder = builder.set_card_details(&card_details, optional_card_info, req.card_cvc.clone()); // Tokenize card let (optional_card, optional_cvc) = builder.get_optional_card_and_cvc(); let domain_card = optional_card.get_required_value("card")?; let network_token_details = executor .tokenize_card(&customer.id, &domain_card, optional_cvc) .await?; let builder = builder.set_token_details(&network_token_details); // Store token in locker let store_token_resp = executor .store_network_token_in_locker( &network_token_details, &customer.id, card_details.name_on_card.clone(), card_details.nick_name.clone().map(Secret::new), ) .await?; let builder = builder.set_stored_token_response(&store_token_resp); // Update payment method let updated_payment_method = executor .update_payment_method( &store_token_resp, payment_method, &network_token_details, &domain_card, ) .await?; let builder = builder.set_payment_method(&updated_payment_method); Ok(builder.build()) } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="6102" end="6102"> use diesel_models::payment_method; use hyperswitch_domain_models::customer::CustomerUpdate; use masking::Secret; use super::tokenize::NetworkTokenizationProcess; use crate::core::payment_methods::{ add_payment_method_status_update_task, tokenize, utils::{get_merchant_pm_filter_graph, make_pm_graph, refresh_pm_filters_cache}, }; use crate::types::domain::types::AsyncLift; use crate::{ configs::{ defaults::{get_billing_required_fields, get_shipping_required_fields}, settings, }, consts as router_consts, core::{ errors::{self, StorageErrorExt}, payment_methods::{network_tokenization, transformers as payment_methods, vault}, payments::{ helpers, routing::{self, SessionFlowRoutingInput}, }, utils as core_utils, }, db, logger, pii::prelude::*, routes::{self, metrics, payment_methods::ParentPaymentMethodToken}, services, types::{ api::{self, routing as routing_types, PaymentMethodCreateExt}, domain::{self, Profile}, storage::{self, enums, PaymentMethodListContext, PaymentTokenData}, transformers::{ForeignFrom, ForeignTryFrom}, }, utils, utils::OptionExt, }; <file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="6038" end="6097"> pub async fn execute_card_tokenization( executor: tokenize::CardNetworkTokenizeExecutor<'_, domain::TokenizeCardRequest>, builder: tokenize::NetworkTokenizationBuilder<'_, tokenize::TokenizeWithCard>, req: &domain::TokenizeCardRequest, ) -> errors::RouterResult<api::CardNetworkTokenizeResponse> { // Validate request and get optional customer let optional_customer = executor .validate_request_and_fetch_optional_customer() .await?; let builder = builder.set_validate_result(); // Perform BIN lookup and validate card network let optional_card_info = executor .fetch_bin_details_and_validate_card_network( req.raw_card_number.clone(), req.card_issuer.as_ref(), req.card_network.as_ref(), req.card_type.as_ref(), req.card_issuing_country.as_ref(), ) .await?; let builder = builder.set_card_details(req, optional_card_info); // Create customer if not present let customer = match optional_customer { Some(customer) => customer, None => executor.create_customer().await?, }; let builder = builder.set_customer(&customer); // Tokenize card let (optional_card, optional_cvc) = builder.get_optional_card_and_cvc(); let domain_card = optional_card .get_required_value("card") .change_context(errors::ApiErrorResponse::InternalServerError)?; let network_token_details = executor .tokenize_card(&customer.id, &domain_card, optional_cvc) .await?; let builder = builder.set_token_details(&network_token_details); // Store card and token in locker let store_card_and_token_resp = executor .store_card_and_token_in_locker(&network_token_details, &domain_card, &customer.id) .await?; let builder = builder.set_stored_card_response(&store_card_and_token_resp); let builder = builder.set_stored_token_response(&store_card_and_token_resp); // Create payment method let payment_method = executor .create_payment_method( &store_card_and_token_resp, &network_token_details, &domain_card, &customer.id, ) .await?; let builder = builder.set_payment_method_response(&payment_method); Ok(builder.build()) } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="6000" end="6032"> pub async fn tokenize_card_flow( state: &routes::SessionState, req: domain::CardNetworkTokenizeRequest, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> errors::RouterResult<api::CardNetworkTokenizeResponse> { match req.data { domain::TokenizeDataRequest::Card(ref card_req) => { let executor = tokenize::CardNetworkTokenizeExecutor::new( state, key_store, merchant_account, card_req, &req.customer, ); let builder = tokenize::NetworkTokenizationBuilder::<tokenize::TokenizeWithCard>::default(); execute_card_tokenization(executor, builder, card_req).await } domain::TokenizeDataRequest::ExistingPaymentMethod(ref payment_method) => { let executor = tokenize::CardNetworkTokenizeExecutor::new( state, key_store, merchant_account, payment_method, &req.customer, ); let builder = tokenize::NetworkTokenizationBuilder::<tokenize::TokenizeWithPmId>::default(); execute_payment_method_tokenization(executor, builder, payment_method).await } } } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2477" end="2511"> pub async fn get_card_from_locker( state: &routes::SessionState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, card_reference: &str, ) -> errors::RouterResult<Card> { metrics::GET_FROM_LOCKER.add(1, &[]); let get_card_from_rs_locker_resp = common_utils::metrics::utils::record_operation_time( async { get_card_from_hs_locker( state, customer_id, merchant_id, card_reference, api_enums::LockerChoice::HyperswitchCardVault, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while getting card from hyperswitch card vault") .inspect_err(|_| { metrics::CARD_LOCKER_FAILURES.add( 1, router_env::metric_attributes!(("locker", "rust"), ("operation", "get")), ); }) }, &metrics::CARD_GET_TIME, router_env::metric_attributes!(("locker", "rust")), ) .await?; logger::debug!("card retrieved from rust locker"); Ok(get_card_from_rs_locker_resp) } <file_sep path="hyperswitch/crates/router/src/services.rs" role="context" start="39" end="39"> pub type Store = RouterStore<StoreType>; <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2691" end="2713"> pub struct CardNetworkTokenizeResponse { /// Response for payment method entry in DB pub payment_method_response: Option<PaymentMethodResponse>, /// Customer details #[schema(value_type = CustomerDetails)] pub customer: Option<payments::CustomerDetails>, /// Card network tokenization status pub card_tokenized: bool, /// Error code #[serde(skip_serializing_if = "Option::is_none")] pub error_code: Option<String>, /// Error message #[serde(skip_serializing_if = "Option::is_none")] pub error_message: Option<String>, /// Details that were sent for tokenization #[serde(skip_serializing_if = "Option::is_none")] pub tokenization_data: Option<TokenizeDataRequest>, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/tokenization.rs<|crate|> router anchor=save_network_token_in_locker 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="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/core/payments/tokenization.rs" role="context" start="1005" end="1005"> use api_models::payment_methods::PaymentMethodsData; use api_models::{ payment_methods::PaymentMethodDataWalletInfo, payments::ConnectorMandateReferenceId, }; 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="1101" end="1181"> pub async fn add_payment_method_token<F: Clone, T: types::Tokenizable + Clone>( state: &SessionState, connector: &api::ConnectorData, tokenization_action: &payments::TokenizationAction, router_data: &mut types::RouterData<F, T, types::PaymentsResponseData>, pm_token_request_data: types::PaymentMethodTokenizationData, should_continue_payment: bool, ) -> RouterResult<types::PaymentMethodTokenResult> { if should_continue_payment { match tokenization_action { payments::TokenizationAction::TokenizeInConnector | payments::TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(_) => { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::PaymentMethodToken, types::PaymentMethodTokenizationData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); let pm_token_response_data: Result< types::PaymentsResponseData, types::ErrorResponse, > = Err(types::ErrorResponse::default()); let pm_token_router_data = helpers::router_data_type_conversion::<_, api::PaymentMethodToken, _, _, _, _>( router_data.clone(), pm_token_request_data, pm_token_response_data, ); router_data .request .set_session_token(pm_token_router_data.session_token.clone()); let resp = services::execute_connector_processing_step( state, connector_integration, &pm_token_router_data, payments::CallConnectorAction::Trigger, None, ) .await .to_payment_failed_response()?; metrics::CONNECTOR_PAYMENT_METHOD_TOKENIZATION.add( 1, router_env::metric_attributes!( ("connector", connector.connector_name.to_string()), ("payment_method", router_data.payment_method.to_string()), ), ); let payment_token_resp = resp.response.map(|res| { if let types::PaymentsResponseData::TokenizationResponse { token } = res { Some(token) } else { None } }); Ok(types::PaymentMethodTokenResult { payment_method_token_result: payment_token_resp, is_payment_method_tokenization_performed: true, connector_response: resp.connector_response.clone(), }) } _ => Ok(types::PaymentMethodTokenResult { payment_method_token_result: Ok(None), is_payment_method_tokenization_performed: false, connector_response: None, }), } } else { logger::debug!("Skipping connector tokenization based on should_continue_payment flag"); Ok(types::PaymentMethodTokenResult { payment_method_token_result: Ok(None), is_payment_method_tokenization_performed: false, connector_response: None, }) } } <file_sep path="hyperswitch/crates/router/src/core/payments/tokenization.rs" role="context" start="1078" end="1099"> pub fn create_payment_method_metadata( metadata: Option<&pii::SecretSerdeValue>, connector_token: Option<(String, String)>, ) -> RouterResult<Option<serde_json::Value>> { let mut meta = match metadata { None => serde_json::Map::new(), Some(meta) => { let metadata = meta.clone().expose(); let existing_metadata: serde_json::Map<String, serde_json::Value> = metadata .parse_value("Map<String, Value>") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse the metadata")?; existing_metadata } }; Ok(connector_token.and_then(|connector_and_token| { meta.insert( connector_and_token.0, serde_json::Value::String(connector_and_token.1), ) })) } <file_sep path="hyperswitch/crates/router/src/core/payments/tokenization.rs" role="context" start="989" end="1000"> 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>, )> { todo!() } <file_sep path="hyperswitch/crates/router/src/core/payments/tokenization.rs" role="context" start="977" end="986"> pub async fn save_in_locker( _state: &SessionState, _merchant_account: &domain::MerchantAccount, _payment_method_request: api::PaymentMethodCreate, ) -> RouterResult<( api_models::payment_methods::PaymentMethodResponse, Option<payment_methods::transformers::DataDuplicationCheck>, )> { 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="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/connector/payone/transformers.rs" role="context" start="117" end="121"> pub struct Card { card_holder_name: Secret<String>, card_number: CardNumber, expiry_date: Secret<String>, } <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/admin.rs<|crate|> router anchor=create_domain_model_from_request 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="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="606" end="606"> }) .map(|business_profile| business_profiles_vector.push(business_profile)) .ok(); } Ok(business_profiles_vector) } } #[cfg(all(feature = "v2", feature = "olap"))] #[async_trait::async_trait] impl MerchantAccountCreateBridge for api::MerchantAccountCreate { 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", }, <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="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="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="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="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="4451" end="4453"> pub fn new(profile: domain::Profile) -> Self { Self { profile } } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="425" end="433"> enum CreateOrValidateOrganization { /// Creates a new organization #[cfg(feature = "v1")] Create, /// Validates if this organization exists in the records Validate { organization_id: id_type::OrganizationId, }, } <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-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/webhooks/outgoing.rs<|crate|> router anchor=raise_webhooks_analytics_event 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="457" end="530"> async fn raise_webhooks_analytics_event( state: SessionState, trigger_webhook_result: CustomResult<(), errors::WebhooksFlowError>, content: Option<api::OutgoingWebhookContent>, merchant_id: common_utils::id_type::MerchantId, event: domain::Event, merchant_key_store: &domain::MerchantKeyStore, ) { let key_manager_state: &KeyManagerState = &(&state).into(); let event_id = event.event_id; let error = if let Err(error) = trigger_webhook_result { logger::error!(?error, "Failed to send webhook to merchant"); serde_json::to_value(error.current_context()) .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) .inspect_err(|error| { logger::error!(?error, "Failed to serialize outgoing webhook error as JSON"); }) .ok() } else { None }; let outgoing_webhook_event_content = content .as_ref() .and_then(api::OutgoingWebhookContent::get_outgoing_webhook_event_content) .or_else(|| get_outgoing_webhook_event_content_from_event_metadata(event.metadata)); // Fetch updated_event from db let updated_event = state .store .find_event_by_merchant_id_event_id( key_manager_state, &merchant_id, &event_id, merchant_key_store, ) .await .attach_printable_lazy(|| format!("event not found for id: {}", &event_id)) .map_err(|error| { logger::error!(?error); error }) .ok(); // Get status_code from webhook response let status_code = updated_event.and_then(|updated_event| { let webhook_response: Option<OutgoingWebhookResponseContent> = updated_event.response.and_then(|res| { res.peek() .parse_struct("OutgoingWebhookResponseContent") .map_err(|error| { logger::error!(?error, "Error deserializing webhook response"); error }) .ok() }); webhook_response.and_then(|res| res.status_code) }); let webhook_event = OutgoingWebhookEvent::new( state.tenant.tenant_id.clone(), merchant_id, event_id, event.event_type, outgoing_webhook_event_content, error, event.initial_attempt_id, status_code, event.delivery_attempt, ); state.event_handler().log_event(&webhook_event); } <file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="456" end="456"> use api_models::{ webhook_events::{OutgoingWebhookRequestContent, OutgoingWebhookResponseContent}, webhooks, }; use common_utils::{ ext_traits::{Encode, StringExt}, request::RequestContent, type_name, types::keymanager::{Identifier, KeyManagerState}, }; use crate::compatibility::stripe::webhooks as stripe_webhooks; use crate::{ core::{ errors::{self, CustomResult}, metrics, }, db::StorageInterface, events::outgoing_webhook_logs::{ OutgoingWebhookEvent, OutgoingWebhookEventContent, OutgoingWebhookEventMetric, }, logger, routes::{app::SessionStateInfo, SessionState}, services, types::{ api, domain::{self}, storage::{self, enums}, transformers::ForeignFrom, }, utils::{OptionExt, ValueExt}, workflows::outgoing_webhook_retry, }; <file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="592" end="606"> fn get_webhook_url_from_business_profile( business_profile: &domain::Profile, ) -> CustomResult<String, errors::WebhooksFlowError> { let webhook_details = business_profile .webhook_details .clone() .get_required_value("webhook_details") .change_context(errors::WebhooksFlowError::MerchantWebhookDetailsNotFound)?; webhook_details .webhook_url .get_required_value("webhook_url") .change_context(errors::WebhooksFlowError::MerchantWebhookUrlNotConfigured) .map(ExposeInterface::expose) } <file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="532" end="590"> pub(crate) async fn add_outgoing_webhook_retry_task_to_process_tracker( db: &dyn StorageInterface, business_profile: &domain::Profile, event: &domain::Event, ) -> CustomResult<storage::ProcessTracker, errors::StorageError> { let schedule_time = outgoing_webhook_retry::get_webhook_delivery_retry_schedule_time( db, &business_profile.merchant_id, 0, ) .await .ok_or(errors::StorageError::ValueNotFound( "Process tracker schedule time".into(), // Can raise a better error here )) .attach_printable("Failed to obtain initial process tracker schedule time")?; let tracking_data = types::OutgoingWebhookTrackingData { merchant_id: business_profile.merchant_id.clone(), business_profile_id: business_profile.get_id().to_owned(), event_type: event.event_type, event_class: event.event_class, primary_object_id: event.primary_object_id.clone(), primary_object_type: event.primary_object_type, initial_attempt_id: event.initial_attempt_id.clone(), }; let runner = storage::ProcessTrackerRunner::OutgoingWebhookRetryWorkflow; let task = "OUTGOING_WEBHOOK_RETRY"; let tag = ["OUTGOING_WEBHOOKS"]; let process_tracker_id = scheduler::utils::get_process_tracker_id( runner, task, &event.event_id, &business_profile.merchant_id, ); let process_tracker_entry = storage::ProcessTrackerNew::new( process_tracker_id, task, runner, tag, tracking_data, None, schedule_time, common_types::consts::API_VERSION, ) .map_err(errors::StorageError::from)?; let attributes = router_env::metric_attributes!(("flow", "OutgoingWebhookRetry")); match db.insert_process(process_tracker_entry).await { Ok(process_tracker) => { crate::routes::metrics::TASKS_ADDED_COUNT.add(1, attributes); Ok(process_tracker) } Err(error) => { crate::routes::metrics::TASK_ADDITION_FAILURES_COUNT.add(1, attributes); Err(error) } } } <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/src/core/webhooks/outgoing.rs" role="context" start="198" end="236"> pub(crate) async fn trigger_webhook_and_raise_event( state: SessionState, business_profile: domain::Profile, merchant_key_store: &domain::MerchantKeyStore, event: domain::Event, request_content: OutgoingWebhookRequestContent, delivery_attempt: enums::WebhookDeliveryAttempt, content: Option<api::OutgoingWebhookContent>, process_tracker: Option<storage::ProcessTracker>, ) { logger::debug!( event_id=%event.event_id, idempotent_event_id=?event.idempotent_event_id, initial_attempt_id=?event.initial_attempt_id, "Attempting to send webhook" ); let merchant_id = business_profile.merchant_id.clone(); let trigger_webhook_result = trigger_webhook_to_merchant( state.clone(), business_profile, merchant_key_store, event.clone(), request_content, delivery_attempt, process_tracker, ) .await; let _ = raise_webhooks_analytics_event( state, trigger_webhook_result, content, merchant_id, event, merchant_key_store, ) .await; } <file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="980" end="1021"> fn get_outgoing_webhook_event_content_from_event_metadata( event_metadata: Option<storage::EventMetadata>, ) -> Option<OutgoingWebhookEventContent> { event_metadata.map(|metadata| match metadata { diesel_models::EventMetadata::Payment { payment_id } => { OutgoingWebhookEventContent::Payment { payment_id, content: serde_json::Value::Null, } } diesel_models::EventMetadata::Payout { payout_id } => OutgoingWebhookEventContent::Payout { payout_id, content: serde_json::Value::Null, }, diesel_models::EventMetadata::Refund { payment_id, refund_id, } => OutgoingWebhookEventContent::Refund { payment_id, refund_id, content: serde_json::Value::Null, }, diesel_models::EventMetadata::Dispute { payment_id, attempt_id, dispute_id, } => OutgoingWebhookEventContent::Dispute { payment_id, attempt_id, dispute_id, content: serde_json::Value::Null, }, diesel_models::EventMetadata::Mandate { payment_method_id, mandate_id, } => OutgoingWebhookEventContent::Mandate { payment_method_id, mandate_id, content: serde_json::Value::Null, }, }) } <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/migrations/2022-09-29-084920_create_initial_tables/up.sql" role="context" start="279" end="295"> phone_country_code VARCHAR(255), description VARCHAR(255), address JSON, created_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP, metadata JSON, PRIMARY KEY (customer_id, merchant_id) ); CREATE TABLE events ( id SERIAL PRIMARY KEY, event_id VARCHAR(255) NOT NULL, event_type "EventType" NOT NULL, event_class "EventClass" NOT NULL, is_webhook_notified BOOLEAN NOT NULL DEFAULT FALSE, intent_reference_id VARCHAR(255), primary_object_id VARCHAR(255) NOT NULL, primary_object_type "EventObjectType" NOT NULL,
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/fraud_check.rs<|crate|> router anchor=make_frm_data_and_fraud_check_operation 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="405" end="473"> pub async fn make_frm_data_and_fraud_check_operation<F, D>( _db: &dyn StorageInterface, state: &SessionState, merchant_account: &domain::MerchantAccount, payment_data: D, frm_routing_algorithm: FrmRoutingAlgorithm, profile_id: common_utils::id_type::ProfileId, frm_configs: FrmConfigsObject, _customer: &Option<domain::Customer>, ) -> RouterResult<FrmInfo<F, D>> where F: Send + Clone, D: payments::OperationSessionGetters<F> + payments::OperationSessionSetters<F> + Send + Sync + Clone, { let order_details = payment_data .get_payment_intent() .order_details .clone() .or_else(|| // when the order_details are present within the meta_data, we need to take those to support backward compatibility payment_data.get_payment_intent().metadata.clone().and_then(|meta| { let order_details = meta.get("order_details").to_owned(); order_details.map(|order| vec![masking::Secret::new(order.to_owned())]) })) .map(|order_details_value| { order_details_value .into_iter() .map(|data| { data.peek() .to_owned() .parse_value("OrderDetailsWithAmount") .attach_printable("unable to parse OrderDetailsWithAmount") }) .collect::<Result<Vec<_>, _>>() .unwrap_or_default() }); let frm_connector_details = ConnectorDetailsCore { connector_name: frm_routing_algorithm.data, profile_id, }; let payment_to_frm_data = PaymentToFrmData { amount: payment_data.get_amount(), payment_intent: payment_data.get_payment_intent().to_owned(), payment_attempt: payment_data.get_payment_attempt().to_owned(), merchant_account: merchant_account.to_owned(), address: payment_data.get_address().clone(), connector_details: frm_connector_details.clone(), order_details, frm_metadata: payment_data.get_payment_intent().frm_metadata.clone(), }; let fraud_check_operation: operation::BoxedFraudCheckOperation<F, D> = fraud_check_operation_by_frm_preferred_flow_type(frm_configs.frm_preferred_flow_type); let frm_data = fraud_check_operation .to_get_tracker()? .get_trackers(state, payment_to_frm_data, frm_connector_details) .await?; Ok(FrmInfo { fraud_check_operation, frm_data, suggested_action: None, }) } <file_sep path="hyperswitch/crates/router/src/core/fraud_check.rs" role="context" start="404" end="404"> use masking::PeekInterface; 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="489" end="578"> pub async fn pre_payment_frm_core<F, Req, D>( state: &SessionState, merchant_account: &domain::MerchantAccount, payment_data: &mut D, frm_info: &mut FrmInfo<F, D>, frm_configs: FrmConfigsObject, customer: &Option<domain::Customer>, should_continue_transaction: &mut bool, should_continue_capture: &mut bool, key_store: domain::MerchantKeyStore, operation: &BoxedOperation<'_, F, Req, D>, ) -> RouterResult<Option<FrmData>> where F: Send + Clone, D: payments::OperationSessionGetters<F> + payments::OperationSessionSetters<F> + Send + Sync + Clone, { let mut frm_data = None; if is_operation_allowed(operation) { frm_data = if let Some(frm_data) = &mut frm_info.frm_data { if matches!( frm_configs.frm_preferred_flow_type, api_enums::FrmPreferredFlowTypes::Pre ) { let fraud_check_operation = &mut frm_info.fraud_check_operation; let frm_router_data = fraud_check_operation .to_domain()? .pre_payment_frm( state, payment_data, frm_data, merchant_account, customer, key_store.clone(), ) .await?; let _router_data = call_frm_service::<F, frm_api::Transaction, _, D>( state, payment_data, frm_data, merchant_account, &key_store, customer, ) .await?; let frm_data_updated = fraud_check_operation .to_update_tracker()? .update_tracker( state, &key_store, frm_data.clone(), payment_data, None, frm_router_data, ) .await?; let frm_fraud_check = frm_data_updated.fraud_check.clone(); payment_data.set_frm_message(frm_fraud_check.clone()); if matches!(frm_fraud_check.frm_status, FraudCheckStatus::Fraud) { *should_continue_transaction = false; frm_info.suggested_action = Some(FrmSuggestion::FrmCancelTransaction); } logger::debug!( "frm_updated_data: {:?} {:?}", frm_info.fraud_check_operation, frm_info.suggested_action ); Some(frm_data_updated) } else if matches!( frm_configs.frm_preferred_flow_type, api_enums::FrmPreferredFlowTypes::Post ) && !matches!( frm_data.fraud_check.frm_status, FraudCheckStatus::TransactionFailure // Incase of TransactionFailure frm status(No frm decision is taken by frm processor), if capture method is automatic we should not change it to manual. ) { *should_continue_capture = false; Some(frm_data.to_owned()) } else { Some(frm_data.to_owned()) } } else { None }; } Ok(frm_data) } <file_sep path="hyperswitch/crates/router/src/core/fraud_check.rs" role="context" start="475" end="486"> fn fraud_check_operation_by_frm_preferred_flow_type<F, D>( frm_preferred_flow_type: api_enums::FrmPreferredFlowTypes, ) -> operation::BoxedFraudCheckOperation<F, D> where operation::FraudCheckPost: operation::FraudCheckOperation<F, D>, operation::FraudCheckPre: operation::FraudCheckOperation<F, D>, { match frm_preferred_flow_type { api_enums::FrmPreferredFlowTypes::Pre => Box::new(operation::FraudCheckPre), api_enums::FrmPreferredFlowTypes::Post => Box::new(operation::FraudCheckPost), } } <file_sep path="hyperswitch/crates/router/src/core/fraud_check.rs" role="context" start="382" end="401"> pub async fn make_frm_data_and_fraud_check_operation<F, D>( _db: &dyn StorageInterface, state: &SessionState, merchant_account: &domain::MerchantAccount, payment_data: D, frm_routing_algorithm: FrmRoutingAlgorithm, profile_id: common_utils::id_type::ProfileId, frm_configs: FrmConfigsObject, _customer: &Option<domain::Customer>, ) -> RouterResult<FrmInfo<F, D>> where F: Send + Clone, D: payments::OperationSessionGetters<F> + payments::OperationSessionSetters<F> + Send + Sync + Clone, { todo!() } <file_sep path="hyperswitch/crates/router/src/core/fraud_check.rs" role="context" start="173" end="378"> pub async fn should_call_frm<F, D>( merchant_account: &domain::MerchantAccount, payment_data: &D, state: &SessionState, key_store: domain::MerchantKeyStore, ) -> RouterResult<( bool, Option<FrmRoutingAlgorithm>, Option<common_utils::id_type::ProfileId>, Option<FrmConfigsObject>, )> where F: Send + Clone, D: payments::OperationSessionGetters<F> + Send + Sync + Clone, { use common_utils::ext_traits::OptionExt; use masking::ExposeInterface; let db = &*state.store; match merchant_account.frm_routing_algorithm.clone() { Some(frm_routing_algorithm_value) => { let frm_routing_algorithm_struct: FrmRoutingAlgorithm = frm_routing_algorithm_value .clone() .parse_value("FrmRoutingAlgorithm") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "frm_routing_algorithm", }) .attach_printable("Data field not found in frm_routing_algorithm")?; let profile_id = payment_data .get_payment_intent() .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("profile_id is not set in payment_intent")? .clone(); #[cfg(feature = "v1")] let merchant_connector_account_from_db_option = db .find_merchant_connector_account_by_profile_id_connector_name( &state.into(), &profile_id, &frm_routing_algorithm_struct.data, &key_store, ) .await .map_err(|error| { logger::error!( "{:?}", error.change_context( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_account.get_id().get_string_repr().to_owned(), } ) ) }) .ok(); let enabled_merchant_connector_account_from_db_option = merchant_connector_account_from_db_option.and_then(|mca| { if mca.disabled.unwrap_or(false) { logger::info!("No eligible connector found for FRM"); None } else { Some(mca) } }); #[cfg(feature = "v2")] let merchant_connector_account_from_db_option: Option< domain::MerchantConnectorAccount, > = { let _ = key_store; let _ = frm_routing_algorithm_struct; let _ = profile_id; todo!() }; match enabled_merchant_connector_account_from_db_option { Some(merchant_connector_account_from_db) => { let frm_configs_option = merchant_connector_account_from_db .frm_configs .ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "frm_configs", }) .ok(); match frm_configs_option { Some(frm_configs_value) => { let frm_configs_struct: Vec<api_models::admin::FrmConfigs> = frm_configs_value .into_iter() .map(|config| { config .expose() .parse_value("FrmConfigs") .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "frm_configs".to_string(), expected_format: r#"[{ "gateway": "stripe", "payment_methods": [{ "payment_method": "card","flow": "post"}]}]"#.to_string(), }) }) .collect::<Result<Vec<_>, _>>()?; let mut is_frm_connector_enabled = false; let mut is_frm_pm_enabled = false; let connector = payment_data.get_payment_attempt().connector.clone(); let filtered_frm_config = frm_configs_struct .iter() .filter(|frm_config| match (&connector, &frm_config.gateway) { (Some(current_connector), Some(configured_connector)) => { let is_enabled = *current_connector == configured_connector.to_string(); if is_enabled { is_frm_connector_enabled = true; } is_enabled } (None, _) | (_, None) => true, }) .collect::<Vec<_>>(); let filtered_payment_methods = filtered_frm_config .iter() .map(|frm_config| { let filtered_frm_config_by_pm = frm_config .payment_methods .iter() .filter(|frm_config_pm| { match ( payment_data.get_payment_attempt().payment_method, frm_config_pm.payment_method, ) { ( Some(current_pm), Some(configured_connector_pm), ) => { let is_enabled = current_pm.to_string() == configured_connector_pm.to_string(); if is_enabled { is_frm_pm_enabled = true; } is_enabled } (None, _) | (_, None) => true, } }) .collect::<Vec<_>>(); filtered_frm_config_by_pm }) .collect::<Vec<_>>() .concat(); let is_frm_enabled = is_frm_connector_enabled && is_frm_pm_enabled; logger::debug!( "is_frm_connector_enabled {:?}, is_frm_pm_enabled: {:?}, is_frm_enabled :{:?}", is_frm_connector_enabled, is_frm_pm_enabled, is_frm_enabled ); // filtered_frm_config... // Panic Safety: we are first checking if the object is present... only if present, we try to fetch index 0 let frm_configs_object = FrmConfigsObject { frm_enabled_gateway: filtered_frm_config .first() .and_then(|c| c.gateway), frm_enabled_pm: filtered_payment_methods .first() .and_then(|pm| pm.payment_method), // flow type should be consumed from payment_method.flow. To provide backward compatibility, if we don't find it there, we consume it from payment_method.payment_method_types[0].flow_type. frm_preferred_flow_type: filtered_payment_methods .first() .and_then(|pm| pm.flow.clone()) .or(filtered_payment_methods.first().and_then(|pm| { pm.payment_method_types.as_ref().and_then(|pmt| { pmt.first().map(|pmts| pmts.flow.clone()) }) })) .ok_or(errors::ApiErrorResponse::InvalidDataFormat { field_name: "frm_configs".to_string(), expected_format: r#"[{ "gateway": "stripe", "payment_methods": [{ "payment_method": "card","flow": "post"}]}]"#.to_string(), })?, }; logger::debug!( "frm_routing_configs: {:?} {:?} {:?} {:?}", frm_routing_algorithm_struct, profile_id, frm_configs_object, is_frm_enabled ); Ok(( is_frm_enabled, Some(frm_routing_algorithm_struct), Some(profile_id), Some(frm_configs_object), )) } None => { logger::error!("Cannot find frm_configs for FRM provider"); Ok((false, None, None, None)) } } } None => { logger::error!("Cannot find merchant connector account for FRM provider"); Ok((false, None, None, None)) } } } _ => Ok((false, None, None, None)), } } <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="66" end="70"> pub struct FrmInfo<F, D> { pub fraud_check_operation: BoxedFraudCheckOperation<F, D>, pub frm_data: Option<FrmData>, pub suggested_action: Option<FrmSuggestion>, } <file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="1" end="11"> -- This file contains all new columns being added as part of v2 refactoring. -- The new columns added should work with both v1 and v2 applications. ALTER TABLE customers ADD COLUMN IF NOT EXISTS merchant_reference_id VARCHAR(64), ADD COLUMN IF NOT EXISTS default_billing_address BYTEA DEFAULT NULL, ADD COLUMN IF NOT EXISTS default_shipping_address BYTEA DEFAULT NULL, ADD COLUMN IF NOT EXISTS status "DeleteStatus"; CREATE TYPE "OrderFulfillmentTimeOrigin" AS ENUM ('create', 'confirm'); ALTER TABLE business_profile
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments.rs<|crate|> router anchor=call_create_connector_customer_if_required kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="4382" end="4462"> pub async fn call_create_connector_customer_if_required<F, Req, D>( state: &SessionState, customer: &Option<domain::Customer>, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, merchant_connector_account: &domain::MerchantConnectorAccount, payment_data: &mut D, ) -> RouterResult<Option<storage::CustomerUpdate>> where F: Send + Clone + Sync, Req: Send + Sync, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, Req, router_types::PaymentsResponseData>, RouterData<F, Req, router_types::PaymentsResponseData>: Feature<F, Req> + Send, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, Req, router_types::PaymentsResponseData>, { let connector_name = payment_data.get_payment_attempt().connector.clone(); match connector_name { Some(connector_name) => { let connector = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &connector_name, api::GetToken::Connector, Some(merchant_connector_account.get_id()), )?; let merchant_connector_id = merchant_connector_account.get_id(); let (should_call_connector, existing_connector_customer_id) = customers::should_call_connector_create_customer( state, &connector, customer, &merchant_connector_id, ); if should_call_connector { // Create customer at connector and update the customer table to store this data let router_data = payment_data .construct_router_data( state, connector.connector.id(), merchant_account, key_store, customer, merchant_connector_account, None, None, ) .await?; let connector_customer_id = router_data .create_connector_customer(state, &connector) .await?; let customer_update = customers::update_connector_customer_in_customers( merchant_connector_id, customer.as_ref(), connector_customer_id.clone(), ) .await; payment_data.set_connector_customer_id(connector_customer_id); Ok(customer_update) } else { // Customer already created in previous calls use the same value, no need to update payment_data.set_connector_customer_id( existing_connector_customer_id.map(ToOwned::to_owned), ); Ok(None) } } None => Ok(None), } } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="4381" end="4381"> // Customer already created in previous calls use the same value, no need to update payment_data.set_connector_customer_id( existing_connector_customer_id.map(ToOwned::to_owned), ); Ok(None) } } None => Ok(None), } } #[cfg(feature = "v2")] pub async fn call_create_connector_customer_if_required<F, Req, D>( state: &SessionState, customer: &Option<domain::Customer>, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, merchant_connector_account: &domain::MerchantConnectorAccount, payment_data: &mut D, ) -> RouterResult<Option<storage::CustomerUpdate>> where F: Send + Clone + Sync, Req: Send + Sync, // To create connector flow specific interface data <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="4632" end="4695"> async fn complete_postprocessing_steps_if_required<F, Q, RouterDReq, D>( state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_conn_account: &helpers::MerchantConnectorAccountType, connector: &api::ConnectorData, payment_data: &mut D, _operation: &BoxedOperation<'_, F, Q, D>, header_payload: Option<HeaderPayload>, ) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>> where F: Send + Clone + Sync, RouterDReq: Send + Sync, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send, dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, { let mut router_data = payment_data .construct_router_data( state, connector.connector.id(), merchant_account, key_store, customer, merchant_conn_account, None, header_payload, ) .await?; match payment_data.get_payment_method_data() { Some(domain::PaymentMethodData::OpenBanking(domain::OpenBankingData::OpenBankingPIS { .. })) => { if connector.connector_name == router_types::Connector::Plaid { router_data = router_data.postprocessing_steps(state, connector).await?; let token = if let Ok(ref res) = router_data.response { match res { router_types::PaymentsResponseData::PostProcessingResponse { session_token, } => session_token .as_ref() .map(|token| api::SessionToken::OpenBanking(token.clone())), _ => None, } } else { None }; if let Some(t) = token { payment_data.push_sessions_token(t); } Ok(router_data) } else { Ok(router_data) } } _ => Ok(router_data), } } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="4464" end="4628"> async fn complete_preprocessing_steps_if_required<F, Req, Q, D>( state: &SessionState, connector: &api::ConnectorData, payment_data: &D, mut router_data: RouterData<F, Req, router_types::PaymentsResponseData>, operation: &BoxedOperation<'_, F, Q, D>, should_continue_payment: bool, ) -> RouterResult<(RouterData<F, Req, router_types::PaymentsResponseData>, bool)> where F: Send + Clone + Sync, D: OperationSessionGetters<F> + Send + Sync + Clone, Req: Send + Sync, RouterData<F, Req, router_types::PaymentsResponseData>: Feature<F, Req> + Send, dyn api::Connector: services::api::ConnectorIntegration<F, Req, router_types::PaymentsResponseData>, { if !is_operation_complete_authorize(&operation) && connector .connector_name .is_pre_processing_required_before_authorize() { router_data = router_data.preprocessing_steps(state, connector).await?; return Ok((router_data, should_continue_payment)); } //TODO: For ACH transfers, if preprocessing_step is not required for connectors encountered in future, add the check let router_data_and_should_continue_payment = match payment_data.get_payment_method_data() { Some(domain::PaymentMethodData::BankTransfer(_)) => (router_data, should_continue_payment), Some(domain::PaymentMethodData::Wallet(_)) => { if is_preprocessing_required_for_wallets(connector.connector_name.to_string()) { ( router_data.preprocessing_steps(state, connector).await?, false, ) } else { (router_data, should_continue_payment) } } Some(domain::PaymentMethodData::Card(_)) => { if connector.connector_name == router_types::Connector::Payme && !matches!(format!("{operation:?}").as_str(), "CompleteAuthorize") { router_data = router_data.preprocessing_steps(state, connector).await?; let is_error_in_response = router_data.response.is_err(); // If is_error_in_response is true, should_continue_payment should be false, we should throw the error (router_data, !is_error_in_response) } else if connector.connector_name == router_types::Connector::Nmi && !matches!(format!("{operation:?}").as_str(), "CompleteAuthorize") && router_data.auth_type == storage_enums::AuthenticationType::ThreeDs && !matches!( payment_data .get_payment_attempt() .external_three_ds_authentication_attempted, Some(true) ) { router_data = router_data.preprocessing_steps(state, connector).await?; (router_data, false) } else if connector.connector_name == router_types::Connector::Cybersource && is_operation_complete_authorize(&operation) && router_data.auth_type == storage_enums::AuthenticationType::ThreeDs { router_data = router_data.preprocessing_steps(state, connector).await?; // Should continue the flow only if no redirection_data is returned else a response with redirection form shall be returned let should_continue = matches!( router_data.response, Ok(router_types::PaymentsResponseData::TransactionResponse { ref redirection_data, .. }) if redirection_data.is_none() ) && router_data.status != common_enums::AttemptStatus::AuthenticationFailed; (router_data, should_continue) } else if router_data.auth_type == common_enums::AuthenticationType::ThreeDs && ((connector.connector_name == router_types::Connector::Nexixpay && is_operation_complete_authorize(&operation)) || ((connector.connector_name == router_types::Connector::Nuvei || connector.connector_name == router_types::Connector::Shift4) && !is_operation_complete_authorize(&operation))) { router_data = router_data.preprocessing_steps(state, connector).await?; (router_data, should_continue_payment) } else if connector.connector_name == router_types::Connector::Xendit && is_operation_confirm(&operation) { match payment_data.get_payment_intent().split_payments { Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment( common_types::payments::XenditSplitRequest::MultipleSplits(_), )) => { router_data = router_data.preprocessing_steps(state, connector).await?; let is_error_in_response = router_data.response.is_err(); (router_data, !is_error_in_response) } _ => (router_data, should_continue_payment), } } else if connector.connector_name == router_types::Connector::Redsys && router_data.auth_type == common_enums::AuthenticationType::ThreeDs && is_operation_confirm(&operation) { router_data = router_data.preprocessing_steps(state, connector).await?; let should_continue = match router_data.response { Ok(router_types::PaymentsResponseData::TransactionResponse { ref connector_metadata, .. }) => { let three_ds_invoke_data: Option< api_models::payments::PaymentsConnectorThreeDsInvokeData, > = connector_metadata.clone().and_then(|metadata| { metadata .parse_value("PaymentsConnectorThreeDsInvokeData") .ok() // "ThreeDsInvokeData was not found; proceeding with the payment flow without triggering the ThreeDS invoke action" }); three_ds_invoke_data.is_none() } _ => false, }; (router_data, should_continue) } else { (router_data, should_continue_payment) } } Some(domain::PaymentMethodData::GiftCard(gift_card_data)) => { if connector.connector_name == router_types::Connector::Adyen && matches!(gift_card_data.deref(), domain::GiftCardData::Givex(..)) { router_data = router_data.preprocessing_steps(state, connector).await?; let is_error_in_response = router_data.response.is_err(); // If is_error_in_response is true, should_continue_payment should be false, we should throw the error (router_data, !is_error_in_response) } else { (router_data, should_continue_payment) } } Some(domain::PaymentMethodData::BankDebit(_)) => { if connector.connector_name == router_types::Connector::Gocardless { router_data = router_data.preprocessing_steps(state, connector).await?; let is_error_in_response = router_data.response.is_err(); // If is_error_in_response is true, should_continue_payment should be false, we should throw the error (router_data, !is_error_in_response) } else { (router_data, should_continue_payment) } } _ => { // 3DS validation for paypal cards after verification (authorize call) if connector.connector_name == router_types::Connector::Paypal && payment_data.get_payment_attempt().get_payment_method() == Some(storage_enums::PaymentMethod::Card) && matches!(format!("{operation:?}").as_str(), "CompleteAuthorize") { router_data = router_data.preprocessing_steps(state, connector).await?; let is_error_in_response = router_data.response.is_err(); // If is_error_in_response is true, should_continue_payment should be false, we should throw the error (router_data, !is_error_in_response) } else { (router_data, should_continue_payment) } } }; Ok(router_data_and_should_continue_payment) } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="4274" end="4379"> pub async fn call_create_connector_customer_if_required<F, Req, D>( state: &SessionState, customer: &Option<domain::Customer>, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, merchant_connector_account: &helpers::MerchantConnectorAccountType, payment_data: &mut D, ) -> RouterResult<Option<storage::CustomerUpdate>> where F: Send + Clone + Sync, Req: Send + Sync, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, Req, router_types::PaymentsResponseData>, RouterData<F, Req, router_types::PaymentsResponseData>: Feature<F, Req> + Send, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, Req, router_types::PaymentsResponseData>, { let connector_name = payment_data.get_payment_attempt().connector.clone(); match connector_name { Some(connector_name) => { let connector = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &connector_name, api::GetToken::Connector, merchant_connector_account.get_mca_id(), )?; let label = { let connector_label = core_utils::get_connector_label( payment_data.get_payment_intent().business_country, payment_data.get_payment_intent().business_label.as_ref(), payment_data .get_payment_attempt() .business_sub_label .as_ref(), &connector_name, ); if let Some(connector_label) = merchant_connector_account .get_mca_id() .map(|mca_id| mca_id.get_string_repr().to_string()) .or(connector_label) { connector_label } else { let profile_id = payment_data .get_payment_intent() .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("profile_id is not set in payment_intent")?; format!("{connector_name}_{}", profile_id.get_string_repr()) } }; let (should_call_connector, existing_connector_customer_id) = customers::should_call_connector_create_customer( state, &connector, customer, &label, ); if should_call_connector { // Create customer at connector and update the customer table to store this data let router_data = payment_data .construct_router_data( state, connector.connector.id(), merchant_account, key_store, customer, merchant_connector_account, None, None, ) .await?; let connector_customer_id = router_data .create_connector_customer(state, &connector) .await?; let customer_update = customers::update_connector_customer_in_customers( &label, customer.as_ref(), connector_customer_id.clone(), ) .await; payment_data.set_connector_customer_id(connector_customer_id); Ok(customer_update) } else { // Customer already created in previous calls use the same value, no need to update payment_data.set_connector_customer_id( existing_connector_customer_id.map(ToOwned::to_owned), ); Ok(None) } } None => Ok(None), } } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="4248" end="4271"> fn validate_customer_details_for_click_to_pay(customer_details: &CustomerData) -> RouterResult<()> { match ( customer_details.phone.as_ref(), customer_details.phone_country_code.as_ref(), customer_details.email.as_ref() ) { (None, None, Some(_)) => Ok(()), (Some(_), Some(_), Some(_)) => Ok(()), (Some(_), Some(_), None) => Ok(()), (Some(_), None, Some(_)) => Ok(()), (None, Some(_), None) => Err(errors::ApiErrorResponse::MissingRequiredField { field_name: "phone", }) .attach_printable("phone number is not present in payment_intent.customer_details"), (Some(_), None, None) => Err(errors::ApiErrorResponse::MissingRequiredField { field_name: "phone_country_code", }) .attach_printable("phone_country_code is not present in payment_intent.customer_details"), (_, _, _) => Err(errors::ApiErrorResponse::MissingRequiredFields { field_names: vec!["phone", "phone_country_code", "email"], }) .attach_printable("either of phone, phone_country_code or email is not present in payment_intent.customer_details"), } } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="2975" end="3231"> pub async fn call_connector_service<F, RouterDReq, ApiRequest, D>( state: &SessionState, req_state: ReqState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, connector: api::ConnectorData, operation: &BoxedOperation<'_, F, ApiRequest, D>, payment_data: &mut D, customer: &Option<domain::Customer>, call_connector_action: CallConnectorAction, validate_result: &operations::ValidateResult, schedule_time: Option<time::PrimitiveDateTime>, header_payload: HeaderPayload, frm_suggestion: Option<storage_enums::FrmSuggestion>, business_profile: &domain::Profile, is_retry_payment: bool, should_retry_with_pan: bool, ) -> RouterResult<( RouterData<F, RouterDReq, router_types::PaymentsResponseData>, helpers::MerchantConnectorAccountType, )> where F: Send + Clone + Sync, RouterDReq: Send + Sync, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, { let stime_connector = Instant::now(); let merchant_connector_account = construct_profile_id_and_get_mca( state, merchant_account, payment_data, &connector.connector_name.to_string(), connector.merchant_connector_id.as_ref(), key_store, false, ) .await?; #[cfg(feature = "v1")] if payment_data .get_payment_attempt() .merchant_connector_id .is_none() { payment_data.set_merchant_connector_id_in_attempt(merchant_connector_account.get_mca_id()); } operation .to_domain()? .populate_payment_data( state, payment_data, merchant_account, business_profile, &connector, ) .await?; let (pd, tokenization_action) = get_connector_tokenization_action_when_confirm_true( state, operation, payment_data, validate_result, &merchant_connector_account, key_store, customer, business_profile, should_retry_with_pan, ) .await?; *payment_data = pd; // Validating the blocklist guard and generate the fingerprint blocklist_guard(state, merchant_account, key_store, operation, payment_data).await?; let updated_customer = call_create_connector_customer_if_required( state, customer, merchant_account, key_store, &merchant_connector_account, payment_data, ) .await?; #[cfg(feature = "v1")] let merchant_recipient_data = if let Some(true) = payment_data .get_payment_intent() .is_payment_processor_token_flow { None } else { payment_data .get_merchant_recipient_data( state, merchant_account, key_store, &merchant_connector_account, &connector, ) .await? }; // TODO: handle how we read `is_processor_token_flow` in v2 and then call `get_merchant_recipient_data` #[cfg(feature = "v2")] let merchant_recipient_data = None; let mut router_data = payment_data .construct_router_data( state, connector.connector.id(), merchant_account, key_store, customer, &merchant_connector_account, merchant_recipient_data, None, ) .await?; let add_access_token_result = router_data .add_access_token( state, &connector, merchant_account, payment_data.get_creds_identifier(), ) .await?; router_data = router_data.add_session_token(state, &connector).await?; let should_continue_further = access_token::update_router_data_with_access_token_result( &add_access_token_result, &mut router_data, &call_connector_action, ); router_data.payment_method_token = if let Some(decrypted_token) = add_decrypted_payment_method_token(tokenization_action.clone(), payment_data).await? { Some(decrypted_token) } else { router_data.payment_method_token }; let payment_method_token_response = router_data .add_payment_method_token( state, &connector, &tokenization_action, should_continue_further, ) .await?; let mut should_continue_further = tokenization::update_router_data_with_payment_method_token_result( payment_method_token_response, &mut router_data, is_retry_payment, should_continue_further, ); (router_data, should_continue_further) = complete_preprocessing_steps_if_required( state, &connector, payment_data, router_data, operation, should_continue_further, ) .await?; if let Ok(router_types::PaymentsResponseData::PreProcessingResponse { session_token: Some(session_token), .. }) = router_data.response.to_owned() { payment_data.push_sessions_token(session_token); }; // In case of authorize flow, pre-task and post-tasks are being called in build request // if we do not want to proceed further, then the function will return Ok(None, false) let (connector_request, should_continue_further) = if should_continue_further { // Check if the actual flow specific request can be built with available data router_data .build_flow_specific_connector_request(state, &connector, call_connector_action.clone()) .await? } else { (None, false) }; if should_add_task_to_process_tracker(payment_data) { operation .to_domain()? .add_task_to_process_tracker( state, payment_data.get_payment_attempt(), validate_result.requeue, schedule_time, ) .await .map_err(|error| logger::error!(process_tracker_error=?error)) .ok(); } // Update the payment trackers just before calling the connector // Since the request is already built in the previous step, // there should be no error in request construction from hyperswitch end (_, *payment_data) = operation .to_update_tracker()? .update_trackers( state, req_state, payment_data.clone(), customer.clone(), merchant_account.storage_scheme, updated_customer, key_store, frm_suggestion, header_payload.clone(), ) .await?; let router_data = if should_continue_further { // The status of payment_attempt and intent will be updated in the previous step // update this in router_data. // This is added because few connector integrations do not update the status, // and rely on previous status set in router_data router_data.status = payment_data.get_payment_attempt().status; router_data .decide_flows( state, &connector, call_connector_action, connector_request, business_profile, header_payload.clone(), ) .await } else { Ok(router_data) }?; let etime_connector = Instant::now(); let duration_connector = etime_connector.saturating_duration_since(stime_connector); tracing::info!(duration = format!("Duration taken: {}", duration_connector.as_millis())); Ok((router_data, merchant_connector_account)) } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="3236" end="3377"> pub async fn call_connector_service<F, RouterDReq, ApiRequest, D>( state: &SessionState, req_state: ReqState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, connector: api::ConnectorData, operation: &BoxedOperation<'_, F, ApiRequest, D>, payment_data: &mut D, customer: &Option<domain::Customer>, call_connector_action: CallConnectorAction, schedule_time: Option<time::PrimitiveDateTime>, header_payload: HeaderPayload, frm_suggestion: Option<storage_enums::FrmSuggestion>, business_profile: &domain::Profile, is_retry_payment: bool, should_retry_with_pan: bool, ) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>> where F: Send + Clone + Sync, RouterDReq: Send + Sync, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, { let stime_connector = Instant::now(); let merchant_connector_id = connector .merchant_connector_id .as_ref() .get_required_value("merchant_connector_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("connector id is not set")?; let merchant_connector_account = state .store .find_merchant_connector_account_by_id(&state.into(), merchant_connector_id, key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_owned(), })?; let updated_customer = call_create_connector_customer_if_required( state, customer, merchant_account, key_store, &merchant_connector_account, payment_data, ) .await?; let mut router_data = payment_data .construct_router_data( state, connector.connector.id(), merchant_account, key_store, customer, &merchant_connector_account, None, None, ) .await?; let add_access_token_result = router_data .add_access_token( state, &connector, merchant_account, payment_data.get_creds_identifier(), ) .await?; router_data = router_data.add_session_token(state, &connector).await?; let should_continue_further = access_token::update_router_data_with_access_token_result( &add_access_token_result, &mut router_data, &call_connector_action, ); // In case of authorize flow, pre-task and post-tasks are being called in build request // if we do not want to proceed further, then the function will return Ok(None, false) let (connector_request, should_continue_further) = if should_continue_further { // Check if the actual flow specific request can be built with available data router_data .build_flow_specific_connector_request(state, &connector, call_connector_action.clone()) .await? } else { (None, false) }; // Update the payment trackers just before calling the connector // Since the request is already built in the previous step, // there should be no error in request construction from hyperswitch end (_, *payment_data) = operation .to_update_tracker()? .update_trackers( state, req_state, payment_data.clone(), customer.clone(), merchant_account.storage_scheme, updated_customer, key_store, frm_suggestion, header_payload.clone(), ) .await?; let router_data = if should_continue_further { // The status of payment_attempt and intent will be updated in the previous step // update this in router_data. // This is added because few connector integrations do not update the status, // and rely on previous status set in router_data // TODO: status is already set when constructing payment data, why should this be done again? // router_data.status = payment_data.get_payment_attempt().status; router_data .decide_flows( state, &connector, call_connector_action, connector_request, business_profile, header_payload.clone(), ) .await } else { Ok(router_data) }?; let etime_connector = Instant::now(); let duration_connector = etime_connector.saturating_duration_since(stime_connector); tracing::info!(duration = format!("Duration taken: {}", duration_connector.as_millis())); Ok(router_data) } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="8054" end="8097"> pub trait OperationSessionSetters<F> { // Setter functions for PaymentData fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent); fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt); fn set_payment_method_data(&mut self, payment_method_data: Option<domain::PaymentMethodData>); fn set_email_if_not_present(&mut self, email: pii::Email); fn set_payment_method_id_in_attempt(&mut self, payment_method_id: Option<String>); fn set_pm_token(&mut self, token: String); fn set_connector_customer_id(&mut self, customer_id: Option<String>); fn push_sessions_token(&mut self, token: api::SessionToken); fn set_surcharge_details(&mut self, surcharge_details: Option<types::SurchargeDetails>); fn set_merchant_connector_id_in_attempt( &mut self, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, ); #[cfg(feature = "v1")] fn set_capture_method_in_attempt(&mut self, capture_method: enums::CaptureMethod); fn set_frm_message(&mut self, frm_message: FraudCheck); fn set_payment_intent_status(&mut self, status: storage_enums::IntentStatus); fn set_authentication_type_in_attempt( &mut self, authentication_type: Option<enums::AuthenticationType>, ); fn set_recurring_mandate_payment_data( &mut self, recurring_mandate_payment_data: hyperswitch_domain_models::router_data::RecurringMandatePaymentData, ); fn set_mandate_id(&mut self, mandate_id: api_models::payments::MandateIds); fn set_setup_future_usage_in_payment_intent( &mut self, setup_future_usage: storage_enums::FutureUsage, ); #[cfg(feature = "v1")] fn set_straight_through_algorithm_in_payment_attempt( &mut self, straight_through_algorithm: serde_json::Value, ); fn set_connector_in_payment_attempt(&mut self, connector: Option<String>); #[cfg(feature = "v1")] fn set_vault_operation(&mut self, vault_operation: domain_payments::VaultOperation); } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="8013" end="8052"> pub trait OperationSessionGetters<F> { fn get_payment_attempt(&self) -> &storage::PaymentAttempt; fn get_payment_intent(&self) -> &storage::PaymentIntent; fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod>; fn get_mandate_id(&self) -> Option<&payments_api::MandateIds>; fn get_address(&self) -> &PaymentAddress; fn get_creds_identifier(&self) -> Option<&str>; fn get_token(&self) -> Option<&str>; fn get_multiple_capture_data(&self) -> Option<&types::MultipleCaptureData>; fn get_payment_link_data(&self) -> Option<api_models::payments::PaymentLinkResponse>; fn get_ephemeral_key(&self) -> Option<ephemeral_key::EphemeralKey>; fn get_setup_mandate(&self) -> Option<&MandateData>; fn get_poll_config(&self) -> Option<router_types::PollConfig>; fn get_authentication(&self) -> Option<&storage::Authentication>; fn get_frm_message(&self) -> Option<FraudCheck>; fn get_refunds(&self) -> Vec<storage::Refund>; fn get_disputes(&self) -> Vec<storage::Dispute>; fn get_authorizations(&self) -> Vec<diesel_models::authorization::Authorization>; fn get_attempts(&self) -> Option<Vec<storage::PaymentAttempt>>; fn get_recurring_details(&self) -> Option<&RecurringDetails>; // TODO: this should be a mandatory field, should we throw an error instead of returning an Option? fn get_payment_intent_profile_id(&self) -> Option<&id_type::ProfileId>; fn get_currency(&self) -> storage_enums::Currency; fn get_amount(&self) -> api::Amount; fn get_payment_attempt_connector(&self) -> Option<&str>; fn get_billing_address(&self) -> Option<hyperswitch_domain_models::address::Address>; fn get_payment_method_data(&self) -> Option<&domain::PaymentMethodData>; fn get_sessions_token(&self) -> Vec<api::SessionToken>; fn get_token_data(&self) -> Option<&storage::PaymentTokenData>; fn get_mandate_connector(&self) -> Option<&MandateConnectorDetails>; fn get_force_sync(&self) -> Option<bool>; fn get_capture_method(&self) -> Option<enums::CaptureMethod>; fn get_merchant_connector_id_in_attempt(&self) -> Option<id_type::MerchantConnectorAccountId>; #[cfg(feature = "v1")] fn get_vault_operation(&self) -> Option<&domain_payments::VaultOperation>; #[cfg(feature = "v2")] fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt>; } <file_sep path="hyperswitch/crates/router/src/core/payments/flows.rs" role="context" start="86" end="193"> pub trait Feature<F, T> { 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> where Self: Sized, F: Clone, dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>; async fn add_access_token<'a>( &self, state: &SessionState, connector: &api::ConnectorData, merchant_account: &domain::MerchantAccount, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> where F: Clone, Self: Sized, dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>; async fn add_session_token<'a>( self, _state: &SessionState, _connector: &api::ConnectorData, ) -> RouterResult<Self> where F: Clone, Self: Sized, dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>, { Ok(self) } async fn add_payment_method_token<'a>( &mut self, _state: &SessionState, _connector: &api::ConnectorData, _tokenization_action: &payments::TokenizationAction, _should_continue_payment: bool, ) -> RouterResult<types::PaymentMethodTokenResult> where F: Clone, Self: Sized, dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>, { Ok(types::PaymentMethodTokenResult { payment_method_token_result: Ok(None), is_payment_method_tokenization_performed: false, connector_response: None, }) } async fn preprocessing_steps<'a>( self, _state: &SessionState, _connector: &api::ConnectorData, ) -> RouterResult<Self> where F: Clone, Self: Sized, dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>, { Ok(self) } async fn postprocessing_steps<'a>( self, _state: &SessionState, _connector: &api::ConnectorData, ) -> RouterResult<Self> where F: Clone, Self: Sized, dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>, { Ok(self) } async fn create_connector_customer<'a>( &self, _state: &SessionState, _connector: &api::ConnectorData, ) -> RouterResult<Option<String>> where F: Clone, Self: Sized, dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>, { Ok(None) } /// Returns the connector request and a bool which specifies whether to proceed with further async fn build_flow_specific_connector_request( &mut self, _state: &SessionState, _connector: &api::ConnectorData, _call_connector_action: payments::CallConnectorAction, ) -> RouterResult<(Option<services::Request>, bool)> { Ok((None, true)) } }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/admin.rs<|crate|> router anchor=validate_bank_account_data 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="4783" end="4862"> fn validate_bank_account_data(data: &types::MerchantAccountData) -> RouterResult<()> { match data { types::MerchantAccountData::Iban { iban, .. } => { // IBAN check algorithm if iban.peek().len() > IBAN_MAX_LENGTH { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "IBAN length must be up to 34 characters".to_string(), } .into()); } let pattern = Regex::new(r"^[A-Z0-9]*$") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to create regex pattern")?; let mut iban = iban.peek().to_string(); if !pattern.is_match(iban.as_str()) { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "IBAN data must be alphanumeric".to_string(), } .into()); } // MOD check let first_4 = iban.chars().take(4).collect::<String>(); iban.push_str(first_4.as_str()); let len = iban.len(); let rearranged_iban = iban .chars() .rev() .take(len - 4) .collect::<String>() .chars() .rev() .collect::<String>(); let mut result = String::new(); rearranged_iban.chars().for_each(|c| { if c.is_ascii_uppercase() { let digit = (u32::from(c) - u32::from('A')) + 10; result.push_str(&format!("{:02}", digit)); } else { result.push(c); } }); let num = result .parse::<u128>() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to validate IBAN")?; if num % 97 != 1 { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid IBAN".to_string(), } .into()); } Ok(()) } types::MerchantAccountData::Bacs { account_number, sort_code, .. } => { if account_number.peek().len() > BACS_MAX_ACCOUNT_NUMBER_LENGTH || sort_code.peek().len() != BACS_SORT_CODE_LENGTH { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid BACS numbers".to_string(), } .into()); } Ok(()) } } } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="4782" end="4782"> use common_utils::{ date_time, ext_traits::{AsyncExt, Encode, OptionExt, ValueExt}, fp_utils, id_type, pii, type_name, types::keymanager::{self as km_types, KeyManagerState, ToEncryptable}, }; use pm_auth::{connector::plaid::transformers::PlaidAuthType, types as pm_auth_types}; use regex::Regex; 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="4949" end="4982"> async fn locker_recipient_create_call( state: &SessionState, merchant_id: &id_type::MerchantId, data: &types::MerchantAccountData, ) -> RouterResult<String> { let enc_data = serde_json::to_string(data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to convert to MerchantAccountData json to String")?; let merchant_id_string = merchant_id.get_string_repr().to_owned(); let cust_id = id_type::CustomerId::try_from(std::borrow::Cow::from(merchant_id_string)) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to convert to CustomerId")?; let payload = transformers::StoreLockerReq::LockerGeneric(transformers::StoreGenericReq { merchant_id: merchant_id.to_owned(), merchant_customer_id: cust_id.clone(), enc_data, ttl: state.conf.locker.ttl_for_storage_in_secs, }); let store_resp = cards::add_card_to_hs_locker( state, &payload, &cust_id, api_enums::LockerChoice::HyperswitchCardVault, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encrypt merchant bank account data")?; Ok(store_resp.card_reference) } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="4864" end="4947"> async fn connector_recipient_create_call( state: &SessionState, merchant_id: &id_type::MerchantId, connector_name: String, auth: &types::ConnectorAuthType, data: &types::MerchantAccountData, ) -> RouterResult<String> { let connector = pm_auth_types::api::PaymentAuthConnectorData::get_connector_by_name( connector_name.as_str(), )?; let auth = pm_auth_types::ConnectorAuthType::foreign_try_from(auth.clone()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while converting ConnectorAuthType")?; let connector_integration: pm_auth_types::api::BoxedConnectorIntegration< '_, pm_auth_types::api::auth_service::RecipientCreate, pm_auth_types::RecipientCreateRequest, pm_auth_types::RecipientCreateResponse, > = connector.connector.get_connector_integration(); let req = match data { types::MerchantAccountData::Iban { iban, name, .. } => { pm_auth_types::RecipientCreateRequest { name: name.clone(), account_data: pm_auth_types::RecipientAccountData::Iban(iban.clone()), address: None, } } types::MerchantAccountData::Bacs { account_number, sort_code, name, .. } => pm_auth_types::RecipientCreateRequest { name: name.clone(), account_data: pm_auth_types::RecipientAccountData::Bacs { sort_code: sort_code.clone(), account_number: account_number.clone(), }, address: None, }, }; let router_data = pm_auth_types::RecipientCreateRouterData { flow: std::marker::PhantomData, merchant_id: Some(merchant_id.to_owned()), connector: Some(connector_name), request: req, response: Err(pm_auth_types::ErrorResponse { status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(), code: consts::NO_ERROR_CODE.to_string(), message: consts::UNSUPPORTED_ERROR_MESSAGE.to_string(), reason: None, }), connector_http_status_code: None, connector_auth_type: auth, }; let resp = payment_initiation_service::execute_connector_processing_step( state, connector_integration, &router_data, &connector.connector_name, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while calling recipient create connector api")?; let recipient_create_resp = resp.response .map_err(|err| errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: connector.connector_name.to_string(), status_code: err.status_code, reason: err.reason, })?; let recipient_id = recipient_create_resp.recipient_id; Ok(recipient_id) } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="4700" end="4781"> async fn process_open_banking_connectors( state: &SessionState, merchant_id: &id_type::MerchantId, auth: &types::ConnectorAuthType, connector_type: &api_enums::ConnectorType, connector: &api_enums::Connector, additional_merchant_data: types::AdditionalMerchantData, ) -> RouterResult<types::MerchantRecipientData> { let new_merchant_data = match additional_merchant_data { types::AdditionalMerchantData::OpenBankingRecipientData(merchant_data) => { if connector_type != &api_enums::ConnectorType::PaymentProcessor { return Err(errors::ApiErrorResponse::InvalidConnectorConfiguration { config: "OpenBanking connector for Payment Initiation should be a payment processor" .to_string(), } .into()); } match &merchant_data { types::MerchantRecipientData::AccountData(acc_data) => { validate_bank_account_data(acc_data)?; let connector_name = api_enums::Connector::to_string(connector); let recipient_creation_not_supported = state .conf .locker_based_open_banking_connectors .connector_list .contains(connector_name.as_str()); let recipient_id = if recipient_creation_not_supported { locker_recipient_create_call(state, merchant_id, acc_data).await } else { connector_recipient_create_call( state, merchant_id, connector_name, auth, acc_data, ) .await } .attach_printable("failed to get recipient_id")?; let conn_recipient_id = if recipient_creation_not_supported { Some(types::RecipientIdType::LockerId(Secret::new(recipient_id))) } else { Some(types::RecipientIdType::ConnectorId(Secret::new( recipient_id, ))) }; let account_data = match &acc_data { types::MerchantAccountData::Iban { iban, name, .. } => { types::MerchantAccountData::Iban { iban: iban.clone(), name: name.clone(), connector_recipient_id: conn_recipient_id.clone(), } } types::MerchantAccountData::Bacs { account_number, sort_code, name, .. } => types::MerchantAccountData::Bacs { account_number: account_number.clone(), sort_code: sort_code.clone(), name: name.clone(), connector_recipient_id: conn_recipient_id.clone(), }, }; types::MerchantRecipientData::AccountData(account_data) } _ => merchant_data.clone(), } } }; Ok(new_merchant_data) } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="4687" end="4698"> pub async fn transfer_key_store_to_key_manager( state: SessionState, req: admin_types::MerchantKeyTransferRequest, ) -> RouterResponse<admin_types::TransferKeyResponse> { let resp = transfer_encryption_key(&state, req).await?; Ok(service_api::ApplicationResponse::Json( admin_types::TransferKeyResponse { total_transferred: resp, }, )) } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="4451" end="4453"> pub fn new(profile: domain::Profile) -> Self { Self { profile } } <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/src/core/payment_methods/tokenize/card_executor.rs<|crate|> router anchor=create_payment_method kind=fn pack=symbol_neighborhood lang=rust role_window=k2 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payment_methods/tokenize/card_executor.rs" role="context" start="515" end="588"> pub async fn create_payment_method( &self, stored_locker_resp: &StoreLockerResponse, network_token_details: &NetworkTokenizationResponse, card_details: &domain::CardDetail, customer_id: &id_type::CustomerId, ) -> RouterResult<domain::PaymentMethod> { let payment_method_id = common_utils::generate_id(consts::ID_LENGTH, "pm"); // Form encrypted PM data (original card) let enc_pm_data = self.encrypt_card(card_details, true).await?; // Form encrypted network token data let enc_token_data = self .encrypt_network_token(network_token_details, card_details, true) .await?; // Form PM create entry let payment_method_create = api::PaymentMethodCreate { payment_method: Some(api_enums::PaymentMethod::Card), payment_method_type: card_details .card_type .as_ref() .and_then(|card_type| api_enums::PaymentMethodType::from_str(card_type).ok()), payment_method_issuer: card_details.card_issuer.clone(), payment_method_issuer_code: None, card: Some(api::CardDetail { card_number: card_details.card_number.clone(), card_exp_month: card_details.card_exp_month.clone(), card_exp_year: card_details.card_exp_year.clone(), card_holder_name: card_details.card_holder_name.clone(), nick_name: card_details.nick_name.clone(), card_issuing_country: card_details.card_issuing_country.clone(), card_network: card_details.card_network.clone(), card_issuer: card_details.card_issuer.clone(), card_type: card_details.card_type.clone(), }), metadata: None, customer_id: Some(customer_id.clone()), card_network: card_details .card_network .as_ref() .map(|network| network.to_string()), bank_transfer: None, wallet: None, client_secret: None, payment_method_data: None, billing: None, connector_mandate_details: None, network_transaction_id: None, }; create_payment_method( self.state, &payment_method_create, customer_id, &payment_method_id, Some(stored_locker_resp.store_card_resp.card_reference.clone()), self.merchant_account.get_id(), None, None, Some(enc_pm_data), self.key_store, None, None, None, self.merchant_account.storage_scheme, None, None, network_token_details.1.clone(), Some(stored_locker_resp.store_token_resp.card_reference.clone()), Some(enc_token_data), ) .await } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/tokenize/card_executor.rs" role="context" start="514" end="514"> use api_models::{enums as api_enums, payment_methods as payment_methods_api}; use common_utils::{ consts, ext_traits::OptionExt, generate_customer_id_of_default_length, id_type, pii::Email, type_name, types::keymanager::{Identifier, KeyManagerState, ToEncryptable}, }; use super::{ migration, CardNetworkTokenizeExecutor, NetworkTokenizationBuilder, NetworkTokenizationProcess, NetworkTokenizationResponse, State, StoreLockerResponse, TransitionTo, }; use crate::{ core::payment_methods::{ cards::{add_card_to_hs_locker, create_payment_method}, transformers as pm_transformers, }, errors::{self, RouterResult}, types::{api, domain}, utils, }; <file_sep path="hyperswitch/crates/router/src/core/payment_methods/tokenize/card_executor.rs" role="context" start="476" end="513"> pub async fn store_card_in_locker( &self, card: &domain::CardDetail, customer_id: &id_type::CustomerId, ) -> RouterResult<pm_transformers::StoreCardRespPayload> { let merchant_id = self.merchant_account.get_id(); let locker_req = pm_transformers::StoreLockerReq::LockerCard(pm_transformers::StoreCardReq { merchant_id: merchant_id.clone(), merchant_customer_id: customer_id.clone(), card: payment_methods_api::Card { card_number: card.card_number.clone(), card_exp_month: card.card_exp_month.clone(), card_exp_year: card.card_exp_year.clone(), card_isin: Some(card.card_number.get_card_isin().clone()), name_on_card: card.card_holder_name.clone(), nick_name: card .nick_name .as_ref() .map(|nick_name| nick_name.clone().expose()), card_brand: None, }, requestor_card_reference: None, ttl: self.state.conf.locker.ttl_for_storage_in_secs, }); let stored_resp = add_card_to_hs_locker( self.state, &locker_req, customer_id, api_enums::LockerChoice::HyperswitchCardVault, ) .await .inspect_err(|err| logger::info!("Error adding card in locker: {:?}", err)) .change_context(errors::ApiErrorResponse::InternalServerError)?; Ok(stored_resp) } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/tokenize/card_executor.rs" role="context" start="454" end="474"> pub async fn store_card_and_token_in_locker( &self, network_token: &NetworkTokenizationResponse, card: &domain::CardDetail, customer_id: &id_type::CustomerId, ) -> RouterResult<StoreLockerResponse> { let stored_card_resp = self.store_card_in_locker(card, customer_id).await?; let stored_token_resp = self .store_network_token_in_locker( network_token, customer_id, card.card_holder_name.clone(), card.nick_name.clone(), ) .await?; let store_locker_response = StoreLockerResponse { store_card_resp: stored_card_resp, store_token_resp: stored_token_resp, }; Ok(store_locker_response) } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1075" end="1083"> pub struct Card { pub card_number: CardNumber, pub name_on_card: Option<masking::Secret<String>>, pub card_exp_month: masking::Secret<String>, pub card_exp_year: masking::Secret<String>, pub card_brand: Option<String>, pub card_isin: Option<String>, pub nick_name: Option<String>, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/webhooks/incoming.rs<|crate|> router anchor=bank_transfer_webhook_flow kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/webhooks/incoming.rs" role="context" start="1683" end="1766"> async fn bank_transfer_webhook_flow( state: SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, business_profile: domain::Profile, key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, source_verified: bool, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { let response = if source_verified { let payment_attempt = get_payment_attempt_from_object_reference_id( &state, webhook_details.object_reference_id, &merchant_account, ) .await?; let payment_id = payment_attempt.payment_id; let request = api::PaymentsRequest { payment_id: Some(api_models::payments::PaymentIdType::PaymentIntentId( payment_id, )), payment_token: payment_attempt.payment_token, ..Default::default() }; Box::pin(payments::payments_core::< api::Authorize, api::PaymentsResponse, _, _, _, payments::PaymentData<api::Authorize>, >( state.clone(), req_state, merchant_account.to_owned(), None, key_store.clone(), payments::PaymentConfirm, request, services::api::AuthFlow::Merchant, payments::CallConnectorAction::Trigger, None, HeaderPayload::with_source(common_enums::PaymentSource::Webhook), None, //Platform merchant account )) .await } else { Err(report!( errors::ApiErrorResponse::WebhookAuthenticationFailed )) }; match response? { services::ApplicationResponse::JsonWithHeaders((payments_response, _)) => { let payment_id = payments_response.payment_id.clone(); let event_type: Option<enums::EventType> = payments_response.status.foreign_into(); let status = payments_response.status; // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook if let Some(outgoing_event_type) = event_type { let primary_object_created_at = payments_response.created; Box::pin(super::create_event_and_trigger_outgoing_webhook( state, merchant_account, business_profile, &key_store, outgoing_event_type, enums::EventClass::Payments, payment_id.get_string_repr().to_owned(), enums::EventObjectType::PaymentDetails, api::OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)), primary_object_created_at, )) .await?; } Ok(WebhookResponseTracker::Payment { payment_id, status }) } _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("received non-json response from payments core")?, } } <file_sep path="hyperswitch/crates/router/src/core/webhooks/incoming.rs" role="context" start="1682" end="1682"> payment_id: dispute_object.payment_id, status: dispute_object.dispute_status, }) } else { metrics::INCOMING_DISPUTE_WEBHOOK_SIGNATURE_FAILURE_METRIC.add(1, &[]); Err(report!( errors::ApiErrorResponse::WebhookAuthenticationFailed )) } } #[instrument(skip_all)] async fn bank_transfer_webhook_flow( state: SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, business_profile: domain::Profile, key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, source_verified: bool, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { let response = if source_verified { let payment_attempt = get_payment_attempt_from_object_reference_id( &state, webhook_details.object_reference_id, <file_sep path="hyperswitch/crates/router/src/core/webhooks/incoming.rs" role="context" start="1806" end="1864"> 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.rs" role="context" start="1768" end="1803"> async fn get_payment_id( db: &dyn StorageInterface, payment_id: &api::PaymentIdType, merchant_id: &common_utils::id_type::MerchantId, storage_scheme: enums::MerchantStorageScheme, ) -> errors::RouterResult<common_utils::id_type::PaymentId> { let pay_id = || async { match payment_id { api_models::payments::PaymentIdType::PaymentIntentId(ref id) => Ok(id.to_owned()), api_models::payments::PaymentIdType::ConnectorTransactionId(ref id) => db .find_payment_attempt_by_merchant_id_connector_txn_id( merchant_id, id, storage_scheme, ) .await .map(|p| p.payment_id), api_models::payments::PaymentIdType::PaymentAttemptId(ref id) => db .find_payment_attempt_by_attempt_id_merchant_id(id, merchant_id, storage_scheme) .await .map(|p| p.payment_id), api_models::payments::PaymentIdType::PreprocessingId(ref id) => db .find_payment_attempt_by_preprocessing_id_merchant_id( id, merchant_id, storage_scheme, ) .await .map(|p| p.payment_id), } }; pay_id() .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) } <file_sep path="hyperswitch/crates/router/src/core/webhooks/incoming.rs" role="context" start="1611" end="1680"> async fn disputes_incoming_webhook_flow( state: SessionState, merchant_account: domain::MerchantAccount, business_profile: domain::Profile, key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, source_verified: bool, connector: &ConnectorEnum, request_details: &IncomingWebhookRequestDetails<'_>, event_type: webhooks::IncomingWebhookEvent, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { metrics::INCOMING_DISPUTE_WEBHOOK_METRIC.add(1, &[]); if source_verified { let db = &*state.store; let dispute_details = connector.get_dispute_details(request_details).switch()?; let payment_attempt = get_payment_attempt_from_object_reference_id( &state, webhook_details.object_reference_id, &merchant_account, ) .await?; let option_dispute = db .find_by_merchant_id_payment_id_connector_dispute_id( merchant_account.get_id(), &payment_attempt.payment_id, &dispute_details.connector_dispute_id, ) .await .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound)?; let dispute_object = get_or_update_dispute_object( state.clone(), option_dispute, dispute_details, merchant_account.get_id(), &merchant_account.organization_id, &payment_attempt, event_type, &business_profile, connector.id(), ) .await?; let disputes_response = Box::new(dispute_object.clone().foreign_into()); let event_type: enums::EventType = dispute_object.dispute_status.foreign_into(); Box::pin(super::create_event_and_trigger_outgoing_webhook( state, merchant_account, business_profile, &key_store, event_type, enums::EventClass::Disputes, dispute_object.dispute_id.clone(), enums::EventObjectType::DisputeDetails, api::OutgoingWebhookContent::DisputeDetails(disputes_response), Some(dispute_object.created_at), )) .await?; metrics::INCOMING_DISPUTE_WEBHOOK_MERCHANT_NOTIFIED_METRIC.add(1, &[]); Ok(WebhookResponseTracker::Dispute { dispute_id: dispute_object.dispute_id, payment_id: dispute_object.payment_id, status: dispute_object.dispute_status, }) } else { metrics::INCOMING_DISPUTE_WEBHOOK_SIGNATURE_FAILURE_METRIC.add(1, &[]); Err(report!( errors::ApiErrorResponse::WebhookAuthenticationFailed )) } } <file_sep path="hyperswitch/crates/router/src/core/webhooks/incoming.rs" role="context" start="1498" end="1607"> async fn frm_incoming_webhook_flow( state: SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, source_verified: bool, event_type: webhooks::IncomingWebhookEvent, object_ref_id: api::ObjectReferenceId, business_profile: domain::Profile, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { if source_verified { let payment_attempt = get_payment_attempt_from_object_reference_id(&state, object_ref_id, &merchant_account) .await?; let payment_response = match event_type { webhooks::IncomingWebhookEvent::FrmApproved => { Box::pin(payments::payments_core::< api::Capture, api::PaymentsResponse, _, _, _, payments::PaymentData<api::Capture>, >( state.clone(), req_state, merchant_account.clone(), None, key_store.clone(), payments::PaymentApprove, api::PaymentsCaptureRequest { payment_id: payment_attempt.payment_id, amount_to_capture: payment_attempt.amount_to_capture, ..Default::default() }, services::api::AuthFlow::Merchant, payments::CallConnectorAction::Trigger, None, HeaderPayload::default(), None, // Platform merchant account )) .await? } webhooks::IncomingWebhookEvent::FrmRejected => { Box::pin(payments::payments_core::< api::Void, api::PaymentsResponse, _, _, _, payments::PaymentData<api::Void>, >( state.clone(), req_state, merchant_account.clone(), None, key_store.clone(), payments::PaymentReject, api::PaymentsCancelRequest { payment_id: payment_attempt.payment_id.clone(), cancellation_reason: Some( "Rejected by merchant based on FRM decision".to_string(), ), ..Default::default() }, services::api::AuthFlow::Merchant, payments::CallConnectorAction::Trigger, None, HeaderPayload::default(), None, // Platform merchant account )) .await? } _ => Err(errors::ApiErrorResponse::EventNotFound)?, }; match payment_response { services::ApplicationResponse::JsonWithHeaders((payments_response, _)) => { let payment_id = payments_response.payment_id.clone(); let status = payments_response.status; let event_type: Option<enums::EventType> = payments_response.status.foreign_into(); if let Some(outgoing_event_type) = event_type { let primary_object_created_at = payments_response.created; Box::pin(super::create_event_and_trigger_outgoing_webhook( state, merchant_account, business_profile, &key_store, outgoing_event_type, enums::EventClass::Payments, payment_id.get_string_repr().to_owned(), enums::EventObjectType::PaymentDetails, api::OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)), primary_object_created_at, )) .await?; }; let response = WebhookResponseTracker::Payment { payment_id, status }; Ok(response) } _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure).attach_printable( "Did not get payment id as object reference id in webhook payments flow", )?, } } else { logger::error!("Webhook source verification failed for frm webhooks flow"); Err(report!( errors::ApiErrorResponse::WebhookAuthenticationFailed )) } } <file_sep path="hyperswitch/crates/router/src/core/webhooks/incoming.rs" role="context" start="126" end="556"> async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( state: SessionState, req_state: ReqState, req: &actix_web::HttpRequest, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, connector_name_or_mca_id: &str, body: actix_web::web::Bytes, is_relay_webhook: bool, ) -> errors::RouterResult<( services::ApplicationResponse<serde_json::Value>, WebhookResponseTracker, serde_json::Value, )> { let key_manager_state = &(&state).into(); 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_optional_mca_and_connector( &state, &merchant_account, connector_name_or_mca_id, &key_store, ) .await?; let decoded_body = connector .decode_webhook_body( &request_details, merchant_account.get_id(), merchant_connector_account .clone() .and_then(|merchant_connector_account| { merchant_connector_account.connector_webhook_details }), 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 merchant_connector_account = match merchant_connector_account { Some(merchant_connector_account) => merchant_connector_account, None => { match Box::pin(helper_utils::get_mca_from_object_reference_id( &state, object_ref_id.clone(), &merchant_account, &connector_name, &key_store, )) .await { Ok(mca) => mca, Err(error) => { return handle_incoming_webhook_error( error, &connector, connector_name.as_str(), &request_details, ); } } } }; 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")? }; if source_verified { metrics::WEBHOOK_SOURCE_VERIFIED_COUNT.add( 1, router_env::metric_attributes!((MERCHANT_ID, merchant_account.get_id().clone())), ); } else if connector.is_webhook_source_verification_mandatory() { // if webhook consumption is mandatory for connector, fail webhook // so that merchant can retrigger it after updating merchant_secret return Err(errors::ApiErrorResponse::WebhookAuthenticationFailed.into()); } logger::info!(source_verified=?source_verified); 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", )?, }; let profile_id = &merchant_connector_account.profile_id; let business_profile = state .store .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(), })?; // If the incoming webhook is a relay webhook, then we need to trigger the relay webhook flow let result_response = if is_relay_webhook { let relay_webhook_response = Box::pin(relay_incoming_webhook_flow( state.clone(), merchant_account, business_profile, key_store, webhook_details, event_type, source_verified, )) .await .attach_printable("Incoming webhook flow for relay failed"); // Using early return ensures unsupported webhooks are acknowledged to the connector if let Some(errors::ApiErrorResponse::NotSupported { .. }) = relay_webhook_response .as_ref() .err() .map(|a| a.current_context()) { logger::error!( webhook_payload =? request_details.body, "Failed while identifying the event type", ); let response = connector .get_webhook_api_response(&request_details, None) .switch() .attach_printable( "Failed while early return in case of not supported event type in relay webhooks", )?; return Ok(( response, WebhookResponseTracker::NoEffect, serde_json::Value::Null, )); }; relay_webhook_response } else { match flow_type { api::WebhookFlow::Payment => Box::pin(payments_incoming_webhook_flow( state.clone(), req_state, merchant_account, business_profile, key_store, webhook_details, source_verified, &connector, &request_details, event_type, )) .await .attach_printable("Incoming webhook flow for payments failed"), api::WebhookFlow::Refund => Box::pin(refunds_incoming_webhook_flow( state.clone(), merchant_account, business_profile, key_store, webhook_details, connector_name.as_str(), source_verified, event_type, )) .await .attach_printable("Incoming webhook flow for refunds failed"), api::WebhookFlow::Dispute => Box::pin(disputes_incoming_webhook_flow( state.clone(), merchant_account, business_profile, key_store, webhook_details, source_verified, &connector, &request_details, event_type, )) .await .attach_printable("Incoming webhook flow for disputes failed"), api::WebhookFlow::BankTransfer => Box::pin(bank_transfer_webhook_flow( state.clone(), req_state, merchant_account, business_profile, key_store, webhook_details, source_verified, )) .await .attach_printable("Incoming bank-transfer webhook flow failed"), api::WebhookFlow::ReturnResponse => Ok(WebhookResponseTracker::NoEffect), api::WebhookFlow::Mandate => Box::pin(mandates_incoming_webhook_flow( state.clone(), merchant_account, business_profile, key_store, webhook_details, source_verified, event_type, )) .await .attach_printable("Incoming webhook flow for mandates failed"), api::WebhookFlow::ExternalAuthentication => { Box::pin(external_authentication_incoming_webhook_flow( state.clone(), req_state, merchant_account, key_store, source_verified, event_type, &request_details, &connector, object_ref_id, business_profile, merchant_connector_account, )) .await .attach_printable("Incoming webhook flow for external authentication failed") } api::WebhookFlow::FraudCheck => Box::pin(frm_incoming_webhook_flow( state.clone(), req_state, merchant_account, key_store, source_verified, event_type, object_ref_id, business_profile, )) .await .attach_printable("Incoming webhook flow for fraud check failed"), #[cfg(feature = "payouts")] api::WebhookFlow::Payout => Box::pin(payouts_incoming_webhook_flow( state.clone(), merchant_account, business_profile, key_store, webhook_details, event_type, source_verified, )) .await .attach_printable("Incoming webhook flow for payouts failed"), _ => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unsupported Flow Type received in incoming webhooks"), } }; match result_response { Ok(response) => response, Err(error) => { return handle_incoming_webhook_error( error, &connector, connector_name.as_str(), &request_details, ); } } } 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/core/webhooks/incoming.rs" role="context" start="1117" end="1151"> async fn get_payment_attempt_from_object_reference_id( state: &SessionState, object_reference_id: webhooks::ObjectReferenceId, merchant_account: &domain::MerchantAccount, ) -> CustomResult<PaymentAttempt, errors::ApiErrorResponse> { let db = &*state.store; match object_reference_id { api::ObjectReferenceId::PaymentId(api::PaymentIdType::ConnectorTransactionId(ref id)) => db .find_payment_attempt_by_merchant_id_connector_txn_id( merchant_account.get_id(), id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound), api::ObjectReferenceId::PaymentId(api::PaymentIdType::PaymentAttemptId(ref id)) => db .find_payment_attempt_by_attempt_id_merchant_id( id, merchant_account.get_id(), merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound), api::ObjectReferenceId::PaymentId(api::PaymentIdType::PreprocessingId(ref id)) => db .find_payment_attempt_by_preprocessing_id_merchant_id( id, merchant_account.get_id(), merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound), _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("received a non-payment id for retrieving payment")?, } } <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 );
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payouts/access_token.rs<|crate|> router anchor=add_access_token_for_payout kind=fn pack=symbol_neighborhood lang=rust role_window=k2 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payouts/access_token.rs" role="context" start="50" end="133"> pub async fn add_access_token_for_payout<F: Clone + 'static>( state: &SessionState, connector: &api_types::ConnectorData, merchant_account: &domain::MerchantAccount, router_data: &types::PayoutsRouterData<F>, payout_type: Option<enums::PayoutType>, ) -> RouterResult<types::AddAccessTokenResult> { use crate::types::api::ConnectorCommon; if connector .connector_name .supports_access_token_for_payout(payout_type) { let merchant_id = merchant_account.get_id(); let store = &*state.store; let old_access_token = store .get_access_token(merchant_id, connector.connector.id()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("DB error when accessing the access token")?; let res = match old_access_token { Some(access_token) => Ok(Some(access_token)), None => { let cloned_router_data = router_data.clone(); let refresh_token_request_data = types::AccessTokenRequestData::try_from( router_data.connector_auth_type.clone(), ) .attach_printable( "Could not create access token request, invalid connector account credentials", )?; let refresh_token_response_data: Result<types::AccessToken, types::ErrorResponse> = Err(types::ErrorResponse::default()); let refresh_token_router_data = payments::helpers::router_data_type_conversion::< _, api_types::AccessTokenAuth, _, _, _, _, >( cloned_router_data, refresh_token_request_data, refresh_token_response_data, ); refresh_connector_auth( state, connector, merchant_account, &refresh_token_router_data, ) .await? .async_map(|access_token| async { //Store the access token in db let store = &*state.store; // This error should not be propagated, we don't want payments to fail once we have // the access token, the next request will create new access token let _ = store .set_access_token( merchant_id, connector.connector.id(), access_token.clone(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("DB error when setting the access token"); Some(access_token) }) .await } }; Ok(types::AddAccessTokenResult { access_token_result: res, connector_supports_access_token: true, }) } else { Ok(types::AddAccessTokenResult { access_token_result: Err(types::ErrorResponse::default()), connector_supports_access_token: false, }) } } <file_sep path="hyperswitch/crates/router/src/core/payouts/access_token.rs" role="context" start="49" end="49"> use common_utils::ext_traits::AsyncExt; use error_stack::ResultExt; use crate::{ consts, core::{ errors::{self, RouterResult}, payments, }, routes::{metrics, SessionState}, services, types::{self, api as api_types, domain, storage::enums}, }; <file_sep path="hyperswitch/crates/router/src/core/payouts/access_token.rs" role="context" start="136" end="194"> pub async fn refresh_connector_auth( state: &SessionState, connector: &api_types::ConnectorData, _merchant_account: &domain::MerchantAccount, router_data: &types::RouterData< api_types::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken, >, ) -> RouterResult<Result<types::AccessToken, types::ErrorResponse>> { let connector_integration: services::BoxedAccessTokenConnectorIntegrationInterface< api_types::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken, > = connector.connector.get_connector_integration(); let access_token_router_data_result = services::execute_connector_processing_step( state, connector_integration, router_data, payments::CallConnectorAction::Trigger, None, ) .await; let access_token_router_data = match access_token_router_data_result { Ok(router_data) => Ok(router_data.response), Err(connector_error) => { // If we receive a timeout error from the connector, then // the error has to be handled gracefully by updating the payment status to failed. // further payment flow will not be continued if connector_error.current_context().is_connector_timeout() { let error_response = types::ErrorResponse { code: consts::REQUEST_TIMEOUT_ERROR_CODE.to_string(), message: consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string(), reason: Some(consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string()), status_code: 504, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, }; Ok(Err(error_response)) } else { Err(connector_error .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not refresh access token")) } } }?; metrics::ACCESS_TOKEN_CREATION.add( 1, router_env::metric_attributes!(("connector", connector.connector_name.to_string())), ); Ok(access_token_router_data) } <file_sep path="hyperswitch/crates/router/src/core/payouts/access_token.rs" role="context" start="19" end="47"> pub async fn create_access_token<F: Clone + 'static>( state: &SessionState, connector_data: &api_types::ConnectorData, merchant_account: &domain::MerchantAccount, router_data: &mut types::PayoutsRouterData<F>, payout_type: Option<enums::PayoutType>, ) -> RouterResult<()> { let connector_access_token = add_access_token_for_payout( state, connector_data, merchant_account, router_data, payout_type, ) .await?; if connector_access_token.connector_supports_access_token { match connector_access_token.access_token_result { Ok(access_token) => { router_data.access_token = access_token; } Err(connector_error) => { router_data.response = Err(connector_error); } } } Ok(()) } <file_sep path="hyperswitch/crates/router/src/services.rs" role="context" start="39" end="39"> pub type Store = RouterStore<StoreType>; <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/fraud_check.rs<|crate|> router anchor=pre_payment_frm_core 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="489" end="578"> pub async fn pre_payment_frm_core<F, Req, D>( state: &SessionState, merchant_account: &domain::MerchantAccount, payment_data: &mut D, frm_info: &mut FrmInfo<F, D>, frm_configs: FrmConfigsObject, customer: &Option<domain::Customer>, should_continue_transaction: &mut bool, should_continue_capture: &mut bool, key_store: domain::MerchantKeyStore, operation: &BoxedOperation<'_, F, Req, D>, ) -> RouterResult<Option<FrmData>> where F: Send + Clone, D: payments::OperationSessionGetters<F> + payments::OperationSessionSetters<F> + Send + Sync + Clone, { let mut frm_data = None; if is_operation_allowed(operation) { frm_data = if let Some(frm_data) = &mut frm_info.frm_data { if matches!( frm_configs.frm_preferred_flow_type, api_enums::FrmPreferredFlowTypes::Pre ) { let fraud_check_operation = &mut frm_info.fraud_check_operation; let frm_router_data = fraud_check_operation .to_domain()? .pre_payment_frm( state, payment_data, frm_data, merchant_account, customer, key_store.clone(), ) .await?; let _router_data = call_frm_service::<F, frm_api::Transaction, _, D>( state, payment_data, frm_data, merchant_account, &key_store, customer, ) .await?; let frm_data_updated = fraud_check_operation .to_update_tracker()? .update_tracker( state, &key_store, frm_data.clone(), payment_data, None, frm_router_data, ) .await?; let frm_fraud_check = frm_data_updated.fraud_check.clone(); payment_data.set_frm_message(frm_fraud_check.clone()); if matches!(frm_fraud_check.frm_status, FraudCheckStatus::Fraud) { *should_continue_transaction = false; frm_info.suggested_action = Some(FrmSuggestion::FrmCancelTransaction); } logger::debug!( "frm_updated_data: {:?} {:?}", frm_info.fraud_check_operation, frm_info.suggested_action ); Some(frm_data_updated) } else if matches!( frm_configs.frm_preferred_flow_type, api_enums::FrmPreferredFlowTypes::Post ) && !matches!( frm_data.fraud_check.frm_status, FraudCheckStatus::TransactionFailure // Incase of TransactionFailure frm status(No frm decision is taken by frm processor), if capture method is automatic we should not change it to manual. ) { *should_continue_capture = false; Some(frm_data.to_owned()) } else { Some(frm_data.to_owned()) } } else { None }; } Ok(frm_data) } <file_sep path="hyperswitch/crates/router/src/core/fraud_check.rs" role="context" start="488" end="488"> use api_models::{self, enums as api_enums}; use router_env::{ logger, tracing::{self, instrument}, }; 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="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.rs" role="context" start="581" end="674"> pub async fn post_payment_frm_core<F, D>( state: &SessionState, req_state: ReqState, merchant_account: &domain::MerchantAccount, payment_data: &mut D, frm_info: &mut FrmInfo<F, D>, frm_configs: FrmConfigsObject, customer: &Option<domain::Customer>, key_store: domain::MerchantKeyStore, should_continue_capture: &mut bool, platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<Option<FrmData>> where F: Send + Clone, D: payments::OperationSessionGetters<F> + payments::OperationSessionSetters<F> + Send + Sync + Clone, { if let Some(frm_data) = &mut frm_info.frm_data { // Allow the Post flow only if the payment is authorized, // this logic has to be removed if we are going to call /sale or /transaction after failed transaction let fraud_check_operation = &mut frm_info.fraud_check_operation; if payment_data.get_payment_attempt().status == AttemptStatus::Authorized { let frm_router_data_opt = fraud_check_operation .to_domain()? .post_payment_frm( state, req_state.clone(), payment_data, frm_data, merchant_account, customer, key_store.clone(), ) .await?; if let Some(frm_router_data) = frm_router_data_opt { let mut frm_data = fraud_check_operation .to_update_tracker()? .update_tracker( state, &key_store, frm_data.to_owned(), payment_data, None, frm_router_data.to_owned(), ) .await?; let frm_fraud_check = frm_data.fraud_check.clone(); let mut frm_suggestion = None; payment_data.set_frm_message(frm_fraud_check.clone()); if matches!(frm_fraud_check.frm_status, FraudCheckStatus::Fraud) { frm_info.suggested_action = Some(FrmSuggestion::FrmCancelTransaction); } else if matches!(frm_fraud_check.frm_status, FraudCheckStatus::ManualReview) { frm_info.suggested_action = Some(FrmSuggestion::FrmManualReview); } fraud_check_operation .to_domain()? .execute_post_tasks( state, req_state, &mut frm_data, merchant_account, frm_configs, &mut frm_suggestion, key_store.clone(), payment_data, customer, should_continue_capture, platform_merchant_account, ) .await?; logger::debug!("frm_post_tasks_data: {:?}", frm_data); let updated_frm_data = fraud_check_operation .to_update_tracker()? .update_tracker( state, &key_store, frm_data.to_owned(), payment_data, frm_suggestion, frm_router_data.to_owned(), ) .await?; return Ok(Some(updated_frm_data)); } } Ok(Some(frm_data.to_owned())) } else { Ok(None) } } <file_sep path="hyperswitch/crates/router/src/core/fraud_check.rs" role="context" start="475" end="486"> fn fraud_check_operation_by_frm_preferred_flow_type<F, D>( frm_preferred_flow_type: api_enums::FrmPreferredFlowTypes, ) -> operation::BoxedFraudCheckOperation<F, D> where operation::FraudCheckPost: operation::FraudCheckOperation<F, D>, operation::FraudCheckPre: operation::FraudCheckOperation<F, D>, { match frm_preferred_flow_type { api_enums::FrmPreferredFlowTypes::Pre => Box::new(operation::FraudCheckPre), api_enums::FrmPreferredFlowTypes::Post => Box::new(operation::FraudCheckPost), } } <file_sep path="hyperswitch/crates/router/src/core/fraud_check.rs" role="context" start="405" end="473"> pub async fn make_frm_data_and_fraud_check_operation<F, D>( _db: &dyn StorageInterface, state: &SessionState, merchant_account: &domain::MerchantAccount, payment_data: D, frm_routing_algorithm: FrmRoutingAlgorithm, profile_id: common_utils::id_type::ProfileId, frm_configs: FrmConfigsObject, _customer: &Option<domain::Customer>, ) -> RouterResult<FrmInfo<F, D>> where F: Send + Clone, D: payments::OperationSessionGetters<F> + payments::OperationSessionSetters<F> + Send + Sync + Clone, { let order_details = payment_data .get_payment_intent() .order_details .clone() .or_else(|| // when the order_details are present within the meta_data, we need to take those to support backward compatibility payment_data.get_payment_intent().metadata.clone().and_then(|meta| { let order_details = meta.get("order_details").to_owned(); order_details.map(|order| vec![masking::Secret::new(order.to_owned())]) })) .map(|order_details_value| { order_details_value .into_iter() .map(|data| { data.peek() .to_owned() .parse_value("OrderDetailsWithAmount") .attach_printable("unable to parse OrderDetailsWithAmount") }) .collect::<Result<Vec<_>, _>>() .unwrap_or_default() }); let frm_connector_details = ConnectorDetailsCore { connector_name: frm_routing_algorithm.data, profile_id, }; let payment_to_frm_data = PaymentToFrmData { amount: payment_data.get_amount(), payment_intent: payment_data.get_payment_intent().to_owned(), payment_attempt: payment_data.get_payment_attempt().to_owned(), merchant_account: merchant_account.to_owned(), address: payment_data.get_address().clone(), connector_details: frm_connector_details.clone(), order_details, frm_metadata: payment_data.get_payment_intent().frm_metadata.clone(), }; let fraud_check_operation: operation::BoxedFraudCheckOperation<F, D> = fraud_check_operation_by_frm_preferred_flow_type(frm_configs.frm_preferred_flow_type); let frm_data = fraud_check_operation .to_get_tracker()? .get_trackers(state, payment_to_frm_data, frm_connector_details) .await?; Ok(FrmInfo { fraud_check_operation, frm_data, suggested_action: None, }) } <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/types.rs" role="context" start="53" end="63"> pub struct FrmData { pub payment_intent: PaymentIntent, pub payment_attempt: PaymentAttempt, pub merchant_account: MerchantAccount, pub fraud_check: FraudCheck, pub address: PaymentAddress, pub connector_details: ConnectorDetailsCore, pub order_details: Option<Vec<OrderDetailsWithAmount>>, pub refund: Option<RefundResponse>, pub frm_metadata: Option<SecretSerdeValue>, } <file_sep path="hyperswitch/crates/api_models/src/enums.rs" role="context" start="185" end="188"> pub enum FrmPreferredFlowTypes { Pre, Post, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/routing/helpers.rs<|crate|> router anchor=default_specific_dynamic_routing_setup 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="1519" end="1602"> pub async fn default_specific_dynamic_routing_setup( state: &SessionState, key_store: domain::MerchantKeyStore, business_profile: domain::Profile, feature_to_enable: routing_types::DynamicRoutingFeatures, mut dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef, dynamic_routing_type: routing_types::DynamicRoutingType, ) -> RouterResult<ApplicationResponse<routing_types::RoutingDictionaryRecord>> { let db = state.store.as_ref(); let key_manager_state = &state.into(); let profile_id = business_profile.get_id().clone(); let merchant_id = business_profile.merchant_id.clone(); let algorithm_id = common_utils::generate_routing_id_of_default_length(); let timestamp = common_utils::date_time::now(); let algo = match dynamic_routing_type { routing_types::DynamicRoutingType::SuccessRateBasedRouting => { let default_success_based_routing_config = routing_types::SuccessBasedRoutingConfig::default(); routing_algorithm::RoutingAlgorithm { algorithm_id: algorithm_id.clone(), profile_id: profile_id.clone(), merchant_id, name: SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM.to_string(), description: None, kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic, algorithm_data: serde_json::json!(default_success_based_routing_config), created_at: timestamp, modified_at: timestamp, algorithm_for: common_enums::TransactionType::Payment, } } routing_types::DynamicRoutingType::EliminationRouting => { let default_elimination_routing_config = routing_types::EliminationRoutingConfig::default(); routing_algorithm::RoutingAlgorithm { algorithm_id: algorithm_id.clone(), profile_id: profile_id.clone(), merchant_id, name: ELIMINATION_BASED_DYNAMIC_ROUTING_ALGORITHM.to_string(), description: None, kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic, algorithm_data: serde_json::json!(default_elimination_routing_config), created_at: timestamp, modified_at: timestamp, algorithm_for: common_enums::TransactionType::Payment, } } routing_types::DynamicRoutingType::ContractBasedRouting => { return Err((errors::ApiErrorResponse::InvalidRequestData { message: "Contract routing cannot be set as default".to_string(), }) .into()) } }; let record = db .insert_routing_algorithm(algo) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to insert record in routing algorithm table")?; dynamic_routing_algo_ref.update_algorithm_id( algorithm_id, feature_to_enable, dynamic_routing_type, ); update_business_profile_active_dynamic_algorithm_ref( db, key_manager_state, &key_store, business_profile, dynamic_routing_algo_ref, ) .await?; let new_record = record.foreign_into(); core_metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add( 1, router_env::metric_attributes!(("profile_id", profile_id.clone())), ); Ok(ApplicationResponse::Json(new_record)) } <file_sep path="hyperswitch/crates/router/src/core/routing/helpers.rs" role="context" start="1518" end="1518"> use api_models::routing as routing_types; use common_utils::ext_traits::ValueExt; use common_utils::{ext_traits::Encode, id_type, types::keymanager::KeyManagerState}; use diesel_models::configs; use diesel_models::dynamic_routing_stats::{DynamicRoutingStatsNew, DynamicRoutingStatsUpdate}; use diesel_models::routing_algorithm; use hyperswitch_domain_models::api::ApplicationResponse; use router_env::logger; use router_env::{instrument, tracing}; 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="1636" end="1675"> pub fn get_string_val( &self, params: &Vec<routing_types::DynamicRoutingConfigParams>, ) -> String { let mut parts: Vec<String> = Vec::new(); for param in params { let val = match param { routing_types::DynamicRoutingConfigParams::PaymentMethod => self .payment_method .as_ref() .map_or(String::new(), |pm| pm.to_string()), routing_types::DynamicRoutingConfigParams::PaymentMethodType => self .payment_method_type .as_ref() .map_or(String::new(), |pmt| pmt.to_string()), routing_types::DynamicRoutingConfigParams::AuthenticationType => self .authentication_type .as_ref() .map_or(String::new(), |at| at.to_string()), routing_types::DynamicRoutingConfigParams::Currency => self .currency .as_ref() .map_or(String::new(), |cur| cur.to_string()), routing_types::DynamicRoutingConfigParams::Country => self .country .as_ref() .map_or(String::new(), |cn| cn.to_string()), routing_types::DynamicRoutingConfigParams::CardNetwork => { self.card_network.clone().unwrap_or_default() } routing_types::DynamicRoutingConfigParams::CardBin => { self.card_bin.clone().unwrap_or_default() } }; if !val.is_empty() { parts.push(val); } } parts.join(":") } <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/src/core/routing/helpers.rs" role="context" start="1443" end="1515"> pub async fn enable_specific_routing_algorithm<A>( state: &SessionState, key_store: domain::MerchantKeyStore, business_profile: domain::Profile, feature_to_enable: routing_types::DynamicRoutingFeatures, mut dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef, dynamic_routing_type: routing_types::DynamicRoutingType, algo_type: Option<A>, ) -> RouterResult<ApplicationResponse<routing_types::RoutingDictionaryRecord>> where A: routing_types::DynamicRoutingAlgoAccessor + Clone + Debug, { // Algorithm wasn't created yet let Some(mut algo_type) = algo_type else { return default_specific_dynamic_routing_setup( state, key_store, business_profile, feature_to_enable, dynamic_routing_algo_ref, dynamic_routing_type, ) .await; }; // Algorithm was in disabled state let Some(algo_type_algorithm_id) = algo_type .clone() .get_algorithm_id_with_timestamp() .algorithm_id else { return default_specific_dynamic_routing_setup( state, key_store, business_profile, feature_to_enable, dynamic_routing_algo_ref, dynamic_routing_type, ) .await; }; let db = state.store.as_ref(); let profile_id = business_profile.get_id().clone(); let algo_type_enabled_features = algo_type.get_enabled_features(); if *algo_type_enabled_features == feature_to_enable { // algorithm already has the required feature return Err(errors::ApiErrorResponse::PreconditionFailed { message: format!("{} is already enabled", dynamic_routing_type), } .into()); }; *algo_type_enabled_features = feature_to_enable; dynamic_routing_algo_ref.update_enabled_features(dynamic_routing_type, feature_to_enable); update_business_profile_active_dynamic_algorithm_ref( db, &state.into(), &key_store, business_profile, dynamic_routing_algo_ref.clone(), ) .await?; let routing_algorithm = db .find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algo_type_algorithm_id) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; let updated_routing_record = routing_algorithm.foreign_into(); core_metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add( 1, router_env::metric_attributes!(("profile_id", profile_id.clone())), ); Ok(ApplicationResponse::Json(updated_routing_record)) } <file_sep path="hyperswitch/crates/router/src/core/routing/helpers.rs" role="context" start="1396" end="1440"> pub async fn enable_dynamic_routing_algorithm( state: &SessionState, key_store: domain::MerchantKeyStore, business_profile: domain::Profile, feature_to_enable: routing_types::DynamicRoutingFeatures, dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef, dynamic_routing_type: routing_types::DynamicRoutingType, ) -> RouterResult<ApplicationResponse<routing_types::RoutingDictionaryRecord>> { let mut dynamic_routing = dynamic_routing_algo_ref.clone(); match dynamic_routing_type { routing_types::DynamicRoutingType::SuccessRateBasedRouting => { dynamic_routing .disable_algorithm_id(routing_types::DynamicRoutingType::ContractBasedRouting); enable_specific_routing_algorithm( state, key_store, business_profile, feature_to_enable, dynamic_routing.clone(), dynamic_routing_type, dynamic_routing.success_based_algorithm, ) .await } routing_types::DynamicRoutingType::EliminationRouting => { enable_specific_routing_algorithm( state, key_store, business_profile, feature_to_enable, dynamic_routing.clone(), dynamic_routing_type, dynamic_routing.elimination_routing_algorithm, ) .await } routing_types::DynamicRoutingType::ContractBasedRouting => { Err((errors::ApiErrorResponse::InvalidRequestData { message: "Contract routing cannot be set as default".to_string(), }) .into()) } } } <file_sep path="hyperswitch/crates/router/src/core/routing/helpers.rs" role="context" start="264" end="288"> pub async fn update_business_profile_active_dynamic_algorithm_ref( db: &dyn StorageInterface, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, current_business_profile: domain::Profile, dynamic_routing_algorithm_ref: routing_types::DynamicRoutingAlgorithmRef, ) -> RouterResult<()> { let ref_val = dynamic_routing_algorithm_ref .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to convert dynamic routing ref to value")?; let business_profile_update = domain::ProfileUpdate::DynamicRoutingAlgorithmUpdate { dynamic_routing_algorithm: Some(ref_val), }; db.update_profile_by_profile_id( key_manager_state, merchant_key_store, current_business_profile, business_profile_update, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update dynamic routing algorithm ref in business profile")?; Ok(()) } <file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="1906" end="1906"> pub struct Profile; <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 );
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments.rs<|crate|> router anchor=get_session_token_for_click_to_pay kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="4168" end="4246"> pub async fn get_session_token_for_click_to_pay( state: &SessionState, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, authentication_product_ids: common_types::payments::AuthenticationConnectorAccountMap, payment_intent: &hyperswitch_domain_models::payments::PaymentIntent, ) -> RouterResult<api_models::payments::SessionToken> { let click_to_pay_mca_id = authentication_product_ids .get_click_to_pay_connector_account_id() .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "authentication_product_ids", })?; let key_manager_state = &(state).into(); let merchant_connector_account = state .store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_id, &click_to_pay_mca_id, key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: click_to_pay_mca_id.get_string_repr().to_string(), })?; let click_to_pay_metadata: ClickToPayMetaData = merchant_connector_account .metadata .parse_value("ClickToPayMetaData") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while parsing ClickToPayMetaData")?; let transaction_currency = payment_intent .currency .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("currency is not present in payment_data.payment_intent")?; let required_amount_type = common_utils::types::StringMajorUnitForConnector; let transaction_amount = required_amount_type .convert(payment_intent.amount, transaction_currency) .change_context(errors::ApiErrorResponse::AmountConversionFailed { amount_type: "string major unit", })?; let customer_details_value = payment_intent .customer_details .clone() .get_required_value("customer_details")?; let customer_details: CustomerData = customer_details_value .parse_value("CustomerData") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while parsing customer data from payment intent")?; validate_customer_details_for_click_to_pay(&customer_details)?; let provider = match merchant_connector_account.connector_name.as_str() { "ctp_mastercard" => Some(enums::CtpServiceProvider::Mastercard), "ctp_visa" => Some(enums::CtpServiceProvider::Visa), _ => None, }; Ok(api_models::payments::SessionToken::ClickToPay(Box::new( api_models::payments::ClickToPaySessionResponse { dpa_id: click_to_pay_metadata.dpa_id, dpa_name: click_to_pay_metadata.dpa_name, locale: click_to_pay_metadata.locale, card_brands: click_to_pay_metadata.card_brands, acquirer_bin: click_to_pay_metadata.acquirer_bin, acquirer_merchant_id: click_to_pay_metadata.acquirer_merchant_id, merchant_category_code: click_to_pay_metadata.merchant_category_code, merchant_country_code: click_to_pay_metadata.merchant_country_code, transaction_amount, transaction_currency_code: transaction_currency, phone_number: customer_details.phone.clone(), email: customer_details.email.clone(), phone_country_code: customer_details.phone_country_code.clone(), provider, dpa_client_id: click_to_pay_metadata.dpa_client_id.clone(), }, ))) } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="4167" end="4167"> } } let call_connectors_end_time = Instant::now(); let call_connectors_duration = call_connectors_end_time.saturating_duration_since(call_connectors_start_time); tracing::info!(duration = format!("Duration taken: {}", call_connectors_duration.as_millis())); Ok(payment_data) } #[cfg(feature = "v1")] pub async fn get_session_token_for_click_to_pay( state: &SessionState, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, authentication_product_ids: common_types::payments::AuthenticationConnectorAccountMap, payment_intent: &hyperswitch_domain_models::payments::PaymentIntent, ) -> RouterResult<api_models::payments::SessionToken> { let click_to_pay_mca_id = authentication_product_ids .get_click_to_pay_connector_account_id() .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "authentication_product_ids", })?; let key_manager_state = &(state).into(); <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="4274" end="4379"> pub async fn call_create_connector_customer_if_required<F, Req, D>( state: &SessionState, customer: &Option<domain::Customer>, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, merchant_connector_account: &helpers::MerchantConnectorAccountType, payment_data: &mut D, ) -> RouterResult<Option<storage::CustomerUpdate>> where F: Send + Clone + Sync, Req: Send + Sync, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, Req, router_types::PaymentsResponseData>, RouterData<F, Req, router_types::PaymentsResponseData>: Feature<F, Req> + Send, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, Req, router_types::PaymentsResponseData>, { let connector_name = payment_data.get_payment_attempt().connector.clone(); match connector_name { Some(connector_name) => { let connector = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &connector_name, api::GetToken::Connector, merchant_connector_account.get_mca_id(), )?; let label = { let connector_label = core_utils::get_connector_label( payment_data.get_payment_intent().business_country, payment_data.get_payment_intent().business_label.as_ref(), payment_data .get_payment_attempt() .business_sub_label .as_ref(), &connector_name, ); if let Some(connector_label) = merchant_connector_account .get_mca_id() .map(|mca_id| mca_id.get_string_repr().to_string()) .or(connector_label) { connector_label } else { let profile_id = payment_data .get_payment_intent() .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("profile_id is not set in payment_intent")?; format!("{connector_name}_{}", profile_id.get_string_repr()) } }; let (should_call_connector, existing_connector_customer_id) = customers::should_call_connector_create_customer( state, &connector, customer, &label, ); if should_call_connector { // Create customer at connector and update the customer table to store this data let router_data = payment_data .construct_router_data( state, connector.connector.id(), merchant_account, key_store, customer, merchant_connector_account, None, None, ) .await?; let connector_customer_id = router_data .create_connector_customer(state, &connector) .await?; let customer_update = customers::update_connector_customer_in_customers( &label, customer.as_ref(), connector_customer_id.clone(), ) .await; payment_data.set_connector_customer_id(connector_customer_id); Ok(customer_update) } else { // Customer already created in previous calls use the same value, no need to update payment_data.set_connector_customer_id( existing_connector_customer_id.map(ToOwned::to_owned), ); Ok(None) } } None => Ok(None), } } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="4248" end="4271"> fn validate_customer_details_for_click_to_pay(customer_details: &CustomerData) -> RouterResult<()> { match ( customer_details.phone.as_ref(), customer_details.phone_country_code.as_ref(), customer_details.email.as_ref() ) { (None, None, Some(_)) => Ok(()), (Some(_), Some(_), Some(_)) => Ok(()), (Some(_), Some(_), None) => Ok(()), (Some(_), None, Some(_)) => Ok(()), (None, Some(_), None) => Err(errors::ApiErrorResponse::MissingRequiredField { field_name: "phone", }) .attach_printable("phone number is not present in payment_intent.customer_details"), (Some(_), None, None) => Err(errors::ApiErrorResponse::MissingRequiredField { field_name: "phone_country_code", }) .attach_printable("phone_country_code is not present in payment_intent.customer_details"), (_, _, _) => Err(errors::ApiErrorResponse::MissingRequiredFields { field_names: vec!["phone", "phone_country_code", "email"], }) .attach_printable("either of phone, phone_country_code or email is not present in payment_intent.customer_details"), } } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="4031" end="4165"> pub async fn call_multiple_connectors_service<F, Op, Req, D>( state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, connectors: api::SessionConnectorDatas, _operation: &Op, mut payment_data: D, customer: &Option<domain::Customer>, session_surcharge_details: Option<api::SessionSurchargeDetails>, business_profile: &domain::Profile, header_payload: HeaderPayload, ) -> RouterResult<D> where Op: Debug, F: Send + Clone, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, Req, router_types::PaymentsResponseData>, RouterData<F, Req, router_types::PaymentsResponseData>: Feature<F, Req>, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, Req, router_types::PaymentsResponseData>, { let call_connectors_start_time = Instant::now(); let mut join_handlers = Vec::with_capacity(connectors.len()); for session_connector_data in connectors.iter() { let connector_id = session_connector_data.connector.connector.id(); let merchant_connector_account = construct_profile_id_and_get_mca( state, merchant_account, &payment_data, &session_connector_data.connector.connector_name.to_string(), session_connector_data .connector .merchant_connector_id .as_ref(), key_store, false, ) .await?; payment_data.set_surcharge_details(session_surcharge_details.as_ref().and_then( |session_surcharge_details| { session_surcharge_details.fetch_surcharge_details( session_connector_data.payment_method_sub_type.into(), session_connector_data.payment_method_sub_type, None, ) }, )); let router_data = payment_data .construct_router_data( state, connector_id, merchant_account, key_store, customer, &merchant_connector_account, None, None, ) .await?; let res = router_data.decide_flows( state, &session_connector_data.connector, CallConnectorAction::Trigger, None, business_profile, header_payload.clone(), ); join_handlers.push(res); } let result = join_all(join_handlers).await; for (connector_res, session_connector) in result.into_iter().zip(connectors) { let connector_name = session_connector.connector.connector_name.to_string(); match connector_res { Ok(connector_response) => { if let Ok(router_types::PaymentsResponseData::SessionResponse { session_token, .. }) = connector_response.response.clone() { // If session token is NoSessionTokenReceived, it is not pushed into the sessions_token as there is no response or there can be some error // In case of error, that error is already logged if !matches!( session_token, api_models::payments::SessionToken::NoSessionTokenReceived, ) { payment_data.push_sessions_token(session_token); } } if let Err(connector_error_response) = connector_response.response { logger::error!( "sessions_connector_error {} {:?}", connector_name, connector_error_response ); } } Err(api_error) => { logger::error!("sessions_api_error {} {:?}", connector_name, api_error); } } } // If click_to_pay is enabled and authentication_product_ids is configured in profile, we need to attach click_to_pay block in the session response for invoking click_to_pay SDK if business_profile.is_click_to_pay_enabled { if let Some(value) = business_profile.authentication_product_ids.clone() { let session_token = get_session_token_for_click_to_pay( state, merchant_account.get_id(), key_store, value, payment_data.get_payment_intent(), ) .await?; payment_data.push_sessions_token(session_token); } } let call_connectors_end_time = Instant::now(); let call_connectors_duration = call_connectors_end_time.saturating_duration_since(call_connectors_start_time); tracing::info!(duration = format!("Duration taken: {}", call_connectors_duration.as_millis())); Ok(payment_data) } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="3918" end="4027"> pub async fn call_multiple_connectors_service<F, Op, Req, D>( state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, connectors: api::SessionConnectorDatas, _operation: &Op, mut payment_data: D, customer: &Option<domain::Customer>, _session_surcharge_details: Option<api::SessionSurchargeDetails>, business_profile: &domain::Profile, header_payload: HeaderPayload, ) -> RouterResult<D> where Op: Debug, F: Send + Clone, // To create connector flow specific interface data D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, Req, router_types::PaymentsResponseData>, RouterData<F, Req, router_types::PaymentsResponseData>: Feature<F, Req>, // To construct connector flow specific api dyn api::Connector: services::api::ConnectorIntegration<F, Req, router_types::PaymentsResponseData>, { let call_connectors_start_time = Instant::now(); let mut join_handlers = Vec::with_capacity(connectors.len()); for session_connector_data in connectors.iter() { let merchant_connector_id = session_connector_data .connector .merchant_connector_id .as_ref() .get_required_value("merchant_connector_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("connector id is not set")?; // TODO: make this DB call parallel let merchant_connector_account = state .store .find_merchant_connector_account_by_id(&state.into(), merchant_connector_id, key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_owned(), })?; let connector_id = session_connector_data.connector.connector.id(); let router_data = payment_data .construct_router_data( state, connector_id, merchant_account, key_store, customer, &merchant_connector_account, None, None, ) .await?; let res = router_data.decide_flows( state, &session_connector_data.connector, CallConnectorAction::Trigger, None, business_profile, header_payload.clone(), ); join_handlers.push(res); } let result = join_all(join_handlers).await; for (connector_res, session_connector) in result.into_iter().zip(connectors) { let connector_name = session_connector.connector.connector_name.to_string(); match connector_res { Ok(connector_response) => { if let Ok(router_types::PaymentsResponseData::SessionResponse { session_token, .. }) = connector_response.response.clone() { // If session token is NoSessionTokenReceived, it is not pushed into the sessions_token as there is no response or there can be some error // In case of error, that error is already logged if !matches!( session_token, api_models::payments::SessionToken::NoSessionTokenReceived, ) { payment_data.push_sessions_token(session_token); } } if let Err(connector_error_response) = connector_response.response { logger::error!( "sessions_connector_error {} {:?}", connector_name, connector_error_response ); } } Err(api_error) => { logger::error!("sessions_api_error {} {:?}", connector_name, api_error); } } } let call_connectors_end_time = Instant::now(); let call_connectors_duration = call_connectors_end_time.saturating_duration_since(call_connectors_start_time); tracing::info!(duration = format!("Duration taken: {}", call_connectors_duration.as_millis())); Ok(payment_data) } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="5433" end="5433"> type Error = error_stack::Report<errors::ConnectorError>; <file_sep path="hyperswitch/crates/router/src/core/unified_authentication_service/types.rs" role="context" start="33" end="33"> pub struct ClickToPay; <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/core/payments/helpers.rs<|crate|> router anchor=make_new_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="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="4440" end="4440"> #[derive(Debug, Eq, PartialEq, Clone)] pub enum AttemptType { New, SameOld, } impl AttemptType { #[cfg(feature = "v1")] // The function creates a new payment_attempt from the previous payment attempt but doesn't populate fields like payment_method, error_code etc. // Logic to override the fields with data provided in the request should be done after this if required. // In case if fields are not overridden by the request then they contain the same data that was in the previous attempt provided it is populated in this function. #[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, ) -> 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, <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="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="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="4262" end="4317"> pub fn router_data_type_conversion<F1, F2, Req1, Req2, Res1, Res2>( router_data: RouterData<F1, Req1, Res1>, request: Req2, response: Result<Res2, ErrorResponse>, ) -> RouterData<F2, Req2, Res2> { RouterData { flow: std::marker::PhantomData, request, response, merchant_id: router_data.merchant_id, tenant_id: router_data.tenant_id, address: router_data.address, amount_captured: router_data.amount_captured, minor_amount_captured: router_data.minor_amount_captured, auth_type: router_data.auth_type, connector: router_data.connector, connector_auth_type: router_data.connector_auth_type, connector_meta_data: router_data.connector_meta_data, description: router_data.description, payment_id: router_data.payment_id, payment_method: router_data.payment_method, status: router_data.status, attempt_id: router_data.attempt_id, access_token: router_data.access_token, session_token: router_data.session_token, payment_method_status: router_data.payment_method_status, reference_id: router_data.reference_id, payment_method_token: router_data.payment_method_token, customer_id: router_data.customer_id, connector_customer: router_data.connector_customer, preprocessing_id: router_data.preprocessing_id, payment_method_balance: router_data.payment_method_balance, recurring_mandate_payment_data: router_data.recurring_mandate_payment_data, connector_request_reference_id: router_data.connector_request_reference_id, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, test_mode: router_data.test_mode, connector_api_version: router_data.connector_api_version, connector_http_status_code: router_data.connector_http_status_code, external_latency: router_data.external_latency, apple_pay_flow: router_data.apple_pay_flow, frm_metadata: router_data.frm_metadata, refund_id: router_data.refund_id, dispute_id: router_data.dispute_id, connector_response: router_data.connector_response, integrity_check: Ok(()), connector_wallets_details: router_data.connector_wallets_details, additional_merchant_data: router_data.additional_merchant_data, header_payload: router_data.header_payload, connector_mandate_request_reference_id: router_data.connector_mandate_request_reference_id, authentication_id: router_data.authentication_id, psd2_sca_exemption_type: router_data.psd2_sca_exemption_type, } } <file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="1362" end="1373"> pub fn payment_attempt_status_fsm( payment_method_data: Option<&api::payments::PaymentMethodData>, confirm: Option<bool>, ) -> storage_enums::AttemptStatus { match payment_method_data { Some(_) => match confirm { Some(true) => storage_enums::AttemptStatus::PaymentMethodAwaited, _ => storage_enums::AttemptStatus::ConfirmationAwaited, }, None => storage_enums::AttemptStatus::PaymentMethodAwaited, } } <file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207"> pub struct PaymentMethodData { pub id: Option<String>, pub object: &'static str, pub card: Option<CardDetails>, pub created: Option<time::PrimitiveDateTime>, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/webhooks/incoming.rs<|crate|> router anchor=frm_incoming_webhook_flow kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/webhooks/incoming.rs" role="context" start="1498" end="1607"> async fn frm_incoming_webhook_flow( state: SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, source_verified: bool, event_type: webhooks::IncomingWebhookEvent, object_ref_id: api::ObjectReferenceId, business_profile: domain::Profile, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { if source_verified { let payment_attempt = get_payment_attempt_from_object_reference_id(&state, object_ref_id, &merchant_account) .await?; let payment_response = match event_type { webhooks::IncomingWebhookEvent::FrmApproved => { Box::pin(payments::payments_core::< api::Capture, api::PaymentsResponse, _, _, _, payments::PaymentData<api::Capture>, >( state.clone(), req_state, merchant_account.clone(), None, key_store.clone(), payments::PaymentApprove, api::PaymentsCaptureRequest { payment_id: payment_attempt.payment_id, amount_to_capture: payment_attempt.amount_to_capture, ..Default::default() }, services::api::AuthFlow::Merchant, payments::CallConnectorAction::Trigger, None, HeaderPayload::default(), None, // Platform merchant account )) .await? } webhooks::IncomingWebhookEvent::FrmRejected => { Box::pin(payments::payments_core::< api::Void, api::PaymentsResponse, _, _, _, payments::PaymentData<api::Void>, >( state.clone(), req_state, merchant_account.clone(), None, key_store.clone(), payments::PaymentReject, api::PaymentsCancelRequest { payment_id: payment_attempt.payment_id.clone(), cancellation_reason: Some( "Rejected by merchant based on FRM decision".to_string(), ), ..Default::default() }, services::api::AuthFlow::Merchant, payments::CallConnectorAction::Trigger, None, HeaderPayload::default(), None, // Platform merchant account )) .await? } _ => Err(errors::ApiErrorResponse::EventNotFound)?, }; match payment_response { services::ApplicationResponse::JsonWithHeaders((payments_response, _)) => { let payment_id = payments_response.payment_id.clone(); let status = payments_response.status; let event_type: Option<enums::EventType> = payments_response.status.foreign_into(); if let Some(outgoing_event_type) = event_type { let primary_object_created_at = payments_response.created; Box::pin(super::create_event_and_trigger_outgoing_webhook( state, merchant_account, business_profile, &key_store, outgoing_event_type, enums::EventClass::Payments, payment_id.get_string_repr().to_owned(), enums::EventObjectType::PaymentDetails, api::OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)), primary_object_created_at, )) .await?; }; let response = WebhookResponseTracker::Payment { payment_id, status }; Ok(response) } _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure).attach_printable( "Did not get payment id as object reference id in webhook payments flow", )?, } } else { logger::error!("Webhook source verification failed for frm webhooks flow"); Err(report!( errors::ApiErrorResponse::WebhookAuthenticationFailed )) } } <file_sep path="hyperswitch/crates/router/src/core/webhooks/incoming.rs" role="context" start="1497" end="1497"> status: updated_mandate.mandate_status, }) } else { logger::error!("Webhook source verification failed for mandates webhook flow"); Err(report!( errors::ApiErrorResponse::WebhookAuthenticationFailed )) } } #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] async fn frm_incoming_webhook_flow( state: SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, source_verified: bool, event_type: webhooks::IncomingWebhookEvent, object_ref_id: api::ObjectReferenceId, business_profile: domain::Profile, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { if source_verified { let payment_attempt = get_payment_attempt_from_object_reference_id(&state, object_ref_id, &merchant_account) <file_sep path="hyperswitch/crates/router/src/core/webhooks/incoming.rs" role="context" start="1683" end="1766"> async fn bank_transfer_webhook_flow( state: SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, business_profile: domain::Profile, key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, source_verified: bool, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { let response = if source_verified { let payment_attempt = get_payment_attempt_from_object_reference_id( &state, webhook_details.object_reference_id, &merchant_account, ) .await?; let payment_id = payment_attempt.payment_id; let request = api::PaymentsRequest { payment_id: Some(api_models::payments::PaymentIdType::PaymentIntentId( payment_id, )), payment_token: payment_attempt.payment_token, ..Default::default() }; Box::pin(payments::payments_core::< api::Authorize, api::PaymentsResponse, _, _, _, payments::PaymentData<api::Authorize>, >( state.clone(), req_state, merchant_account.to_owned(), None, key_store.clone(), payments::PaymentConfirm, request, services::api::AuthFlow::Merchant, payments::CallConnectorAction::Trigger, None, HeaderPayload::with_source(common_enums::PaymentSource::Webhook), None, //Platform merchant account )) .await } else { Err(report!( errors::ApiErrorResponse::WebhookAuthenticationFailed )) }; match response? { services::ApplicationResponse::JsonWithHeaders((payments_response, _)) => { let payment_id = payments_response.payment_id.clone(); let event_type: Option<enums::EventType> = payments_response.status.foreign_into(); let status = payments_response.status; // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook if let Some(outgoing_event_type) = event_type { let primary_object_created_at = payments_response.created; Box::pin(super::create_event_and_trigger_outgoing_webhook( state, merchant_account, business_profile, &key_store, outgoing_event_type, enums::EventClass::Payments, payment_id.get_string_repr().to_owned(), enums::EventObjectType::PaymentDetails, api::OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)), primary_object_created_at, )) .await?; } Ok(WebhookResponseTracker::Payment { payment_id, status }) } _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("received non-json response from payments core")?, } } <file_sep path="hyperswitch/crates/router/src/core/webhooks/incoming.rs" role="context" start="1611" end="1680"> async fn disputes_incoming_webhook_flow( state: SessionState, merchant_account: domain::MerchantAccount, business_profile: domain::Profile, key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, source_verified: bool, connector: &ConnectorEnum, request_details: &IncomingWebhookRequestDetails<'_>, event_type: webhooks::IncomingWebhookEvent, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { metrics::INCOMING_DISPUTE_WEBHOOK_METRIC.add(1, &[]); if source_verified { let db = &*state.store; let dispute_details = connector.get_dispute_details(request_details).switch()?; let payment_attempt = get_payment_attempt_from_object_reference_id( &state, webhook_details.object_reference_id, &merchant_account, ) .await?; let option_dispute = db .find_by_merchant_id_payment_id_connector_dispute_id( merchant_account.get_id(), &payment_attempt.payment_id, &dispute_details.connector_dispute_id, ) .await .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound)?; let dispute_object = get_or_update_dispute_object( state.clone(), option_dispute, dispute_details, merchant_account.get_id(), &merchant_account.organization_id, &payment_attempt, event_type, &business_profile, connector.id(), ) .await?; let disputes_response = Box::new(dispute_object.clone().foreign_into()); let event_type: enums::EventType = dispute_object.dispute_status.foreign_into(); Box::pin(super::create_event_and_trigger_outgoing_webhook( state, merchant_account, business_profile, &key_store, event_type, enums::EventClass::Disputes, dispute_object.dispute_id.clone(), enums::EventObjectType::DisputeDetails, api::OutgoingWebhookContent::DisputeDetails(disputes_response), Some(dispute_object.created_at), )) .await?; metrics::INCOMING_DISPUTE_WEBHOOK_MERCHANT_NOTIFIED_METRIC.add(1, &[]); Ok(WebhookResponseTracker::Dispute { dispute_id: dispute_object.dispute_id, payment_id: dispute_object.payment_id, status: dispute_object.dispute_status, }) } else { metrics::INCOMING_DISPUTE_WEBHOOK_SIGNATURE_FAILURE_METRIC.add(1, &[]); Err(report!( errors::ApiErrorResponse::WebhookAuthenticationFailed )) } } <file_sep path="hyperswitch/crates/router/src/core/webhooks/incoming.rs" role="context" start="1410" end="1494"> async fn mandates_incoming_webhook_flow( state: SessionState, merchant_account: domain::MerchantAccount, business_profile: domain::Profile, key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, source_verified: bool, event_type: webhooks::IncomingWebhookEvent, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { if source_verified { let db = &*state.store; let mandate = match webhook_details.object_reference_id { webhooks::ObjectReferenceId::MandateId(webhooks::MandateIdType::MandateId( mandate_id, )) => db .find_mandate_by_merchant_id_mandate_id( merchant_account.get_id(), mandate_id.as_str(), merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?, webhooks::ObjectReferenceId::MandateId( webhooks::MandateIdType::ConnectorMandateId(connector_mandate_id), ) => db .find_mandate_by_merchant_id_connector_mandate_id( merchant_account.get_id(), connector_mandate_id.as_str(), merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?, _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("received a non-mandate id for retrieving mandate")?, }; let mandate_status = common_enums::MandateStatus::foreign_try_from(event_type) .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("event type to mandate status mapping failed")?; let mandate_id = mandate.mandate_id.clone(); let updated_mandate = db .update_mandate_by_merchant_id_mandate_id( merchant_account.get_id(), &mandate_id, storage::MandateUpdate::StatusUpdate { mandate_status }, mandate, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; let mandates_response = Box::new( api::mandates::MandateResponse::from_db_mandate( &state, key_store.clone(), updated_mandate.clone(), merchant_account.storage_scheme, ) .await?, ); let event_type: Option<enums::EventType> = updated_mandate.mandate_status.foreign_into(); if let Some(outgoing_event_type) = event_type { Box::pin(super::create_event_and_trigger_outgoing_webhook( state, merchant_account, business_profile, &key_store, outgoing_event_type, enums::EventClass::Mandates, updated_mandate.mandate_id.clone(), enums::EventObjectType::MandateDetails, api::OutgoingWebhookContent::MandateDetails(mandates_response), Some(updated_mandate.created_at), )) .await?; } Ok(WebhookResponseTracker::Mandate { mandate_id: updated_mandate.mandate_id, status: updated_mandate.mandate_status, }) } else { logger::error!("Webhook source verification failed for mandates webhook flow"); Err(report!( errors::ApiErrorResponse::WebhookAuthenticationFailed )) } } <file_sep path="hyperswitch/crates/router/src/core/webhooks/incoming.rs" role="context" start="1234" end="1407"> async fn external_authentication_incoming_webhook_flow( state: SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, source_verified: bool, event_type: webhooks::IncomingWebhookEvent, request_details: &IncomingWebhookRequestDetails<'_>, connector: &ConnectorEnum, object_ref_id: api::ObjectReferenceId, business_profile: domain::Profile, merchant_connector_account: domain::MerchantConnectorAccount, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { if source_verified { let authentication_details = connector .get_external_authentication_details(request_details) .switch()?; let trans_status = authentication_details.trans_status; let authentication_update = storage::AuthenticationUpdate::PostAuthenticationUpdate { authentication_status: common_enums::AuthenticationStatus::foreign_from( trans_status.clone(), ), trans_status, authentication_value: authentication_details.authentication_value, eci: authentication_details.eci, }; let authentication = if let webhooks::ObjectReferenceId::ExternalAuthenticationID(authentication_id_type) = object_ref_id { match authentication_id_type { webhooks::AuthenticationIdType::AuthenticationId(authentication_id) => state .store .find_authentication_by_merchant_id_authentication_id( merchant_account.get_id(), authentication_id.clone(), ) .await .to_not_found_response(errors::ApiErrorResponse::AuthenticationNotFound { id: authentication_id, }) .attach_printable("Error while fetching authentication record"), webhooks::AuthenticationIdType::ConnectorAuthenticationId( connector_authentication_id, ) => state .store .find_authentication_by_merchant_id_connector_authentication_id( merchant_account.get_id().clone(), connector_authentication_id.clone(), ) .await .to_not_found_response(errors::ApiErrorResponse::AuthenticationNotFound { id: connector_authentication_id, }) .attach_printable("Error while fetching authentication record"), } } else { Err(errors::ApiErrorResponse::WebhookProcessingFailure).attach_printable( "received a non-external-authentication id for retrieving authentication", ) }?; let updated_authentication = state .store .update_authentication_by_merchant_id_authentication_id( authentication, authentication_update, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while updating authentication")?; // Check if it's a payment authentication flow, payment_id would be there only for payment authentication flows if let Some(payment_id) = updated_authentication.payment_id { let is_pull_mechanism_enabled = helper_utils::check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata(merchant_connector_account.metadata.map(|metadata| metadata.expose())); // Merchant doesn't have pull mechanism enabled and if it's challenge flow, we have to authorize whenever we receive a ARes webhook if !is_pull_mechanism_enabled && updated_authentication.authentication_type == Some(common_enums::DecoupledAuthenticationType::Challenge) && event_type == webhooks::IncomingWebhookEvent::ExternalAuthenticationARes { let payment_confirm_req = api::PaymentsRequest { payment_id: Some(api_models::payments::PaymentIdType::PaymentIntentId( payment_id, )), merchant_id: Some(merchant_account.get_id().clone()), ..Default::default() }; let payments_response = Box::pin(payments::payments_core::< api::Authorize, api::PaymentsResponse, _, _, _, payments::PaymentData<api::Authorize>, >( state.clone(), req_state, merchant_account.clone(), None, key_store.clone(), payments::PaymentConfirm, payment_confirm_req, services::api::AuthFlow::Merchant, payments::CallConnectorAction::Trigger, None, HeaderPayload::with_source(enums::PaymentSource::ExternalAuthenticator), None, // Platform merchant account )) .await?; match payments_response { services::ApplicationResponse::JsonWithHeaders((payments_response, _)) => { let payment_id = payments_response.payment_id.clone(); let status = payments_response.status; let event_type: Option<enums::EventType> = payments_response.status.foreign_into(); // Set poll_id as completed in redis to allow the fetch status of poll through retrieve_poll_status api from client let poll_id = core_utils::get_poll_id( merchant_account.get_id(), core_utils::get_external_authentication_request_poll_id(&payment_id), ); let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; redis_conn .set_key_without_modifying_ttl( &poll_id.into(), api_models::poll::PollStatus::Completed.to_string(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add poll_id in redis")?; // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook if let Some(outgoing_event_type) = event_type { let primary_object_created_at = payments_response.created; Box::pin(super::create_event_and_trigger_outgoing_webhook( state, merchant_account, business_profile, &key_store, outgoing_event_type, enums::EventClass::Payments, payment_id.get_string_repr().to_owned(), enums::EventObjectType::PaymentDetails, api::OutgoingWebhookContent::PaymentDetails(Box::new( payments_response, )), primary_object_created_at, )) .await?; }; let response = WebhookResponseTracker::Payment { payment_id, status }; Ok(response) } _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure).attach_printable( "Did not get payment id as object reference id in webhook payments flow", )?, } } else { Ok(WebhookResponseTracker::NoEffect) } } else { Ok(WebhookResponseTracker::NoEffect) } } else { logger::error!( "Webhook source verification failed for external authentication webhook flow" ); Err(report!( errors::ApiErrorResponse::WebhookAuthenticationFailed )) } } <file_sep path="hyperswitch/crates/router/src/core/webhooks/incoming.rs" role="context" start="126" end="556"> async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( state: SessionState, req_state: ReqState, req: &actix_web::HttpRequest, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, connector_name_or_mca_id: &str, body: actix_web::web::Bytes, is_relay_webhook: bool, ) -> errors::RouterResult<( services::ApplicationResponse<serde_json::Value>, WebhookResponseTracker, serde_json::Value, )> { let key_manager_state = &(&state).into(); 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_optional_mca_and_connector( &state, &merchant_account, connector_name_or_mca_id, &key_store, ) .await?; let decoded_body = connector .decode_webhook_body( &request_details, merchant_account.get_id(), merchant_connector_account .clone() .and_then(|merchant_connector_account| { merchant_connector_account.connector_webhook_details }), 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 merchant_connector_account = match merchant_connector_account { Some(merchant_connector_account) => merchant_connector_account, None => { match Box::pin(helper_utils::get_mca_from_object_reference_id( &state, object_ref_id.clone(), &merchant_account, &connector_name, &key_store, )) .await { Ok(mca) => mca, Err(error) => { return handle_incoming_webhook_error( error, &connector, connector_name.as_str(), &request_details, ); } } } }; 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")? }; if source_verified { metrics::WEBHOOK_SOURCE_VERIFIED_COUNT.add( 1, router_env::metric_attributes!((MERCHANT_ID, merchant_account.get_id().clone())), ); } else if connector.is_webhook_source_verification_mandatory() { // if webhook consumption is mandatory for connector, fail webhook // so that merchant can retrigger it after updating merchant_secret return Err(errors::ApiErrorResponse::WebhookAuthenticationFailed.into()); } logger::info!(source_verified=?source_verified); 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", )?, }; let profile_id = &merchant_connector_account.profile_id; let business_profile = state .store .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(), })?; // If the incoming webhook is a relay webhook, then we need to trigger the relay webhook flow let result_response = if is_relay_webhook { let relay_webhook_response = Box::pin(relay_incoming_webhook_flow( state.clone(), merchant_account, business_profile, key_store, webhook_details, event_type, source_verified, )) .await .attach_printable("Incoming webhook flow for relay failed"); // Using early return ensures unsupported webhooks are acknowledged to the connector if let Some(errors::ApiErrorResponse::NotSupported { .. }) = relay_webhook_response .as_ref() .err() .map(|a| a.current_context()) { logger::error!( webhook_payload =? request_details.body, "Failed while identifying the event type", ); let response = connector .get_webhook_api_response(&request_details, None) .switch() .attach_printable( "Failed while early return in case of not supported event type in relay webhooks", )?; return Ok(( response, WebhookResponseTracker::NoEffect, serde_json::Value::Null, )); }; relay_webhook_response } else { match flow_type { api::WebhookFlow::Payment => Box::pin(payments_incoming_webhook_flow( state.clone(), req_state, merchant_account, business_profile, key_store, webhook_details, source_verified, &connector, &request_details, event_type, )) .await .attach_printable("Incoming webhook flow for payments failed"), api::WebhookFlow::Refund => Box::pin(refunds_incoming_webhook_flow( state.clone(), merchant_account, business_profile, key_store, webhook_details, connector_name.as_str(), source_verified, event_type, )) .await .attach_printable("Incoming webhook flow for refunds failed"), api::WebhookFlow::Dispute => Box::pin(disputes_incoming_webhook_flow( state.clone(), merchant_account, business_profile, key_store, webhook_details, source_verified, &connector, &request_details, event_type, )) .await .attach_printable("Incoming webhook flow for disputes failed"), api::WebhookFlow::BankTransfer => Box::pin(bank_transfer_webhook_flow( state.clone(), req_state, merchant_account, business_profile, key_store, webhook_details, source_verified, )) .await .attach_printable("Incoming bank-transfer webhook flow failed"), api::WebhookFlow::ReturnResponse => Ok(WebhookResponseTracker::NoEffect), api::WebhookFlow::Mandate => Box::pin(mandates_incoming_webhook_flow( state.clone(), merchant_account, business_profile, key_store, webhook_details, source_verified, event_type, )) .await .attach_printable("Incoming webhook flow for mandates failed"), api::WebhookFlow::ExternalAuthentication => { Box::pin(external_authentication_incoming_webhook_flow( state.clone(), req_state, merchant_account, key_store, source_verified, event_type, &request_details, &connector, object_ref_id, business_profile, merchant_connector_account, )) .await .attach_printable("Incoming webhook flow for external authentication failed") } api::WebhookFlow::FraudCheck => Box::pin(frm_incoming_webhook_flow( state.clone(), req_state, merchant_account, key_store, source_verified, event_type, object_ref_id, business_profile, )) .await .attach_printable("Incoming webhook flow for fraud check failed"), #[cfg(feature = "payouts")] api::WebhookFlow::Payout => Box::pin(payouts_incoming_webhook_flow( state.clone(), merchant_account, business_profile, key_store, webhook_details, event_type, source_verified, )) .await .attach_printable("Incoming webhook flow for payouts failed"), _ => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unsupported Flow Type received in incoming webhooks"), } }; match result_response { Ok(response) => response, Err(error) => { return handle_incoming_webhook_error( error, &connector, connector_name.as_str(), &request_details, ); } } } 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/core/webhooks/incoming.rs" role="context" start="1117" end="1151"> async fn get_payment_attempt_from_object_reference_id( state: &SessionState, object_reference_id: webhooks::ObjectReferenceId, merchant_account: &domain::MerchantAccount, ) -> CustomResult<PaymentAttempt, errors::ApiErrorResponse> { let db = &*state.store; match object_reference_id { api::ObjectReferenceId::PaymentId(api::PaymentIdType::ConnectorTransactionId(ref id)) => db .find_payment_attempt_by_merchant_id_connector_txn_id( merchant_account.get_id(), id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound), api::ObjectReferenceId::PaymentId(api::PaymentIdType::PaymentAttemptId(ref id)) => db .find_payment_attempt_by_attempt_id_merchant_id( id, merchant_account.get_id(), merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound), api::ObjectReferenceId::PaymentId(api::PaymentIdType::PreprocessingId(ref id)) => db .find_payment_attempt_by_preprocessing_id_merchant_id( id, merchant_account.get_id(), merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound), _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("received a non-payment id for retrieving payment")?, } } <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),
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments.rs<|crate|> router anchor=decide_payment_method_tokenize_action kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="4956" end="5051"> async fn decide_payment_method_tokenize_action( state: &SessionState, connector_name: &str, payment_method: storage::enums::PaymentMethod, pm_parent_token: Option<&str>, is_connector_tokenization_enabled: bool, apple_pay_flow: Option<domain::ApplePayFlow>, payment_method_type: Option<storage_enums::PaymentMethodType>, merchant_connector_account: &helpers::MerchantConnectorAccountType, ) -> RouterResult<TokenizationAction> { if let Some(storage_enums::PaymentMethodType::Paze) = payment_method_type { // Paze generates a one time use network token which should not be tokenized in the connector or router. match &state.conf.paze_decrypt_keys { Some(paze_keys) => Ok(TokenizationAction::DecryptPazeToken( PazePaymentProcessingDetails { paze_private_key: paze_keys.get_inner().paze_private_key.clone(), paze_private_key_passphrase: paze_keys .get_inner() .paze_private_key_passphrase .clone(), }, )), None => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to fetch Paze configs"), } } else if let Some(storage_enums::PaymentMethodType::GooglePay) = payment_method_type { let google_pay_details = get_google_pay_connector_wallet_details(state, merchant_connector_account); match google_pay_details { Some(wallet_details) => Ok(TokenizationAction::DecryptGooglePayToken(wallet_details)), None => { if is_connector_tokenization_enabled { Ok(TokenizationAction::TokenizeInConnectorAndRouter) } else { Ok(TokenizationAction::TokenizeInRouter) } } } } else { match pm_parent_token { None => Ok(match (is_connector_tokenization_enabled, apple_pay_flow) { (true, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => { TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt( payment_processing_details, ) } (true, _) => TokenizationAction::TokenizeInConnectorAndRouter, (false, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => { TokenizationAction::DecryptApplePayToken(payment_processing_details) } (false, _) => TokenizationAction::TokenizeInRouter, }), Some(token) => { let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let key = format!( "pm_token_{}_{}_{}", token.to_owned(), payment_method, connector_name ); let connector_token_option = redis_conn .get_key::<Option<String>>(&key.into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to fetch the token from redis")?; match connector_token_option { Some(connector_token) => { Ok(TokenizationAction::ConnectorToken(connector_token)) } None => Ok(match (is_connector_tokenization_enabled, apple_pay_flow) { ( true, Some(domain::ApplePayFlow::Simplified(payment_processing_details)), ) => TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt( payment_processing_details, ), (true, _) => TokenizationAction::TokenizeInConnectorAndRouter, ( false, Some(domain::ApplePayFlow::Simplified(payment_processing_details)), ) => TokenizationAction::DecryptApplePayToken(payment_processing_details), (false, _) => TokenizationAction::TokenizeInRouter, }), } } } } } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="4955" end="4955"> ) -> bool { match (current_pm_type).zip(pm_type_filter) { Some((pm_type, type_filter)) => match type_filter { PaymentMethodTypeTokenFilter::AllAccepted => true, PaymentMethodTypeTokenFilter::EnableOnly(enabled) => enabled.contains(&pm_type), PaymentMethodTypeTokenFilter::DisableOnly(disabled) => !disabled.contains(&pm_type), }, None => true, // Allow all types if payment_method_type is not present } } #[allow(clippy::too_many_arguments)] async fn decide_payment_method_tokenize_action( state: &SessionState, connector_name: &str, payment_method: storage::enums::PaymentMethod, pm_parent_token: Option<&str>, is_connector_tokenization_enabled: bool, apple_pay_flow: Option<domain::ApplePayFlow>, payment_method_type: Option<storage_enums::PaymentMethodType>, merchant_connector_account: &helpers::MerchantConnectorAccountType, ) -> RouterResult<TokenizationAction> { if let Some(storage_enums::PaymentMethodType::Paze) = payment_method_type { // Paze generates a one time use network token which should not be tokenized in the connector or router. match &state.conf.paze_decrypt_keys { <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="5102" end="5244"> pub async fn get_connector_tokenization_action_when_confirm_true<F, Req, D>( state: &SessionState, operation: &BoxedOperation<'_, F, Req, D>, payment_data: &mut D, validate_result: &operations::ValidateResult, merchant_connector_account: &helpers::MerchantConnectorAccountType, merchant_key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, business_profile: &domain::Profile, should_retry_with_pan: bool, ) -> RouterResult<(D, TokenizationAction)> where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { let connector = payment_data.get_payment_attempt().connector.to_owned(); let is_mandate = payment_data .get_mandate_id() .as_ref() .and_then(|inner| inner.mandate_reference_id.as_ref()) .map(|mandate_reference| match mandate_reference { api_models::payments::MandateReferenceId::ConnectorMandateId(_) => true, api_models::payments::MandateReferenceId::NetworkMandateId(_) | api_models::payments::MandateReferenceId::NetworkTokenWithNTI(_) => false, }) .unwrap_or(false); let payment_data_and_tokenization_action = match connector { Some(_) if is_mandate => ( payment_data.to_owned(), TokenizationAction::SkipConnectorTokenization, ), Some(connector) if is_operation_confirm(&operation) => { let payment_method = payment_data .get_payment_attempt() .payment_method .get_required_value("payment_method")?; let payment_method_type = payment_data.get_payment_attempt().payment_method_type; let apple_pay_flow = decide_apple_pay_flow(state, payment_method_type, Some(merchant_connector_account)); let is_connector_tokenization_enabled = is_payment_method_tokenization_enabled_for_connector( state, &connector, payment_method, payment_method_type, &apple_pay_flow, )?; add_apple_pay_flow_metrics( &apple_pay_flow, payment_data.get_payment_attempt().connector.clone(), payment_data.get_payment_attempt().merchant_id.clone(), ); let payment_method_action = decide_payment_method_tokenize_action( state, &connector, payment_method, payment_data.get_token(), is_connector_tokenization_enabled, apple_pay_flow, payment_method_type, merchant_connector_account, ) .await?; let connector_tokenization_action = match payment_method_action { TokenizationAction::TokenizeInRouter => { let (_operation, payment_method_data, pm_id) = operation .to_domain()? .make_pm_data( state, payment_data, validate_result.storage_scheme, merchant_key_store, customer, business_profile, should_retry_with_pan, ) .await?; payment_data.set_payment_method_data(payment_method_data); payment_data.set_payment_method_id_in_attempt(pm_id); TokenizationAction::SkipConnectorTokenization } TokenizationAction::TokenizeInConnector => TokenizationAction::TokenizeInConnector, TokenizationAction::TokenizeInConnectorAndRouter => { let (_operation, payment_method_data, pm_id) = operation .to_domain()? .make_pm_data( state, payment_data, validate_result.storage_scheme, merchant_key_store, customer, business_profile, should_retry_with_pan, ) .await?; payment_data.set_payment_method_data(payment_method_data); payment_data.set_payment_method_id_in_attempt(pm_id); TokenizationAction::TokenizeInConnector } TokenizationAction::ConnectorToken(token) => { payment_data.set_pm_token(token); TokenizationAction::SkipConnectorTokenization } TokenizationAction::SkipConnectorTokenization => { TokenizationAction::SkipConnectorTokenization } TokenizationAction::DecryptApplePayToken(payment_processing_details) => { TokenizationAction::DecryptApplePayToken(payment_processing_details) } TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt( payment_processing_details, ) => TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt( payment_processing_details, ), TokenizationAction::DecryptPazeToken(paze_payment_processing_details) => { TokenizationAction::DecryptPazeToken(paze_payment_processing_details) } TokenizationAction::DecryptGooglePayToken( google_pay_payment_processing_details, ) => { TokenizationAction::DecryptGooglePayToken(google_pay_payment_processing_details) } }; (payment_data.to_owned(), connector_tokenization_action) } _ => ( payment_data.to_owned(), TokenizationAction::SkipConnectorTokenization, ), }; Ok(payment_data_and_tokenization_action) } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="5081" end="5098"> pub async fn get_connector_tokenization_action_when_confirm_true<F, Req, D>( _state: &SessionState, _operation: &BoxedOperation<'_, F, Req, D>, payment_data: &mut D, _validate_result: &operations::ValidateResult, _merchant_connector_account: &helpers::MerchantConnectorAccountType, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, ) -> RouterResult<(D, TokenizationAction)> where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { // TODO: Implement this function let payment_data = payment_data.to_owned(); Ok((payment_data, TokenizationAction::SkipConnectorTokenization)) } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="4941" end="4953"> fn is_payment_method_type_allowed_for_connector( current_pm_type: Option<storage::enums::PaymentMethodType>, pm_type_filter: Option<PaymentMethodTypeTokenFilter>, ) -> bool { match (current_pm_type).zip(pm_type_filter) { Some((pm_type, type_filter)) => match type_filter { PaymentMethodTypeTokenFilter::AllAccepted => true, PaymentMethodTypeTokenFilter::EnableOnly(enabled) => enabled.contains(&pm_type), PaymentMethodTypeTokenFilter::DisableOnly(disabled) => !disabled.contains(&pm_type), }, None => true, // Allow all types if payment_method_type is not present } } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="4880" end="4939"> fn get_google_pay_connector_wallet_details( state: &SessionState, merchant_connector_account: &helpers::MerchantConnectorAccountType, ) -> Option<GooglePayPaymentProcessingDetails> { let google_pay_root_signing_keys = state .conf .google_pay_decrypt_keys .as_ref() .map(|google_pay_keys| google_pay_keys.google_pay_root_signing_keys.clone()); match merchant_connector_account.get_connector_wallets_details() { Some(wallet_details) => { let google_pay_wallet_details = wallet_details .parse_value::<api_models::payments::GooglePayWalletDetails>( "GooglePayWalletDetails", ) .map_err(|error| { logger::warn!(?error, "Failed to Parse Value to GooglePayWalletDetails") }); google_pay_wallet_details .ok() .and_then( |google_pay_wallet_details| { match google_pay_wallet_details .google_pay .provider_details { api_models::payments::GooglePayProviderDetails::GooglePayMerchantDetails(merchant_details) => { match ( merchant_details .merchant_info .tokenization_specification .parameters .private_key, google_pay_root_signing_keys, merchant_details .merchant_info .tokenization_specification .parameters .recipient_id, ) { (Some(google_pay_private_key), Some(google_pay_root_signing_keys), Some(google_pay_recipient_id)) => { Some(GooglePayPaymentProcessingDetails { google_pay_private_key, google_pay_root_signing_keys, google_pay_recipient_id }) } _ => { logger::warn!("One or more of the following fields are missing in GooglePayMerchantDetails: google_pay_private_key, google_pay_root_signing_keys, google_pay_recipient_id"); None } } } } } ) } None => None, } } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="5067" end="5077"> pub enum TokenizationAction { TokenizeInRouter, TokenizeInConnector, TokenizeInConnectorAndRouter, ConnectorToken(String), SkipConnectorTokenization, DecryptApplePayToken(payments_api::PaymentProcessingDetails), TokenizeInConnectorAndApplepayPreDecrypt(payments_api::PaymentProcessingDetails), DecryptPazeToken(PazePaymentProcessingDetails), DecryptGooglePayToken(GooglePayPaymentProcessingDetails), } <file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="5054" end="5057"> pub struct PazePaymentProcessingDetails { pub paze_private_key: Secret<String>, pub paze_private_key_passphrase: Secret<String>, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/stripe/transformers.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/connector/stripe/transformers.rs" role="context" start="2884" end="2951"> fn try_from( item: types::ResponseRouterData<F, SetupIntentResponse, T, types::PaymentsResponseData>, ) -> Result<Self, Self::Error> { let redirect_data = item.response.next_action.clone(); let redirection_data = redirect_data .and_then(|redirection_data| redirection_data.get_url()) .map(|redirection_url| { services::RedirectForm::from((redirection_url, services::Method::Get)) }); let mandate_reference = item.response.payment_method.map(|payment_method_id| { // Implemented Save and re-use payment information for recurring charges // For more info: https://docs.stripe.com/recurring-payments#accept-recurring-payments // For backward compatibility payment_method_id & connector_mandate_id is being populated with the same value let connector_mandate_id = Some(payment_method_id.clone()); let payment_method_id = Some(payment_method_id); types::MandateReference { connector_mandate_id, payment_method_id, mandate_metadata: None, connector_mandate_request_reference_id: None, } }); let status = enums::AttemptStatus::from(item.response.status); let connector_response_data = item .response .latest_attempt .as_ref() .and_then(extract_payment_method_connector_response_from_latest_attempt); let response = if connector_util::is_payment_failure(status) { types::PaymentsResponseData::foreign_try_from(( &item.response.last_setup_error, item.http_code, item.response.id.clone(), )) } else { let network_transaction_id = match item.response.latest_attempt { Some(LatestAttempt::PaymentIntentAttempt(attempt)) => attempt .payment_method_details .and_then(|payment_method_details| match payment_method_details { StripePaymentMethodDetailsResponse::Card { card } => { card.network_transaction_id } _ => None, }), _ => None, }; Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(redirection_data), mandate_reference: Box::new(mandate_reference), connector_metadata: None, network_txn_id: network_transaction_id, connector_response_reference_id: Some(item.response.id), incremental_authorization_allowed: None, charges: None, }) }; Ok(Self { status, response, connector_response: connector_response_data, ..item.data }) } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="2883" end="2883"> use std::{collections::HashMap, ops::Deref}; use api_models::{self, enums as api_enums, payments}; use common_utils::{ errors::CustomResult, ext_traits::{ByteSliceExt, Encode}, pii::{self, Email}, request::RequestContent, types::MinorUnit, }; use error_stack::ResultExt; use hyperswitch_domain_models::mandates::AcceptanceType; use masking::{ExposeInterface, ExposeOptionInterface, Mask, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use serde_json::Value; use time::PrimitiveDateTime; use url::Url; pub use self::connect::*; use crate::{ collect_missing_value_keys, connector::utils::{self as connector_util, ApplePay, ApplePayDecrypt, RouterData}, consts, core::errors, headers, services, types::{ self, api, domain, storage::enums, transformers::{ForeignFrom, ForeignTryFrom}, }, utils::OptionExt, }; <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="2985" end="2999"> fn get_url(&self) -> Option<Url> { match self { Self::RedirectToUrl(redirect_to_url) | Self::AlipayHandleRedirect(redirect_to_url) => { Some(redirect_to_url.url.to_owned()) } Self::WechatPayDisplayQrCode(_) => None, Self::VerifyWithMicrodeposits(verify_with_microdeposits) => { Some(verify_with_microdeposits.hosted_verification_url.to_owned()) } Self::CashappHandleRedirectOrDisplayQrCode(_) => None, Self::DisplayBankTransferInstructions(_) => None, Self::MultibancoDisplayDetails(_) => None, Self::NoNextActionBody => None, } } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="2955" end="2968"> fn foreign_from(latest_attempt: Option<LatestAttempt>) -> Self { match latest_attempt { Some(LatestAttempt::PaymentIntentAttempt(attempt)) => attempt .payment_method_options .and_then(|payment_method_options| match payment_method_options { StripePaymentMethodOptions::Card { network_transaction_id, .. } => network_transaction_id.map(|network_id| network_id.expose()), _ => None, }), _ => None, } } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="2741" end="2876"> fn try_from( item: types::ResponseRouterData< F, PaymentIntentSyncResponse, T, types::PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let redirect_data = item.response.next_action.clone(); let redirection_data = redirect_data .and_then(|redirection_data| redirection_data.get_url()) .map(|redirection_url| { services::RedirectForm::from((redirection_url, services::Method::Get)) }); let mandate_reference = item .response .payment_method .clone() .map(|payment_method_id| { // Implemented Save and re-use payment information for recurring charges // For more info: https://docs.stripe.com/recurring-payments#accept-recurring-payments // For backward compatibility payment_method_id & connector_mandate_id is being populated with the same value let connector_mandate_id = Some(payment_method_id.clone().expose()); let payment_method_id = match item.response.latest_charge.clone() { Some(StripeChargeEnum::ChargeObject(charge)) => { match charge.payment_method_details { Some(StripePaymentMethodDetailsResponse::Bancontact { bancontact }) => { bancontact .attached_payment_method .map(|attached_payment_method| attached_payment_method.expose()) .unwrap_or(payment_method_id.expose()) } Some(StripePaymentMethodDetailsResponse::Ideal { ideal }) => ideal .attached_payment_method .map(|attached_payment_method| attached_payment_method.expose()) .unwrap_or(payment_method_id.expose()), Some(StripePaymentMethodDetailsResponse::Sofort { sofort }) => sofort .attached_payment_method .map(|attached_payment_method| attached_payment_method.expose()) .unwrap_or(payment_method_id.expose()), Some(StripePaymentMethodDetailsResponse::Blik) | Some(StripePaymentMethodDetailsResponse::Eps) | Some(StripePaymentMethodDetailsResponse::Fpx) | Some(StripePaymentMethodDetailsResponse::Giropay) | Some(StripePaymentMethodDetailsResponse::Przelewy24) | Some(StripePaymentMethodDetailsResponse::Card { .. }) | Some(StripePaymentMethodDetailsResponse::Klarna) | Some(StripePaymentMethodDetailsResponse::Affirm) | Some(StripePaymentMethodDetailsResponse::AfterpayClearpay) | Some(StripePaymentMethodDetailsResponse::AmazonPay) | Some(StripePaymentMethodDetailsResponse::ApplePay) | Some(StripePaymentMethodDetailsResponse::Ach) | Some(StripePaymentMethodDetailsResponse::Sepa) | Some(StripePaymentMethodDetailsResponse::Becs) | Some(StripePaymentMethodDetailsResponse::Bacs) | Some(StripePaymentMethodDetailsResponse::Wechatpay) | Some(StripePaymentMethodDetailsResponse::Alipay) | Some(StripePaymentMethodDetailsResponse::CustomerBalance) | Some(StripePaymentMethodDetailsResponse::Cashapp { .. }) | None => payment_method_id.expose(), } } Some(StripeChargeEnum::ChargeId(_)) | None => payment_method_id.expose(), }; types::MandateReference { connector_mandate_id, payment_method_id: Some(payment_method_id), mandate_metadata: None, connector_mandate_request_reference_id: None, } }); let connector_metadata = get_connector_metadata(item.response.next_action.as_ref(), item.response.amount)?; let status = enums::AttemptStatus::from(item.response.status.to_owned()); let connector_response_data = item .response .latest_charge .as_ref() .and_then(extract_payment_method_connector_response_from_latest_charge); let response = if connector_util::is_payment_failure(status) { types::PaymentsResponseData::foreign_try_from(( &item.response.payment_intent_fields.last_payment_error, item.http_code, item.response.id.clone(), )) } else { let network_transaction_id = match item.response.latest_charge.clone() { Some(StripeChargeEnum::ChargeObject(charge_object)) => charge_object .payment_method_details .and_then(|payment_method_details| match payment_method_details { StripePaymentMethodDetailsResponse::Card { card } => { card.network_transaction_id } _ => None, }), _ => None, }; let charges = item .response .latest_charge .as_ref() .map(|charge| match charge { StripeChargeEnum::ChargeId(charges) => charges.clone(), StripeChargeEnum::ChargeObject(charge) => charge.id.clone(), }) .and_then(|charge_id| construct_charge_response(charge_id, &item.data.request)); Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(redirection_data), mandate_reference: Box::new(mandate_reference), connector_metadata, network_txn_id: network_transaction_id, connector_response_reference_id: Some(item.response.id.clone()), incremental_authorization_allowed: None, charges, }) }; Ok(Self { status: enums::AttemptStatus::from(item.response.status.to_owned()), response, amount_captured: item .response .amount_received .map(|amount| amount.get_amount_as_i64()), minor_amount_captured: item.response.amount_received, connector_response: connector_response_data, ..item.data }) } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="2623" end="2732"> pub fn get_connector_metadata( next_action: Option<&StripeNextActionResponse>, amount: MinorUnit, ) -> CustomResult<Option<Value>, errors::ConnectorError> { let next_action_response = next_action .and_then(|next_action_response| match next_action_response { StripeNextActionResponse::DisplayBankTransferInstructions(response) => { match response.financial_addresses.clone() { FinancialInformation::StripeFinancialInformation(financial_addresses) => { let bank_instructions = financial_addresses.first(); let (sepa_bank_instructions, bacs_bank_instructions) = bank_instructions .map_or((None, None), |financial_address| { ( financial_address.iban.to_owned().map( |sepa_financial_details| SepaFinancialDetails { account_holder_name: sepa_financial_details .account_holder_name, bic: sepa_financial_details.bic, country: sepa_financial_details.country, iban: sepa_financial_details.iban, reference: response.reference.to_owned(), }, ), financial_address.sort_code.to_owned(), ) }); let bank_transfer_instructions = SepaAndBacsBankTransferInstructions { sepa_bank_instructions, bacs_bank_instructions, receiver: SepaAndBacsReceiver { amount_received: amount - response.amount_remaining, amount_remaining: response.amount_remaining, }, }; Some(bank_transfer_instructions.encode_to_value()) } FinancialInformation::AchFinancialInformation(financial_addresses) => { let mut ach_financial_information = HashMap::new(); for address in financial_addresses { match address.financial_details { AchFinancialDetails::Aba(aba_details) => { ach_financial_information .insert("account_number", aba_details.account_number); ach_financial_information .insert("bank_name", aba_details.bank_name); ach_financial_information .insert("routing_number", aba_details.routing_number); } AchFinancialDetails::Swift(swift_details) => { ach_financial_information .insert("swift_code", swift_details.swift_code); } } } let ach_financial_information_value = serde_json::to_value(ach_financial_information).ok()?; let ach_transfer_instruction = serde_json::from_value::<payments::AchTransfer>( ach_financial_information_value, ) .ok()?; let bank_transfer_instructions = payments::BankTransferNextStepsData { bank_transfer_instructions: payments::BankTransferInstructions::AchCreditTransfer(Box::new( ach_transfer_instruction, )), receiver: None, }; Some(bank_transfer_instructions.encode_to_value()) } } } StripeNextActionResponse::WechatPayDisplayQrCode(response) => { let wechat_pay_instructions = QrCodeNextInstructions { image_data_url: response.image_data_url.to_owned(), display_to_timestamp: None, }; Some(wechat_pay_instructions.encode_to_value()) } StripeNextActionResponse::CashappHandleRedirectOrDisplayQrCode(response) => { let cashapp_qr_instructions: QrCodeNextInstructions = QrCodeNextInstructions { image_data_url: response.qr_code.image_url_png.to_owned(), display_to_timestamp: response.qr_code.expires_at.to_owned(), }; Some(cashapp_qr_instructions.encode_to_value()) } StripeNextActionResponse::MultibancoDisplayDetails(response) => { let multibanco_bank_transfer_instructions = payments::BankTransferNextStepsData { bank_transfer_instructions: payments::BankTransferInstructions::Multibanco( Box::new(payments::MultibancoTransferInstructions { reference: response.clone().reference, entity: response.clone().entity.expose(), }), ), receiver: None, }; Some(multibanco_bank_transfer_instructions.encode_to_value()) } _ => None, }) .transpose() .change_context(errors::ConnectorError::ResponseHandlingFailed)?; Ok(next_action_response) } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="3253" end="3260"> fn from(item: RefundStatus) -> Self { match item { RefundStatus::Succeeded => Self::Success, RefundStatus::Failed => Self::Failure, RefundStatus::Pending => Self::Pending, RefundStatus::RequiresAction => Self::ManualReview, } } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="4196" end="4237"> fn foreign_try_from( (response, http_code, response_id): (&Option<ErrorDetails>, u16, String), ) -> Result<Self, Self::Error> { let (code, error_message) = match response { Some(error_details) => ( error_details .code .to_owned() .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), error_details .message .to_owned() .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), ), None => ( consts::NO_ERROR_CODE.to_string(), consts::NO_ERROR_MESSAGE.to_string(), ), }; Err(types::ErrorResponse { code, message: error_message.clone(), reason: response.clone().and_then(|res| { res.decline_code .clone() .map(|decline_code| { format!( "message - {}, decline_code - {}", error_message, decline_code ) }) .or(Some(error_message.clone())) }), status_code: http_code, attempt_status: None, connector_transaction_id: Some(response_id), network_advice_code: None, network_decline_code: None, network_error_message: None, }) } <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="46" end="46"> type Error = error_stack::Report<errors::ConnectorError>; <file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="3484" end="3487"> pub enum LatestAttempt { PaymentIntentAttempt(Box<LatestPaymentAttempt>), SetupAttempt(String), } <file_sep path="hyperswitch/crates/router/src/connector/payone/transformers.rs" role="context" start="117" end="121"> pub struct Card { card_holder_name: Secret<String>, card_number: CardNumber, expiry_date: Secret<String>, } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1075" end="1083"> pub struct Card { pub card_number: CardNumber, pub name_on_card: Option<masking::Secret<String>>, pub card_exp_month: masking::Secret<String>, pub card_exp_year: masking::Secret<String>, pub card_brand: Option<String>, pub card_isin: Option<String>, pub nick_name: Option<String>, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/aci.rs<|crate|> router<|connector|> aci anchor=construct_refund_router_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/aci.rs" role="context" start="138" end="208"> fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { let auth = ConnectorAuthentication::new() .aci .expect("Missing ACI connector authentication configuration"); let merchant_id = id_type::MerchantId::try_from(Cow::from("aci")).unwrap(); types::RouterData { flow: PhantomData, merchant_id, customer_id: Some(id_type::CustomerId::try_from(Cow::from("aci")).unwrap()), tenant_id: id_type::TenantId::try_from_string("public".to_string()).unwrap(), connector: "aci".to_string(), payment_id: uuid::Uuid::new_v4().to_string(), attempt_id: uuid::Uuid::new_v4().to_string(), payment_method_status: None, status: enums::AttemptStatus::default(), payment_method: enums::PaymentMethod::Card, auth_type: enums::AuthenticationType::NoThreeDs, connector_auth_type: utils::to_connector_auth_type(auth.into()), description: Some("This is a test".to_string()), request: types::RefundsData { payment_amount: 1000, currency: enums::Currency::USD, refund_id: uuid::Uuid::new_v4().to_string(), connector_transaction_id: String::new(), refund_amount: 100, webhook_url: None, connector_metadata: None, reason: None, connector_refund_id: None, browser_info: None, ..utils::PaymentRefundType::default().0 }, response: Err(types::ErrorResponse::default()), address: PaymentAddress::default(), connector_meta_data: None, connector_wallets_details: None, amount_captured: None, minor_amount_captured: None, access_token: None, session_token: None, reference_id: None, payment_method_token: None, connector_customer: None, recurring_mandate_payment_data: None, connector_response: None, preprocessing_id: None, connector_request_reference_id: uuid::Uuid::new_v4().to_string(), #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, test_mode: None, payment_method_balance: None, connector_api_version: None, connector_http_status_code: None, apple_pay_flow: None, external_latency: None, frm_metadata: None, refund_id: None, dispute_id: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, } } <file_sep path="hyperswitch/crates/router/tests/connectors/aci.rs" role="context" start="137" end="137"> use std::{borrow::Cow, marker::PhantomData, str::FromStr, sync::Arc}; use router::{ configs::settings::Settings, core::payments, db::StorageImpl, routes, services, types::{self, storage::enums, PaymentAddress}, }; use crate::{connector_auth::ConnectorAuthentication, utils}; <file_sep path="hyperswitch/crates/router/tests/connectors/aci.rs" role="context" start="260" end="319"> async fn payments_create_failure() { { let conf = Settings::new().unwrap(); use router::connector::Aci; let tx: oneshot::Sender<()> = oneshot::channel().0; let app_state = Box::pin(routes::AppState::with_storage( conf, StorageImpl::PostgresqlTest, tx, Box::new(services::MockApiClient), )) .await; let state = Arc::new(app_state) .get_session_state( &id_type::TenantId::try_from_string("public".to_string()).unwrap(), None, || {}, ) .unwrap(); let connector = utils::construct_connector_data_old( Box::new(Aci::new()), types::Connector::Aci, types::api::GetToken::Connector, None, ); let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< types::api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); let mut request = construct_payment_router_data(); request.request.payment_method_data = types::domain::PaymentMethodData::Card(types::domain::Card { card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), card_exp_month: Secret::new("10".to_string()), card_exp_year: Secret::new("2025".to_string()), card_cvc: Secret::new("99".to_string()), card_issuer: None, card_network: None, card_type: None, card_issuing_country: None, bank_code: None, nick_name: Some(Secret::new("nick_name".into())), card_holder_name: Some(Secret::new("card holder name".into())), }); let response = services::api::execute_connector_processing_step( &state, connector_integration, &request, payments::CallConnectorAction::Trigger, None, ) .await .is_err(); println!("{response:?}"); assert!(response, "The payment was intended to fail but it passed"); } } <file_sep path="hyperswitch/crates/router/tests/connectors/aci.rs" role="context" start="211" end="256"> async fn payments_create_success() { let conf = Settings::new().unwrap(); let tx: oneshot::Sender<()> = oneshot::channel().0; let app_state = Box::pin(routes::AppState::with_storage( conf, StorageImpl::PostgresqlTest, tx, Box::new(services::MockApiClient), )) .await; let state = Arc::new(app_state) .get_session_state( &id_type::TenantId::try_from_string("public".to_string()).unwrap(), None, || {}, ) .unwrap(); use router::connector::Aci; let connector = utils::construct_connector_data_old( Box::new(Aci::new()), types::Connector::Aci, types::api::GetToken::Connector, None, ); let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< types::api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); let request = construct_payment_router_data(); let response = services::api::execute_connector_processing_step( &state, connector_integration, &request, payments::CallConnectorAction::Trigger, None, ) .await .unwrap(); assert!( response.status == enums::AttemptStatus::Charged, "The payment failed" ); } <file_sep path="hyperswitch/crates/router/tests/connectors/aci.rs" role="context" start="19" end="136"> fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { let auth = ConnectorAuthentication::new() .aci .expect("Missing ACI connector authentication configuration"); let merchant_id = id_type::MerchantId::try_from(Cow::from("aci")).unwrap(); types::RouterData { flow: PhantomData, merchant_id, customer_id: Some(id_type::CustomerId::try_from(Cow::from("aci")).unwrap()), tenant_id: id_type::TenantId::try_from_string("public".to_string()).unwrap(), connector: "aci".to_string(), payment_id: uuid::Uuid::new_v4().to_string(), attempt_id: uuid::Uuid::new_v4().to_string(), status: enums::AttemptStatus::default(), auth_type: enums::AuthenticationType::NoThreeDs, payment_method: enums::PaymentMethod::Card, connector_auth_type: utils::to_connector_auth_type(auth.into()), description: Some("This is a test".to_string()), payment_method_status: None, request: types::PaymentsAuthorizeData { amount: 1000, currency: enums::Currency::USD, payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), card_exp_month: Secret::new("10".to_string()), card_exp_year: Secret::new("2025".to_string()), card_cvc: Secret::new("999".to_string()), card_issuer: None, card_network: None, card_type: None, card_issuing_country: None, bank_code: None, nick_name: Some(Secret::new("nick_name".into())), card_holder_name: Some(Secret::new("card holder name".into())), }), 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: None, browser_info: None, order_details: None, order_category: None, email: None, customer_name: None, session_token: None, enrolled_for_3ds: false, related_transaction_id: None, payment_experience: None, payment_method_type: None, router_return_url: None, webhook_url: None, complete_authorize_url: None, customer_id: None, surcharge_details: None, request_incremental_authorization: false, metadata: None, authentication_data: None, customer_acceptance: None, ..utils::PaymentAuthorizeType::default().0 }, response: Err(types::ErrorResponse::default()), address: PaymentAddress::new( None, None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("John".to_string())), last_name: Some(Secret::new("Doe".to_string())), ..Default::default() }), phone: Some(PhoneDetails { number: Some(Secret::new("9123456789".to_string())), country_code: Some("+351".to_string()), }), email: None, }), None, ), connector_meta_data: None, connector_wallets_details: None, amount_captured: None, minor_amount_captured: None, access_token: None, session_token: None, reference_id: None, payment_method_token: None, connector_customer: None, recurring_mandate_payment_data: None, connector_response: None, preprocessing_id: None, connector_request_reference_id: uuid::Uuid::new_v4().to_string(), #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, test_mode: None, payment_method_balance: None, connector_api_version: None, connector_http_status_code: None, apple_pay_flow: None, external_latency: None, frm_metadata: None, refund_id: None, dispute_id: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, } } <file_sep path="hyperswitch/crates/router/tests/connectors/aci.rs" role="context" start="396" end="439"> async fn refunds_create_failure() { let conf = Settings::new().unwrap(); use router::connector::Aci; let connector = utils::construct_connector_data_old( Box::new(Aci::new()), types::Connector::Aci, types::api::GetToken::Connector, None, ); let tx: oneshot::Sender<()> = oneshot::channel().0; let app_state = Box::pin(routes::AppState::with_storage( conf, StorageImpl::PostgresqlTest, tx, Box::new(services::MockApiClient), )) .await; let state = Arc::new(app_state) .get_session_state( &id_type::TenantId::try_from_string("public".to_string()).unwrap(), None, || {}, ) .unwrap(); let connector_integration: services::BoxedRefundConnectorIntegrationInterface< types::api::Execute, types::RefundsData, types::RefundsResponseData, > = connector.connector.get_connector_integration(); let mut request = construct_refund_router_data(); request.request.connector_transaction_id = "1234".to_string(); let response = services::api::execute_connector_processing_step( &state, connector_integration, &request, payments::CallConnectorAction::Trigger, None, ) .await .is_err(); println!("{response:?}"); assert!(response, "The refund was intended to fail but it passed"); } <file_sep path="hyperswitch/crates/router/tests/connectors/aci.rs" role="context" start="322" end="392"> async fn refund_for_successful_payments() { let conf = Settings::new().unwrap(); use router::connector::Aci; let connector = utils::construct_connector_data_old( Box::new(Aci::new()), types::Connector::Aci, types::api::GetToken::Connector, None, ); let tx: oneshot::Sender<()> = oneshot::channel().0; let app_state = Box::pin(routes::AppState::with_storage( conf, StorageImpl::PostgresqlTest, tx, Box::new(services::MockApiClient), )) .await; let state = Arc::new(app_state) .get_session_state( &id_type::TenantId::try_from_string("public".to_string()).unwrap(), None, || {}, ) .unwrap(); let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< types::api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); let request = construct_payment_router_data(); let response = services::api::execute_connector_processing_step( &state, connector_integration, &request, payments::CallConnectorAction::Trigger, None, ) .await .unwrap(); assert!( response.status == enums::AttemptStatus::Charged, "The payment failed" ); let connector_integration: services::BoxedRefundConnectorIntegrationInterface< types::api::Execute, types::RefundsData, types::RefundsResponseData, > = connector.connector.get_connector_integration(); let mut refund_request = construct_refund_router_data(); refund_request.request.connector_transaction_id = match response.response.unwrap() { types::PaymentsResponseData::TransactionResponse { resource_id, .. } => { resource_id.get_connector_transaction_id().unwrap() } _ => panic!("Connector transaction id not found"), }; let response = services::api::execute_connector_processing_step( &state, connector_integration, &refund_request, payments::CallConnectorAction::Trigger, None, ) .await .unwrap(); println!("{response:?}"); assert!( response.response.unwrap().refund_status == enums::RefundStatus::Success, "The refund transaction failed" ); } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1075" end="1083"> pub struct Card { pub card_number: CardNumber, pub name_on_card: Option<masking::Secret<String>>, pub card_exp_month: masking::Secret<String>, pub card_exp_year: masking::Secret<String>, pub card_brand: Option<String>, pub card_isin: Option<String>, pub nick_name: Option<String>, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/gpayments/transformers.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/connector/gpayments/transformers.rs" role="context" start="162" end="237"> fn try_from( item: &GpaymentsRouterData<&types::authentication::ConnectorAuthenticationRouterData>, ) -> Result<Self, Self::Error> { let request = &item.router_data.request; let browser_details = match request.browser_details.clone() { Some(details) => Ok::<Option<types::BrowserInformation>, Self::Error>(Some(details)), None => { if request.device_channel == DeviceChannel::Browser { Err(errors::ConnectorError::MissingRequiredField { field_name: "browser_info", })? } else { Ok(None) } } }?; let card_details = get_card_details(request.payment_method_data.clone(), "gpayments")?; let metadata = GpaymentsMetaData::try_from(&item.router_data.connector_meta_data)?; Ok(Self { acct_number: card_details.card_number.clone(), authentication_ind: "01".into(), card_expiry_date: card_details.get_expiry_date_as_yymm()?.expose(), merchant_id: metadata.merchant_id, message_category: match item.router_data.request.message_category.clone() { MessageCategory::Payment => "01".into(), MessageCategory::NonPayment => "02".into(), }, notification_url: request .return_url .clone() .ok_or(errors::ConnectorError::RequestEncodingFailed) .attach_printable("missing return_url")?, three_ds_comp_ind: request.threeds_method_comp_ind.clone(), purchase_amount: item.amount.to_string(), purchase_date: date_time::DateTime::<date_time::YYYYMMDDHHmmss>::from(date_time::now()) .to_string(), three_ds_server_trans_id: request .pre_authentication_data .threeds_server_transaction_id .clone(), browser_info_collected: BrowserInfoCollected { browser_javascript_enabled: browser_details .as_ref() .and_then(|details| details.java_script_enabled), browser_accept_header: browser_details .as_ref() .and_then(|details| details.accept_header.clone()), browser_ip: browser_details .clone() .and_then(|details| details.ip_address.map(|ip| Secret::new(ip.to_string()))), browser_java_enabled: browser_details .as_ref() .and_then(|details| details.java_enabled), browser_language: browser_details .as_ref() .and_then(|details| details.language.clone()), browser_color_depth: browser_details .as_ref() .and_then(|details| details.color_depth.map(|a| a.to_string())), browser_screen_height: browser_details .as_ref() .and_then(|details| details.screen_height.map(|a| a.to_string())), browser_screen_width: browser_details .as_ref() .and_then(|details| details.screen_width.map(|a| a.to_string())), browser_tz: browser_details .as_ref() .and_then(|details| details.time_zone.map(|a| a.to_string())), browser_user_agent: browser_details .as_ref() .and_then(|details| details.user_agent.clone().map(|a| a.to_string())), }, }) } <file_sep path="hyperswitch/crates/router/src/connector/gpayments/transformers.rs" role="context" start="161" end="161"> use api_models::payments::DeviceChannel; use common_utils::{date_time, types::MinorUnit}; use masking::{ExposeInterface, Secret}; use serde_json::to_string; use crate::{ connector::{ gpayments::gpayments_types::{ AuthStatus, BrowserInfoCollected, GpaymentsAuthenticationSuccessResponse, }, utils, utils::{get_card_details, CardData}, }, consts::BASE64_ENGINE, core::errors, types::{self, api, api::MessageCategory, authentication::ChallengeParams}, }; <file_sep path="hyperswitch/crates/router/src/connector/gpayments/transformers.rs" role="context" start="313" end="361"> fn try_from( item: types::ResponseRouterData< api::PreAuthentication, gpayments_types::GpaymentsPreAuthenticationResponse, types::authentication::PreAuthNRequestData, types::authentication::AuthenticationResponseData, >, ) -> Result<Self, Self::Error> { let threeds_method_response = item.response; let three_ds_method_data = threeds_method_response .three_ds_method_url .as_ref() .map(|_| { let three_ds_method_data_json = serde_json::json!({ "threeDSServerTransID": threeds_method_response.three_ds_server_trans_id, "threeDSMethodNotificationURL": "https://webhook.site/bd06863d-82c2-42ea-b35b-5ffd5ecece71" }); to_string(&three_ds_method_data_json) .change_context(errors::ConnectorError::ResponseDeserializationFailed) .attach_printable("error while constructing three_ds_method_data_str") .map(|three_ds_method_data_string| { Engine::encode(&BASE64_ENGINE, three_ds_method_data_string) }) }) .transpose()?; let connector_metadata = Some(serde_json::json!( gpayments_types::GpaymentsConnectorMetaData { authentication_url: threeds_method_response.auth_url, three_ds_requestor_trans_id: None, } )); let response: Result< types::authentication::AuthenticationResponseData, types::ErrorResponse, > = Ok( types::authentication::AuthenticationResponseData::PreAuthThreeDsMethodCallResponse { threeds_server_transaction_id: threeds_method_response .three_ds_server_trans_id .clone(), three_ds_method_data, three_ds_method_url: threeds_method_response.three_ds_method_url, connector_metadata, }, ); Ok(Self { response, ..item.data.clone() }) } <file_sep path="hyperswitch/crates/router/src/connector/gpayments/transformers.rs" role="context" start="250" end="299"> fn try_from( item: types::ResponseRouterData< api::Authentication, GpaymentsAuthenticationSuccessResponse, types::authentication::ConnectorAuthenticationRequestData, types::authentication::AuthenticationResponseData, >, ) -> Result<Self, Self::Error> { let response_auth = item.response; let creq = serde_json::json!({ "threeDSServerTransID": response_auth.three_ds_server_trans_id, "acsTransID": response_auth.acs_trans_id, "messageVersion": response_auth.message_version, "messageType": "CReq", "challengeWindowSize": "01", }); let creq_str = to_string(&creq) .change_context(errors::ConnectorError::ResponseDeserializationFailed) .attach_printable("error while constructing creq_str")?; let creq_base64 = Engine::encode(&BASE64_ENGINE, creq_str) .trim_end_matches('=') .to_owned(); let response: Result< types::authentication::AuthenticationResponseData, types::ErrorResponse, > = Ok( types::authentication::AuthenticationResponseData::AuthNResponse { trans_status: response_auth.trans_status.clone().into(), authn_flow_type: if response_auth.trans_status == AuthStatus::C { types::authentication::AuthNFlowType::Challenge(Box::new(ChallengeParams { acs_url: response_auth.acs_url, challenge_request: Some(creq_base64), acs_reference_number: Some(response_auth.acs_reference_number.clone()), acs_trans_id: Some(response_auth.acs_trans_id.clone()), three_dsserver_trans_id: Some(response_auth.three_ds_server_trans_id), acs_signed_content: None, })) } else { types::authentication::AuthNFlowType::Frictionless }, authentication_value: response_auth.authentication_value, ds_trans_id: Some(response_auth.ds_trans_id), connector_metadata: None, }, ); Ok(Self { response, ..item.data.clone() }) } <file_sep path="hyperswitch/crates/router/src/connector/gpayments/transformers.rs" role="context" start="138" end="154"> fn try_from( value: &GpaymentsRouterData<&types::authentication::PreAuthNRouterData>, ) -> Result<Self, Self::Error> { let router_data = value.router_data; let metadata = GpaymentsMetaData::try_from(&router_data.connector_meta_data)?; Ok(Self { acct_number: router_data.request.card.card_number.clone(), card_scheme: None, challenge_window_size: Some(gpayments_types::ChallengeWindowSize::FullScreen), event_callback_url: "https://webhook.site/55e3db24-7c4e-4432-9941-d806f68d210b" .to_string(), merchant_id: metadata.merchant_id, skip_auto_browser_info_collect: Some(true), // should auto generate this id. three_ds_requestor_trans_id: uuid::Uuid::new_v4().hyphenated().to_string(), }) } <file_sep path="hyperswitch/crates/router/src/connector/gpayments/transformers.rs" role="context" start="109" end="130"> fn try_from( item: types::ResponseRouterData< api::PreAuthenticationVersionCall, gpayments_types::GpaymentsPreAuthVersionCallResponse, types::authentication::PreAuthNRequestData, types::authentication::AuthenticationResponseData, >, ) -> Result<Self, Self::Error> { let version_response = item.response; let response = Ok( types::authentication::AuthenticationResponseData::PreAuthVersionCallResponse { maximum_supported_3ds_version: version_response .supported_message_versions .and_then(|supported_version| supported_version.iter().max().cloned()) // if no version is returned for the card number, then .unwrap_or(common_utils::types::SemanticVersion::new(0, 0, 0)), }, ); Ok(Self { response, ..item.data.clone() }) } <file_sep path="hyperswitch/crates/router/src/connector/gpayments/transformers.rs" role="context" start="29" end="34"> fn from((amount, item): (MinorUnit, T)) -> Self { Self { amount, router_data: item, } } <file_sep path="hyperswitch/crates/router/src/connector/gpayments/transformers.rs" role="context" start="46" end="46"> type Error = error_stack::Report<errors::ConnectorError>; <file_sep path="hyperswitch/crates/router/src/connector/gpayments/transformers.rs" role="context" start="79" end="82"> pub struct GpaymentsMetaData { pub endpoint_prefix: String, pub merchant_id: common_utils::id_type::MerchantId, } <file_sep path="hyperswitch/crates/router/src/connector/netcetera/netcetera_types.rs" role="context" start="1336" end="1461"> pub struct Browser { /// Exact content of the HTTP accept headers as sent to the 3DS Requestor from the Cardholder's browser. /// This field is limited to maximum 2048 characters and if the total length exceeds the limit, the 3DS Server /// truncates the excess portion. /// /// This field is required for requests where deviceChannel=02 (BRW). browser_accept_header: Option<String>, /// IP address of the browser as returned by the HTTP headers to the 3DS Requestor. The field is limited to maximum 45 /// characters and the accepted values are as following: /// - IPv4 address is represented in the dotted decimal format of 4 sets of decimal numbers separated by dots. The /// decimal number in each and every set is in the range 0 - 255. Example: 1.12.123.255 /// - IPv6 address is represented as eight groups of four hexadecimal digits, each group representing 16 bits (two /// octets). The groups are separated by colons (:). Example: 2011:0db8:85a3:0101:0101:8a2e:0370:7334 /// /// This field is required for requests when deviceChannel = 02 (BRW) where regionally acceptable. #[serde(rename = "browserIP")] browser_ip: Option<masking::Secret<String, common_utils::pii::IpAddress>>, /// Boolean that represents the ability of the cardholder browser to execute Java. Value is returned from the /// navigator.javaEnabled property. /// /// Depending on the message version, the field is required for requests: /// - with message version = 2.1.0 and deviceChannel = 02 (BRW). /// - with message version = 2.2.0 and deviceChannel = 02 (BRW) and browserJavascriptEnabled = true. browser_java_enabled: Option<bool>, /// Value representing the browser language as defined in IETF BCP47. /// /// Until EMV 3DS 2.2.0: /// The value is limited to 1-8 characters. If the value exceeds 8 characters, it will be truncated to a /// semantically valid value, if possible. The value is returned from navigator.language property. /// /// This field is required for requests where deviceChannel = 02 (BRW) /// In other cases this field is optional. /// /// Starting from EMV 3DS 2.3.1: /// The value is limited to 35 characters. If the value exceeds 35 characters, it will be truncated to a /// semantically valid value, if possible. The value is returned from navigator.language property. /// /// This field is required for requests where deviceChannel = 02 (BRW) and browserJavascriptEnabled = true. /// In other cases this field is optional. browser_language: Option<String>, /// Value representing the bit depth of the colour palette for displaying images, in bits per pixel. Obtained from /// Cardholder browser using the screen.colorDepth property. The field is limited to 1-2 characters. /// /// Accepted values are: /// - 1 -> 1 bit /// - 4 -> 4 bits /// - 8 -> 8 bits /// - 15 -> 15 bits /// - 16 -> 16 bits /// - 24 -> 24 bits /// - 32 -> 32 bits /// - 48 -> 48 bits /// /// If the value is not in the accepted values, it will be resolved to the first accepted value lower from the one /// provided. /// /// Depending on the message version, the field is required for requests: /// - with message version = 2.1.0 and deviceChannel = 02 (BRW). /// - with message version = 2.2.0 and deviceChannel = 02 (BRW) and browserJavascriptEnabled = true. browser_color_depth: Option<String>, /// Total height of the Cardholder's screen in pixels. Value is returned from the screen.height property. The value is /// limited to 1-6 characters. /// /// Depending on the message version, the field is required for requests: /// - with message version = 2.1.0 and deviceChannel = 02 (BRW). /// - with message version = 2.2.0 and deviceChannel = 02 (BRW) and browserJavascriptEnabled = true. browser_screen_height: Option<u32>, /// Total width of the Cardholder's screen in pixels. Value is returned from the screen.width property. The value is /// limited to 1-6 characters. /// /// Depending on the message version, the field is required for requests: /// - with message version = 2.1.0 and deviceChannel = 02 (BRW). /// - with message version = 2.2.0 and deviceChannel = 02 (BRW) and browserJavascriptEnabled = true. browser_screen_width: Option<u32>, /// Time difference between UTC time and the Cardholder browser local time, in minutes. The field is limited to 1-5 /// characters where the vauyes is returned from the getTimezoneOffset() method. /// /// Depending on the message version, the field is required for requests: /// - with message version = 2.1.0 and deviceChannel = 02 (BRW). /// - with message version = 2.2.0 and deviceChannel = 02 (BRW) and browserJavascriptEnabled = true. #[serde(rename = "browserTZ")] browser_tz: Option<i32>, /// Exact content of the HTTP user-agent header. The field is limited to maximum 2048 characters. If the total length of /// the User-Agent sent by the browser exceeds 2048 characters, the 3DS Server truncates the excess portion. /// /// This field is required for requests where deviceChannel = 02 (BRW). browser_user_agent: Option<String>, /// Dimensions of the challenge window that has been displayed to the Cardholder. The ACS shall reply with content /// that is formatted to appropriately render in this window to provide the best possible user experience. /// /// Preconfigured sizes are width X height in pixels of the window displayed in the Cardholder browser window. This is /// used only to prepare the CReq request and it is not part of the AReq flow. If not present it will be omitted. /// /// However, when sending the Challenge Request, this field is required when deviceChannel = 02 (BRW). /// /// Accepted values are: /// - 01 -> 250 x 400 /// - 02 -> 390 x 400 /// - 03 -> 500 x 600 /// - 04 -> 600 x 400 /// - 05 -> Full screen challenge_window_size: Option<ChallengeWindowSizeEnum>, /// Boolean that represents the ability of the cardholder browser to execute JavaScript. /// /// This field is required for requests where deviceChannel = 02 (BRW). /// Available for supporting EMV 3DS 2.2.0 and later versions. browser_javascript_enabled: Option<bool>, /// Value representing the browser language preference present in the http header, as defined in IETF BCP 47. /// /// The value is limited to 1-99 elements. Each element should contain a maximum of 100 characters. /// /// This field is required for requests where deviceChannel = 02 (BRW). /// Available for supporting EMV 3DS 2.3.1 and later versions. accept_language: Option<Vec<String>>, } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2478" end="2478"> type Error = error_stack::Report<errors::ValidationError>; <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/cookies.rs<|crate|> router anchor=get_set_cookie_header kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/src/services/authentication/cookies.rs" role="context" start="88" end="90"> fn get_set_cookie_header() -> String { actix_http::header::SET_COOKIE.to_string() } <file_sep path="hyperswitch/crates/router/src/services/authentication/cookies.rs" role="context" start="92" end="94"> pub fn get_cookie_header() -> String { actix_http::header::COOKIE.to_string() } <file_sep path="hyperswitch/crates/router/src/services/authentication/cookies.rs" role="context" start="81" end="85"> fn get_expiry_and_max_age_from_seconds(seconds: i64) -> (OffsetDateTime, Duration) { let max_age = Duration::seconds(seconds); let expiry = OffsetDateTime::now_utc().saturating_add(max_age); (expiry, max_age) } <file_sep path="hyperswitch/crates/router/src/services/authentication/cookies.rs" role="context" start="65" end="78"> fn create_cookie<'c>( token: Secret<String>, expires: OffsetDateTime, max_age: Duration, ) -> Cookie<'c> { Cookie::build((JWT_TOKEN_COOKIE_NAME, token.expose())) .http_only(true) .secure(true) .same_site(SameSite::Strict) .path("/") .expires(expires) .max_age(max_age) .build() } <file_sep path="hyperswitch/crates/router/src/services/authentication/cookies.rs" role="context" start="41" end="50"> pub fn remove_cookie_response() -> UserResponse<()> { let (expiry, max_age) = get_expiry_and_max_age_from_seconds(0); let header_key = get_set_cookie_header(); let header_value = create_cookie("".to_string().into(), expiry, max_age) .to_string() .into_masked(); let header = vec![(header_key, header_value)]; Ok(ApplicationResponse::JsonWithHeaders(((), header))) } <file_sep path="hyperswitch/crates/router/src/services/authentication/cookies.rs" role="context" start="25" end="38"> pub fn set_cookie_response<R>(response: R, token: Secret<String>) -> UserResponse<R> { let jwt_expiry_in_seconds = JWT_TOKEN_TIME_IN_SECS .try_into() .map_err(|_| UserErrors::InternalServerError)?; let (expiry, max_age) = get_expiry_and_max_age_from_seconds(jwt_expiry_in_seconds); let header_value = create_cookie(token, expiry, max_age) .to_string() .into_masked(); let header_key = get_set_cookie_header(); let header = vec![(header_key, header_value)]; Ok(ApplicationResponse::JsonWithHeaders((response, header))) }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/utils/user.rs<|crate|> router anchor=get_oidc_key kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/src/utils/user.rs" role="context" start="270" end="272"> fn get_oidc_key(oidc_state: &str) -> String { format!("{}{oidc_state}", REDIS_SSO_PREFIX) } <file_sep path="hyperswitch/crates/router/src/utils/user.rs" role="context" start="269" end="269"> use crate::{ consts::user::{REDIS_SSO_PREFIX, REDIS_SSO_TTL}, core::errors::{StorageError, UserErrors, UserResult}, routes::SessionState, services::{ authentication::{AuthToken, UserFromToken}, authorization::roles::RoleInfo, }, types::{ domain::{self, MerchantAccount, UserFromStorage}, transformers::ForeignFrom, }, }; <file_sep path="hyperswitch/crates/router/src/utils/user.rs" role="context" start="278" end="283"> pub fn is_sso_auth_type(auth_type: UserAuthType) -> bool { match auth_type { UserAuthType::OpenIdConnect => true, UserAuthType::Password | UserAuthType::MagicLink => false, } } <file_sep path="hyperswitch/crates/router/src/utils/user.rs" role="context" start="274" end="276"> pub fn get_oidc_sso_redirect_url(state: &SessionState, provider: &str) -> String { format!("{}/redirect/oidc/{}", state.conf.user.base_url, provider) } <file_sep path="hyperswitch/crates/router/src/utils/user.rs" role="context" start="255" end="268"> pub async fn get_sso_id_from_redis( state: &SessionState, oidc_state: Secret<String>, ) -> UserResult<String> { let connection = get_redis_connection(state)?; let key = get_oidc_key(&oidc_state.expose()); connection .get_key::<Option<String>>(&key.into()) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to get sso id from redis")? .ok_or(UserErrors::SSOFailed) .attach_printable("Cannot find oidc state in redis. Oidc state invalid or expired") } <file_sep path="hyperswitch/crates/router/src/utils/user.rs" role="context" start="241" end="253"> pub async fn set_sso_id_in_redis( state: &SessionState, oidc_state: Secret<String>, sso_id: String, ) -> UserResult<()> { let connection = get_redis_connection(state)?; let key = get_oidc_key(&oidc_state.expose()); connection .set_key_with_expiry(&key.into(), sso_id, REDIS_SSO_TTL) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to set sso id in redis") }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/services/openidconnect.rs<|crate|> router anchor=get_oidc_redis_key kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <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="186" end="186"> 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="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/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="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="16" end="44"> pub async fn get_authorization_url( state: SessionState, redirect_url: String, redirect_state: Secret<String>, base_url: Secret<String>, client_id: Secret<String>, ) -> UserResult<url::Url> { let discovery_document = get_discovery_document(base_url, &state).await?; let (auth_url, csrf_token, nonce) = get_oidc_core_client(discovery_document, client_id, None, redirect_url)? .authorize_url( oidc_core::CoreAuthenticationFlow::AuthorizationCode, || oidc::CsrfToken::new(redirect_state.expose()), oidc::Nonce::new_random, ) .add_scope(oidc::Scope::new("email".to_string())) .url(); // Save csrf & nonce as key value respectively let key = get_oidc_redis_key(csrf_token.secret()); get_redis_connection(&state)? .set_key_with_expiry(&key.into(), nonce.secret(), consts::user::REDIS_SSO_TTL) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to save csrf-nonce in redis")?; Ok(auth_url) }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/utils/user/theme.rs<|crate|> router anchor=get_specific_file_key kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/src/utils/user/theme.rs" role="context" start="19" end="23"> pub fn get_specific_file_key(theme_id: &str, file_name: &str) -> PathBuf { let mut path = get_theme_dir_key(theme_id); path.push(file_name); path } <file_sep path="hyperswitch/crates/router/src/utils/user/theme.rs" role="context" start="18" end="18"> use std::path::PathBuf; <file_sep path="hyperswitch/crates/router/src/utils/user/theme.rs" role="context" start="29" end="33"> fn path_buf_to_str(path: &PathBuf) -> UserResult<&str> { path.to_str() .ok_or(UserErrors::InternalServerError) .attach_printable(format!("Failed to convert path {:#?} to string", path)) } <file_sep path="hyperswitch/crates/router/src/utils/user/theme.rs" role="context" start="25" end="27"> pub fn get_theme_file_key(theme_id: &str) -> PathBuf { get_specific_file_key(theme_id, "theme.json") } <file_sep path="hyperswitch/crates/router/src/utils/user/theme.rs" role="context" start="15" end="17"> fn get_theme_dir_key(theme_id: &str) -> PathBuf { ["themes", theme_id].iter().collect() }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/thunes.rs<|crate|> router<|connector|> thunes anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/thunes.rs" role="context" start="184" end="187"> async fn should_make_payment() { let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/thunes.rs" role="context" start="215" end="224"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/thunes.rs" role="context" start="191" end="211"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/thunes.rs" role="context" start="162" end="180"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund(payment_method_details(), None, None, get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/thunes.rs" role="context" start="141" end="158"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/thunes.rs" role="context" start="38" end="40"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/thunes.rs" role="context" start="42" end="44"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/xendit.rs<|crate|> router<|connector|> xendit anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/xendit.rs" role="context" start="184" end="187"> async fn should_make_payment() { let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/xendit.rs" role="context" start="183" end="183"> use router::{ types::{self, api, storage::enums, }}; <file_sep path="hyperswitch/crates/router/tests/connectors/xendit.rs" role="context" start="215" end="224"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/xendit.rs" role="context" start="191" end="211"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/xendit.rs" role="context" start="162" end="180"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund(payment_method_details(), None, None, get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/xendit.rs" role="context" start="141" end="158"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/xendit.rs" role="context" start="42" end="44"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/xendit.rs" role="context" start="38" end="40"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/digitalvirgo.rs<|crate|> router<|connector|> digitalvirgo anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/digitalvirgo.rs" role="context" start="184" end="187"> async fn should_make_payment() { let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/digitalvirgo.rs" role="context" start="183" end="183"> use router::{ types::{self, api, storage::enums, }}; <file_sep path="hyperswitch/crates/router/tests/connectors/digitalvirgo.rs" role="context" start="215" end="224"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/digitalvirgo.rs" role="context" start="191" end="211"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/digitalvirgo.rs" role="context" start="162" end="180"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund(payment_method_details(), None, None, get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/digitalvirgo.rs" role="context" start="141" end="158"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/digitalvirgo.rs" role="context" start="42" end="44"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/digitalvirgo.rs" role="context" start="38" end="40"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/types/domain/user.rs<|crate|> router anchor=from_pii_email 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="126" end="129"> pub fn from_pii_email(email: pii::Email) -> UserResult<Self> { let email_string = email.expose().map(|inner| inner.to_lowercase()); Self::new(email_string) } <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="125" end="125"> use common_utils::{ crypto::Encryptable, id_type, new_type::MerchantName, pii, type_name, types::keymanager::Identifier, }; use crate::{ consts, core::{ admin, errors::{UserErrors, UserResult}, }, db::GlobalStorageInterface, routes::SessionState, services::{self, authentication::UserFromToken}, types::{domain, transformers::ForeignFrom}, utils::user::password, }; pub use decision_manager::*; <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="135" end="137"> pub fn get_inner(&self) -> &pii::Email { &self.0 } <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="131" end="133"> pub fn into_inner(self) -> pii::Email { self.0 } <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="104" end="124"> pub fn new(email: Secret<String, pii::EmailStrategy>) -> UserResult<Self> { use validator::ValidateEmail; let email_string = email.expose().to_lowercase(); let email = pii::Email::from_str(&email_string).change_context(UserErrors::EmailParsingError)?; if email_string.validate_email() { let (_username, domain) = match email_string.as_str().split_once('@') { Some((u, d)) => (u, d), None => return Err(UserErrors::EmailParsingError.into()), }; if BLOCKED_EMAIL.contains(domain) { return Err(UserErrors::InvalidEmailError.into()); } Ok(Self(email)) } else { Err(UserErrors::EmailParsingError.into()) } } <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="79" end="88"> fn try_from(value: pii::Email) -> UserResult<Self> { Self::new(Secret::new( value .peek() .split_once('@') .ok_or(UserErrors::InvalidEmailError)? .0 .to_string(), )) } <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="156" end="158"> fn try_from(value: pii::Email) -> Result<Self, Self::Error> { Self::from_pii_email(value) } <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/core/errors/user.rs" role="context" start="5" end="5"> pub type UserResult<T> = CustomResult<T, UserErrors>;
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/types/domain/user.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/types/domain/user.rs" role="context" start="279" end="283"> fn from(_value: user_api::SignUpRequest) -> Self { let new_organization = api_org::OrganizationNew::new(None); let db_organization = ForeignFrom::foreign_from(new_organization); Self(db_organization) } <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="278" end="278"> use api_models::{ admin as admin_api, organization as api_org, user as user_api, user_role as user_role_api, }; use crate::{ consts, core::{ admin, errors::{UserErrors, UserResult}, }, db::GlobalStorageInterface, routes::SessionState, services::{self, authentication::UserFromToken}, types::{domain, transformers::ForeignFrom}, utils::user::password, }; type InviteeUserRequestWithInvitedUserToken = (user_api::InviteUserRequest, UserFromToken); type UserMerchantCreateRequestWithToken = (UserFromStorage, user_api::UserMerchantCreate, UserFromToken); <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="295" end="304"> fn from( (_value, org_id): (user_api::CreateInternalUserRequest, id_type::OrganizationId), ) -> Self { let new_organization = api_org::OrganizationNew { org_id, org_name: None, }; let db_organization = ForeignFrom::foreign_from(new_organization); Self(db_organization) } <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="287" end="291"> fn from(_value: user_api::ConnectAccountRequest) -> Self { let new_organization = api_org::OrganizationNew::new(None); let db_organization = ForeignFrom::foreign_from(new_organization); Self(db_organization) } <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="269" end="275"> fn try_from(value: user_api::SignUpWithMerchantIdRequest) -> UserResult<Self> { let new_organization = api_org::OrganizationNew::new(Some( UserCompanyName::new(value.company_name)?.get_secret(), )); let db_organization = ForeignFrom::foreign_from(new_organization); Ok(Self(db_organization)) } <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="262" end="264"> pub fn get_organization_id(&self) -> id_type::OrganizationId { self.0.get_organization_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="1244" end="1249"> fn foreign_from(value: UserStatus) -> Self { match value { UserStatus::Active => Self::Active, UserStatus::InvitationSent => Self::InvitationSent, } } <file_sep path="hyperswitch/crates/router/src/types/transformers.rs" role="context" start="45" end="47"> pub trait ForeignFrom<F> { fn foreign_from(from: F) -> Self; } <file_sep path="hyperswitch/crates/api_models/src/user.rs" role="context" start="25" end="28"> pub struct SignUpRequest { pub email: pii::Email, pub password: Secret<String>, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/paypal.rs<|crate|> router<|connector|> paypal anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/paypal.rs" role="context" start="313" end="319"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(get_payment_data(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Pending); } <file_sep path="hyperswitch/crates/router/tests/connectors/paypal.rs" role="context" start="312" end="312"> use router::types::{self, domain, storage::enums, AccessToken, ConnectorAuthType}; <file_sep path="hyperswitch/crates/router/tests/connectors/paypal.rs" role="context" start="364" end="373"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(get_payment_data(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/paypal.rs" role="context" start="323" end="359"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(get_payment_data(), get_default_payment_info()) .await .unwrap(); assert_eq!( authorize_response.status.clone(), enums::AttemptStatus::Pending ); let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()); assert_ne!(txn_id, None, "Empty connector transaction id"); let connector_meta = utils::get_connector_metadata(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { mandate_id: None, connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), encoded_data: None, capture_method: Some(enums::CaptureMethod::Automatic), sync_type: types::SyncRequestType::SinglePaymentSync, connector_meta, payment_method_type: None, currency: enums::Currency::USD, payment_experience: None, amount: MinorUnit::new(100), integrity_object: None, ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Pending); } <file_sep path="hyperswitch/crates/router/tests/connectors/paypal.rs" role="context" start="266" end="309"> async fn should_sync_manually_captured_refund() { let authorize_response = CONNECTOR .authorize_payment(get_payment_data(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = "".to_string(); let capture_connector_meta = utils::get_connector_metadata(authorize_response.response); let capture_response = CONNECTOR .capture_payment( txn_id, Some(types::PaymentsCaptureData { connector_meta: capture_connector_meta, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); let refund_txn_id = utils::get_connector_transaction_id(capture_response.response.clone()).unwrap(); let refund_response = CONNECTOR .refund_payment( refund_txn_id, Some(types::RefundsData { ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/paypal.rs" role="context" start="226" end="261"> async fn should_partially_refund_manually_captured_payment() { let authorize_response = CONNECTOR .authorize_payment(get_payment_data(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = "".to_string(); let capture_connector_meta = utils::get_connector_metadata(authorize_response.response); let capture_response = CONNECTOR .capture_payment( txn_id, Some(types::PaymentsCaptureData { connector_meta: capture_connector_meta, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); let refund_txn_id = utils::get_connector_transaction_id(capture_response.response.clone()).unwrap(); let response = CONNECTOR .refund_payment( refund_txn_id, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/paypal.rs" role="context" start="51" end="56"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { access_token: get_access_token(), ..Default::default() }) } <file_sep path="hyperswitch/crates/router/tests/connectors/paypal.rs" role="context" start="58" end="66"> fn get_payment_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4000020000000000").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }) }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/bluesnap.rs<|crate|> router<|connector|> bluesnap anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/bluesnap.rs" role="context" start="241" end="247"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/bluesnap.rs" role="context" start="240" end="240"> use router::types::{self, domain, storage::enums, ConnectorAuthType, PaymentAddress}; <file_sep path="hyperswitch/crates/router/tests/connectors/bluesnap.rs" role="context" start="281" end="299"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_payment_info()) .await .unwrap(); let rsync_response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, response.response.unwrap().connector_refund_id, None, None, ) .await .unwrap(); assert_eq!( rsync_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/bluesnap.rs" role="context" start="253" end="275"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_payment_info()) .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(), ), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/bluesnap.rs" role="context" start="217" end="235"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund(payment_method_details(), None, None, get_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, None, ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/bluesnap.rs" role="context" start="185" end="211"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_payment_info(), ) .await .unwrap(); let rsync_response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, response.response.unwrap().connector_refund_id, None, None, ) .await .unwrap(); assert_eq!( rsync_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/bluesnap.rs" role="context" start="41" end="46"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { email: Some(Email::from_str("test@gmail.com").unwrap()), ..utils::PaymentAuthorizeType::default().0 }) } <file_sep path="hyperswitch/crates/router/tests/connectors/bluesnap.rs" role="context" start="47" end="65"> fn get_payment_info() -> Option<PaymentInfo> { Some(PaymentInfo { address: Some(PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("joseph".to_string())), last_name: Some(Secret::new("Doe".to_string())), ..Default::default() }), phone: None, email: None, }), None, None, )), ..Default::default() }) }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/wellsfargo.rs<|crate|> router<|connector|> wellsfargo anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/wellsfargo.rs" role="context" start="193" end="199"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/wellsfargo.rs" role="context" start="192" end="192"> use router::types::{self, api, domain, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/wellsfargo.rs" role="context" start="230" end="239"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/wellsfargo.rs" role="context" start="203" end="226"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/wellsfargo.rs" role="context" start="166" end="189"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/wellsfargo.rs" role="context" start="145" end="162"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/wellsfargo.rs" role="context" start="41" end="43"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/wellsfargo.rs" role="context" start="37" end="39"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/amazonpay.rs<|crate|> router<|connector|> amazonpay anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/amazonpay.rs" role="context" start="194" end="200"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/amazonpay.rs" role="context" start="193" end="193"> use router::types::{self, api, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/amazonpay.rs" role="context" start="231" end="240"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/amazonpay.rs" role="context" start="204" end="227"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/amazonpay.rs" role="context" start="167" end="190"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/amazonpay.rs" role="context" start="146" end="163"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/amazonpay.rs" role="context" start="38" end="40"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/amazonpay.rs" role="context" start="42" end="44"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/payme.rs<|crate|> router<|connector|> payme anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/payme.rs" role="context" start="264" end="270"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/payme.rs" role="context" start="263" end="263"> use router::types::{self, domain, storage::enums, PaymentAddress}; <file_sep path="hyperswitch/crates/router/tests/connectors/payme.rs" role="context" start="302" end="311"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/payme.rs" role="context" start="275" end="298"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/payme.rs" role="context" start="237" end="260"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/payme.rs" role="context" start="216" end="232"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/payme.rs" role="context" start="78" end="108"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { order_details: Some(vec![OrderDetailsWithAmount { product_name: "iphone 13".to_string(), quantity: 1, amount: MinorUnit::new(1000), product_img_link: None, requires_shipping: None, product_id: None, category: None, sub_category: None, brand: None, product_type: None, product_tax_code: None, tax_rate: None, total_tax_amount: None, }]), router_return_url: Some("https://hyperswitch.io".to_string()), webhook_url: Some("https://hyperswitch.io".to_string()), email: Some(Email::from_str("test@gmail.com").unwrap()), payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_cvc: Secret::new("123".to_string()), card_exp_month: Secret::new("10".to_string()), card_exp_year: Secret::new("2025".to_string()), ..utils::CCardType::default().0 }), amount: 1000, ..PaymentAuthorizeType::default().0 }) } <file_sep path="hyperswitch/crates/router/tests/connectors/payme.rs" role="context" start="44" end="76"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: Some(PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { city: None, country: None, line1: None, line2: None, line3: None, zip: None, state: None, first_name: Some(Secret::new("John".to_string())), last_name: Some(Secret::new("Doe".to_string())), }), phone: None, email: None, }), None, None, )), auth_type: None, access_token: None, connector_meta_data: None, connector_customer: None, payment_method_token: None, #[cfg(feature = "payouts")] currency: None, #[cfg(feature = "payouts")] payout_method_data: None, }) }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/boku.rs<|crate|> router<|connector|> boku anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/boku.rs" role="context" start="193" end="199"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/boku.rs" role="context" start="192" end="192"> use router::types::{self, domain, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/boku.rs" role="context" start="230" end="239"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/boku.rs" role="context" start="203" end="226"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/boku.rs" role="context" start="166" end="189"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/boku.rs" role="context" start="145" end="162"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/boku.rs" role="context" start="37" end="39"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/boku.rs" role="context" start="41" end="43"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/paystack.rs<|crate|> router<|connector|> paystack anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/paystack.rs" role="context" start="194" end="200"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/paystack.rs" role="context" start="193" end="193"> use router::types::{self, api, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/paystack.rs" role="context" start="231" end="240"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/paystack.rs" role="context" start="204" end="227"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/paystack.rs" role="context" start="167" end="190"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/paystack.rs" role="context" start="146" end="163"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/paystack.rs" role="context" start="42" end="44"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/paystack.rs" role="context" start="38" end="40"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/inespay.rs<|crate|> router<|connector|> inespay anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/inespay.rs" role="context" start="194" end="200"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/inespay.rs" role="context" start="193" end="193"> use router::types::{self, api, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/inespay.rs" role="context" start="231" end="240"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/inespay.rs" role="context" start="204" end="227"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/inespay.rs" role="context" start="167" end="190"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/inespay.rs" role="context" start="146" end="163"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/inespay.rs" role="context" start="42" end="44"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/inespay.rs" role="context" start="38" end="40"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/datatrans.rs<|crate|> router<|connector|> datatrans anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/datatrans.rs" role="context" start="193" end="199"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/datatrans.rs" role="context" start="192" end="192"> use router::types::{self, api, domain, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/datatrans.rs" role="context" start="230" end="239"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/datatrans.rs" role="context" start="203" end="226"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/datatrans.rs" role="context" start="166" end="189"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/datatrans.rs" role="context" start="145" end="162"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/datatrans.rs" role="context" start="41" end="43"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/datatrans.rs" role="context" start="37" end="39"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/netcetera.rs<|crate|> router<|connector|> netcetera anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/netcetera.rs" role="context" start="192" end="198"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/netcetera.rs" role="context" start="191" end="191"> use router::types::{self, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/netcetera.rs" role="context" start="229" end="238"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/netcetera.rs" role="context" start="202" end="225"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/netcetera.rs" role="context" start="165" end="188"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/netcetera.rs" role="context" start="144" end="161"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/netcetera.rs" role="context" start="36" end="38"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/netcetera.rs" role="context" start="40" end="42"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/wellsfargopayout.rs<|crate|> router<|connector|> wellsfargopayout anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/wellsfargopayout.rs" role="context" start="193" end="199"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/wellsfargopayout.rs" role="context" start="192" end="192"> use router::types::{self, api, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/wellsfargopayout.rs" role="context" start="230" end="239"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/wellsfargopayout.rs" role="context" start="203" end="226"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/wellsfargopayout.rs" role="context" start="166" end="189"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/wellsfargopayout.rs" role="context" start="145" end="162"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/wellsfargopayout.rs" role="context" start="37" end="39"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/wellsfargopayout.rs" role="context" start="41" end="43"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <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/tests/connectors/coingate.rs<|crate|> router<|connector|> coingate anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/coingate.rs" role="context" start="193" end="199"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/coingate.rs" role="context" start="192" end="192"> use router::types::{self, api, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/coingate.rs" role="context" start="230" end="239"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/coingate.rs" role="context" start="203" end="226"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/coingate.rs" role="context" start="166" end="189"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/coingate.rs" role="context" start="145" end="162"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/coingate.rs" role="context" start="41" end="43"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/coingate.rs" role="context" start="37" end="39"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/jpmorgan.rs<|crate|> router<|connector|> jpmorgan anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/jpmorgan.rs" role="context" start="200" end="206"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/jpmorgan.rs" role="context" start="199" end="199"> use router::types::{self, api, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/jpmorgan.rs" role="context" start="237" end="246"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/jpmorgan.rs" role="context" start="210" end="233"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/jpmorgan.rs" role="context" start="173" end="196"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/jpmorgan.rs" role="context" start="152" end="169"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/jpmorgan.rs" role="context" start="48" end="50"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/jpmorgan.rs" role="context" start="44" end="46"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/paybox.rs<|crate|> router<|connector|> paybox anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/paybox.rs" role="context" start="193" end="199"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/paybox.rs" role="context" start="192" end="192"> use router::types::{self, api, domain, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/paybox.rs" role="context" start="230" end="239"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/paybox.rs" role="context" start="203" end="226"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/paybox.rs" role="context" start="166" end="189"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/paybox.rs" role="context" start="145" end="162"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/paybox.rs" role="context" start="41" end="43"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/paybox.rs" role="context" start="37" end="39"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/unified_authentication_service.rs<|crate|> router<|connector|> unified_authentication_service anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/unified_authentication_service.rs" role="context" start="194" end="200"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/unified_authentication_service.rs" role="context" start="193" end="193"> use router::types::{self, api, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/unified_authentication_service.rs" role="context" start="231" end="240"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/unified_authentication_service.rs" role="context" start="204" end="227"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/unified_authentication_service.rs" role="context" start="167" end="190"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/unified_authentication_service.rs" role="context" start="146" end="163"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/unified_authentication_service.rs" role="context" start="42" end="44"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/unified_authentication_service.rs" role="context" start="38" end="40"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/dummyconnector.rs<|crate|> router<|connector|> dummyconnector anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/dummyconnector.rs" role="context" start="196" end="202"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/dummyconnector.rs" role="context" start="195" end="195"> use router::types::{self, domain, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/dummyconnector.rs" role="context" start="233" end="242"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/dummyconnector.rs" role="context" start="206" end="229"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/dummyconnector.rs" role="context" start="169" end="192"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/dummyconnector.rs" role="context" start="148" end="165"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/dummyconnector.rs" role="context" start="40" end="42"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/dummyconnector.rs" role="context" start="44" end="46"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/globepay.rs<|crate|> router<|connector|> globepay anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/globepay.rs" role="context" start="195" end="201"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/globepay.rs" role="context" start="194" end="194"> use router::types::{self, domain, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/globepay.rs" role="context" start="232" end="241"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/globepay.rs" role="context" start="205" end="228"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/globepay.rs" role="context" start="168" end="191"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/globepay.rs" role="context" start="147" end="164"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/globepay.rs" role="context" start="39" end="41"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/globepay.rs" role="context" start="43" end="45"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/fiserv.rs<|crate|> router<|connector|> fiserv anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="232" end="238"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="231" end="231"> use router::types::{self, domain, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="271" end="280"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="243" end="266"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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"); tokio::time::sleep(std::time::Duration::from_secs(7)).await; let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="203" end="227"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); tokio::time::sleep(std::time::Duration::from_secs(7)).await; let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="181" end="198"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="43" end="61"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4005550000000019").unwrap(), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2035".to_string()), card_cvc: Secret::new("123".to_string()), card_issuer: None, card_network: None, card_type: None, card_issuing_country: None, bank_code: None, nick_name: Some(Secret::new("nick_name".into())), card_holder_name: Some(Secret::new("card holder name".into())), }), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 }) } <file_sep path="hyperswitch/crates/router/tests/connectors/fiserv.rs" role="context" start="63" end="68"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { connector_meta_data: Some(json!({"terminalId": "10000001"})), ..utils::PaymentInfo::with_default_billing_name() }) }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/payone.rs<|crate|> router<|connector|> payone anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/payone.rs" role="context" start="193" end="199"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/payone.rs" role="context" start="192" end="192"> use router::types::{self, domain, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/payone.rs" role="context" start="230" end="239"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/payone.rs" role="context" start="203" end="226"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/payone.rs" role="context" start="166" end="189"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/payone.rs" role="context" start="145" end="162"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/payone.rs" role="context" start="37" end="39"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/payone.rs" role="context" start="41" end="43"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/razorpay.rs<|crate|> router<|connector|> razorpay anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/razorpay.rs" role="context" start="193" end="199"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/razorpay.rs" role="context" start="192" end="192"> use router::types::{self, domain, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/razorpay.rs" role="context" start="230" end="239"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/razorpay.rs" role="context" start="203" end="226"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/razorpay.rs" role="context" start="166" end="189"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/razorpay.rs" role="context" start="145" end="162"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/razorpay.rs" role="context" start="37" end="39"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/razorpay.rs" role="context" start="41" end="43"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/opayo.rs<|crate|> router<|connector|> opayo anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/opayo.rs" role="context" start="198" end="204"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/opayo.rs" role="context" start="197" end="197"> use router::types::{self, domain, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/opayo.rs" role="context" start="235" end="244"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/opayo.rs" role="context" start="208" end="231"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/opayo.rs" role="context" start="171" end="194"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/opayo.rs" role="context" start="150" end="167"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/opayo.rs" role="context" start="46" end="48"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/opayo.rs" role="context" start="42" end="44"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/getnet.rs<|crate|> router<|connector|> getnet anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/getnet.rs" role="context" start="194" end="200"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/getnet.rs" role="context" start="193" end="193"> use router::types::{self, api, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/getnet.rs" role="context" start="231" end="240"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/getnet.rs" role="context" start="204" end="227"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/getnet.rs" role="context" start="167" end="190"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/getnet.rs" role="context" start="146" end="163"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/getnet.rs" role="context" start="38" end="40"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/getnet.rs" role="context" start="42" end="44"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/facilitapay.rs<|crate|> router<|connector|> facilitapay anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/facilitapay.rs" role="context" start="194" end="200"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/facilitapay.rs" role="context" start="193" end="193"> use router::types::{self, api, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/facilitapay.rs" role="context" start="231" end="240"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/facilitapay.rs" role="context" start="204" end="227"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/facilitapay.rs" role="context" start="167" end="190"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/facilitapay.rs" role="context" start="146" end="163"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/facilitapay.rs" role="context" start="42" end="44"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/facilitapay.rs" role="context" start="38" end="40"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/volt.rs<|crate|> router<|connector|> volt anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/volt.rs" role="context" start="193" end="199"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/volt.rs" role="context" start="192" end="192"> use router::types::{self, domain, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/volt.rs" role="context" start="230" end="239"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/volt.rs" role="context" start="203" end="226"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/volt.rs" role="context" start="166" end="189"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/volt.rs" role="context" start="145" end="162"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/volt.rs" role="context" start="41" end="43"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/volt.rs" role="context" start="37" end="39"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/fiuu.rs<|crate|> router<|connector|> fiuu anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/fiuu.rs" role="context" start="194" end="200"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/fiuu.rs" role="context" start="193" end="193"> use router::types::{self, api, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/fiuu.rs" role="context" start="231" end="240"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/fiuu.rs" role="context" start="204" end="227"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/fiuu.rs" role="context" start="167" end="190"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/fiuu.rs" role="context" start="146" end="163"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/fiuu.rs" role="context" start="42" end="44"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/fiuu.rs" role="context" start="38" end="40"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/hipay.rs<|crate|> router<|connector|> hipay anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/hipay.rs" role="context" start="194" end="200"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/hipay.rs" role="context" start="193" end="193"> use router::types::{self, api, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/hipay.rs" role="context" start="231" end="240"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/hipay.rs" role="context" start="204" end="227"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/hipay.rs" role="context" start="167" end="190"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/hipay.rs" role="context" start="146" end="163"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/hipay.rs" role="context" start="42" end="44"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/hipay.rs" role="context" start="38" end="40"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/itaubank.rs<|crate|> router<|connector|> itaubank anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/itaubank.rs" role="context" start="193" end="199"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/itaubank.rs" role="context" start="192" end="192"> use router::types::{self, api, domain, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/itaubank.rs" role="context" start="230" end="239"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/itaubank.rs" role="context" start="203" end="226"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/itaubank.rs" role="context" start="166" end="189"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/itaubank.rs" role="context" start="145" end="162"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/itaubank.rs" role="context" start="41" end="43"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/itaubank.rs" role="context" start="37" end="39"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/helcim.rs<|crate|> router<|connector|> helcim anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/helcim.rs" role="context" start="193" end="199"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/helcim.rs" role="context" start="192" end="192"> use router::types::{self, domain, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/helcim.rs" role="context" start="230" end="239"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/helcim.rs" role="context" start="203" end="226"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/helcim.rs" role="context" start="166" end="189"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/helcim.rs" role="context" start="145" end="162"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/helcim.rs" role="context" start="37" end="39"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/helcim.rs" role="context" start="41" end="43"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/plaid.rs<|crate|> router<|connector|> plaid anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/plaid.rs" role="context" start="194" end="200"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/plaid.rs" role="context" start="193" end="193"> use router::types::{self, api, domain, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/plaid.rs" role="context" start="231" end="240"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/plaid.rs" role="context" start="204" end="227"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/plaid.rs" role="context" start="167" end="190"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/plaid.rs" role="context" start="146" end="163"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/plaid.rs" role="context" start="42" end="44"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/plaid.rs" role="context" start="38" end="40"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/mifinity.rs<|crate|> router<|connector|> mifinity anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/mifinity.rs" role="context" start="193" end="199"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/mifinity.rs" role="context" start="192" end="192"> use router::types::{self, domain, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/mifinity.rs" role="context" start="230" end="239"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/mifinity.rs" role="context" start="203" end="226"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/mifinity.rs" role="context" start="166" end="189"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/mifinity.rs" role="context" start="145" end="162"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/mifinity.rs" role="context" start="37" end="39"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/mifinity.rs" role="context" start="41" end="43"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/bankofamerica.rs<|crate|> router<|connector|> bankofamerica anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/bankofamerica.rs" role="context" start="194" end="200"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/bankofamerica.rs" role="context" start="193" end="193"> use router::types::{self, domain, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/bankofamerica.rs" role="context" start="231" end="240"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/bankofamerica.rs" role="context" start="204" end="227"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/bankofamerica.rs" role="context" start="167" end="190"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/bankofamerica.rs" role="context" start="146" end="163"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/bankofamerica.rs" role="context" start="42" end="44"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/bankofamerica.rs" role="context" start="38" end="40"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/redsys.rs<|crate|> router<|connector|> redsys anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/redsys.rs" role="context" start="194" end="200"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/redsys.rs" role="context" start="193" end="193"> use router::types::{self, api, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/redsys.rs" role="context" start="231" end="240"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/redsys.rs" role="context" start="204" end="227"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/redsys.rs" role="context" start="167" end="190"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/redsys.rs" role="context" start="146" end="163"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/redsys.rs" role="context" start="38" end="40"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/redsys.rs" role="context" start="42" end="44"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/gocardless.rs<|crate|> router<|connector|> gocardless anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/gocardless.rs" role="context" start="193" end="199"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/gocardless.rs" role="context" start="192" end="192"> use router::types::{self, domain, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/gocardless.rs" role="context" start="230" end="239"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/gocardless.rs" role="context" start="203" end="226"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/gocardless.rs" role="context" start="166" end="189"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/gocardless.rs" role="context" start="145" end="162"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/gocardless.rs" role="context" start="41" end="43"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/gocardless.rs" role="context" start="37" end="39"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/airwallex.rs<|crate|> router<|connector|> airwallex anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/airwallex.rs" role="context" start="254" end="260"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/airwallex.rs" role="context" start="253" end="253"> use router::types::{self, domain, storage::enums, AccessToken}; <file_sep path="hyperswitch/crates/router/tests/connectors/airwallex.rs" role="context" start="293" end="302"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/airwallex.rs" role="context" start="265" end="287"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/airwallex.rs" role="context" start="226" end="249"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/airwallex.rs" role="context" start="203" end="220"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/airwallex.rs" role="context" start="52" end="71"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { access_token: get_access_token(), address: Some(types::PaymentAddress::new( None, None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("John".to_string())), last_name: Some(Secret::new("Doe".to_string())), ..Default::default() }), phone: None, email: None, }), None, )), ..Default::default() }) } <file_sep path="hyperswitch/crates/router/tests/connectors/airwallex.rs" role="context" start="72" end="92"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4035501000000008").unwrap(), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2035".to_string()), card_cvc: Secret::new("123".to_string()), card_issuer: None, card_network: None, card_type: None, card_issuing_country: None, bank_code: None, nick_name: Some(Secret::new("nick_name".into())), card_holder_name: Some(Secret::new("card holder name".into())), }), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), router_return_url: Some("https://google.com".to_string()), complete_authorize_url: Some("https://google.com".to_string()), ..utils::PaymentAuthorizeType::default().0 }) }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/checkout.rs<|crate|> router<|connector|> checkout anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/checkout.rs" role="context" start="203" end="209"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/checkout.rs" role="context" start="202" end="202"> use router::types::{self, domain, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/checkout.rs" role="context" start="242" end="251"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/checkout.rs" role="context" start="214" end="237"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/checkout.rs" role="context" start="175" end="198"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/checkout.rs" role="context" start="153" end="170"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/checkout.rs" role="context" start="42" end="44"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/checkout.rs" role="context" start="38" end="40"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/billwerk.rs<|crate|> router<|connector|> billwerk anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/billwerk.rs" role="context" start="194" end="200"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/billwerk.rs" role="context" start="193" end="193"> use router::types::{self, domain, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/billwerk.rs" role="context" start="231" end="240"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/billwerk.rs" role="context" start="204" end="227"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/billwerk.rs" role="context" start="167" end="190"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/billwerk.rs" role="context" start="146" end="163"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/billwerk.rs" role="context" start="42" end="44"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/billwerk.rs" role="context" start="38" end="40"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/ebanx.rs<|crate|> router<|connector|> ebanx anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/ebanx.rs" role="context" start="193" end="199"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/ebanx.rs" role="context" start="192" end="192"> use router::types::{self, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/ebanx.rs" role="context" start="230" end="239"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/ebanx.rs" role="context" start="203" end="226"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/ebanx.rs" role="context" start="166" end="189"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/ebanx.rs" role="context" start="145" end="162"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/ebanx.rs" role="context" start="41" end="43"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/ebanx.rs" role="context" start="37" end="39"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/elavon.rs<|crate|> router<|connector|> elavon anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/elavon.rs" role="context" start="200" end="206"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/elavon.rs" role="context" start="199" end="199"> use router::types::{self, api, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/elavon.rs" role="context" start="237" end="246"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/elavon.rs" role="context" start="210" end="233"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/elavon.rs" role="context" start="173" end="196"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/elavon.rs" role="context" start="152" end="169"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/elavon.rs" role="context" start="44" end="46"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/elavon.rs" role="context" start="48" end="50"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/fiservemea.rs<|crate|> router<|connector|> fiservemea anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/fiservemea.rs" role="context" start="194" end="200"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/fiservemea.rs" role="context" start="193" end="193"> use router::types::{self, api, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/fiservemea.rs" role="context" start="231" end="240"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/fiservemea.rs" role="context" start="204" end="227"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/fiservemea.rs" role="context" start="167" end="190"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/fiservemea.rs" role="context" start="146" end="163"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/fiservemea.rs" role="context" start="38" end="40"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/fiservemea.rs" role="context" start="42" end="44"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/recurly.rs<|crate|> router<|connector|> recurly anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/recurly.rs" role="context" start="194" end="200"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/recurly.rs" role="context" start="193" end="193"> use router::types::{self, api, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/recurly.rs" role="context" start="231" end="240"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/recurly.rs" role="context" start="204" end="227"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/recurly.rs" role="context" start="167" end="190"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/recurly.rs" role="context" start="146" end="163"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/recurly.rs" role="context" start="38" end="40"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/recurly.rs" role="context" start="42" end="44"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/placetopay.rs<|crate|> router<|connector|> placetopay anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/placetopay.rs" role="context" start="193" end="199"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/placetopay.rs" role="context" start="192" end="192"> use router::types::{self, domain, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/placetopay.rs" role="context" start="230" end="239"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/placetopay.rs" role="context" start="203" end="226"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/placetopay.rs" role="context" start="166" end="189"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/placetopay.rs" role="context" start="145" end="162"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/placetopay.rs" role="context" start="37" end="39"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/placetopay.rs" role="context" start="41" end="43"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/moneris.rs<|crate|> router<|connector|> moneris anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/moneris.rs" role="context" start="194" end="200"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/moneris.rs" role="context" start="193" end="193"> use router::types::{self, api, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/moneris.rs" role="context" start="231" end="240"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/moneris.rs" role="context" start="204" end="227"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/moneris.rs" role="context" start="167" end="190"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/moneris.rs" role="context" start="146" end="163"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/moneris.rs" role="context" start="42" end="44"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/moneris.rs" role="context" start="38" end="40"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/nexixpay.rs<|crate|> router<|connector|> nexixpay anchor=should_make_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/nexixpay.rs" role="context" start="194" end="200"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/nexixpay.rs" role="context" start="193" end="193"> use router::types::{self, api, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/nexixpay.rs" role="context" start="231" end="240"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/nexixpay.rs" role="context" start="204" end="227"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .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(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/nexixpay.rs" role="context" start="167" end="190"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .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(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/nexixpay.rs" role="context" start="146" end="163"> async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/nexixpay.rs" role="context" start="42" end="44"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/nexixpay.rs" role="context" start="38" end="40"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/types/domain/user.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/types/domain/user.rs" role="context" start="318" end="322"> fn from(_value: InviteeUserRequestWithInvitedUserToken) -> Self { let new_organization = api_org::OrganizationNew::new(None); let db_organization = ForeignFrom::foreign_from(new_organization); Self(db_organization) } <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="317" end="317"> use api_models::{ admin as admin_api, organization as api_org, user as user_api, user_role as user_role_api, }; use crate::{ consts, core::{ admin, errors::{UserErrors, UserResult}, }, db::GlobalStorageInterface, routes::SessionState, services::{self, authentication::UserFromToken}, types::{domain, transformers::ForeignFrom}, utils::user::password, }; type InviteeUserRequestWithInvitedUserToken = (user_api::InviteUserRequest, UserFromToken); <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="344" end="356"> fn foreign_from(item: api_models::user::UserOrgMerchantCreateRequest) -> Self { let org_id = id_type::OrganizationId::default(); let api_models::user::UserOrgMerchantCreateRequest { organization_name, organization_details, metadata, .. } = item; let mut org_new_db = Self::new(org_id, Some(organization_name.expose())); org_new_db.organization_details = organization_details; org_new_db.metadata = metadata; org_new_db } <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="326" end="338"> fn from( (_value, merchant_account_identifier): ( user_api::CreateTenantUserRequest, MerchantAccountIdentifier, ), ) -> Self { let new_organization = api_org::OrganizationNew { org_id: merchant_account_identifier.org_id, org_name: None, }; let db_organization = ForeignFrom::foreign_from(new_organization); Self(db_organization) } <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="308" end="313"> fn from(value: UserMerchantCreateRequestWithToken) -> Self { Self(diesel_org::OrganizationNew::new( value.2.org_id, Some(value.1.company_name), )) } <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="295" end="304"> fn from( (_value, org_id): (user_api::CreateInternalUserRequest, id_type::OrganizationId), ) -> Self { let new_organization = api_org::OrganizationNew { org_id, org_name: None, }; let db_organization = ForeignFrom::foreign_from(new_organization); Self(db_organization) } <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="1244" end="1249"> fn foreign_from(value: UserStatus) -> Self { match value { UserStatus::Active => Self::Active, UserStatus::InvitationSent => Self::InvitationSent, } } <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="316" end="316"> type InviteeUserRequestWithInvitedUserToken = (user_api::InviteUserRequest, UserFromToken); <file_sep path="hyperswitch/crates/router/src/types/transformers.rs" role="context" start="45" end="47"> pub trait ForeignFrom<F> { fn foreign_from(from: F) -> Self; } <file_sep path="hyperswitch/crates/api_models/src/organization.rs" role="context" start="3" end="6"> pub struct OrganizationNew { pub org_id: id_type::OrganizationId, pub org_name: Option<String>, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/utils/user/theme.rs<|crate|> router anchor=path_buf_to_str kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/utils/user/theme.rs" role="context" start="29" end="33"> fn path_buf_to_str(path: &PathBuf) -> UserResult<&str> { path.to_str() .ok_or(UserErrors::InternalServerError) .attach_printable(format!("Failed to convert path {:#?} to string", path)) } <file_sep path="hyperswitch/crates/router/src/utils/user/theme.rs" role="context" start="28" end="28"> use std::path::PathBuf; use crate::{ core::errors::{StorageErrorExt, UserErrors, UserResult}, routes::SessionState, services::authentication::UserFromToken, }; <file_sep path="hyperswitch/crates/router/src/utils/user/theme.rs" role="context" start="46" end="56"> pub async fn upload_file_to_theme_bucket( state: &SessionState, path: &PathBuf, data: Vec<u8>, ) -> UserResult<()> { state .theme_storage_client .upload_file(path_buf_to_str(path)?, data) .await .change_context(UserErrors::ErrorUploadingFile) } <file_sep path="hyperswitch/crates/router/src/utils/user/theme.rs" role="context" start="35" end="44"> pub async fn retrieve_file_from_theme_bucket( state: &SessionState, path: &PathBuf, ) -> UserResult<Vec<u8>> { state .theme_storage_client .retrieve_file(path_buf_to_str(path)?) .await .change_context(UserErrors::ErrorRetrievingFile) } <file_sep path="hyperswitch/crates/router/src/utils/user/theme.rs" role="context" start="25" end="27"> pub fn get_theme_file_key(theme_id: &str) -> PathBuf { get_specific_file_key(theme_id, "theme.json") } <file_sep path="hyperswitch/crates/router/src/utils/user/theme.rs" role="context" start="19" end="23"> pub fn get_specific_file_key(theme_id: &str, file_name: &str) -> PathBuf { let mut path = get_theme_dir_key(theme_id); path.push(file_name); path } <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/tests/connectors/bluesnap.rs<|crate|> router<|connector|> bluesnap anchor=should_only_authorize_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/bluesnap.rs" role="context" start="72" end="78"> async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } <file_sep path="hyperswitch/crates/router/tests/connectors/bluesnap.rs" role="context" start="71" end="71"> use router::types::{self, domain, storage::enums, ConnectorAuthType, PaymentAddress}; <file_sep path="hyperswitch/crates/router/tests/connectors/bluesnap.rs" role="context" start="96" end="109"> 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_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/bluesnap.rs" role="context" start="84" end="90"> async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/bluesnap.rs" role="context" start="47" end="65"> fn get_payment_info() -> Option<PaymentInfo> { Some(PaymentInfo { address: Some(PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("joseph".to_string())), last_name: Some(Secret::new("Doe".to_string())), ..Default::default() }), phone: None, email: None, }), None, None, )), ..Default::default() }) } <file_sep path="hyperswitch/crates/router/tests/connectors/bluesnap.rs" role="context" start="41" end="46"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { email: Some(Email::from_str("test@gmail.com").unwrap()), ..utils::PaymentAuthorizeType::default().0 }) }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/noon.rs<|crate|> router<|connector|> noon anchor=should_only_authorize_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/noon.rs" role="context" start="55" end="61"> 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::Authorized); } <file_sep path="hyperswitch/crates/router/tests/connectors/noon.rs" role="context" start="54" end="54"> use router::types::{self, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/noon.rs" role="context" start="75" end="88"> 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(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/noon.rs" role="context" start="65" end="71"> async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/noon.rs" role="context" start="45" end="50"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { currency: enums::Currency::AED, ..utils::PaymentAuthorizeType::default().0 }) } <file_sep path="hyperswitch/crates/router/tests/connectors/noon.rs" role="context" start="41" end="43"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/amazonpay.rs<|crate|> router<|connector|> amazonpay anchor=should_only_authorize_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/amazonpay.rs" role="context" start="49" end="55"> 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::Authorized); } <file_sep path="hyperswitch/crates/router/tests/connectors/amazonpay.rs" role="context" start="48" end="48"> use router::types::{self, api, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/amazonpay.rs" role="context" start="69" end="82"> 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(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/amazonpay.rs" role="context" start="59" end="65"> async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/amazonpay.rs" role="context" start="42" end="44"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/amazonpay.rs" role="context" start="38" end="40"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/boku.rs<|crate|> router<|connector|> boku anchor=should_only_authorize_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/boku.rs" role="context" start="48" end="54"> 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::Authorized); } <file_sep path="hyperswitch/crates/router/tests/connectors/boku.rs" role="context" start="47" end="47"> use router::types::{self, domain, storage::enums}; <file_sep path="hyperswitch/crates/router/tests/connectors/boku.rs" role="context" start="68" end="81"> 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(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/boku.rs" role="context" start="58" end="64"> async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/boku.rs" role="context" start="41" end="43"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/boku.rs" role="context" start="37" end="39"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { None }
symbol_neighborhood