repo
stringclasses
4 values
file_path
stringlengths
6
193
extension
stringclasses
23 values
content
stringlengths
0
1.73M
token_count
int64
0
724k
__index_level_0__
int64
0
10.8k
hyperswitch
crates/router/src/connector/riskified.rs
.rs
pub mod transformers; #[cfg(feature = "frm")] use base64::Engine; use common_utils::types::{ AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector, }; #[cfg(feature = "frm")] use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent}; #[cfg(feature = "frm")] use error_stack::ResultExt; #[cfg(feature = "frm")] use masking::{ExposeInterface, PeekInterface, Secret}; #[cfg(feature = "frm")] use ring::hmac; #[cfg(feature = "frm")] use transformers as riskified; use super::utils::convert_amount; #[cfg(feature = "frm")] use super::utils::{self as connector_utils, FrmTransactionRouterDataRequest}; use crate::{ configs::settings, core::errors::{self, CustomResult}, services::{self, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation}, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, }, }; #[cfg(feature = "frm")] use crate::{ consts, events::connector_api_logs::ConnectorEvent, headers, services::request, types::{api::fraud_check as frm_api, fraud_check as frm_types, ErrorResponse, Response}, utils::BytesExt, }; #[derive(Clone)] pub struct Riskified { amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), } impl Riskified { pub fn new() -> &'static Self { &Self { amount_converter: &StringMajorUnitForConnector, } } #[cfg(feature = "frm")] pub fn generate_authorization_signature( &self, auth: &riskified::RiskifiedAuthType, payload: &str, ) -> CustomResult<String, errors::ConnectorError> { let key = hmac::Key::new( hmac::HMAC_SHA256, auth.secret_token.clone().expose().as_bytes(), ); let signature_value = hmac::sign(&key, payload.as_bytes()); let digest = signature_value.as_ref(); Ok(hex::encode(digest)) } } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Riskified where Self: ConnectorIntegration<Flow, Request, Response>, { #[cfg(feature = "frm")] fn build_headers( &self, req: &types::RouterData<Flow, Request, Response>, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let auth: riskified::RiskifiedAuthType = riskified::RiskifiedAuthType::try_from(&req.connector_auth_type)?; let riskified_req = self.get_request_body(req, connectors)?; let binding = riskified_req.get_inner_value(); let payload = binding.peek(); let digest = self .generate_authorization_signature(&auth, payload) .change_context(errors::ConnectorError::RequestEncodingFailed)?; let header = vec![ ( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), ), ( "X-RISKIFIED-SHOP-DOMAIN".to_string(), auth.domain_name.clone().into(), ), ( "X-RISKIFIED-HMAC-SHA256".to_string(), request::Mask::into_masked(digest), ), ( "Accept".to_string(), "application/vnd.riskified.com; version=2".into(), ), ]; Ok(header) } } impl ConnectorCommon for Riskified { fn id(&self) -> &'static str { "riskified" } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.riskified.base_url.as_ref() } #[cfg(feature = "frm")] fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: riskified::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(ErrorResponse { status_code: res.status_code, attempt_status: None, code: consts::NO_ERROR_CODE.to_string(), message: response.error.message.clone(), reason: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, }) } } #[cfg(feature = "frm")] impl ConnectorIntegration< frm_api::Checkout, frm_types::FraudCheckCheckoutData, frm_types::FraudCheckResponseData, > for Riskified { fn get_headers( &self, req: &frm_types::FrmCheckoutRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &frm_types::FrmCheckoutRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}{}", self.base_url(connectors), "/decide")) } fn get_request_body( &self, req: &frm_types::FrmCheckoutRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = convert_amount( self.amount_converter, MinorUnit::new(req.request.amount), req.request .currency .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "currency", })?, )?; let req_data = riskified::RiskifiedRouterData::from((amount, req)); let req_obj = riskified::RiskifiedPaymentsCheckoutRequest::try_from(&req_data)?; Ok(RequestContent::Json(Box::new(req_obj))) } fn build_request( &self, req: &frm_types::FrmCheckoutRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&frm_types::FrmCheckoutType::get_url(self, req, connectors)?) .attach_default_headers() .headers(frm_types::FrmCheckoutType::get_headers( self, req, connectors, )?) .set_body(frm_types::FrmCheckoutType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &frm_types::FrmCheckoutRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<frm_types::FrmCheckoutRouterData, errors::ConnectorError> { let response: riskified::RiskifiedPaymentsResponse = res .response .parse_struct("RiskifiedPaymentsResponse Checkout") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); <frm_types::FrmCheckoutRouterData>::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl api::Payment for Riskified {} impl api::PaymentAuthorize for Riskified {} impl api::PaymentSync for Riskified {} impl api::PaymentVoid for Riskified {} impl api::PaymentCapture for Riskified {} impl api::MandateSetup for Riskified {} impl api::ConnectorAccessToken for Riskified {} impl api::PaymentToken for Riskified {} impl api::Refund for Riskified {} impl api::RefundExecute for Riskified {} impl api::RefundSync for Riskified {} impl ConnectorValidation for Riskified {} #[cfg(feature = "frm")] impl ConnectorIntegration< frm_api::Sale, frm_types::FraudCheckSaleData, frm_types::FraudCheckResponseData, > for Riskified { } #[cfg(feature = "frm")] impl ConnectorIntegration< frm_api::Transaction, frm_types::FraudCheckTransactionData, frm_types::FraudCheckResponseData, > for Riskified { fn get_headers( &self, req: &frm_types::FrmTransactionRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &frm_types::FrmTransactionRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { match req.is_payment_successful() { Some(false) => Ok(format!( "{}{}", self.base_url(connectors), "/checkout_denied" )), _ => Ok(format!("{}{}", self.base_url(connectors), "/decision")), } } fn get_request_body( &self, req: &frm_types::FrmTransactionRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { match req.is_payment_successful() { Some(false) => { let req_obj = riskified::TransactionFailedRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj))) } _ => { let amount = convert_amount( self.amount_converter, MinorUnit::new(req.request.amount), req.request .currency .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "currency", })?, )?; let req_data = riskified::RiskifiedRouterData::from((amount, req)); let req_obj = riskified::TransactionSuccessRequest::try_from(&req_data)?; Ok(RequestContent::Json(Box::new(req_obj))) } } } fn build_request( &self, req: &frm_types::FrmTransactionRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&frm_types::FrmTransactionType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(frm_types::FrmTransactionType::get_headers( self, req, connectors, )?) .set_body(frm_types::FrmTransactionType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &frm_types::FrmTransactionRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<frm_types::FrmTransactionRouterData, errors::ConnectorError> { let response: riskified::RiskifiedTransactionResponse = res .response .parse_struct("RiskifiedPaymentsResponse Transaction") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); match response { riskified::RiskifiedTransactionResponse::FailedResponse(response_data) => { <frm_types::FrmTransactionRouterData>::try_from(types::ResponseRouterData { response: response_data, data: data.clone(), http_code: res.status_code, }) } riskified::RiskifiedTransactionResponse::SuccessResponse(response_data) => { <frm_types::FrmTransactionRouterData>::try_from(types::ResponseRouterData { response: response_data, data: data.clone(), http_code: res.status_code, }) } } } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "frm")] impl ConnectorIntegration< frm_api::Fulfillment, frm_types::FraudCheckFulfillmentData, frm_types::FraudCheckResponseData, > for Riskified { fn get_headers( &self, req: &frm_types::FrmFulfillmentRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &frm_types::FrmFulfillmentRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}{}", self.base_url(connectors), "/fulfill")) } fn get_request_body( &self, req: &frm_types::FrmFulfillmentRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let req_obj = riskified::RiskifiedFulfillmentRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj))) } fn build_request( &self, req: &frm_types::FrmFulfillmentRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&frm_types::FrmFulfillmentType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(frm_types::FrmFulfillmentType::get_headers( self, req, connectors, )?) .set_body(frm_types::FrmFulfillmentType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &frm_types::FrmFulfillmentRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<frm_types::FrmFulfillmentRouterData, errors::ConnectorError> { let response: riskified::RiskifiedFulfilmentResponse = res .response .parse_struct("RiskifiedFulfilmentResponse fulfilment") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); frm_types::FrmFulfillmentRouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "frm")] impl ConnectorIntegration< frm_api::RecordReturn, frm_types::FraudCheckRecordReturnData, frm_types::FraudCheckResponseData, > for Riskified { } impl ConnectorIntegration< api::PaymentMethodToken, types::PaymentMethodTokenizationData, types::PaymentsResponseData, > for Riskified { } impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> for Riskified { } impl ConnectorIntegration< api::SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData, > for Riskified { fn build_request( &self, _req: &types::RouterData< api::SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData, >, _connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Err( errors::ConnectorError::NotImplemented("Setup Mandate flow for Riskified".to_string()) .into(), ) } } impl api::PaymentSession for Riskified {} impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> for Riskified { } impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> for Riskified { } impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> for Riskified { } impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> for Riskified { } impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> for Riskified { } impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Riskified { } impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Riskified { } #[cfg(feature = "frm")] impl api::FraudCheck for Riskified {} #[cfg(feature = "frm")] impl frm_api::FraudCheckSale for Riskified {} #[cfg(feature = "frm")] impl frm_api::FraudCheckCheckout for Riskified {} #[cfg(feature = "frm")] impl frm_api::FraudCheckTransaction for Riskified {} #[cfg(feature = "frm")] impl frm_api::FraudCheckFulfillment for Riskified {} #[cfg(feature = "frm")] impl frm_api::FraudCheckRecordReturn for Riskified {} #[cfg(feature = "frm")] #[async_trait::async_trait] impl api::IncomingWebhook for Riskified { fn get_webhook_source_verification_algorithm( &self, _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { Ok(Box::new(crypto::HmacSha256)) } fn get_webhook_source_verification_signature( &self, request: &api::IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let header_value = connector_utils::get_header_key_value("x-riskified-hmac-sha256", request.headers)?; Ok(header_value.as_bytes().to_vec()) } async fn verify_webhook_source( &self, request: &api::IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, _connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>, connector_label: &str, ) -> CustomResult<bool, errors::ConnectorError> { let connector_webhook_secrets = self .get_webhook_source_verification_merchant_secret( merchant_id, connector_label, connector_webhook_details, ) .await .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let signature = self .get_webhook_source_verification_signature(request, &connector_webhook_secrets) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let message = self .get_webhook_source_verification_message( request, merchant_id, &connector_webhook_secrets, ) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let signing_key = hmac::Key::new(hmac::HMAC_SHA256, &connector_webhook_secrets.secret); let signed_message = hmac::sign(&signing_key, &message); let payload_sign = consts::BASE64_ENGINE.encode(signed_message.as_ref()); Ok(payload_sign.as_bytes().eq(&signature)) } fn get_webhook_source_verification_message( &self, request: &api::IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { Ok(request.body.to_vec()) } fn get_webhook_object_reference_id( &self, request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { let resource: riskified::RiskifiedWebhookBody = request .body .parse_struct("RiskifiedWebhookBody") .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; Ok(api::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::PaymentAttemptId(resource.id), )) } fn get_webhook_event_type( &self, request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { let resource: riskified::RiskifiedWebhookBody = request .body .parse_struct("RiskifiedWebhookBody") .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; Ok(api::IncomingWebhookEvent::from(resource.status)) } fn get_webhook_resource_object( &self, request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { let resource: riskified::RiskifiedWebhookBody = request .body .parse_struct("RiskifiedWebhookBody") .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?; Ok(Box::new(resource)) } } impl ConnectorSpecifications for Riskified {}
5,020
1,505
hyperswitch
crates/router/src/connector/plaid.rs
.rs
pub mod transformers; use common_utils::types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector}; use error_stack::ResultExt; use transformers as plaid; use crate::{ configs::settings, connector::utils as connector_utils, core::errors::{self, CustomResult}, events::connector_api_logs::ConnectorEvent, headers, services::{ self, request::{self, Mask}, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, }, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, ErrorResponse, RequestContent, Response, }, utils::BytesExt, }; #[derive(Clone)] pub struct Plaid { amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync), } impl Plaid { pub fn new() -> &'static Self { &Self { amount_converter: &FloatMajorUnitForConnector, } } } impl api::Payment for Plaid {} impl api::PaymentSession for Plaid {} impl api::ConnectorAccessToken for Plaid {} impl api::MandateSetup for Plaid {} impl api::PaymentAuthorize for Plaid {} impl api::PaymentSync for Plaid {} impl api::PaymentCapture for Plaid {} impl api::PaymentVoid for Plaid {} impl api::Refund for Plaid {} impl api::RefundExecute for Plaid {} impl api::RefundSync for Plaid {} impl api::PaymentToken for Plaid {} impl api::PaymentsPostProcessing for Plaid {} impl ConnectorIntegration< api::PaymentMethodToken, types::PaymentMethodTokenizationData, types::PaymentsResponseData, > for Plaid { // Not Implemented (R) } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Plaid where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &types::RouterData<Flow, Request, Response>, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), )]; let mut auth = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut auth); Ok(header) } } impl ConnectorCommon for Plaid { fn id(&self) -> &'static str { "plaid" } fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Base } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.plaid.base_url.as_ref() } fn get_auth_header( &self, auth_type: &types::ConnectorAuthType, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth = plaid::PlaidAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let client_id = auth.client_id.into_masked(); let secret = auth.secret.into_masked(); Ok(vec![ ("PLAID-CLIENT-ID".to_string(), client_id), ("PLAID-SECRET".to_string(), secret), ]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: plaid::PlaidErrorResponse = res.response .parse_struct("PlaidErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(ErrorResponse { status_code: res.status_code, code: response .error_code .unwrap_or(crate::consts::NO_ERROR_CODE.to_string()), message: response.error_message, reason: response.display_message, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, }) } } impl ConnectorValidation for Plaid { //TODO: implement functions when support enabled } impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> for Plaid { //TODO: implement sessions flow } impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> for Plaid { } impl ConnectorIntegration< api::SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData, > for Plaid { } impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> for Plaid { fn get_headers( &self, req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}/payment_initiation/payment/create", self.base_url(connectors) )) } fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = connector_utils::convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, )?; let connector_router_data = plaid::PlaidRouterData::from((amount, req)); let connector_req = plaid::PlaidPaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PaymentsAuthorizeType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: plaid::PlaidPaymentsResponse = res .response .parse_struct("PlaidPaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> for Plaid { fn get_headers( &self, req: &types::PaymentsSyncRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_request_body( &self, req: &types::PaymentsSyncRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = plaid::PlaidSyncRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn get_url( &self, _req: &types::PaymentsSyncRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}/payment_initiation/payment/get", self.base_url(connectors) )) } fn build_request( &self, req: &types::PaymentsSyncRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .set_body(types::PaymentsSyncType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &types::PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: plaid::PlaidSyncResponse = res .response .parse_struct("PlaidSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration< api::PostProcessing, types::PaymentsPostProcessingData, types::PaymentsResponseData, > for Plaid { fn get_headers( &self, req: &types::PaymentsPostProcessingRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &types::PaymentsPostProcessingRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}/link/token/create", self.base_url(connectors))) } fn get_request_body( &self, req: &types::PaymentsPostProcessingRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = plaid::PlaidLinkTokenRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &types::PaymentsPostProcessingRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PaymentsPostProcessingType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PaymentsPostProcessingType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsPostProcessingType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &types::PaymentsPostProcessingRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsPostProcessingRouterData, errors::ConnectorError> { let response: plaid::PlaidLinkTokenResponse = res .response .parse_struct("PlaidLinkTokenResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> for Plaid { } impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> for Plaid { } impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Plaid {} impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Plaid {} #[async_trait::async_trait] impl api::IncomingWebhook for Plaid { fn get_webhook_object_reference_id( &self, _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> { Err((errors::ConnectorError::WebhooksNotImplemented).into()) } fn get_webhook_event_type( &self, _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { Err((errors::ConnectorError::WebhooksNotImplemented).into()) } fn get_webhook_resource_object( &self, _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err((errors::ConnectorError::WebhooksNotImplemented).into()) } } impl ConnectorSpecifications for Plaid {}
3,301
1,506
hyperswitch
crates/router/src/connector/payone/transformers.rs
.rs
#[cfg(feature = "payouts")] use api_models::payouts::PayoutMethodData; #[cfg(feature = "payouts")] use cards::CardNumber; use common_utils::types::MinorUnit; #[cfg(feature = "payouts")] use error_stack::ResultExt; use masking::Secret; use serde::{Deserialize, Serialize}; use serde_repr::{Deserialize_repr, Serialize_repr}; use crate::connector::{ utils, utils::{get_unimplemented_payment_method_error_message, CardIssuer}, }; #[cfg(feature = "payouts")] type Error = error_stack::Report<errors::ConnectorError>; #[cfg(feature = "payouts")] use crate::{ connector::utils::{CardData, PayoutsData, RouterData}, core::errors, types::{self, api, storage::enums as storage_enums, transformers::ForeignFrom}, utils::OptionExt, }; #[cfg(not(feature = "payouts"))] use crate::{core::errors, types}; pub struct PayoneRouterData<T> { pub amount: MinorUnit, pub router_data: T, } impl<T> From<(MinorUnit, T)> for PayoneRouterData<T> { fn from((amount, item): (MinorUnit, T)) -> Self { Self { amount, router_data: item, } } } #[derive(Debug, Deserialize, Serialize)] pub struct ErrorResponse { pub errors: Option<Vec<SubError>>, pub error_id: Option<i32>, } #[derive(Debug, Deserialize, Serialize, Clone)] pub struct SubError { pub code: String, pub message: String, pub http_status_code: u16, } impl From<SubError> for utils::ErrorCodeAndMessage { fn from(error: SubError) -> Self { Self { error_code: error.code.to_string(), error_message: error.code.to_string(), } } } // Auth Struct pub struct PayoneAuthType { pub(super) api_key: Secret<String>, pub merchant_account: Secret<String>, pub api_secret: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for PayoneAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { types::ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } => Ok(Self { api_key: api_key.to_owned(), merchant_account: key1.to_owned(), api_secret: api_secret.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType)?, } } } #[cfg(feature = "payouts")] #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct PayonePayoutFulfillRequest { amount_of_money: AmountOfMoney, card_payout_method_specific_input: CardPayoutMethodSpecificInput, } #[cfg(feature = "payouts")] #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct AmountOfMoney { amount: MinorUnit, currency_code: String, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CardPayoutMethodSpecificInput { card: Card, payment_product_id: PaymentProductId, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct Card { card_holder_name: Secret<String>, card_number: CardNumber, expiry_date: Secret<String>, } #[cfg(feature = "payouts")] impl TryFrom<PayoneRouterData<&types::PayoutsRouterData<api::PoFulfill>>> for PayonePayoutFulfillRequest { type Error = Error; fn try_from( item: PayoneRouterData<&types::PayoutsRouterData<api::PoFulfill>>, ) -> Result<Self, Self::Error> { let request = item.router_data.request.to_owned(); let payout_type = request.get_payout_type()?; match payout_type { storage_enums::PayoutType::Card => { let amount_of_money: AmountOfMoney = AmountOfMoney { amount: item.amount, currency_code: item.router_data.request.destination_currency.to_string(), }; let card_payout_method_specific_input = match item .router_data .get_payout_method_data()? { PayoutMethodData::Card(card_data) => CardPayoutMethodSpecificInput { card: Card { card_number: card_data.card_number.clone(), card_holder_name: card_data .card_holder_name .clone() .get_required_value("card_holder_name") .change_context(errors::ConnectorError::MissingRequiredField { field_name: "payout_method_data.card.holder_name", })?, expiry_date: card_data .get_card_expiry_month_year_2_digit_with_delimiter( "".to_string(), )?, }, payment_product_id: PaymentProductId::try_from( card_data.get_card_issuer()?, )?, }, PayoutMethodData::Bank(_) | PayoutMethodData::Wallet(_) => { Err(errors::ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("Payone"), ))? } }; Ok(Self { amount_of_money, card_payout_method_specific_input, }) } storage_enums::PayoutType::Wallet | storage_enums::PayoutType::Bank => { Err(errors::ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("Payone"), ))? } } } } #[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize_repr, Deserialize_repr)] #[repr(i32)] pub enum PaymentProductId { Visa = 1, MasterCard = 3, } impl TryFrom<CardIssuer> for PaymentProductId { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(issuer: CardIssuer) -> Result<Self, Self::Error> { match issuer { CardIssuer::Master => Ok(Self::MasterCard), CardIssuer::Visa => Ok(Self::Visa), CardIssuer::AmericanExpress | CardIssuer::Maestro | CardIssuer::Discover | CardIssuer::DinersClub | CardIssuer::JCB | CardIssuer::CarteBlanche => Err(errors::ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("payone"), ) .into()), } } } #[cfg(feature = "payouts")] #[derive(Debug, Default, Clone, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PayoneStatus { Created, #[default] PendingApproval, Rejected, PayoutRequested, AccountCredited, RejectedCredit, Cancelled, Reversed, } #[cfg(feature = "payouts")] #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PayonePayoutFulfillResponse { id: String, payout_output: PayoutOutput, status: PayoneStatus, } #[cfg(feature = "payouts")] #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PayoutOutput { amount_of_money: AmountOfMoney, } #[cfg(feature = "payouts")] impl ForeignFrom<PayoneStatus> for storage_enums::PayoutStatus { fn foreign_from(payone_status: PayoneStatus) -> Self { match payone_status { PayoneStatus::AccountCredited => Self::Success, PayoneStatus::RejectedCredit | PayoneStatus::Rejected => Self::Failed, PayoneStatus::Cancelled | PayoneStatus::Reversed => Self::Cancelled, PayoneStatus::Created | PayoneStatus::PendingApproval | PayoneStatus::PayoutRequested => Self::Pending, } } } #[cfg(feature = "payouts")] impl<F> TryFrom<types::PayoutsResponseRouterData<F, PayonePayoutFulfillResponse>> for types::PayoutsRouterData<F> { type Error = Error; fn try_from( item: types::PayoutsResponseRouterData<F, PayonePayoutFulfillResponse>, ) -> Result<Self, Self::Error> { let response: PayonePayoutFulfillResponse = item.response; Ok(Self { response: Ok(types::PayoutsResponseData { status: Some(storage_enums::PayoutStatus::foreign_from(response.status)), connector_payout_id: Some(response.id), payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: None, error_message: None, }), ..item.data }) } }
1,940
1,507
hyperswitch
crates/router/src/connector/wise/transformers.rs
.rs
#[cfg(feature = "payouts")] use api_models::payouts::PayoutMethodData; #[cfg(feature = "payouts")] use common_utils::pii::Email; use common_utils::types::MinorUnit; use masking::Secret; use serde::{Deserialize, Serialize}; type Error = error_stack::Report<errors::ConnectorError>; #[cfg(feature = "payouts")] use crate::{ connector::utils::{self, PayoutsData, RouterData}, types::{ api::payouts, storage::enums::{self as storage_enums, PayoutEntityType}, }, }; use crate::{core::errors, types}; #[derive(Debug, Serialize)] pub struct WiseRouterData<T> { pub amount: MinorUnit, pub router_data: T, } impl<T> From<(MinorUnit, T)> for WiseRouterData<T> { fn from((amount, router_data): (MinorUnit, T)) -> Self { Self { amount, router_data, } } } pub struct WiseAuthType { pub(super) api_key: Secret<String>, #[allow(dead_code)] pub(super) profile_id: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for WiseAuthType { type Error = Error; fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { api_key: api_key.to_owned(), profile_id: key1.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType)?, } } } // Wise error response #[derive(Debug, Deserialize, Serialize)] pub struct ErrorResponse { pub timestamp: Option<String>, pub errors: Option<Vec<SubError>>, pub status: Option<String>, pub error: Option<String>, pub error_description: Option<String>, pub message: Option<String>, pub path: Option<String>, } #[derive(Debug, Deserialize, Serialize)] pub struct SubError { pub code: String, pub message: String, pub path: Option<String>, pub field: Option<String>, } // Payouts #[cfg(feature = "payouts")] #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct WiseRecipientCreateRequest { currency: String, #[serde(rename = "type")] recipient_type: RecipientType, profile: Secret<String>, account_holder_name: Secret<String>, details: WiseBankDetails, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] #[allow(dead_code)] pub enum RecipientType { Aba, Iban, SortCode, SwiftCode, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "UPPERCASE")] pub enum AccountType { Checking, } #[cfg(feature = "payouts")] #[derive(Debug, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct WiseBankDetails { legal_type: LegalType, account_type: Option<AccountType>, address: Option<WiseAddressDetails>, post_code: Option<String>, nationality: Option<String>, account_holder_name: Option<Secret<String>>, email: Option<Email>, account_number: Option<Secret<String>>, city: Option<String>, sort_code: Option<Secret<String>>, iban: Option<Secret<String>>, bic: Option<Secret<String>>, transit_number: Option<Secret<String>>, routing_number: Option<Secret<String>>, abartn: Option<Secret<String>>, swift_code: Option<Secret<String>>, payin_reference: Option<String>, psp_reference: Option<String>, tax_id: Option<String>, order_id: Option<String>, job: Option<String>, } #[cfg(feature = "payouts")] #[derive(Debug, Default, Serialize, Deserialize)] #[serde(rename_all = "UPPERCASE")] pub enum LegalType { Business, #[default] Private, } #[cfg(feature = "payouts")] #[derive(Debug, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct WiseAddressDetails { country: Option<storage_enums::CountryAlpha2>, country_code: Option<storage_enums::CountryAlpha2>, first_line: Option<Secret<String>>, post_code: Option<Secret<String>>, city: Option<String>, state: Option<Secret<String>>, } #[allow(dead_code)] #[cfg(feature = "payouts")] #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct WiseRecipientCreateResponse { id: i64, business: Option<i64>, profile: Option<i64>, account_holder_name: Secret<String>, currency: String, country: String, #[serde(rename = "type")] request_type: String, details: Option<WiseBankDetails>, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct WisePayoutQuoteRequest { source_currency: String, target_currency: String, source_amount: Option<MinorUnit>, target_amount: Option<MinorUnit>, pay_out: WisePayOutOption, } #[cfg(feature = "payouts")] #[derive(Debug, Default, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum WisePayOutOption { Balance, #[default] BankTransfer, Swift, SwiftOur, Interac, } #[allow(dead_code)] #[cfg(feature = "payouts")] #[derive(Debug, Default, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct WisePayoutQuoteResponse { source_amount: f64, client_id: String, id: String, status: WiseStatus, profile: i64, rate: Option<i8>, source_currency: Option<String>, target_currency: Option<String>, user: Option<i64>, rate_type: Option<WiseRateType>, pay_out: Option<WisePayOutOption>, } #[cfg(feature = "payouts")] #[derive(Debug, Default, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum WiseRateType { #[default] Fixed, Floating, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct WisePayoutCreateRequest { target_account: i64, quote_uuid: String, customer_transaction_id: String, details: WiseTransferDetails, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct WiseTransferDetails { transfer_purpose: Option<String>, source_of_funds: Option<String>, transfer_purpose_sub_transfer_purpose: Option<String>, } #[allow(dead_code)] #[cfg(feature = "payouts")] #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct WisePayoutResponse { id: i64, user: i64, target_account: i64, source_account: Option<i64>, quote_uuid: String, status: WiseStatus, reference: Option<String>, rate: Option<f32>, business: Option<i64>, details: Option<WiseTransferDetails>, has_active_issues: Option<bool>, source_currency: Option<String>, source_value: Option<f64>, target_currency: Option<String>, target_value: Option<f64>, customer_transaction_id: Option<String>, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct WisePayoutFulfillRequest { #[serde(rename = "type")] fund_type: FundType, } // NOTE - Only balance is allowed as time of incorporating this field - https://api-docs.transferwise.com/api-reference/transfer#fund #[cfg(feature = "payouts")] #[derive(Debug, Default, Serialize)] #[serde(rename_all = "UPPERCASE")] pub enum FundType { #[default] Balance, } #[allow(dead_code)] #[cfg(feature = "payouts")] #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct WiseFulfillResponse { status: WiseStatus, error_code: Option<String>, error_message: Option<String>, balance_transaction_id: Option<i64>, } #[cfg(feature = "payouts")] #[derive(Debug, Default, Clone, Serialize, Deserialize)] #[serde(rename_all = "UPPERCASE")] pub enum WiseStatus { Completed, Pending, Rejected, #[serde(rename = "cancelled")] Cancelled, #[serde(rename = "processing")] #[default] Processing, #[serde(rename = "incoming_payment_waiting")] IncomingPaymentWaiting, } #[cfg(feature = "payouts")] 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(), }) }) } #[cfg(feature = "payouts")] 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"), ))?, } } // Payouts recipient create request transform #[cfg(feature = "payouts")] impl<F> TryFrom<&WiseRouterData<&types::PayoutsRouterData<F>>> for WiseRecipientCreateRequest { type Error = Error; 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, }) } } } } // Payouts recipient fulfill response transform #[cfg(feature = "payouts")] impl<F> TryFrom<types::PayoutsResponseRouterData<F, WiseRecipientCreateResponse>> for types::PayoutsRouterData<F> { type Error = Error; 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 }) } } // Payouts quote request transform #[cfg(feature = "payouts")] impl<F> TryFrom<&WiseRouterData<&types::PayoutsRouterData<F>>> for WisePayoutQuoteRequest { type Error = Error; 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"), ))? } } } } // Payouts quote response transform #[cfg(feature = "payouts")] impl<F> TryFrom<types::PayoutsResponseRouterData<F, WisePayoutQuoteResponse>> for types::PayoutsRouterData<F> { type Error = Error; fn try_from( item: types::PayoutsResponseRouterData<F, WisePayoutQuoteResponse>, ) -> Result<Self, Self::Error> { let response: WisePayoutQuoteResponse = item.response; Ok(Self { response: Ok(types::PayoutsResponseData { status: Some(storage_enums::PayoutStatus::RequiresCreation), connector_payout_id: Some(response.id), payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: None, error_message: None, }), ..item.data }) } } // Payouts transfer creation request #[cfg(feature = "payouts")] impl<F> TryFrom<&types::PayoutsRouterData<F>> for WisePayoutCreateRequest { type Error = Error; fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> { let request = item.request.to_owned(); let payout_type = request.get_payout_type()?; match payout_type { storage_enums::PayoutType::Bank => { let connector_customer_id = item.get_connector_customer_id()?; let quote_uuid = item.get_quote_id()?; let wise_transfer_details = WiseTransferDetails { transfer_purpose: None, source_of_funds: None, transfer_purpose_sub_transfer_purpose: None, }; let target_account: i64 = connector_customer_id.trim().parse().map_err(|_| { errors::ConnectorError::MissingRequiredField { field_name: "profile", } })?; Ok(Self { target_account, quote_uuid, customer_transaction_id: request.payout_id, details: wise_transfer_details, }) } storage_enums::PayoutType::Card | storage_enums::PayoutType::Wallet => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Wise"), ))? } } } } // Payouts transfer creation response #[cfg(feature = "payouts")] impl<F> TryFrom<types::PayoutsResponseRouterData<F, WisePayoutResponse>> for types::PayoutsRouterData<F> { type Error = Error; fn try_from( item: types::PayoutsResponseRouterData<F, WisePayoutResponse>, ) -> Result<Self, Self::Error> { let response: WisePayoutResponse = item.response; let status = match storage_enums::PayoutStatus::from(response.status) { storage_enums::PayoutStatus::Cancelled => storage_enums::PayoutStatus::Cancelled, _ => storage_enums::PayoutStatus::RequiresFulfillment, }; Ok(Self { response: Ok(types::PayoutsResponseData { status: Some(status), 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 }) } } // Payouts fulfill request transform #[cfg(feature = "payouts")] impl<F> TryFrom<&types::PayoutsRouterData<F>> for WisePayoutFulfillRequest { type Error = Error; fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> { let payout_type = item.request.get_payout_type()?; match payout_type { storage_enums::PayoutType::Bank => Ok(Self { fund_type: FundType::default(), }), storage_enums::PayoutType::Card | storage_enums::PayoutType::Wallet => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Wise"), ))? } } } } // Payouts fulfill response transform #[cfg(feature = "payouts")] impl<F> TryFrom<types::PayoutsResponseRouterData<F, WiseFulfillResponse>> for types::PayoutsRouterData<F> { type Error = Error; fn try_from( item: types::PayoutsResponseRouterData<F, WiseFulfillResponse>, ) -> Result<Self, Self::Error> { let response: WiseFulfillResponse = item.response; Ok(Self { response: Ok(types::PayoutsResponseData { status: Some(storage_enums::PayoutStatus::from(response.status)), connector_payout_id: Some( item.data .request .connector_payout_id .clone() .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?, ), payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: None, error_message: None, }), ..item.data }) } } #[cfg(feature = "payouts")] impl From<WiseStatus> for storage_enums::PayoutStatus { fn from(wise_status: WiseStatus) -> Self { match wise_status { WiseStatus::Completed => Self::Success, WiseStatus::Rejected => Self::Failed, WiseStatus::Cancelled => Self::Cancelled, WiseStatus::Pending | WiseStatus::Processing | WiseStatus::IncomingPaymentWaiting => { Self::Pending } } } } #[cfg(feature = "payouts")] impl From<PayoutEntityType> for LegalType { fn from(entity_type: PayoutEntityType) -> Self { match entity_type { PayoutEntityType::Individual | PayoutEntityType::Personal | PayoutEntityType::NonProfit | PayoutEntityType::NaturalPerson => Self::Private, PayoutEntityType::Company | PayoutEntityType::PublicSector | PayoutEntityType::Business => Self::Business, } } } #[cfg(feature = "payouts")] impl TryFrom<PayoutMethodData> for RecipientType { type Error = error_stack::Report<errors::ConnectorError>; 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()), } } }
4,822
1,508
hyperswitch
crates/router/src/connector/ebanx/transformers.rs
.rs
#[cfg(feature = "payouts")] use api_models::enums::Currency; #[cfg(feature = "payouts")] use api_models::payouts::{Bank, PayoutMethodData}; #[cfg(feature = "payouts")] use common_utils::pii::Email; use common_utils::types::FloatMajorUnit; #[cfg(feature = "payouts")] use masking::ExposeInterface; use masking::Secret; use serde::{Deserialize, Serialize}; #[cfg(feature = "payouts")] use crate::{ connector::utils::{AddressDetailsData, RouterData}, connector::utils::{CustomerDetails, PayoutsData}, types::{api, storage::enums as storage_enums}, }; use crate::{core::errors, types}; pub struct EbanxRouterData<T> { pub amount: FloatMajorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. pub router_data: T, } impl<T> From<(FloatMajorUnit, T)> for EbanxRouterData<T> { fn from((amount, item): (FloatMajorUnit, T)) -> Self { Self { amount, router_data: item, } } } #[cfg(feature = "payouts")] #[derive(Debug, Serialize, Clone)] pub struct EbanxPayoutCreateRequest { integration_key: Secret<String>, external_reference: String, country: String, amount: FloatMajorUnit, currency: Currency, target: EbanxPayoutType, target_account: Secret<String>, payee: EbanxPayoutDetails, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize, Clone)] pub enum EbanxPayoutType { BankAccount, Mercadopago, EwalletNequi, PixKey, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize, Clone)] pub struct EbanxPayoutDetails { name: Secret<String>, email: Option<Email>, document: Option<Secret<String>>, document_type: Option<EbanxDocumentType>, bank_info: EbanxBankDetails, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize, Clone)] pub enum EbanxDocumentType { #[serde(rename = "CPF")] NaturalPersonsRegister, #[serde(rename = "CNPJ")] NationalRegistryOfLegalEntities, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize, Clone)] pub struct EbanxBankDetails { bank_name: Option<String>, bank_branch: Option<String>, bank_account: Option<Secret<String>>, account_type: Option<EbanxBankAccountType>, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize, Clone)] pub enum EbanxBankAccountType { #[serde(rename = "C")] CheckingAccount, } #[cfg(feature = "payouts")] impl TryFrom<&EbanxRouterData<&types::PayoutsRouterData<api::PoCreate>>> for EbanxPayoutCreateRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &EbanxRouterData<&types::PayoutsRouterData<api::PoCreate>>, ) -> Result<Self, Self::Error> { let ebanx_auth_type = EbanxAuthType::try_from(&item.router_data.connector_auth_type)?; match item.router_data.get_payout_method_data()? { PayoutMethodData::Bank(Bank::Pix(pix_data)) => { let bank_info = EbanxBankDetails { bank_account: Some(pix_data.bank_account_number), bank_branch: pix_data.bank_branch, bank_name: pix_data.bank_name, account_type: Some(EbanxBankAccountType::CheckingAccount), }; let billing_address = item.router_data.get_billing_address()?; let customer_details = item.router_data.request.get_customer_details()?; let document_type = pix_data.tax_id.clone().map(|tax_id| { if tax_id.clone().expose().len() == 11 { EbanxDocumentType::NaturalPersonsRegister } else { EbanxDocumentType::NationalRegistryOfLegalEntities } }); let payee = EbanxPayoutDetails { name: billing_address.get_full_name()?, email: customer_details.email.clone(), bank_info, document_type, document: pix_data.tax_id.to_owned(), }; Ok(Self { amount: item.amount, integration_key: ebanx_auth_type.integration_key, country: customer_details.get_customer_phone_country_code()?, currency: item.router_data.request.source_currency, external_reference: item.router_data.connector_request_reference_id.to_owned(), target: EbanxPayoutType::PixKey, target_account: pix_data.pix_key, payee, }) } PayoutMethodData::Card(_) | PayoutMethodData::Bank(_) | PayoutMethodData::Wallet(_) => { Err(errors::ConnectorError::NotSupported { message: "Payment Method Not Supported".to_string(), connector: "Ebanx", })? } } } } pub struct EbanxAuthType { pub integration_key: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for EbanxAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self { integration_key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[cfg(feature = "payouts")] #[derive(Debug, Clone, Serialize, Deserialize)] pub enum EbanxPayoutStatus { #[serde(rename = "PA")] Succeeded, #[serde(rename = "CA")] Cancelled, #[serde(rename = "PE")] Processing, #[serde(rename = "OP")] RequiresFulfillment, } #[cfg(feature = "payouts")] impl From<EbanxPayoutStatus> for storage_enums::PayoutStatus { fn from(item: EbanxPayoutStatus) -> Self { match item { EbanxPayoutStatus::Succeeded => Self::Success, EbanxPayoutStatus::Cancelled => Self::Cancelled, EbanxPayoutStatus::Processing => Self::Pending, EbanxPayoutStatus::RequiresFulfillment => Self::RequiresFulfillment, } } } #[cfg(feature = "payouts")] #[derive(Debug, Clone, Serialize, Deserialize)] pub struct EbanxPayoutResponse { payout: EbanxPayoutResponseDetails, } #[cfg(feature = "payouts")] #[derive(Debug, Clone, Serialize, Deserialize)] pub struct EbanxPayoutResponseDetails { uid: String, status: EbanxPayoutStatus, } #[cfg(feature = "payouts")] impl<F> TryFrom<types::PayoutsResponseRouterData<F, EbanxPayoutResponse>> for types::PayoutsRouterData<F> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::PayoutsResponseRouterData<F, EbanxPayoutResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(types::PayoutsResponseData { status: Some(storage_enums::PayoutStatus::from( item.response.payout.status, )), connector_payout_id: Some(item.response.payout.uid), payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: None, error_message: None, }), ..item.data }) } } #[cfg(feature = "payouts")] #[derive(Debug, Clone, Serialize, Deserialize)] pub struct EbanxPayoutFulfillRequest { integration_key: Secret<String>, uid: String, } #[cfg(feature = "payouts")] impl<F> TryFrom<&EbanxRouterData<&types::PayoutsRouterData<F>>> for EbanxPayoutFulfillRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &EbanxRouterData<&types::PayoutsRouterData<F>>) -> Result<Self, Self::Error> { let request = item.router_data.request.to_owned(); let ebanx_auth_type = EbanxAuthType::try_from(&item.router_data.connector_auth_type)?; let payout_type = request.get_payout_type()?; match payout_type { storage_enums::PayoutType::Bank => Ok(Self { integration_key: ebanx_auth_type.integration_key, uid: request .connector_payout_id .to_owned() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "uid" })?, }), storage_enums::PayoutType::Card | storage_enums::PayoutType::Wallet => { Err(errors::ConnectorError::NotSupported { message: "Payout Method Not Supported".to_string(), connector: "Ebanx", })? } } } } #[cfg(feature = "payouts")] #[derive(Debug, Clone, Serialize, Deserialize)] pub struct EbanxFulfillResponse { #[serde(rename = "type")] status: EbanxFulfillStatus, message: String, } #[cfg(feature = "payouts")] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum EbanxFulfillStatus { Success, ApiError, AuthenticationError, InvalidRequestError, RequestError, } #[cfg(feature = "payouts")] impl From<EbanxFulfillStatus> for storage_enums::PayoutStatus { fn from(item: EbanxFulfillStatus) -> Self { match item { EbanxFulfillStatus::Success => Self::Success, EbanxFulfillStatus::ApiError | EbanxFulfillStatus::AuthenticationError | EbanxFulfillStatus::InvalidRequestError | EbanxFulfillStatus::RequestError => Self::Failed, } } } #[cfg(feature = "payouts")] impl<F> TryFrom<types::PayoutsResponseRouterData<F, EbanxFulfillResponse>> for types::PayoutsRouterData<F> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::PayoutsResponseRouterData<F, EbanxFulfillResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(types::PayoutsResponseData { status: Some(storage_enums::PayoutStatus::from(item.response.status)), connector_payout_id: Some(item.data.request.get_transfer_id()?), payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: None, error_message: None, }), ..item.data }) } } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct EbanxErrorResponse { pub code: String, pub status_code: String, pub message: Option<String>, } #[cfg(feature = "payouts")] #[derive(Debug, Clone, Serialize, Deserialize)] pub struct EbanxPayoutCancelRequest { integration_key: Secret<String>, uid: String, } #[cfg(feature = "payouts")] impl<F> TryFrom<&types::PayoutsRouterData<F>> for EbanxPayoutCancelRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> { let request = item.request.to_owned(); let ebanx_auth_type = EbanxAuthType::try_from(&item.connector_auth_type)?; let payout_type = request.get_payout_type()?; match payout_type { storage_enums::PayoutType::Bank => Ok(Self { integration_key: ebanx_auth_type.integration_key, uid: request .connector_payout_id .to_owned() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "uid" })?, }), storage_enums::PayoutType::Card | storage_enums::PayoutType::Wallet => { Err(errors::ConnectorError::NotSupported { message: "Payout Method Not Supported".to_string(), connector: "Ebanx", })? } } } } #[cfg(feature = "payouts")] #[derive(Debug, Clone, Serialize, Deserialize)] pub struct EbanxCancelResponse { #[serde(rename = "type")] status: EbanxCancelStatus, message: String, } #[cfg(feature = "payouts")] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum EbanxCancelStatus { Success, ApiError, AuthenticationError, InvalidRequestError, RequestError, } #[cfg(feature = "payouts")] impl From<EbanxCancelStatus> for storage_enums::PayoutStatus { fn from(item: EbanxCancelStatus) -> Self { match item { EbanxCancelStatus::Success => Self::Cancelled, EbanxCancelStatus::ApiError | EbanxCancelStatus::AuthenticationError | EbanxCancelStatus::InvalidRequestError | EbanxCancelStatus::RequestError => Self::Failed, } } } #[cfg(feature = "payouts")] impl<F> TryFrom<types::PayoutsResponseRouterData<F, EbanxCancelResponse>> for types::PayoutsRouterData<F> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::PayoutsResponseRouterData<F, EbanxCancelResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(types::PayoutsResponseData { status: Some(storage_enums::PayoutStatus::from(item.response.status)), connector_payout_id: item.data.request.connector_payout_id.clone(), payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: None, error_message: None, }), ..item.data }) } }
3,152
1,509
hyperswitch
crates/router/src/connector/signifyd/transformers.rs
.rs
#[cfg(feature = "frm")] pub mod api; pub mod auth; #[cfg(feature = "frm")] pub use self::api::*; pub use self::auth::*;
34
1,510
hyperswitch
crates/router/src/connector/signifyd/transformers/api.rs
.rs
use common_utils::{ext_traits::ValueExt, pii::Email}; use error_stack::{self, ResultExt}; pub use hyperswitch_domain_models::router_request_types::fraud_check::RefundMethod; use masking::Secret; use num_traits::ToPrimitive; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; use crate::{ connector::utils::{ AddressDetailsData, FraudCheckCheckoutRequest, FraudCheckRecordReturnRequest, FraudCheckSaleRequest, FraudCheckTransactionRequest, RouterData, }, core::{errors, fraud_check::types as core_types}, types::{ self, api, api::Fulfillment, fraud_check as frm_types, storage::enums as storage_enums, transformers::ForeignFrom, ResponseId, ResponseRouterData, }, }; #[allow(dead_code)] #[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum DecisionDelivery { Sync, AsyncOnly, } #[derive(Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Purchase { #[serde(with = "common_utils::custom_serde::iso8601")] created_at: PrimitiveDateTime, order_channel: OrderChannel, total_price: i64, products: Vec<Products>, shipments: Shipments, currency: Option<common_enums::Currency>, total_shipping_cost: Option<i64>, confirmation_email: Option<Email>, confirmation_phone: Option<Secret<String>>, } #[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)] #[serde(rename_all(serialize = "SCREAMING_SNAKE_CASE", deserialize = "snake_case"))] pub enum OrderChannel { Web, Phone, MobileApp, Social, Marketplace, InStoreKiosk, ScanAndGo, SmartTv, Mit, } #[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)] #[serde(rename_all(serialize = "SCREAMING_SNAKE_CASE", deserialize = "snake_case"))] pub enum FulfillmentMethod { Delivery, CounterPickup, CubsidePickup, LockerPickup, StandardShipping, ExpeditedShipping, GasPickup, ScheduledDelivery, } #[derive(Debug, Serialize, Eq, PartialEq, Clone)] #[serde(rename_all = "camelCase")] pub struct Products { item_name: String, item_price: i64, item_quantity: i32, item_id: Option<String>, item_category: Option<String>, item_sub_category: Option<String>, item_is_digital: Option<bool>, } #[derive(Debug, Serialize, Eq, PartialEq, Clone)] #[serde(rename_all = "camelCase")] pub struct Shipments { destination: Destination, fulfillment_method: Option<FulfillmentMethod>, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] #[serde(rename_all = "camelCase")] pub struct Destination { full_name: Secret<String>, organization: Option<String>, email: Option<Email>, address: Address, } #[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)] #[serde(rename_all = "camelCase")] pub struct Address { street_address: Secret<String>, unit: Option<Secret<String>>, postal_code: Secret<String>, city: String, province_code: Secret<String>, country_code: common_enums::CountryAlpha2, } #[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)] #[serde(rename_all(serialize = "SCREAMING_SNAKE_CASE", deserialize = "snake_case"))] pub enum CoverageRequests { Fraud, // use when you need a financial guarantee for Payment Fraud. Inr, // use when you need a financial guarantee for Item Not Received. Snad, // use when you need a financial guarantee for fraud alleging items are Significantly Not As Described. All, // use when you need a financial guarantee on all chargebacks. None, // use when you do not need a financial guarantee. Suggested actions in decision.checkpointAction are recommendations. } #[derive(Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct SignifydPaymentsSaleRequest { order_id: String, purchase: Purchase, decision_delivery: DecisionDelivery, coverage_requests: Option<CoverageRequests>, } #[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)] #[serde(rename_all(serialize = "camelCase", deserialize = "snake_case"))] pub struct SignifydFrmMetadata { pub total_shipping_cost: Option<i64>, pub fulfillment_method: Option<FulfillmentMethod>, pub coverage_request: Option<CoverageRequests>, pub order_channel: OrderChannel, } impl TryFrom<&frm_types::FrmSaleRouterData> for SignifydPaymentsSaleRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &frm_types::FrmSaleRouterData) -> Result<Self, Self::Error> { let products = item .request .get_order_details()? .iter() .map(|order_detail| Products { item_name: order_detail.product_name.clone(), item_price: order_detail.amount.get_amount_as_i64(), // This should be changed to MinorUnit when we implement amount conversion for this connector. Additionally, the function get_amount_as_i64() should be avoided in the future. item_quantity: i32::from(order_detail.quantity), item_id: order_detail.product_id.clone(), item_category: order_detail.category.clone(), item_sub_category: order_detail.sub_category.clone(), item_is_digital: order_detail .product_type .as_ref() .map(|product| (product == &common_enums::ProductType::Digital)), }) .collect::<Vec<_>>(); let metadata: SignifydFrmMetadata = item .frm_metadata .clone() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "frm_metadata", })? .parse_value("Signifyd Frm Metadata") .change_context(errors::ConnectorError::InvalidDataFormat { field_name: "frm_metadata", })?; let ship_address = item.get_shipping_address()?; let billing_address = item.get_billing()?; let street_addr = ship_address.get_line1()?; let city_addr = ship_address.get_city()?; let zip_code_addr = ship_address.get_zip()?; let country_code_addr = ship_address.get_country()?; let _first_name_addr = ship_address.get_first_name()?; let _last_name_addr = ship_address.get_last_name()?; let address: Address = Address { street_address: street_addr.clone(), unit: None, postal_code: zip_code_addr.clone(), city: city_addr.clone(), province_code: zip_code_addr.clone(), country_code: country_code_addr.to_owned(), }; let destination: Destination = Destination { full_name: ship_address.get_full_name().unwrap_or_default(), organization: None, email: None, address, }; let created_at = common_utils::date_time::now(); let order_channel = metadata.order_channel; let shipments = Shipments { destination, fulfillment_method: metadata.fulfillment_method, }; let purchase = Purchase { created_at, order_channel, total_price: item.request.amount, products, shipments, currency: item.request.currency, total_shipping_cost: metadata.total_shipping_cost, confirmation_email: item.request.email.clone(), confirmation_phone: billing_address .clone() .phone .and_then(|phone_data| phone_data.number), }; Ok(Self { order_id: item.attempt_id.clone(), purchase, decision_delivery: DecisionDelivery::Sync, // Specify SYNC if you require the Response to contain a decision field. If you have registered for a webhook associated with this checkpoint, then the webhook will also be sent when SYNC is specified. If ASYNC_ONLY is specified, then the decision field in the response will be null, and you will require a Webhook integration to receive Signifyd's final decision coverage_requests: metadata.coverage_request, }) } } #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] #[serde(rename_all = "camelCase")] pub struct Decision { #[serde(with = "common_utils::custom_serde::iso8601")] created_at: PrimitiveDateTime, checkpoint_action: SignifydPaymentStatus, checkpoint_action_reason: Option<String>, checkpoint_action_policy: Option<String>, score: Option<f64>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SignifydPaymentStatus { Accept, Challenge, Credit, Hold, Reject, } impl From<SignifydPaymentStatus> for storage_enums::FraudCheckStatus { fn from(item: SignifydPaymentStatus) -> Self { match item { SignifydPaymentStatus::Accept => Self::Legit, SignifydPaymentStatus::Reject => Self::Fraud, SignifydPaymentStatus::Hold => Self::ManualReview, SignifydPaymentStatus::Challenge | SignifydPaymentStatus::Credit => Self::Pending, } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct SignifydPaymentsResponse { signifyd_id: i64, order_id: String, decision: Decision, } impl<F, T> TryFrom<ResponseRouterData<F, SignifydPaymentsResponse, T, frm_types::FraudCheckResponseData>> for types::RouterData<F, T, frm_types::FraudCheckResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, SignifydPaymentsResponse, T, frm_types::FraudCheckResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(frm_types::FraudCheckResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.order_id), status: storage_enums::FraudCheckStatus::from( item.response.decision.checkpoint_action, ), connector_metadata: None, score: item.response.decision.score.and_then(|data| data.to_i32()), reason: item .response .decision .checkpoint_action_reason .map(serde_json::Value::from), }), ..item.data }) } } #[derive(Debug, Deserialize, PartialEq, Serialize)] pub struct SignifydErrorResponse { pub messages: Vec<String>, pub errors: serde_json::Value, } #[derive(Debug, Serialize, Eq, PartialEq, Clone)] #[serde(rename_all = "camelCase")] pub struct Transactions { transaction_id: String, gateway_status_code: String, payment_method: storage_enums::PaymentMethod, amount: i64, currency: storage_enums::Currency, gateway: Option<String>, } #[derive(Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct SignifydPaymentsTransactionRequest { order_id: String, checkout_id: String, transactions: Transactions, } impl From<storage_enums::AttemptStatus> for GatewayStatusCode { fn from(item: storage_enums::AttemptStatus) -> Self { match item { storage_enums::AttemptStatus::Pending => Self::Pending, storage_enums::AttemptStatus::Failure => Self::Failure, storage_enums::AttemptStatus::Charged => Self::Success, _ => Self::Pending, } } } impl TryFrom<&frm_types::FrmTransactionRouterData> for SignifydPaymentsTransactionRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &frm_types::FrmTransactionRouterData) -> Result<Self, Self::Error> { let currency = item.request.get_currency()?; let transactions = Transactions { amount: item.request.amount, transaction_id: item.clone().payment_id, gateway_status_code: GatewayStatusCode::from(item.status).to_string(), payment_method: item.payment_method, currency, gateway: item.request.connector.clone(), }; Ok(Self { order_id: item.attempt_id.clone(), checkout_id: item.payment_id.clone(), transactions, }) } } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum GatewayStatusCode { Success, Failure, #[default] Pending, Error, Cancelled, Expired, SoftDecline, } #[derive(Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct SignifydPaymentsCheckoutRequest { checkout_id: String, order_id: String, purchase: Purchase, coverage_requests: Option<CoverageRequests>, } impl TryFrom<&frm_types::FrmCheckoutRouterData> for SignifydPaymentsCheckoutRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &frm_types::FrmCheckoutRouterData) -> Result<Self, Self::Error> { let products = item .request .get_order_details()? .iter() .map(|order_detail| Products { item_name: order_detail.product_name.clone(), item_price: order_detail.amount.get_amount_as_i64(), // This should be changed to MinorUnit when we implement amount conversion for this connector. Additionally, the function get_amount_as_i64() should be avoided in the future. item_quantity: i32::from(order_detail.quantity), item_id: order_detail.product_id.clone(), item_category: order_detail.category.clone(), item_sub_category: order_detail.sub_category.clone(), item_is_digital: order_detail .product_type .as_ref() .map(|product| (product == &common_enums::ProductType::Digital)), }) .collect::<Vec<_>>(); let metadata: SignifydFrmMetadata = item .frm_metadata .clone() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "frm_metadata", })? .parse_value("Signifyd Frm Metadata") .change_context(errors::ConnectorError::InvalidDataFormat { field_name: "frm_metadata", })?; let ship_address = item.get_shipping_address()?; let street_addr = ship_address.get_line1()?; let city_addr = ship_address.get_city()?; let zip_code_addr = ship_address.get_zip()?; let country_code_addr = ship_address.get_country()?; let _first_name_addr = ship_address.get_first_name()?; let _last_name_addr = ship_address.get_last_name()?; let billing_address = item.get_billing()?; let address: Address = Address { street_address: street_addr.clone(), unit: None, postal_code: zip_code_addr.clone(), city: city_addr.clone(), province_code: zip_code_addr.clone(), country_code: country_code_addr.to_owned(), }; let destination: Destination = Destination { full_name: ship_address.get_full_name().unwrap_or_default(), organization: None, email: None, address, }; let created_at = common_utils::date_time::now(); let order_channel = metadata.order_channel; let shipments: Shipments = Shipments { destination, fulfillment_method: metadata.fulfillment_method, }; let purchase = Purchase { created_at, order_channel, total_price: item.request.amount, products, shipments, currency: item.request.currency, total_shipping_cost: metadata.total_shipping_cost, confirmation_email: item.request.email.clone(), confirmation_phone: billing_address .clone() .phone .and_then(|phone_data| phone_data.number), }; Ok(Self { checkout_id: item.payment_id.clone(), order_id: item.attempt_id.clone(), purchase, coverage_requests: metadata.coverage_request, }) } } #[derive(Debug, Deserialize, Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[serde_with::skip_serializing_none] #[serde(rename_all = "camelCase")] pub struct FrmFulfillmentSignifydRequest { pub order_id: String, pub fulfillment_status: Option<FulfillmentStatus>, pub fulfillments: Vec<Fulfillments>, } #[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde(untagged)] #[serde_with::skip_serializing_none] #[serde(rename_all = "camelCase")] pub enum FulfillmentStatus { PARTIAL, COMPLETE, REPLACEMENT, CANCELED, } #[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde_with::skip_serializing_none] #[serde(rename_all = "camelCase")] pub struct Fulfillments { pub shipment_id: String, pub products: Option<Vec<Product>>, pub destination: Destination, pub fulfillment_method: Option<String>, pub carrier: Option<String>, pub shipment_status: Option<String>, pub tracking_urls: Option<Vec<String>>, pub tracking_numbers: Option<Vec<String>>, pub shipped_at: Option<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde_with::skip_serializing_none] #[serde(rename_all = "camelCase")] pub struct Product { pub item_name: String, pub item_quantity: i64, pub item_id: String, } impl TryFrom<&frm_types::FrmFulfillmentRouterData> for FrmFulfillmentSignifydRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &frm_types::FrmFulfillmentRouterData) -> Result<Self, Self::Error> { Ok(Self { order_id: item.request.fulfillment_req.order_id.clone(), fulfillment_status: item .request .fulfillment_req .fulfillment_status .as_ref() .map(|fulfillment_status| FulfillmentStatus::from(&fulfillment_status.clone())), fulfillments: Vec::<Fulfillments>::foreign_from(&item.request.fulfillment_req), }) } } impl From<&core_types::FulfillmentStatus> for FulfillmentStatus { fn from(status: &core_types::FulfillmentStatus) -> Self { match status { core_types::FulfillmentStatus::PARTIAL => Self::PARTIAL, core_types::FulfillmentStatus::COMPLETE => Self::COMPLETE, core_types::FulfillmentStatus::REPLACEMENT => Self::REPLACEMENT, core_types::FulfillmentStatus::CANCELED => Self::CANCELED, } } } impl ForeignFrom<&core_types::FrmFulfillmentRequest> for Vec<Fulfillments> { fn foreign_from(fulfillment_req: &core_types::FrmFulfillmentRequest) -> Self { fulfillment_req .fulfillments .iter() .map(|fulfillment| Fulfillments { shipment_id: fulfillment.shipment_id.clone(), products: fulfillment .products .as_ref() .map(|products| products.iter().map(|p| Product::from(p.clone())).collect()), destination: Destination::from(fulfillment.destination.clone()), tracking_urls: fulfillment_req.tracking_urls.clone(), tracking_numbers: fulfillment_req.tracking_numbers.clone(), fulfillment_method: fulfillment_req.fulfillment_method.clone(), carrier: fulfillment_req.carrier.clone(), shipment_status: fulfillment_req.shipment_status.clone(), shipped_at: fulfillment_req.shipped_at.clone(), }) .collect() } } impl From<core_types::Product> for Product { fn from(product: core_types::Product) -> Self { Self { item_name: product.item_name, item_quantity: product.item_quantity, item_id: product.item_id, } } } impl From<core_types::Destination> for Destination { fn from(destination: core_types::Destination) -> Self { Self { full_name: destination.full_name, organization: destination.organization, email: destination.email, address: Address::from(destination.address), } } } impl From<core_types::Address> for Address { fn from(address: core_types::Address) -> Self { Self { street_address: address.street_address, unit: address.unit, postal_code: address.postal_code, city: address.city, province_code: address.province_code, country_code: address.country_code, } } } #[derive(Debug, Deserialize, Serialize, Clone, ToSchema)] #[serde_with::skip_serializing_none] #[serde(rename_all = "camelCase")] pub struct FrmFulfillmentSignifydApiResponse { pub order_id: String, pub shipment_ids: Vec<String>, } impl TryFrom< ResponseRouterData< Fulfillment, FrmFulfillmentSignifydApiResponse, frm_types::FraudCheckFulfillmentData, frm_types::FraudCheckResponseData, >, > for types::RouterData< Fulfillment, frm_types::FraudCheckFulfillmentData, frm_types::FraudCheckResponseData, > { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< Fulfillment, FrmFulfillmentSignifydApiResponse, frm_types::FraudCheckFulfillmentData, frm_types::FraudCheckResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(frm_types::FraudCheckResponseData::FulfillmentResponse { order_id: item.response.order_id, shipment_ids: item.response.shipment_ids, }), ..item.data }) } } #[derive(Debug, Serialize, Eq, PartialEq, Clone)] #[serde_with::skip_serializing_none] #[serde(rename_all = "camelCase")] pub struct SignifydRefund { method: RefundMethod, amount: String, currency: storage_enums::Currency, } #[derive(Debug, Serialize, Eq, PartialEq)] #[serde_with::skip_serializing_none] #[serde(rename_all = "camelCase")] pub struct SignifydPaymentsRecordReturnRequest { order_id: String, return_id: String, refund_transaction_id: Option<String>, refund: SignifydRefund, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde_with::skip_serializing_none] #[serde(rename_all = "camelCase")] pub struct SignifydPaymentsRecordReturnResponse { return_id: String, order_id: String, } impl<F, T> TryFrom< ResponseRouterData< F, SignifydPaymentsRecordReturnResponse, T, frm_types::FraudCheckResponseData, >, > for types::RouterData<F, T, frm_types::FraudCheckResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, SignifydPaymentsRecordReturnResponse, T, frm_types::FraudCheckResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(frm_types::FraudCheckResponseData::RecordReturnResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.order_id), return_id: Some(item.response.return_id.to_string()), connector_metadata: None, }), ..item.data }) } } impl TryFrom<&frm_types::FrmRecordReturnRouterData> for SignifydPaymentsRecordReturnRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &frm_types::FrmRecordReturnRouterData) -> Result<Self, Self::Error> { let currency = item.request.get_currency()?; let refund = SignifydRefund { method: item.request.refund_method.clone(), amount: item.request.amount.to_string(), currency, }; Ok(Self { return_id: uuid::Uuid::new_v4().to_string(), refund_transaction_id: item.request.refund_transaction_id.clone(), refund, order_id: item.attempt_id.clone(), }) } } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct SignifydWebhookBody { pub order_id: String, pub review_disposition: ReviewDisposition, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum ReviewDisposition { Fraudulent, Good, } impl From<ReviewDisposition> for api::IncomingWebhookEvent { fn from(value: ReviewDisposition) -> Self { match value { ReviewDisposition::Fraudulent => Self::FrmRejected, ReviewDisposition::Good => Self::FrmApproved, } } }
5,457
1,511
hyperswitch
crates/router/src/connector/signifyd/transformers/auth.rs
.rs
use error_stack; use masking::Secret; use crate::{core::errors, types}; pub struct SignifydAuthType { pub api_key: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for SignifydAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self { api_key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } }
144
1,512
hyperswitch
crates/router/src/connector/nmi/transformers.rs
.rs
use api_models::webhooks; use cards::CardNumber; use common_enums::CountryAlpha2; use common_utils::{errors::CustomResult, ext_traits::XmlExt, pii::Email, types::FloatMajorUnit}; use error_stack::{report, Report, ResultExt}; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; 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>; #[derive(Debug, Serialize)] #[serde(rename_all = "lowercase")] pub enum TransactionType { Auth, Capture, Refund, Sale, Validate, Void, } pub struct NmiAuthType { pub(super) api_key: Secret<String>, pub(super) public_key: Option<Secret<String>>, } impl TryFrom<&ConnectorAuthType> for NmiAuthType { type Error = Error; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::HeaderKey { api_key } => Ok(Self { api_key: api_key.to_owned(), public_key: None, }), ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { api_key: api_key.to_owned(), public_key: Some(key1.to_owned()), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Debug, Serialize)] pub struct NmiRouterData<T> { pub amount: FloatMajorUnit, pub router_data: T, } impl<T> From<(FloatMajorUnit, T)> for NmiRouterData<T> { fn from((amount, router_data): (FloatMajorUnit, T)) -> Self { Self { amount, router_data, } } } #[derive(Debug, Serialize)] pub struct NmiVaultRequest { security_key: Secret<String>, ccnumber: CardNumber, ccexp: Secret<String>, cvv: Secret<String>, first_name: Secret<String>, last_name: Secret<String>, address1: Option<Secret<String>>, address2: Option<Secret<String>>, city: Option<String>, state: Option<Secret<String>>, zip: Option<Secret<String>>, country: Option<CountryAlpha2>, customer_vault: CustomerAction, } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub enum CustomerAction { AddCustomer, UpdateCustomer, } impl TryFrom<&types::PaymentsPreProcessingRouterData> for NmiVaultRequest { type Error = Error; fn try_from(item: &types::PaymentsPreProcessingRouterData) -> Result<Self, Self::Error> { let auth_type: NmiAuthType = (&item.connector_auth_type).try_into()?; let (ccnumber, ccexp, cvv) = get_card_details(item.request.payment_method_data.clone())?; let billing_details = item.get_billing_address()?; let first_name = billing_details.get_first_name()?; Ok(Self { security_key: auth_type.api_key, ccnumber, ccexp, cvv, first_name: first_name.clone(), last_name: billing_details .get_last_name() .unwrap_or(first_name) .clone(), address1: billing_details.line1.clone(), address2: billing_details.line2.clone(), city: billing_details.city.clone(), state: billing_details.state.clone(), country: billing_details.country, zip: billing_details.zip.clone(), customer_vault: CustomerAction::AddCustomer, }) } } fn get_card_details( payment_method_data: Option<domain::PaymentMethodData>, ) -> CustomResult<(CardNumber, Secret<String>, Secret<String>), errors::ConnectorError> { match payment_method_data { Some(domain::PaymentMethodData::Card(ref card_details)) => Ok(( card_details.card_number.clone(), utils::CardData::get_card_expiry_month_year_2_digit_with_delimiter( card_details, "".to_string(), )?, card_details.card_cvc.clone(), )), _ => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Nmi"), ) .into()), } } #[derive(Debug, Deserialize, Serialize)] pub struct NmiVaultResponse { pub response: Response, pub responsetext: String, pub customer_vault_id: Option<Secret<String>>, pub response_code: String, pub transactionid: String, } impl TryFrom< types::ResponseRouterData< api::PreProcessing, NmiVaultResponse, types::PaymentsPreProcessingData, types::PaymentsResponseData, >, > for types::PaymentsPreProcessingRouterData { type Error = Error; fn try_from( item: types::ResponseRouterData< api::PreProcessing, NmiVaultResponse, types::PaymentsPreProcessingData, types::PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let auth_type: NmiAuthType = (&item.data.connector_auth_type).try_into()?; let amount_data = item.data .request .amount .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "amount", })?; let currency_data = item.data .request .currency .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "currency", })?; let (response, status) = match item.response.response { Response::Approved => ( Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::NoResponseId, redirection_data: Box::new(Some(services::RedirectForm::Nmi { amount: utils::to_currency_base_unit_asf64( amount_data, currency_data.to_owned(), )? .to_string(), currency: currency_data, customer_vault_id: item .response .customer_vault_id .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "customer_vault_id", })? .peek() .to_string(), public_key: auth_type.public_key.ok_or( errors::ConnectorError::InvalidConnectorConfig { config: "public_key", }, )?, order_id: item.data.connector_request_reference_id.clone(), })), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.transactionid), incremental_authorization_allowed: None, charges: None, }), enums::AttemptStatus::AuthenticationPending, ), Response::Declined | Response::Error => ( Err(types::ErrorResponse { code: item.response.response_code, message: item.response.responsetext.to_owned(), reason: Some(item.response.responsetext), status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.transactionid), network_advice_code: None, network_decline_code: None, network_error_message: None, }), enums::AttemptStatus::Failure, ), }; Ok(Self { status, response, ..item.data }) } } #[derive(Debug, Serialize)] pub struct NmiCompleteRequest { amount: FloatMajorUnit, #[serde(rename = "type")] transaction_type: TransactionType, security_key: Secret<String>, orderid: Option<String>, customer_vault_id: Secret<String>, email: Option<Email>, cardholder_auth: Option<String>, cavv: Option<String>, xid: Option<String>, eci: Option<String>, cvv: Secret<String>, three_ds_version: Option<String>, directory_server_id: Option<Secret<String>>, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] #[serde(untagged)] pub enum NmiRedirectResponse { NmiRedirectResponseData(NmiRedirectResponseData), NmiErrorResponseData(NmiErrorResponseData), } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NmiErrorResponseData { pub code: String, pub message: String, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NmiRedirectResponseData { cavv: Option<String>, xid: Option<String>, eci: Option<String>, card_holder_auth: Option<String>, three_ds_version: Option<String>, order_id: Option<String>, directory_server_id: Option<Secret<String>>, customer_vault_id: Secret<String>, } impl TryFrom<&NmiRouterData<&types::PaymentsCompleteAuthorizeRouterData>> for NmiCompleteRequest { type Error = Error; fn try_from( item: &NmiRouterData<&types::PaymentsCompleteAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let transaction_type = match item.router_data.request.is_auto_capture()? { true => TransactionType::Sale, false => TransactionType::Auth, }; let auth_type: NmiAuthType = (&item.router_data.connector_auth_type).try_into()?; let payload_data = item .router_data .request .get_redirect_response_payload()? .expose(); let three_ds_data: NmiRedirectResponseData = serde_json::from_value(payload_data) .change_context(errors::ConnectorError::MissingConnectorRedirectionPayload { field_name: "three_ds_data", })?; let (_, _, cvv) = get_card_details(item.router_data.request.payment_method_data.clone())?; Ok(Self { amount: item.amount, transaction_type, security_key: auth_type.api_key, orderid: three_ds_data.order_id, customer_vault_id: three_ds_data.customer_vault_id, email: item.router_data.request.email.clone(), cvv, cardholder_auth: three_ds_data.card_holder_auth, cavv: three_ds_data.cavv, xid: three_ds_data.xid, eci: three_ds_data.eci, three_ds_version: three_ds_data.three_ds_version, directory_server_id: three_ds_data.directory_server_id, }) } } #[derive(Debug, Deserialize, Serialize)] pub struct NmiCompleteResponse { 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, } impl TryFrom< types::ResponseRouterData< api::CompleteAuthorize, NmiCompleteResponse, types::CompleteAuthorizeData, types::PaymentsResponseData, >, > for types::PaymentsCompleteAuthorizeRouterData { type Error = Error; fn try_from( item: types::ResponseRouterData< api::CompleteAuthorize, NmiCompleteResponse, types::CompleteAuthorizeData, 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, ), 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::Authorizing }, ), Response::Declined | Response::Error => ( Err(types::ErrorResponse::foreign_from(( item.response, item.http_code, ))), enums::AttemptStatus::Failure, ), }; Ok(Self { status, response, ..item.data }) } } impl ForeignFrom<(NmiCompleteResponse, u16)> for types::ErrorResponse { fn foreign_from((response, http_code): (NmiCompleteResponse, 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, } } } #[derive(Debug, Serialize)] pub struct NmiPaymentsRequest { #[serde(rename = "type")] transaction_type: TransactionType, amount: FloatMajorUnit, security_key: Secret<String>, currency: enums::Currency, #[serde(flatten)] payment_method: PaymentMethod, #[serde(flatten)] merchant_defined_field: Option<NmiMerchantDefinedField>, orderid: String, } #[derive(Debug, Serialize)] pub struct NmiMerchantDefinedField { #[serde(flatten)] inner: std::collections::BTreeMap<String, Secret<String>>, } impl NmiMerchantDefinedField { 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 } } } #[derive(Debug, Serialize)] #[serde(untagged)] pub enum PaymentMethod { CardNonThreeDs(Box<CardData>), CardThreeDs(Box<CardThreeDsData>), GPay(Box<GooglePayData>), ApplePay(Box<ApplePayData>), } #[derive(Debug, Serialize)] pub struct CardData { ccnumber: CardNumber, ccexp: Secret<String>, cvv: Secret<String>, } #[derive(Debug, Serialize)] pub struct CardThreeDsData { ccnumber: CardNumber, ccexp: Secret<String>, email: Option<Email>, cardholder_auth: Option<String>, cavv: Option<String>, eci: Option<String>, cvv: Secret<String>, three_ds_version: Option<String>, directory_server_id: Option<Secret<String>>, } #[derive(Debug, Serialize)] pub struct GooglePayData { googlepay_payment_data: Secret<String>, } #[derive(Debug, Serialize)] pub struct ApplePayData { applepay_payment_data: Secret<String>, } impl TryFrom<&NmiRouterData<&types::PaymentsAuthorizeRouterData>> for NmiPaymentsRequest { type Error = Error; fn try_from( item: &NmiRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let transaction_type = match item.router_data.request.is_auto_capture()? { true => TransactionType::Sale, false => TransactionType::Auth, }; let auth_type: NmiAuthType = (&item.router_data.connector_auth_type).try_into()?; let amount = item.amount; let payment_method = PaymentMethod::try_from(( &item.router_data.request.payment_method_data, Some(item.router_data), ))?; Ok(Self { transaction_type, security_key: auth_type.api_key, amount, currency: item.router_data.request.currency, payment_method, merchant_defined_field: item .router_data .request .metadata .as_ref() .map(NmiMerchantDefinedField::new), orderid: item.router_data.connector_request_reference_id.clone(), }) } } impl TryFrom<( &domain::PaymentMethodData, Option<&types::PaymentsAuthorizeRouterData>, )> for PaymentMethod { type Error = Error; fn try_from( item: ( &domain::PaymentMethodData, Option<&types::PaymentsAuthorizeRouterData>, ), ) -> Result<Self, Self::Error> { let (payment_method_data, router_data) = item; match payment_method_data { domain::PaymentMethodData::Card(ref card) => match router_data { Some(data) => match data.auth_type { common_enums::AuthenticationType::NoThreeDs => Ok(Self::try_from(card)?), common_enums::AuthenticationType::ThreeDs => { Ok(Self::try_from((card, &data.request))?) } }, None => Ok(Self::try_from(card)?), }, domain::PaymentMethodData::Wallet(ref wallet_type) => match wallet_type { domain::WalletData::GooglePay(ref googlepay_data) => Ok(Self::from(googlepay_data)), domain::WalletData::ApplePay(ref applepay_data) => Ok(Self::from(applepay_data)), domain::WalletData::AliPayQr(_) | domain::WalletData::AliPayRedirect(_) | domain::WalletData::AliPayHkRedirect(_) | domain::WalletData::AmazonPayRedirect(_) | 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::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} | domain::WalletData::TouchNGoRedirect(_) | domain::WalletData::WeChatPayRedirect(_) | domain::WalletData::WeChatPayQr(_) | domain::WalletData::CashappQr(_) | domain::WalletData::SwishQr(_) | domain::WalletData::Mifinity(_) => { Err(report!(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("nmi"), ))) } }, domain::PaymentMethodData::CardRedirect(_) | domain::PaymentMethodData::PayLater(_) | domain::PaymentMethodData::BankRedirect(_) | domain::PaymentMethodData::BankDebit(_) | domain::PaymentMethodData::BankTransfer(_) | domain::PaymentMethodData::Crypto(_) | domain::PaymentMethodData::MandatePayment | domain::PaymentMethodData::Reward | domain::PaymentMethodData::RealTimePayment(_) | domain::PaymentMethodData::MobilePayment(_) | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) | domain::PaymentMethodData::NetworkToken(_) | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("nmi"), ) .into()) } } } } impl TryFrom<(&domain::payments::Card, &types::PaymentsAuthorizeData)> for PaymentMethod { type Error = Error; fn try_from( val: (&domain::payments::Card, &types::PaymentsAuthorizeData), ) -> Result<Self, Self::Error> { let (card_data, item) = val; let auth_data = &item.get_authentication_data()?; let ccexp = utils::CardData::get_card_expiry_month_year_2_digit_with_delimiter( card_data, "".to_string(), )?; let card_3ds_details = CardThreeDsData { ccnumber: card_data.card_number.clone(), ccexp, cvv: card_data.card_cvc.clone(), email: item.email.clone(), cavv: Some(auth_data.cavv.clone()), eci: auth_data.eci.clone(), cardholder_auth: None, three_ds_version: auth_data .message_version .clone() .map(|version| version.to_string()), directory_server_id: auth_data .threeds_server_transaction_id .clone() .map(Secret::new), }; Ok(Self::CardThreeDs(Box::new(card_3ds_details))) } } impl TryFrom<&domain::payments::Card> for PaymentMethod { type Error = Error; fn try_from(card: &domain::payments::Card) -> Result<Self, Self::Error> { let ccexp = utils::CardData::get_card_expiry_month_year_2_digit_with_delimiter( card, "".to_string(), )?; let card = CardData { ccnumber: card.card_number.clone(), ccexp, cvv: card.card_cvc.clone(), }; Ok(Self::CardNonThreeDs(Box::new(card))) } } impl From<&domain::GooglePayWalletData> for PaymentMethod { fn from(wallet_data: &domain::GooglePayWalletData) -> Self { let gpay_data = GooglePayData { googlepay_payment_data: Secret::new(wallet_data.tokenization_data.token.clone()), }; Self::GPay(Box::new(gpay_data)) } } impl From<&domain::ApplePayWalletData> for PaymentMethod { fn from(wallet_data: &domain::ApplePayWalletData) -> Self { let apple_pay_data = ApplePayData { applepay_payment_data: Secret::new(wallet_data.payment_data.clone()), }; Self::ApplePay(Box::new(apple_pay_data)) } } impl TryFrom<&types::SetupMandateRouterData> for NmiPaymentsRequest { type Error = Error; fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> { let auth_type: NmiAuthType = (&item.connector_auth_type).try_into()?; let payment_method = PaymentMethod::try_from((&item.request.payment_method_data, None))?; Ok(Self { transaction_type: TransactionType::Validate, security_key: auth_type.api_key, amount: FloatMajorUnit::zero(), currency: item.request.currency, payment_method, merchant_defined_field: None, orderid: item.connector_request_reference_id.clone(), }) } } #[derive(Debug, Serialize)] pub struct NmiSyncRequest { pub order_id: String, pub security_key: Secret<String>, } impl TryFrom<&types::PaymentsSyncRouterData> for NmiSyncRequest { type Error = Error; fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> { let auth = NmiAuthType::try_from(&item.connector_auth_type)?; Ok(Self { security_key: auth.api_key, order_id: item.attempt_id.clone(), }) } } #[derive(Debug, Serialize)] pub struct NmiCaptureRequest { #[serde(rename = "type")] pub transaction_type: TransactionType, pub security_key: Secret<String>, pub transactionid: String, pub amount: Option<FloatMajorUnit>, } impl TryFrom<&NmiRouterData<&types::PaymentsCaptureRouterData>> for NmiCaptureRequest { type Error = Error; fn try_from( item: &NmiRouterData<&types::PaymentsCaptureRouterData>, ) -> Result<Self, Self::Error> { let auth = NmiAuthType::try_from(&item.router_data.connector_auth_type)?; Ok(Self { transaction_type: TransactionType::Capture, security_key: auth.api_key, transactionid: item.router_data.request.connector_transaction_id.clone(), amount: Some(item.amount), }) } } impl TryFrom< types::ResponseRouterData< api::Capture, StandardResponse, types::PaymentsCaptureData, types::PaymentsResponseData, >, > for types::RouterData<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> { type Error = Error; 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 }) } } #[derive(Debug, Serialize)] pub struct NmiCancelRequest { #[serde(rename = "type")] pub transaction_type: TransactionType, pub security_key: Secret<String>, pub transactionid: String, pub void_reason: NmiVoidReason, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "snake_case")] pub enum NmiVoidReason { Fraud, UserCancel, IccRejected, IccCardRemoved, IccNoConfirmation, PosTimeout, } impl TryFrom<&types::PaymentsCancelRouterData> for NmiCancelRequest { type Error = Error; 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()), } } } #[derive(Debug, Deserialize, Serialize)] pub enum Response { #[serde(alias = "1")] Approved, #[serde(alias = "2")] Declined, #[serde(alias = "3")] Error, } #[derive(Debug, Deserialize, Serialize)] 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, } impl<T> TryFrom< types::ResponseRouterData< api::SetupMandate, StandardResponse, T, types::PaymentsResponseData, >, > for types::RouterData<api::SetupMandate, T, types::PaymentsResponseData> { type Error = Error; 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 }) } } impl ForeignFrom<(StandardResponse, u16)> for types::ErrorResponse { 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, } } } impl TryFrom<types::PaymentsResponseRouterData<StandardResponse>> for types::RouterData<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> { type Error = Error; 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 }) } } impl<T> TryFrom<types::ResponseRouterData<api::Void, StandardResponse, T, types::PaymentsResponseData>> for types::RouterData<api::Void, T, types::PaymentsResponseData> { type Error = Error; 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 }) } } #[derive(Debug, Deserialize)] #[serde(rename_all = "snake_case")] pub enum NmiStatus { Abandoned, Cancelled, Pendingsettlement, Pending, Failed, Complete, InProgress, Unknown, } impl<F, T> TryFrom<types::ResponseRouterData<F, SyncResponse, T, types::PaymentsResponseData>> for types::RouterData<F, T, types::PaymentsResponseData> { type Error = Error; 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 } } } impl TryFrom<Vec<u8>> for SyncResponse { type Error = Error; 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) } } impl TryFrom<Vec<u8>> for NmiRefundSyncResponse { type Error = Error; 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) } } impl From<NmiStatus> for enums::AttemptStatus { fn from(item: NmiStatus) -> Self { match item { NmiStatus::Abandoned => Self::AuthenticationFailed, NmiStatus::Cancelled => Self::Voided, NmiStatus::Pending => Self::Authorized, NmiStatus::Pendingsettlement | NmiStatus::Complete => Self::Charged, NmiStatus::InProgress => Self::AuthenticationPending, NmiStatus::Failed | NmiStatus::Unknown => Self::Failure, } } } // REFUND : #[derive(Debug, Serialize)] pub struct NmiRefundRequest { #[serde(rename = "type")] transaction_type: TransactionType, security_key: Secret<String>, transactionid: String, orderid: String, amount: FloatMajorUnit, } impl<F> TryFrom<&NmiRouterData<&types::RefundsRouterData<F>>> for NmiRefundRequest { type Error = Error; fn try_from(item: &NmiRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> { let auth_type: NmiAuthType = (&item.router_data.connector_auth_type).try_into()?; Ok(Self { transaction_type: TransactionType::Refund, security_key: auth_type.api_key, transactionid: item.router_data.request.connector_transaction_id.clone(), orderid: item.router_data.request.refund_id.clone(), amount: item.amount, }) } } impl TryFrom<types::RefundsResponseRouterData<api::Execute, StandardResponse>> for types::RefundsRouterData<api::Execute> { type Error = Error; fn try_from( item: types::RefundsResponseRouterData<api::Execute, StandardResponse>, ) -> Result<Self, Self::Error> { let refund_status = enums::RefundStatus::from(item.response.response); Ok(Self { response: Ok(types::RefundsResponseData { connector_refund_id: item.response.orderid, refund_status, }), ..item.data }) } } impl TryFrom<types::RefundsResponseRouterData<api::Capture, StandardResponse>> for types::RefundsRouterData<api::Capture> { type Error = Error; fn try_from( item: types::RefundsResponseRouterData<api::Capture, StandardResponse>, ) -> Result<Self, Self::Error> { let refund_status = enums::RefundStatus::from(item.response.response); Ok(Self { response: Ok(types::RefundsResponseData { connector_refund_id: item.response.transactionid, refund_status, }), ..item.data }) } } impl From<Response> for enums::RefundStatus { fn from(item: Response) -> Self { match item { Response::Approved => Self::Pending, Response::Declined | Response::Error => Self::Failure, } } } impl TryFrom<&types::RefundSyncRouterData> for NmiSyncRequest { type Error = Error; fn try_from(item: &types::RefundSyncRouterData) -> Result<Self, Self::Error> { let auth = NmiAuthType::try_from(&item.connector_auth_type)?; Ok(Self { security_key: auth.api_key, order_id: item .request .connector_refund_id .clone() .ok_or(errors::ConnectorError::MissingConnectorRefundID)?, }) } } impl TryFrom<types::RefundsResponseRouterData<api::RSync, NmiRefundSyncResponse>> for types::RefundsRouterData<api::RSync> { type Error = Report<errors::ConnectorError>; fn try_from( item: types::RefundsResponseRouterData<api::RSync, NmiRefundSyncResponse>, ) -> Result<Self, Self::Error> { let refund_status = enums::RefundStatus::from(NmiStatus::from(item.response.transaction.condition)); Ok(Self { response: Ok(types::RefundsResponseData { connector_refund_id: item.response.transaction.order_id, refund_status, }), ..item.data }) } } impl From<NmiStatus> for enums::RefundStatus { fn from(item: NmiStatus) -> Self { match item { NmiStatus::Abandoned | NmiStatus::Cancelled | NmiStatus::Failed | NmiStatus::Unknown => Self::Failure, NmiStatus::Pending | NmiStatus::InProgress => Self::Pending, NmiStatus::Pendingsettlement | NmiStatus::Complete => Self::Success, } } } impl From<String> for NmiStatus { 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, } } } #[derive(Debug, Deserialize, Serialize)] pub struct SyncTransactionResponse { pub transaction_id: String, pub condition: String, } #[derive(Debug, Deserialize, Serialize)] pub struct SyncResponse { pub transaction: Option<SyncTransactionResponse>, } #[derive(Debug, Deserialize, Serialize)] pub struct RefundSyncBody { order_id: String, condition: String, } #[derive(Debug, Deserialize, Serialize)] pub struct NmiRefundSyncResponse { transaction: RefundSyncBody, } #[derive(Debug, Deserialize)] pub struct NmiWebhookObjectReference { pub event_body: NmiReferenceBody, } #[derive(Debug, Deserialize)] pub struct NmiReferenceBody { pub order_id: String, pub action: NmiActionBody, } #[derive(Debug, Deserialize, Serialize)] pub struct NmiActionBody { pub action_type: NmiActionType, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "lowercase")] pub enum NmiActionType { Auth, Capture, Credit, Refund, Sale, Void, } #[derive(Debug, Deserialize)] pub struct NmiWebhookEventBody { pub event_type: NmiWebhookEventType, } #[derive(Debug, Deserialize, Serialize)] pub enum NmiWebhookEventType { #[serde(rename = "transaction.sale.success")] SaleSuccess, #[serde(rename = "transaction.sale.failure")] SaleFailure, #[serde(rename = "transaction.sale.unknown")] SaleUnknown, #[serde(rename = "transaction.auth.success")] AuthSuccess, #[serde(rename = "transaction.auth.failure")] AuthFailure, #[serde(rename = "transaction.auth.unknown")] AuthUnknown, #[serde(rename = "transaction.refund.success")] RefundSuccess, #[serde(rename = "transaction.refund.failure")] RefundFailure, #[serde(rename = "transaction.refund.unknown")] RefundUnknown, #[serde(rename = "transaction.void.success")] VoidSuccess, #[serde(rename = "transaction.void.failure")] VoidFailure, #[serde(rename = "transaction.void.unknown")] VoidUnknown, #[serde(rename = "transaction.capture.success")] CaptureSuccess, #[serde(rename = "transaction.capture.failure")] CaptureFailure, #[serde(rename = "transaction.capture.unknown")] CaptureUnknown, } impl ForeignFrom<NmiWebhookEventType> for webhooks::IncomingWebhookEvent { 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, } } } #[derive(Debug, Deserialize, Serialize)] pub struct NmiWebhookBody { pub event_body: NmiWebhookObject, } #[derive(Debug, Deserialize, Serialize)] pub struct NmiWebhookObject { pub transaction_id: String, pub order_id: String, pub condition: String, pub action: NmiActionBody, } impl TryFrom<&NmiWebhookBody> for SyncResponse { type Error = Error; fn try_from(item: &NmiWebhookBody) -> Result<Self, Self::Error> { let transaction = Some(SyncTransactionResponse { transaction_id: item.event_body.transaction_id.to_owned(), condition: item.event_body.condition.to_owned(), }); Ok(Self { transaction }) } }
9,793
1,513
hyperswitch
crates/router/src/connector/netcetera/transformers.rs
.rs
use error_stack::ResultExt; use masking::Secret; use serde::{Deserialize, Serialize}; use super::netcetera_types; use crate::{ connector::utils::{self, CardData}, core::errors, types::{self, api}, utils::OptionExt, }; //TODO: Fill the struct with respective fields pub struct NetceteraRouterData<T> { pub amount: i64, // The type of amount that a connector accepts, for example, String, i64, f64, etc. pub router_data: T, } impl<T> TryFrom<(&api::CurrencyUnit, types::storage::enums::Currency, i64, T)> for NetceteraRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (_currency_unit, _currency, amount, item): ( &api::CurrencyUnit, types::storage::enums::Currency, i64, T, ), ) -> Result<Self, Self::Error> { //Todo : use utils to convert the amount to the type of amount that a connector accepts Ok(Self { amount, router_data: item, }) } } impl<T> TryFrom<(i64, T)> for NetceteraRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from((amount, router_data): (i64, T)) -> Result<Self, Self::Error> { Ok(Self { amount, router_data, }) } } impl TryFrom< types::ResponseRouterData< api::PreAuthentication, NetceteraPreAuthenticationResponse, types::authentication::PreAuthNRequestData, types::authentication::AuthenticationResponseData, >, > for types::authentication::PreAuthNRouterData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::ResponseRouterData< api::PreAuthentication, NetceteraPreAuthenticationResponse, types::authentication::PreAuthNRequestData, types::authentication::AuthenticationResponseData, >, ) -> Result<Self, Self::Error> { let response = match item.response { NetceteraPreAuthenticationResponse::Success(pre_authn_response) => { // if card is not enrolled for 3ds, card_range will be None let card_range = pre_authn_response.get_card_range_if_available(); let maximum_supported_3ds_version = card_range .as_ref() .map(|card_range| card_range.highest_common_supported_version.clone()) .unwrap_or_else(|| { // Version "0.0.0" will be less that "2.0.0", hence we will treat this card as not eligible for 3ds authentication common_utils::types::SemanticVersion::new(0, 0, 0) }); let three_ds_method_data = card_range.as_ref().and_then(|card_range| { card_range .three_ds_method_data_form .as_ref() .map(|data| data.three_ds_method_data.clone()) }); let three_ds_method_url = card_range .as_ref() .and_then(|card_range| card_range.get_three_ds_method_url()); Ok( types::authentication::AuthenticationResponseData::PreAuthNResponse { threeds_server_transaction_id: pre_authn_response .three_ds_server_trans_id .clone(), maximum_supported_3ds_version: maximum_supported_3ds_version.clone(), connector_authentication_id: pre_authn_response.three_ds_server_trans_id, three_ds_method_data, three_ds_method_url, message_version: maximum_supported_3ds_version, connector_metadata: None, directory_server_id: card_range .as_ref() .and_then(|card_range| card_range.directory_server_id.clone()), }, ) } NetceteraPreAuthenticationResponse::Failure(error_response) => { Err(types::ErrorResponse { code: error_response.error_details.error_code, message: error_response.error_details.error_description, reason: error_response.error_details.error_detail, status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, }) } }; Ok(Self { response, ..item.data.clone() }) } } impl TryFrom< types::ResponseRouterData< api::Authentication, NetceteraAuthenticationResponse, types::authentication::ConnectorAuthenticationRequestData, types::authentication::AuthenticationResponseData, >, > for types::authentication::ConnectorAuthenticationRouterData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::ResponseRouterData< api::Authentication, NetceteraAuthenticationResponse, types::authentication::ConnectorAuthenticationRequestData, types::authentication::AuthenticationResponseData, >, ) -> Result<Self, Self::Error> { let response = match item.response { NetceteraAuthenticationResponse::Success(response) => { let authn_flow_type = match response.acs_challenge_mandated { Some(ACSChallengeMandatedIndicator::Y) => { types::authentication::AuthNFlowType::Challenge(Box::new( types::authentication::ChallengeParams { acs_url: response.authentication_response.acs_url.clone(), challenge_request: response.encoded_challenge_request, acs_reference_number: response .authentication_response .acs_reference_number, acs_trans_id: response.authentication_response.acs_trans_id, three_dsserver_trans_id: Some(response.three_ds_server_trans_id), acs_signed_content: response .authentication_response .acs_signed_content, }, )) } Some(ACSChallengeMandatedIndicator::N) | None => { types::authentication::AuthNFlowType::Frictionless } }; Ok( types::authentication::AuthenticationResponseData::AuthNResponse { authn_flow_type, authentication_value: response.authentication_value, trans_status: response.trans_status, connector_metadata: None, ds_trans_id: response.authentication_response.ds_trans_id, }, ) } NetceteraAuthenticationResponse::Error(error_response) => Err(types::ErrorResponse { code: error_response.error_details.error_code, message: error_response.error_details.error_description, reason: error_response.error_details.error_detail, status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, }), }; Ok(Self { response, ..item.data.clone() }) } } pub struct NetceteraAuthType { pub(super) certificate: Secret<String>, pub(super) private_key: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for NetceteraAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type.to_owned() { types::ConnectorAuthType::CertificateAuth { certificate, private_key, } => Ok(Self { certificate, private_key, }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NetceteraErrorResponse { pub three_ds_server_trans_id: Option<String>, pub error_details: NetceteraErrorDetails, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NetceteraErrorDetails { /// Universally unique identifier for the transaction assigned by the 3DS Server. #[serde(rename = "threeDSServerTransID")] pub three_ds_server_trans_id: Option<String>, /// Universally Unique identifier for the transaction assigned by the ACS. #[serde(rename = "acsTransID")] pub acs_trans_id: Option<String>, /// Universally unique identifier for the transaction assigned by the DS. #[serde(rename = "dsTransID")] pub ds_trans_id: Option<String>, /// Code indicating the type of problem identified. pub error_code: String, /// Code indicating the 3-D Secure component that identified the error. pub error_component: Option<String>, /// Text describing the problem identified. pub error_description: String, /// Additional detail regarding the problem identified. pub error_detail: Option<String>, /// Universally unique identifier for the transaction assigned by the 3DS SDK. #[serde(rename = "sdkTransID")] pub sdk_trans_id: Option<String>, /// The Message Type that was identified as erroneous. pub error_message_type: Option<String>, } #[derive(Debug, Serialize, Deserialize)] pub struct NetceteraMetaData { pub mcc: Option<String>, pub merchant_country_code: Option<String>, pub merchant_name: Option<String>, pub endpoint_prefix: String, pub three_ds_requestor_name: Option<String>, pub three_ds_requestor_id: Option<String>, pub merchant_configuration_id: Option<String>, } impl TryFrom<&Option<common_utils::pii::SecretSerdeValue>> for NetceteraMetaData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( meta_data: &Option<common_utils::pii::SecretSerdeValue>, ) -> Result<Self, Self::Error> { let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone()) .change_context(errors::ConnectorError::InvalidConnectorConfig { config: "metadata", })?; Ok(metadata) } } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NetceteraPreAuthenticationRequest { cardholder_account_number: cards::CardNumber, scheme_id: Option<netcetera_types::SchemeId>, } #[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum NetceteraPreAuthenticationResponse { Success(Box<NetceteraPreAuthenticationResponseData>), Failure(Box<NetceteraErrorResponse>), } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct NetceteraPreAuthenticationResponseData { #[serde(rename = "threeDSServerTransID")] pub three_ds_server_trans_id: String, pub card_ranges: Vec<CardRange>, } impl NetceteraPreAuthenticationResponseData { pub fn get_card_range_if_available(&self) -> Option<CardRange> { let card_range = self .card_ranges .iter() .max_by_key(|card_range| &card_range.highest_common_supported_version); card_range.cloned() } } #[derive(Debug, Deserialize, Serialize, Clone)] #[serde(rename_all = "camelCase")] pub struct CardRange { pub scheme_id: netcetera_types::SchemeId, pub directory_server_id: Option<String>, pub acs_protocol_versions: Vec<AcsProtocolVersion>, #[serde(rename = "threeDSMethodDataForm")] pub three_ds_method_data_form: Option<ThreeDSMethodDataForm>, pub highest_common_supported_version: common_utils::types::SemanticVersion, } impl CardRange { pub fn get_three_ds_method_url(&self) -> Option<String> { self.acs_protocol_versions .iter() .find(|acs_protocol_version| { acs_protocol_version.version == self.highest_common_supported_version }) .and_then(|acs_version| acs_version.three_ds_method_url.clone()) } } #[derive(Debug, Deserialize, Serialize, Clone)] #[serde(rename_all = "camelCase")] pub struct ThreeDSMethodDataForm { // base64 encoded value for 3ds method data collection #[serde(rename = "threeDSMethodData")] pub three_ds_method_data: String, } #[derive(Debug, Deserialize, Serialize, Clone)] #[serde(rename_all = "camelCase")] pub struct AcsProtocolVersion { pub version: common_utils::types::SemanticVersion, #[serde(rename = "threeDSMethodURL")] pub three_ds_method_url: Option<String>, } impl TryFrom<&NetceteraRouterData<&types::authentication::PreAuthNRouterData>> for NetceteraPreAuthenticationRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( value: &NetceteraRouterData<&types::authentication::PreAuthNRouterData>, ) -> Result<Self, Self::Error> { let router_data = value.router_data; let is_cobadged_card = || { router_data .request .card .card_number .is_cobadged_card() .change_context(errors::ConnectorError::RequestEncodingFailed) .attach_printable("error while checking is_cobadged_card") }; Ok(Self { cardholder_account_number: router_data.request.card.card_number.clone(), scheme_id: router_data .request .card .card_network .clone() .map(|card_network| { is_cobadged_card().map(|is_cobadged_card| { is_cobadged_card .then_some(netcetera_types::SchemeId::try_from(card_network)) }) }) .transpose()? .flatten() .transpose()?, }) } } #[derive(Debug, Deserialize, Serialize, Clone)] #[serde(rename_all = "camelCase")] #[serde_with::skip_serializing_none] pub struct NetceteraAuthenticationRequest { /// Specifies the preferred version of 3D Secure protocol to be utilized while executing 3D Secure authentication. /// 3DS Server initiates an authentication request with the preferred version and if this version is not supported by /// other 3D Secure components, it falls back to the next supported version(s) and continues authentication. /// /// If the preferred version is enforced by setting #enforcePreferredProtocolVersion flag, but this version /// is not supported by one of the 3D Secure components, 3DS Server does not initiate an authentication and provides /// corresponding error message to the customer. /// /// The accepted values are: /// - 2.1.0 -> prefer authentication with 2.1.0 version, /// - 2.2.0 -> prefer authentication with 2.2.0 version, /// - 2.3.1 -> prefer authentication with 2.3.1 version, /// - latest -> prefer authentication with the latest version, the 3DS Server is certified for. 2.3.1 at this moment. pub preferred_protocol_version: Option<common_utils::types::SemanticVersion>, /// Boolean flag that enforces preferred 3D Secure protocol version to be used in 3D Secure authentication. /// The value should be set true to enforce preferred version. If value is false or not provided, /// 3DS Server can fall back to next supported 3DS protocol version while initiating 3D Secure authentication. /// /// For application initiated transactions (deviceChannel = '01'), the preferred protocol version must be enforced. pub enforce_preferred_protocol_version: Option<bool>, pub device_channel: netcetera_types::NetceteraDeviceChannel, /// Identifies the category of the message for a specific use case. The accepted values are: /// /// - 01 -> PA /// - 02 -> NPA /// - 80 - 99 -> PS Specific Values (80 -> MasterCard Identity Check Insights; /// 85 -> MasterCard Identity Check, Production Validation PA; /// 86 -> MasterCard Identity Check, Production Validation NPA) pub message_category: netcetera_types::NetceteraMessageCategory, #[serde(rename = "threeDSCompInd")] pub three_ds_comp_ind: Option<netcetera_types::ThreeDSMethodCompletionIndicator>, /** * Contains the 3DS Server Transaction ID used during the previous execution of the 3DS method. Accepted value * length is 36 characters. Accepted value is a Canonical format as defined in IETF RFC 4122. May utilise any of the * specified versions if the output meets specified requirements. * * This field is required if the 3DS Requestor reuses previous 3DS Method execution with deviceChannel = 02 (BRW). * Available for supporting EMV 3DS 2.3.1 and later versions. */ #[serde(rename = "threeDSMethodId")] pub three_ds_method_id: Option<String>, #[serde(rename = "threeDSRequestor")] pub three_ds_requestor: Option<netcetera_types::ThreeDSRequestor>, #[serde(rename = "threeDSServerTransID")] pub three_ds_server_trans_id: String, #[serde(rename = "threeDSRequestorURL")] pub three_ds_requestor_url: Option<String>, pub cardholder_account: netcetera_types::CardholderAccount, pub cardholder: Option<netcetera_types::Cardholder>, pub purchase: Option<netcetera_types::Purchase>, pub acquirer: Option<netcetera_types::AcquirerData>, pub merchant: Option<netcetera_types::MerchantData>, pub broad_info: Option<String>, pub device_render_options: Option<netcetera_types::DeviceRenderingOptionsSupported>, pub message_extension: Option<Vec<netcetera_types::MessageExtensionAttribute>>, pub challenge_message_extension: Option<Vec<netcetera_types::MessageExtensionAttribute>>, pub browser_information: Option<netcetera_types::Browser>, #[serde(rename = "threeRIInd")] pub three_ri_ind: Option<String>, pub sdk_information: Option<netcetera_types::Sdk>, pub device: Option<String>, pub multi_transaction: Option<String>, pub device_id: Option<String>, pub user_id: Option<String>, pub payee_origin: Option<url::Url>, } impl TryFrom<&NetceteraRouterData<&types::authentication::ConnectorAuthenticationRouterData>> for NetceteraAuthenticationRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &NetceteraRouterData<&types::authentication::ConnectorAuthenticationRouterData>, ) -> Result<Self, Self::Error> { let now = common_utils::date_time::now(); let request = item.router_data.request.clone(); let pre_authn_data = request.pre_authentication_data.clone(); let ip_address = request .browser_details .as_ref() .and_then(|browser| browser.ip_address); let three_ds_requestor = netcetera_types::ThreeDSRequestor::new( ip_address, item.router_data.psd2_sca_exemption_type, item.router_data.request.force_3ds_challenge, item.router_data .request .pre_authentication_data .message_version .clone(), ); let card = utils::get_card_details(request.payment_method_data, "netcetera")?; let is_cobadged_card = card .card_number .clone() .is_cobadged_card() .change_context(errors::ConnectorError::RequestEncodingFailed) .attach_printable("error while checking is_cobadged_card")?; let cardholder_account = netcetera_types::CardholderAccount { acct_type: None, card_expiry_date: Some(card.get_expiry_date_as_yymm()?), acct_info: None, acct_number: card.card_number, scheme_id: card .card_network .clone() .and_then(|card_network| { is_cobadged_card.then_some(netcetera_types::SchemeId::try_from(card_network)) }) .transpose()?, acct_id: None, pay_token_ind: None, pay_token_info: None, card_security_code: Some(card.card_cvc), }; let currency = request .currency .get_required_value("currency") .change_context(errors::ConnectorError::MissingRequiredField { field_name: "currency", })?; let purchase = netcetera_types::Purchase { purchase_instal_data: None, merchant_risk_indicator: None, purchase_amount: request.amount, purchase_currency: currency.iso_4217().to_string(), purchase_exponent: currency.number_of_digits_after_decimal_point(), purchase_date: Some( common_utils::date_time::format_date( now, common_utils::date_time::DateFormat::YYYYMMDDHHmmss, ) .change_context( errors::ConnectorError::RequestEncodingFailedWithReason( "Failed to format Date".to_string(), ), )?, ), recurring_expiry: None, recurring_frequency: None, // 01 -> Goods and Services, hardcoding this as we serve this usecase only for now trans_type: Some("01".to_string()), recurring_amount: None, recurring_currency: None, recurring_exponent: None, recurring_date: None, amount_ind: None, frequency_ind: None, }; let acquirer_details = netcetera_types::AcquirerData { acquirer_bin: request.pre_authentication_data.acquirer_bin, acquirer_merchant_id: request.pre_authentication_data.acquirer_merchant_id, acquirer_country_code: request.pre_authentication_data.acquirer_country_code, }; let connector_meta_data: NetceteraMetaData = item .router_data .connector_meta_data .clone() .parse_value("NetceteraMetaData") .change_context(errors::ConnectorError::RequestEncodingFailed)?; let merchant_data = netcetera_types::MerchantData { merchant_configuration_id: connector_meta_data.merchant_configuration_id, mcc: connector_meta_data.mcc, merchant_country_code: connector_meta_data.merchant_country_code, merchant_name: connector_meta_data.merchant_name, notification_url: request.return_url.clone(), three_ds_requestor_id: connector_meta_data.three_ds_requestor_id, three_ds_requestor_name: connector_meta_data.three_ds_requestor_name, white_list_status: None, trust_list_status: None, seller_info: None, results_response_notification_url: Some(request.webhook_url), }; let browser_information = match request.device_channel { api_models::payments::DeviceChannel::Browser => { request.browser_details.map(netcetera_types::Browser::from) } api_models::payments::DeviceChannel::App => None, }; let sdk_information = match request.device_channel { api_models::payments::DeviceChannel::App => { request.sdk_information.map(netcetera_types::Sdk::from) } api_models::payments::DeviceChannel::Browser => None, }; let device_render_options = match request.device_channel { api_models::payments::DeviceChannel::App => { Some(netcetera_types::DeviceRenderingOptionsSupported { // hard-coded until core provides these values. sdk_interface: netcetera_types::SdkInterface::Both, sdk_ui_type: vec![ netcetera_types::SdkUiType::Text, netcetera_types::SdkUiType::SingleSelect, netcetera_types::SdkUiType::MultiSelect, netcetera_types::SdkUiType::Oob, netcetera_types::SdkUiType::HtmlOther, ], }) } api_models::payments::DeviceChannel::Browser => None, }; Ok(Self { preferred_protocol_version: Some(pre_authn_data.message_version), // For Device channel App, we should enforce the preferred protocol version enforce_preferred_protocol_version: Some(matches!( request.device_channel, api_models::payments::DeviceChannel::App )), device_channel: netcetera_types::NetceteraDeviceChannel::from(request.device_channel), message_category: netcetera_types::NetceteraMessageCategory::from( request.message_category, ), three_ds_comp_ind: Some(netcetera_types::ThreeDSMethodCompletionIndicator::from( request.threeds_method_comp_ind, )), three_ds_method_id: None, three_ds_requestor: Some(three_ds_requestor), three_ds_server_trans_id: pre_authn_data.threeds_server_transaction_id, three_ds_requestor_url: Some(request.three_ds_requestor_url), cardholder_account, cardholder: Some(netcetera_types::Cardholder::try_from(( request.billing_address, request.shipping_address, ))?), purchase: Some(purchase), acquirer: Some(acquirer_details), merchant: Some(merchant_data), broad_info: None, device_render_options, message_extension: None, challenge_message_extension: None, browser_information, three_ri_ind: None, sdk_information, device: None, multi_transaction: None, device_id: None, user_id: None, payee_origin: None, }) } } #[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum NetceteraAuthenticationResponse { Error(NetceteraAuthenticationFailureResponse), Success(NetceteraAuthenticationSuccessResponse), } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct NetceteraAuthenticationSuccessResponse { #[serde(rename = "threeDSServerTransID")] pub three_ds_server_trans_id: String, pub trans_status: common_enums::TransactionStatus, pub authentication_value: Option<String>, pub eci: Option<String>, pub acs_challenge_mandated: Option<ACSChallengeMandatedIndicator>, pub authentication_response: AuthenticationResponse, #[serde(rename = "base64EncodedChallengeRequest")] pub encoded_challenge_request: Option<String>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct NetceteraAuthenticationFailureResponse { pub error_details: NetceteraErrorDetails, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct AuthenticationResponse { #[serde(rename = "acsURL")] pub acs_url: Option<url::Url>, pub acs_reference_number: Option<String>, #[serde(rename = "acsTransID")] pub acs_trans_id: Option<String>, #[serde(rename = "dsTransID")] pub ds_trans_id: Option<String>, pub acs_signed_content: Option<String>, } #[derive(Debug, Deserialize, Serialize, Clone)] pub enum ACSChallengeMandatedIndicator { /// Challenge is mandated Y, /// Challenge is not mandated N, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ResultsResponseData { /// Universally unique transaction identifier assigned by the 3DS Server to identify a single transaction. /// It has the same value as the authentication request and conforms to the format defined in IETF RFC 4122. #[serde(rename = "threeDSServerTransID")] pub three_ds_server_trans_id: String, /// Indicates the status of a transaction in terms of its authentication. /// /// Valid values: /// - `Y`: Authentication / Account verification successful. /// - `N`: Not authenticated / Account not verified; Transaction denied. /// - `U`: Authentication / Account verification could not be performed; technical or other problem. /// - `C`: A challenge is required to complete the authentication. /// - `R`: Authentication / Account verification Rejected. Issuer is rejecting authentication/verification /// and request that authorization not be attempted. /// - `A`: Attempts processing performed; Not authenticated / verified, but a proof of attempt /// authentication / verification is provided. /// - `D`: A challenge is required to complete the authentication. Decoupled Authentication confirmed. /// - `I`: Informational Only; 3DS Requestor challenge preference acknowledged. pub trans_status: Option<common_enums::TransactionStatus>, /// Payment System-specific value provided as part of the ACS registration for each supported DS. /// Authentication Value may be used to provide proof of authentication. pub authentication_value: Option<String>, /// Payment System-specific value provided by the ACS to indicate the results of the attempt to authenticate /// the Cardholder. pub eci: Option<String>, /// The received Results Request from the Directory Server. pub results_request: Option<serde_json::Value>, /// The sent Results Response to the Directory Server. pub results_response: Option<serde_json::Value>, /// Optional object containing error details if any errors occurred during the process. pub error_details: Option<NetceteraErrorDetails>, }
6,344
1,514
hyperswitch
crates/router/src/connector/netcetera/netcetera_types.rs
.rs
use std::collections::HashMap; use common_utils::{pii::Email, types::SemanticVersion}; use hyperswitch_connectors::utils::AddressDetailsData; use masking::ExposeInterface; use serde::{Deserialize, Serialize}; use unidecode::unidecode; use crate::{connector::utils::PhoneDetailsData, errors, types::api::MessageCategory}; #[derive(Debug, Deserialize, Serialize, Clone)] #[serde(untagged)] pub enum SingleOrListElement<T> { Single(T), List(Vec<T>), } impl<T> SingleOrListElement<T> { fn get_version_checked(message_version: SemanticVersion, value: T) -> Self { if message_version.get_major() >= 2 && message_version.get_minor() >= 3 { Self::List(vec![value]) } else { Self::Single(value) } } } impl<T> SingleOrListElement<T> { pub fn new_single(value: T) -> Self { Self::Single(value) } pub fn new_list(value: Vec<T>) -> Self { Self::List(value) } } #[derive(Debug, Deserialize, Serialize, Clone)] pub enum NetceteraDeviceChannel { #[serde(rename = "01")] AppBased, #[serde(rename = "02")] Browser, #[serde(rename = "03")] ThreeDsRequestorInitiated, } impl From<api_models::payments::DeviceChannel> for NetceteraDeviceChannel { fn from(value: api_models::payments::DeviceChannel) -> Self { match value { api_models::payments::DeviceChannel::App => Self::AppBased, api_models::payments::DeviceChannel::Browser => Self::Browser, } } } #[derive(Debug, Deserialize, Serialize, Clone)] pub enum NetceteraMessageCategory { #[serde(rename = "01")] PaymentAuthentication, #[serde(rename = "02")] NonPaymentAuthentication, } impl From<MessageCategory> for NetceteraMessageCategory { fn from(value: MessageCategory) -> Self { match value { MessageCategory::NonPayment => Self::NonPaymentAuthentication, MessageCategory::Payment => Self::PaymentAuthentication, } } } #[derive(Debug, Deserialize, Serialize, Clone)] pub enum ThreeDSMethodCompletionIndicator { /// Successfully completed Y, /// Did not successfully complete N, /// Unavailable - 3DS Method URL was not present in the PRes message data U, } impl From<api_models::payments::ThreeDsCompletionIndicator> for ThreeDSMethodCompletionIndicator { fn from(value: api_models::payments::ThreeDsCompletionIndicator) -> Self { match value { api_models::payments::ThreeDsCompletionIndicator::Success => Self::Y, api_models::payments::ThreeDsCompletionIndicator::Failure => Self::N, api_models::payments::ThreeDsCompletionIndicator::NotAvailable => Self::U, } } } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct ThreeDSRequestor { #[serde(rename = "threeDSRequestorAuthenticationInd")] pub three_ds_requestor_authentication_ind: ThreeDSRequestorAuthenticationIndicator, /// Format of this field was changed with EMV 3DS 2.3.1 version: /// In versions prior to 2.3.1, this field is a single object. /// Starting from EMVCo version 2.3.1, this field is now an array of objects. Accepted value length is 1-3 elements. /// /// This field is optional, but recommended to include. #[serde(rename = "threeDSRequestorAuthenticationInfo")] pub three_ds_requestor_authentication_info: Option<SingleOrListElement<ThreeDSRequestorAuthenticationInformation>>, #[serde(rename = "threeDSRequestorChallengeInd")] pub three_ds_requestor_challenge_ind: Option<SingleOrListElement<ThreeDSRequestorChallengeIndicator>>, #[serde(rename = "threeDSRequestorPriorAuthenticationInfo")] pub three_ds_requestor_prior_authentication_info: Option<SingleOrListElement<ThreeDSRequestorPriorTransactionAuthenticationInformation>>, #[serde(rename = "threeDSRequestorDecReqInd")] pub three_ds_requestor_dec_req_ind: Option<ThreeDSRequestorDecoupledRequestIndicator>, /// Indicates the maximum amount of time that the 3DS Requestor will wait for an ACS to provide the results /// of a Decoupled Authentication transaction (in minutes). Valid values are between 1 and 10080. /// /// The field is optional and if value is not present, the expected action is for the ACS to interpret it as /// 10080 minutes (7 days). /// Available for supporting EMV 3DS 2.2.0 and later versions. /// /// Starting from EMV 3DS 2.3.1: /// This field is required if threeDSRequestorDecReqInd = Y, F or B. #[serde(rename = "threeDSRequestorDecMaxTime")] pub three_ds_requestor_dec_max_time: Option<u32>, /// External IP address (i.e., the device public IP address) used by the 3DS Requestor App when it connects to the /// 3DS Requestor environment. The value length is maximum 45 characters. Accepted values are: /// /// - IPv4 address is represented in the dotted decimal f. Refer to RFC 791. /// - IPv6 address. Refer to RFC 4291. /// /// This field is required when deviceChannel = 01 (APP) and unless market or regional mandate restricts sending /// this information. /// Available for supporting EMV 3DS 2.3.1 and later versions. pub app_ip: Option<std::net::IpAddr>, /// Indicate if the 3DS Requestor supports the SPC authentication. /// /// The accepted values are: /// /// - Y -> Supported /// /// This field is required if deviceChannel = 02 (BRW) and it is supported by the 3DS Requestor. /// Available for supporting EMV 3DS 2.3.1 and later versions. #[serde(rename = "threeDSRequestorSpcSupport")] pub three_ds_requestor_spc_support: Option<String>, /// Reason that the SPC authentication was not completed. /// Accepted value length is 2 characters. /// /// The accepted values are: /// /// - 01 -> SPC did not run or did not successfully complete /// - 02 -> Cardholder cancels the SPC authentication /// /// This field is required if deviceChannel = 02 (BRW) and the 3DS Requestor attempts to invoke SPC API and there is an /// error. /// Available for supporting EMV 3DS 2.3.1 and later versions. pub spc_incomp_ind: Option<String>, } /// Indicates the type of Authentication request. /// /// This data element provides additional information to the ACS to determine the best approach for handling an authentication request. /// /// This value is used for App-based and Browser flows. #[derive(Serialize, Deserialize, Debug, Clone)] pub enum ThreeDSRequestorAuthenticationIndicator { #[serde(rename = "01")] Payment, #[serde(rename = "02")] Recurring, #[serde(rename = "03")] Installment, #[serde(rename = "04")] AddCard, #[serde(rename = "05")] MaintainCard, #[serde(rename = "06")] CardholderVerification, #[serde(rename = "07")] BillingAgreement, } impl ThreeDSRequestor { pub fn new( app_ip: Option<std::net::IpAddr>, psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>, force_3ds_challenge: bool, message_version: SemanticVersion, ) -> Self { // if sca exemption is provided, we need to set the challenge indicator to NoChallengeRequestedTransactionalRiskAnalysis let three_ds_requestor_challenge_ind = if force_3ds_challenge { Some(SingleOrListElement::get_version_checked( message_version, ThreeDSRequestorChallengeIndicator::ChallengeRequestedMandate, )) } else if let Some(common_enums::ScaExemptionType::TransactionRiskAnalysis) = psd2_sca_exemption_type { Some(SingleOrListElement::get_version_checked( message_version, ThreeDSRequestorChallengeIndicator::NoChallengeRequestedTransactionalRiskAnalysis, )) } else { None }; Self { three_ds_requestor_authentication_ind: ThreeDSRequestorAuthenticationIndicator::Payment, three_ds_requestor_authentication_info: None, three_ds_requestor_challenge_ind, three_ds_requestor_prior_authentication_info: None, three_ds_requestor_dec_req_ind: None, three_ds_requestor_dec_max_time: None, app_ip, three_ds_requestor_spc_support: None, spc_incomp_ind: None, } } } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct ThreeDSRequestorAuthenticationInformation { /// Mechanism used by the Cardholder to authenticate to the 3DS Requestor. Accepted values are: /// - 01 -> No 3DS Requestor authentication occurred (i.e. cardholder "logged in" as guest) /// - 02 -> Login to the cardholder account at the 3DS Requestor system using 3DS Requestor's own credentials /// - 03 -> Login to the cardholder account at the 3DS Requestor system using federated ID /// - 04 -> Login to the cardholder account at the 3DS Requestor system using issuer credentials /// - 05 -> Login to the cardholder account at the 3DS Requestor system using third-party authentication /// - 06 -> Login to the cardholder account at the 3DS Requestor system using FIDO Authenticator. /// /// The next values are accepted as well if 3DS Server initiates authentication with EMV 3DS 2.2.0 version or greater (required protocol version can be set in ThreeDSServerAuthenticationRequest#preferredProtocolVersion field): /// - 07 -> Login to the cardholder account at the 3DS Requestor system using FIDO Authenticator (FIDO assurance data signed). /// - 08 -> SRC Assurance Data. /// - Additionally, 80-99 can be used for PS-specific values, regardless of protocol version. #[serde(rename = "threeDSReqAuthMethod")] pub three_ds_req_auth_method: ThreeDSReqAuthMethod, /// Date and time converted into UTC of the cardholder authentication. Field is limited to 12 characters and accepted format is YYYYMMDDHHMM #[serde(rename = "threeDSReqAuthTimestamp")] pub three_ds_req_auth_timestamp: String, /// Data that documents and supports a specific authentication process. In the current version of the specification, this data element is not defined in detail, however the intention is that for each 3DS Requestor Authentication Method, this field carry data that the ACS can use to verify the authentication process. /// For example, if the 3DS Requestor Authentication Method is: /// /// - 03 -> then this element can carry information about the provider of the federated ID and related information /// - 06 -> then this element can carry the FIDO attestation data (incl. the signature) /// - 07 -> then this element can carry FIDO Attestation data with the FIDO assurance data signed. /// - 08 -> then this element can carry the SRC assurance data. #[serde(rename = "threeDSReqAuthData")] pub three_ds_req_auth_data: Option<String>, } /// Indicates whether a challenge is requested for this transaction. For example: For 01-PA, a 3DS Requestor may have /// concerns about the transaction, and request a challenge. For 02-NPA, a challenge may be necessary when adding a new /// card to a wallet. /// /// This field is optional. The accepted values are: /// /// - 01 -> No preference /// - 02 -> No challenge requested /// - 03 -> Challenge requested: 3DS Requestor Preference /// - 04 -> Challenge requested: Mandate. /// The next values are accepted as well if 3DS Server initiates authentication with EMV 3DS 2.2.0 version /// or greater (required protocol version can be set in /// ThreeDSServerAuthenticationRequest#preferredProtocolVersion field): /// /// - 05 -> No challenge requested (transactional risk analysis is already performed) /// - 06 -> No challenge requested (Data share only) /// - 07 -> No challenge requested (strong consumer authentication is already performed) /// - 08 -> No challenge requested (utilise whitelist exemption if no challenge required) /// - 09 -> Challenge requested (whitelist prompt requested if challenge required). /// - Additionally, 80-99 can be used for PS-specific values, regardless of protocol version. /// /// If the element is not provided, the expected action is that the ACS would interpret as 01 -> No preference. /// /// Format of this field was changed with EMV 3DS 2.3.1 version: /// In versions prior to 2.3.1, this field is a String. /// Starting from EMVCo version 2.3.1, this field is now an array of objects. Accepted value length is 1-2 elements. /// When providing two preferences, the 3DS Requestor ensures that they are in preference order and are not /// conflicting. For example, 02 = No challenge requested and 04 = Challenge requested (Mandate). #[derive(Serialize, Deserialize, Debug, Clone)] pub enum ThreeDSRequestorChallengeIndicator { #[serde(rename = "01")] NoPreference, #[serde(rename = "02")] NoChallengeRequested, #[serde(rename = "03")] ChallengeRequested3DSRequestorPreference, #[serde(rename = "04")] ChallengeRequestedMandate, #[serde(rename = "05")] NoChallengeRequestedTransactionalRiskAnalysis, #[serde(rename = "06")] NoChallengeRequestedDataShareOnly, #[serde(rename = "07")] NoChallengeRequestedStrongConsumerAuthentication, #[serde(rename = "08")] NoChallengeRequestedWhitelistExemption, #[serde(rename = "09")] ChallengeRequestedWhitelistPrompt, } /// This field contains information about how the 3DS Requestor authenticated the cardholder as part of a previous 3DS transaction. /// Format of this field was changed with EMV 3DS 2.3.1 version: /// In versions prior to 2.3.1, this field is a single object. /// Starting from EMVCo version 2.3.1, this field is now an array of objects. Accepted value length is 1-3 elements. /// /// This field is optional, but recommended to include for versions prior to 2.3.1. From 2.3.1, /// it is required for 3RI in the case of Decoupled Authentication Fallback or for SPC. #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct ThreeDSRequestorPriorTransactionAuthenticationInformation { /// This data element provides additional information to the ACS to determine the best /// approach for handling a request. The field is limited to 36 characters containing /// ACS Transaction ID for a prior authenticated transaction (for example, the first /// recurring transaction that was authenticated with the cardholder). pub three_ds_req_prior_ref: String, /// Mechanism used by the Cardholder to previously authenticate to the 3DS Requestor. /// Accepted values for this field are: /// - 01 -> Frictionless authentication occurred by ACS /// - 02 -> Cardholder challenge occurred by ACS /// - 03 -> AVS verified /// - 04 -> Other issuer methods /// - 80-99 -> PS-specific value (dependent on the payment scheme type). pub three_ds_req_prior_auth_method: String, /// Date and time converted into UTC of the prior authentication. Accepted date /// format is YYYYMMDDHHMM. pub three_ds_req_prior_auth_timestamp: String, /// Data that documents and supports a specific authentication process. In the current /// version of the specification this data element is not defined in detail, however /// the intention is that for each 3DS Requestor Authentication Method, this field carry /// data that the ACS can use to verify the authentication process. In future versions /// of the application, these details are expected to be included. Field is limited to /// maximum 2048 characters. pub three_ds_req_prior_auth_data: String, } /// Enum indicating whether the 3DS Requestor requests the ACS to utilize Decoupled Authentication. #[derive(Serialize, Deserialize, Debug, Clone)] pub enum ThreeDSRequestorDecoupledRequestIndicator { /// Decoupled Authentication is supported and preferred if challenge is necessary. Y, /// Do not use Decoupled Authentication. N, /// Decoupled Authentication is supported and is to be used only as a fallback challenge method /// if a challenge is necessary (Transaction Status = D in RReq). F, /// Decoupled Authentication is supported and can be used as a primary or fallback challenge method /// if a challenge is necessary (Transaction Status = D in either ARes or RReq). B, } #[derive(Debug, Serialize, Deserialize, Clone)] pub enum SchemeId { Visa, Mastercard, #[serde(rename = "JCB")] Jcb, #[serde(rename = "American Express")] AmericanExpress, Diners, // For Cartes Bancaires and UnionPay, it is recommended to send the scheme ID #[serde(rename = "CB")] CartesBancaires, UnionPay, } impl TryFrom<common_enums::CardNetwork> for SchemeId { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(network: common_enums::CardNetwork) -> Result<Self, Self::Error> { match network { common_enums::CardNetwork::Visa => Ok(Self::Visa), common_enums::CardNetwork::Mastercard => Ok(Self::Mastercard), common_enums::CardNetwork::JCB => Ok(Self::Jcb), common_enums::CardNetwork::AmericanExpress => Ok(Self::AmericanExpress), common_enums::CardNetwork::DinersClub => Ok(Self::Diners), common_enums::CardNetwork::CartesBancaires => Ok(Self::CartesBancaires), common_enums::CardNetwork::UnionPay => Ok(Self::UnionPay), _ => Err(errors::ConnectorError::RequestEncodingFailedWithReason( "Invalid card network".to_string(), ))?, } } } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct CardholderAccount { /// Indicates the type of account. /// This is required if 3DS Requestor is asking Cardholder which Account Type they are using before making /// the purchase. This field is required in some markets. Otherwise, it is optional. pub acct_type: Option<AccountType>, /// Expiry date of the PAN or token supplied to the 3DS Requestor by the Cardholder. /// The field has 4 characters in a format YYMM. /// /// The requirements of the presence of this field are DS specific. pub card_expiry_date: Option<masking::Secret<String>>, /// This field contains additional information about the Cardholder’s account provided by the 3DS Requestor. /// /// The field is optional but recommended to include. /// /// Starting from EMV 3DS 2.3.1, added new field: /// - `ch_acc_req_id` -> The 3DS Requestor assigned account identifier of the transacting Cardholder. /// This identifier is a unique representation of the account identifier for the 3DS Requestor and /// is provided as a String. pub acct_info: Option<CardHolderAccountInformation>, /// Account number that will be used in the authorization request for payment transactions. /// May be represented by PAN or token. /// /// This field is required. pub acct_number: cards::CardNumber, /// ID for the scheme to which the Cardholder's acctNumber belongs to. /// It will be used to identify the Scheme from the 3DS Server configuration. /// /// This field is optional, but recommended to include. /// It should be present when it is not one of the schemes for which scheme resolving regular expressions /// are provided in the 3DS Server Configuration Properties. Additionally, /// if the schemeId is present in the request and there are card ranges found by multiple schemes, the schemeId will be /// used for proper resolving of the versioning data. pub scheme_id: Option<SchemeId>, /// Additional information about the account optionally provided by the 3DS Requestor. /// /// This field is limited to 64 characters and it is optional to use. #[serde(rename = "acctID")] pub acct_id: Option<String>, /// Indicates if the transaction was de-tokenized prior to being received by the ACS. /// /// The boolean value of true is the only valid response for this field when it is present. /// /// The field is required only if there is a de-tokenization of an Account Number. pub pay_token_ind: Option<bool>, /// Information about the de-tokenised Payment Token. /// Note: Data will be formatted into a JSON object prior to being placed into the EMV Payment Token field of the message. /// /// This field is optional. pub pay_token_info: Option<String>, /// Three or four-digit security code printed on the card. /// The value is numeric and limited to 3-4 characters. /// /// This field is required depending on the rules provided by the Directory Server. /// Available for supporting EMV 3DS 2.3.1 and later versions. pub card_security_code: Option<masking::Secret<String>>, } #[derive(Serialize, Deserialize, Debug, Clone)] pub enum AccountType { #[serde(rename = "01")] NotApplicable, #[serde(rename = "02")] Credit, #[serde(rename = "03")] Debit, #[serde(rename = "80")] Jcb, /// 81-99 -> PS-specific value (dependent on the payment scheme type). #[serde(untagged)] PsSpecificValue(String), } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct CardHolderAccountInformation { /// Length of time that the cardholder has had the account with the 3DS Requestor. /// /// Accepted values are: /// - `01` -> No account /// - `02` -> Created during this transaction /// - `03` -> Less than 30 days /// - `04` -> Between 30 and 60 days /// - `05` -> More than 60 days pub ch_acc_age_ind: Option<String>, /// Date converted into UTC that the cardholder opened the account with the 3DS Requestor. /// /// Date format = YYYYMMDD. pub ch_acc_date: Option<String>, /// Length of time since the cardholder’s account information with the 3DS Requestor was /// last changed. /// /// Includes Billing or Shipping address, new payment account, or new user(s) added. /// /// Accepted values are: /// - `01` -> Changed during this transaction /// - `02` -> Less than 30 days /// - `03` -> 30 - 60 days /// - `04` -> More than 60 days pub ch_acc_change_ind: Option<String>, /// Date converted into UTC that the cardholder’s account with the 3DS Requestor was last changed. /// /// Including Billing or Shipping address, new payment account, or new user(s) added. /// /// Date format = YYYYMMDD. pub ch_acc_change: Option<String>, /// Length of time since the cardholder’s account with the 3DS Requestor had a password change /// or account reset. /// /// The accepted values are: /// - `01` -> No change /// - `02` -> Changed during this transaction /// - `03` -> Less than 30 days /// - `04` -> 30 - 60 days /// - `05` -> More than 60 days pub ch_acc_pw_change_ind: Option<String>, /// Date converted into UTC that cardholder’s account with the 3DS Requestor had a password /// change or account reset. /// /// Date format must be YYYYMMDD. pub ch_acc_pw_change: Option<String>, /// Indicates when the shipping address used for this transaction was first used with the /// 3DS Requestor. /// /// Accepted values are: /// - `01` -> This transaction /// - `02` -> Less than 30 days /// - `03` -> 30 - 60 days /// - `04` -> More than 60 days pub ship_address_usage_ind: Option<String>, /// Date converted into UTC when the shipping address used for this transaction was first /// used with the 3DS Requestor. /// /// Date format must be YYYYMMDD. pub ship_address_usage: Option<String>, /// Number of transactions (successful and abandoned) for this cardholder account with the /// 3DS Requestor across all payment accounts in the previous 24 hours. pub txn_activity_day: Option<u32>, /// Number of transactions (successful and abandoned) for this cardholder account with the /// 3DS Requestor across all payment accounts in the previous year. pub txn_activity_year: Option<u32>, /// Number of Add Card attempts in the last 24 hours. pub provision_attempts_day: Option<u32>, /// Number of purchases with this cardholder account during the previous six months. pub nb_purchase_account: Option<u32>, /// Indicates whether the 3DS Requestor has experienced suspicious activity /// (including previous fraud) on the cardholder account. /// /// Accepted values are: /// - `01` -> No suspicious activity has been observed /// - `02` -> Suspicious activity has been observed pub suspicious_acc_activity: Option<String>, /// Indicates if the Cardholder Name on the account is identical to the shipping Name used /// for this transaction. /// /// Accepted values are: /// - `01` -> Account Name identical to shipping Name /// - `02` -> Account Name different than shipping Name pub ship_name_indicator: Option<String>, /// Indicates the length of time that the payment account was enrolled in the cardholder’s /// account with the 3DS Requester. /// /// Accepted values are: /// - `01` -> No account (guest check-out) /// - `02` -> During this transaction /// - `03` -> Less than 30 days /// - `04` -> 30 - 60 days /// - `05` -> More than 60 days pub payment_acc_ind: Option<String>, /// Date converted into UTC that the payment account was enrolled in the cardholder’s account with /// the 3DS Requestor. /// /// Date format must be YYYYMMDD. pub payment_acc_age: Option<String>, /// The 3DS Requestor assigned account identifier of the transacting Cardholder. /// /// This identifier is a unique representation of the account identifier for the 3DS Requestor and /// is provided as a String. Accepted value length is maximum 64 characters. /// /// Added starting from EMV 3DS 2.3.1. pub ch_acc_req_id: Option<String>, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] #[serde_with::skip_serializing_none] pub struct Cardholder { /// Indicates whether the Cardholder Shipping Address and Cardholder Billing Address are the same. /// /// Accepted values: /// - `Y` -> Shipping Address matches Billing Address /// - `N` -> Shipping Address does not match Billing Address /// /// If the field is not set and the shipping and billing addresses are the same, the 3DS Server will set the value to /// `Y`. Otherwise, the value will not be changed. /// /// This field is optional. addr_match: Option<String>, /// The city of the Cardholder billing address associated with the card used for this purchase. /// /// This field is limited to a maximum of 50 characters. /// /// This field is required unless market or regional mandate restricts sending this information. bill_addr_city: Option<String>, /// The country of the Cardholder billing address associated with the card used for this purchase. /// /// This field is limited to 3 characters. This value shall be the ISO 3166-1 numeric country code, except values /// from range 901 - 999 which are reserved by ISO. /// /// The field is required if Cardholder Billing Address State is present and unless market or regional mandate /// restricts sending this information. bill_addr_country: Option<String>, /// First line of the street address or equivalent local portion of the Cardholder billing address associated with /// the card use for this purchase. /// /// This field is limited to a maximum of 50 characters. /// /// This field is required unless market or regional mandate restricts sending this information. bill_addr_line1: Option<masking::Secret<String>>, /// Second line of the street address or equivalent local portion of the Cardholder billing address associated with /// the card use for this purchase. /// /// This field is limited to a maximum of 50 characters. /// /// This field is required unless market or regional mandate restricts sending this information. bill_addr_line2: Option<masking::Secret<String>>, /// Third line of the street address or equivalent local portion of the Cardholder billing address associated with /// the card use for this purchase. /// /// This field is limited to a maximum of 50 characters. /// /// This field is required unless market or regional mandate restricts sending this information. bill_addr_line3: Option<masking::Secret<String>>, /// ZIP or other postal code of the Cardholder billing address associated with the card used for this purchase. /// /// This field is limited to a maximum of 16 characters. /// /// This field is required unless market or regional mandate restricts sending this information. bill_addr_post_code: Option<masking::Secret<String>>, /// The state or province of the Cardholder billing address associated with the card used for this purchase. /// /// This field is limited to 3 characters. The value should be the country subdivision code defined in ISO 3166-2. /// /// This field is required unless State is not applicable for this country and unless market or regional mandate /// restricts sending this information. bill_addr_state: Option<masking::Secret<String>>, /// The email address associated with the account that is either entered by the Cardholder, or is on file with /// the 3DS Requestor. /// /// This field is limited to a maximum of 256 characters and shall meet requirements of Section 3.4 of /// IETF RFC 5322. /// /// This field is required unless market or regional mandate restricts sending this information. email: Option<Email>, /// The home phone provided by the Cardholder. /// /// Refer to ITU-E.164 for additional information on format and length. /// /// This field is required if available, unless market or regional mandate restricts sending this information. home_phone: Option<PhoneNumber>, /// The mobile phone provided by the Cardholder. /// /// Refer to ITU-E.164 for additional information on format and length. /// /// This field is required if available, unless market or regional mandate restricts sending this information. mobile_phone: Option<PhoneNumber>, /// The work phone provided by the Cardholder. /// /// Refer to ITU-E.164 for additional information on format and length. /// /// This field is required if available, unless market or regional mandate restricts sending this information. work_phone: Option<PhoneNumber>, /// Name of the Cardholder. /// /// This field is limited to 2-45 characters. /// /// This field is required unless market or regional mandate restricts sending this information. /// /// Starting from EMV 3DS 2.3.1: /// This field is limited to 1-45 characters. cardholder_name: Option<masking::Secret<String>>, /// City portion of the shipping address requested by the Cardholder. /// /// This field is required unless shipping information is the same as billing information, or market or regional /// mandate restricts sending this information. ship_addr_city: Option<String>, /// Country of the shipping address requested by the Cardholder. /// /// This field is limited to 3 characters. This value shall be the ISO 3166-1 numeric country code, except values /// from range 901 - 999 which are reserved by ISO. /// /// This field is required if Cardholder Shipping Address State is present and if shipping information are not the same /// as billing information. This field can be omitted if market or regional mandate restricts sending this information. ship_addr_country: Option<String>, /// First line of the street address or equivalent local portion of the shipping address associated with /// the card use for this purchase. /// /// This field is limited to a maximum of 50 characters. /// /// This field is required unless shipping information is the same as billing information, or market or regional /// mandate restricts sending this information. ship_addr_line1: Option<masking::Secret<String>>, /// Second line of the street address or equivalent local portion of the shipping address associated with /// the card use for this purchase. /// /// This field is limited to a maximum of 50 characters. /// /// This field is required unless shipping information is the same as billing information, or market or regional /// mandate restricts sending this information. ship_addr_line2: Option<masking::Secret<String>>, /// Third line of the street address or equivalent local portion of the shipping address associated with /// the card use for this purchase. /// /// This field is limited to a maximum of 50 characters. /// /// This field is required unless shipping information is the same as billing information, or market or regional /// mandate restricts sending this information. ship_addr_line3: Option<masking::Secret<String>>, /// ZIP or other postal code of the shipping address associated with the card used for this purchase. /// /// This field is limited to a maximum of 16 characters. /// /// This field is required unless shipping information is the same as billing information, or market or regional /// mandate restricts sending this information. ship_addr_post_code: Option<masking::Secret<String>>, /// The state or province of the shipping address associated with the card used for this purchase. /// /// This field is limited to 3 characters. The value should be the country subdivision code defined in ISO 3166-2. /// /// This field is required unless shipping information is the same as billing information, or State is not applicable /// for this country, or market or regional mandate restricts sending this information. ship_addr_state: Option<masking::Secret<String>>, /// Tax ID is the Cardholder's tax identification. /// /// The value is limited to 45 characters. /// /// This field is required depending on the rules provided by the Directory Server. /// Available for supporting EMV 3DS 2.3.1 and later versions. tax_id: Option<String>, } impl TryFrom<( hyperswitch_domain_models::address::Address, Option<hyperswitch_domain_models::address::Address>, )> for Cardholder { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (billing_address, shipping_address): ( hyperswitch_domain_models::address::Address, Option<hyperswitch_domain_models::address::Address>, ), ) -> Result<Self, Self::Error> { Ok(Self { addr_match: None, bill_addr_city: billing_address .address .as_ref() .and_then(|add| add.city.clone()), bill_addr_country: billing_address.address.as_ref().and_then(|add| { add.country.map(|country| { common_enums::Country::from_alpha2(country) .to_numeric() .to_string() }) }), bill_addr_line1: billing_address .address .as_ref() .and_then(|add| add.line1.clone()), bill_addr_line2: billing_address .address .as_ref() .and_then(|add| add.line2.clone()), bill_addr_line3: billing_address .address .as_ref() .and_then(|add| add.line3.clone()), bill_addr_post_code: billing_address .address .as_ref() .and_then(|add| add.zip.clone()), bill_addr_state: billing_address .address .as_ref() .and_then(|add| add.to_state_code_as_optional().transpose()) .transpose()?, email: billing_address.email, home_phone: billing_address .phone .clone() .map(PhoneNumber::try_from) .transpose()?, mobile_phone: billing_address .phone .clone() .map(PhoneNumber::try_from) .transpose()?, work_phone: billing_address .phone .clone() .map(PhoneNumber::try_from) .transpose()?, cardholder_name: billing_address.address.and_then(|address| { address .get_optional_full_name() .map(|name| masking::Secret::new(unidecode(&name.expose()))) }), ship_addr_city: shipping_address .as_ref() .and_then(|shipping_add| shipping_add.address.as_ref()) .and_then(|add| add.city.clone()), ship_addr_country: shipping_address .as_ref() .and_then(|shipping_add| shipping_add.address.as_ref()) .and_then(|add| { add.country.map(|country| { common_enums::Country::from_alpha2(country) .to_numeric() .to_string() }) }), ship_addr_line1: shipping_address .as_ref() .and_then(|shipping_add| shipping_add.address.as_ref()) .and_then(|add| add.line1.clone()), ship_addr_line2: shipping_address .as_ref() .and_then(|shipping_add| shipping_add.address.as_ref()) .and_then(|add| add.line2.clone()), ship_addr_line3: shipping_address .as_ref() .and_then(|shipping_add| shipping_add.address.as_ref()) .and_then(|add| add.line3.clone()), ship_addr_post_code: shipping_address .as_ref() .and_then(|shipping_add| shipping_add.address.as_ref()) .and_then(|add| add.zip.clone()), ship_addr_state: shipping_address .as_ref() .and_then(|shipping_add| shipping_add.address.as_ref()) .and_then(|add| add.to_state_code_as_optional().transpose()) .transpose()?, tax_id: None, }) } } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct PhoneNumber { /// Country Code of the phone, limited to 1-3 characters #[serde(rename = "cc")] country_code: Option<String>, subscriber: Option<masking::Secret<String>>, } impl TryFrom<hyperswitch_domain_models::address::PhoneDetails> for PhoneNumber { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( value: hyperswitch_domain_models::address::PhoneDetails, ) -> Result<Self, Self::Error> { Ok(Self { country_code: Some(value.extract_country_code()?), subscriber: value.number, }) } } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct Purchase { /// Indicates the maximum number of authorisations permitted for instalment payments. /// /// The field is limited to a maximum of 3 characters and value shall be greater than 1. /// /// The field is required if the Merchant and Cardholder have agreed to installment payments, i.e. if 3DS Requestor /// Authentication Indicator = 03. Omitted if not an installment payment authentication. /// /// Starting from EMV 3DS 2.3.1: /// Additionally this field is required for deviceChannel = 03 (3RI) if threeRIInd = 02. pub purchase_instal_data: Option<i32>, /// Merchant's assessment of the level of fraud risk for the specific authentication for both the cardholder and the /// authentication being conducted. /// /// The field is optional but strongly recommended to include. pub merchant_risk_indicator: Option<MerchantRiskIndicator>, /// Purchase amount in minor units of currency with all punctuation removed. When used in conjunction with the Purchase /// Currentcy Exponent field, proper punctuation can be calculated. Example: If the purchase amount is USD 123.45, /// element will contain the value 12345. The field is limited to maximum 48 characters. /// /// This field is required for 02 - NPA message category if 3DS Requestor Authentication Indicator = 02 or 03. /// /// Starting from EMV 3DS 2.3.1: /// Additionally this field is required for messageCategory = 02 (NPA) if threeRIInd = 01, 02, 06, 07, 08, 09, or 11. pub purchase_amount: Option<i64>, /// Currency in which purchase amount is expressed. The value is limited to 3 numeric characters and is represented by /// the ISO 4217 three-digit currency code, except 955-964 and 999. /// /// This field is required for requests where messageCategory = 01-PA and for 02-NPA if 3DS Requestor Authentication /// Indicator = 02 or 03. /// /// Starting from EMV 3DS 2.3.1: /// Additionally this field is required for messageCategory = 02 (NPA) if threeRIInd = 01, 02, 06, 07, 08, 09, or 11. pub purchase_currency: String, /// Minor units of currency as specified in the ISO 4217 currency exponent. The field is limited to 1 character and it /// is required for 01-PA and for 02-NPA if 3DS Requestor Authentication Indicator = 02 or 03. /// /// Example: for currency USD the exponent should be 2, and for Yen the exponent should be 0. /// /// Starting from EMV 3DS 2.3.1: /// Additionally this field is required for messageCategory = 02 (NPA) if threeRIInd = 01, 02, 06, 07, 08, 09, or 11. pub purchase_exponent: u8, /// Date and time of the purchase, converted into UTC. The field is limited to 14 characters, /// formatted as YYYYMMDDHHMMSS. /// /// This field is required for 01-PA and for 02-NPA, if 3DS Requestor Authentication Indicator = 02 or 03. /// /// Starting from EMV 3DS 2.3.1: /// Additionally this field is required for messageCategory = 02 (NPA) if threeRIInd = 01, 02, 06, 07, 08, 09, or 11. pub purchase_date: Option<String>, /// Date after which no further authorizations shall be performed. This field is limited to 8 characters, and the /// accepted format is YYYYMMDD. /// /// This field is required for 01-PA and for 02-NPA, if 3DS Requestor Authentication Indicator = 02 or 03. /// /// Starting from EMV 3DS 2.3.1: /// This field is required if recurringInd = 01. pub recurring_expiry: Option<String>, /// Indicates the minimum number of days between authorizations. The field is limited to maximum 4 characters. /// /// This field is required if 3DS Requestor Authentication Indicator = 02 or 03. /// /// Starting from EMV 3DS 2.3.1: /// This field is required if recurringInd = 01 pub recurring_frequency: Option<i32>, /// Identifies the type of transaction being authenticated. The values are derived from ISO 8583. Accepted values are: /// - 01 -> Goods / Service purchase /// - 03 -> Check Acceptance /// - 10 -> Account Funding /// - 11 -> Quasi-Cash Transaction /// - 28 -> Prepaid activation and Loan /// /// This field is required in some markets. Otherwise, the field is optional. /// /// This field is required if 3DS Requestor Authentication Indicator = 02 or 03. pub trans_type: Option<String>, /// Recurring amount after first/promotional payment in minor units of currency with all punctuation removed. /// Example: If the recurring amount is USD 123.45, element will contain the value 12345. The field is limited to /// maximum 48 characters. /// /// The field is required if threeDSRequestorAuthenticationInd = 02 or 03 OR threeRIInd = 01 or 02 AND /// purchaseAmount != recurringAmount AND recurringInd = 01. /// /// Available for supporting EMV 3DS 2.3.1 and later versions. pub recurring_amount: Option<i64>, /// Currency in which recurring amount is expressed. The value is limited to 3 numeric characters and is represented by /// the ISO 4217 three-digit currency code, except 955-964 and 999. /// /// This field is required if recurringAmount is present. /// /// Available for supporting EMV 3DS 2.3.1 and later versions. pub recurring_currency: Option<String>, /// Minor units of currency as specified in the ISO 4217 currency exponent. Example: USD = 2, Yen = 0. The value is /// limited to 1 numeric character. /// /// This field is required if recurringAmount is present. /// /// Available for supporting EMV 3DS 2.3.1 and later versions. pub recurring_exponent: Option<i32>, /// Effective date of new authorised amount following first/promotional payment in recurring transaction. The value /// is limited to 8 characters. Accepted format: YYYYMMDD. /// /// This field is required if recurringInd = 01. /// /// Available for supporting EMV 3DS 2.3.1 and later versions. pub recurring_date: Option<String>, /// Part of the indication whether the recurring or instalment payment has a fixed or variable amount. /// /// Accepted values are: /// - 01 -> Fixed Purchase Amount /// - 02 -> Variable Purchase Amount /// - 03–79 -> Reserved for EMVCo future use (values invalid until defined by EMVCo) /// - 80-99 -> PS-specific value (dependent on the payment scheme type) /// /// Available for supporting EMV 3DS 2.3.1 and later versions. pub amount_ind: Option<String>, /// Part of the indication whether the recurring or instalment payment has a fixed or variable frequency. /// /// Accepted values are: /// - 01 -> Fixed Frequency /// - 02 -> Variable Frequency /// - 03–79 -> Reserved for EMVCo future use (values invalid until defined by EMVCo) /// - 80-99 -> PS-specific value (dependent on the payment scheme type) /// /// Available for supporting EMV 3DS 2.3.1 and later versions. pub frequency_ind: Option<String>, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct MerchantRiskIndicator { /// Indicates the shipping method chosen for the transaction. /// /// Merchants must choose the Shipping Indicator code that most accurately describes the cardholder's specific transaction. /// If one or more items are included in the sale, use the Shipping Indicator code for the physical goods, or if all digital goods, /// use the code that describes the most expensive item. /// /// Accepted values: /// - Ship to cardholder's billing address (01) /// - Ship to another verified address on file with merchant (02) /// - Ship to address that is different than the cardholder's billing address (03) /// - Ship to Store / Pick-up at local store (Store address shall be populated in shipping address fields) (04) /// - Digital goods (includes online services, electronic gift cards and redemption codes) (05) /// - Travel and Event tickets, not shipped (06) /// - Other (for example, Gaming, digital services not shipped, e-media subscriptions, etc.) (07) /// - PS-specific value (dependent on the payment scheme type) (80-81) /// /// Starting from EMV 3DS 2.3.1: /// Changed values to shipIndicator -> Accepted values are: /// - 01 -> Ship to cardholder's billing address /// - 02 -> Ship to another verified address on file with merchant /// - 03 -> Ship to address that is different than the cardholder's billing address /// - 04 -> "Ship to Store" / Pick-up at local store (Store address shall be populated in shipping /// address fields) /// - 05 -> Digital goods (includes online services, electronic gift cards and redemption codes) /// - 06 -> Travel and Event tickets, not shipped /// - 07 -> Other (for example, Gaming, digital services not shipped, e-media subscriptions, etc.) /// - 08 -> Pick-up and go delivery /// - 09 -> Locker delivery (or other automated pick-up) ship_indicator: Option<String>, /// Indicates the merchandise delivery timeframe. /// /// Accepted values: /// - Electronic Delivery (01) /// - Same day shipping (02) /// - Overnight shipping (03) /// - Two-day or more shipping (04) delivery_timeframe: Option<String>, /// For electronic delivery, the email address to which the merchandise was delivered. delivery_email_address: Option<String>, /// Indicates whether the cardholder is reordering previously purchased merchandise. /// /// Accepted values: /// - First time ordered (01) /// - Reordered (02) reorder_items_ind: Option<String>, /// Indicates whether Cardholder is placing an order for merchandise with a future availability or release date. /// /// Accepted values: /// - Merchandise available (01) /// - Future availability (02) pre_order_purchase_ind: Option<String>, /// For a pre-ordered purchase, the expected date that the merchandise will be available. /// /// Date format: YYYYMMDD pre_order_date: Option<String>, /// For prepaid or gift card purchase, the purchase amount total of prepaid or gift card(s) in major units. gift_card_amount: Option<i32>, /// For prepaid or gift card purchase, the currency code of the card as defined in ISO 4217 except 955 - 964 and 999. gift_card_curr: Option<String>, // ISO 4217 currency code /// For prepaid or gift card purchase, total count of individual prepaid or gift cards/codes purchased. /// /// Field is limited to 2 characters. gift_card_count: Option<i32>, /// Starting from EMV 3DS 2.3.1.1: /// New field introduced: /// - transChar -> Indicates to the ACS specific transactions identified by the Merchant. /// - Size: Variable, 1-2 elements. JSON Data Type: Array of String. Accepted values: /// - 01 -> Cryptocurrency transaction /// - 02 -> NFT transaction trans_char: Option<String>, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct AcquirerData { /// Acquiring institution identification code as assigned by the DS receiving the AReq message. /// /// This field is limited to 11 characters. This field can be omitted if it there is a MerchantAcquirer already configured for 3DS Server, /// referenced by the acquirerMerchantId. /// /// This field is required if no MerchantAcquirer is present for the acquirer BIN in the 3DS Server configuration and /// for requests where messageCategory = 01 (PA). For requests where messageCategory=02 (NPA), the field is required /// only if scheme is Mastercard, for other schemes it is optional. #[serde(skip_serializing_if = "Option::is_none")] pub acquirer_bin: Option<String>, /// Acquirer-assigned Merchant identifier. /// /// This may be the same value that is used in authorization requests sent on behalf of the 3DS Requestor and is represented in ISO 8583 formatting requirements. /// The field is limited to maximum 35 characters. Individual Directory Servers may impose specific format and character requirements on /// the contents of this field. /// /// This field will be used to identify the Directory Server where the AReq will be sent and the acquirerBin from the 3DS Server configuration. /// If no MerchantAcquirer configuration is present in the 3DS Server, the DirectoryServer information will be resolved from the scheme to which the cardholder account belongs to. /// /// This field is required if merchantConfigurationId is not provided in the request and messageCategory = 01 (PA). /// For Mastercard, if merchantConfigurationId is not provided, the field must be present if messageCategory = 02 (NPA). #[serde(skip_serializing_if = "Option::is_none")] pub acquirer_merchant_id: Option<String>, /// Acquirer Country Code. /// /// This is the code of the country where the acquiring institution is located. The specified /// length of this field is 3 characters and will accept values according to the ISO 3166-1 numeric three-digit /// country code. /// /// The Directory Server may edit the value of this field provided by the 3DS Server. /// /// This field is required. #[serde(skip_serializing_if = "Option::is_none")] pub acquirer_country_code: Option<String>, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] #[serde_with::skip_serializing_none] pub struct MerchantData { /// ID of the merchant. This value will be used to find merchant information from the configuration. /// From the merchant configuration the 3DS Server can fill the other values (mcc, merchantCountryCode and merchantName), if provided. /// /// This field can be left out if merchant information are provided in the request. pub merchant_configuration_id: Option<String>, /// Merchant Category Code. This is the DS-specific code describing the Merchant's type of business, product or service. /// The field is limited to 4 characters. The value correlates to the Merchant Category Code as defined by each Payment System or DS. /// /// If not present in the request it will be filled from the merchant configuration referenced by the merchantConfigurationId. /// /// This field is required for messageCategory=01 (PA) and optional, but strongly recommended for 02 (NPA). #[serde(skip_serializing_if = "Option::is_none")] pub mcc: Option<String>, /// Country code for the merchant. This value correlates to the Merchant Country Code as defined by each Payment System or DS. /// The field is limited to 3 characters accepting ISO 3166-1 format, except 901-999. /// /// If not present in the request it will be filled from the merchant configuration referenced by the merchantConfigurationId. /// /// This field is required for messageCategory=01 (PA) and optional, but strongly recommended for 02 (NPA). #[serde(skip_serializing_if = "Option::is_none")] pub merchant_country_code: Option<String>, /// Merchant name assigned by the Acquirer or Payment System. This field is limited to maximum 40 characters, /// and it is the same name used in the authorisation message as defined in ISO 8583. /// /// If not present in the request it will be filled from the merchant configuration referenced by the merchantConfigurationId. /// /// This field is required for messageCategory=01 (PA) and optional, but strongly recommended for 02 (NPA). #[serde(skip_serializing_if = "Option::is_none")] pub merchant_name: Option<String>, /// Fully qualified URL of the merchant that receives the CRes message or Error Message. /// Incorrect formatting will result in a failure to deliver the notification of the final CRes message. /// This field is limited to 256 characters. /// /// This field should be present if the merchant will receive the final CRes message and the device channel is BROWSER. /// If not present in the request it will be filled from the notificationURL configured in the XML or database configuration. #[serde(rename = "notificationURL")] #[serde(skip_serializing_if = "Option::is_none")] pub notification_url: Option<String>, /// Each DS provides rules for the 3DS Requestor ID. The 3DS Requestor is responsible for providing the 3DS Requestor ID according to the DS rules. /// /// This value is mandatory, therefore it should be either configured for each Merchant Acquirer, or should be /// passed in the transaction payload as part of the Merchant data. #[serde(rename = "threeDSRequestorId")] #[serde(skip_serializing_if = "Option::is_none")] pub three_ds_requestor_id: Option<String>, /// Each DS provides rules for the 3DS Requestor Name. The 3DS Requestor is responsible for providing the 3DS Requestor Name according to the DS rules. /// /// This value is mandatory, therefore it should be either configured for each Merchant Acquirer, or should be /// passed in the transaction payload as part of the Merchant data. #[serde(rename = "threeDSRequestorName")] #[serde(skip_serializing_if = "Option::is_none")] pub three_ds_requestor_name: Option<String>, /// Set whitelisting status of the merchant. /// /// The field is optional and if value is not present, the whitelist remains unchanged. /// This field is only available for supporting EMV 3DS 2.2.0. pub white_list_status: Option<WhitelistStatus>, /// Set trustlisting status of the merchant. /// /// The field is optional and if value is not present, the trustlist remains unchanged. /// From EMV 3DS 2.3.1 this field replaces whiteListStatus. pub trust_list_status: Option<WhitelistStatus>, /// Additional transaction information for transactions where merchants submit transaction details on behalf of another entity. /// The accepted value length is 1-50 elements. /// /// This field is optional. pub seller_info: Option<Vec<SellerInfo>>, /// Fully qualified URL of the merchant that receives the RRes message or Error Message. /// Incorrect formatting will result in a failure to deliver the notification of the final RRes message. /// This field is limited to 256 characters. /// /// This field is not mandatory and could be present if the Results Response (in case of a challenge transaction) /// should be sent to a dynamic URL different from the one present in the configuration, only if dynamic provision /// of the Results Response notification URL is allowed per the license. /// /// If not present in the request it will be filled from the notificationURL configured in the XML or database /// configuration. #[serde(skip_serializing_if = "Option::is_none")] pub results_response_notification_url: Option<String>, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub enum WhitelistStatus { /// 3DS Requestor is whitelisted by cardholder Y, /// 3DS Requestor is not whitelisted by cardholder N, /// Not eligible as determined by issuer E, /// Pending confirmation by cardholder P, /// Cardholder rejected R, /// Whitelist status unknown, unavailable, or does not apply. U, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] #[serde_with::skip_serializing_none] pub struct SellerInfo { /// Name of the Seller. The value length is maximum 100 characters. This field is required. seller_name: String, /// Merchant-assigned Seller identifier. If this data element is present, this must match the Seller ID field /// in the Seller Information object. The value length is maximum 50 characters. This field is required if /// sellerId in multiTransaction object is present. seller_id: Option<String>, /// Business name of the Seller. The value length is maximum 100 characters. This field is optional. seller_business_name: Option<String>, /// Date converted into UTC that the Seller started using the Merchant's services. The accepted value length is /// 8 characters. The accepted format is: YYYYMMDD. seller_acc_date: Option<String>, /// First line of the business or contact street address of the Seller. The value length is maximum 50 characters. /// This field is optional. seller_addr_line1: Option<String>, /// Second line of the business or contact street address of the Seller. The value length is maximum 50 characters. /// This field is optional. seller_addr_line2: Option<String>, /// Third line of the business or contact street address of the Seller. The value length is maximum 50 characters. /// This field is optional. seller_addr_line3: Option<String>, /// Business or contact city of the Seller. The value length is maximum 50 characters. This field is optional. seller_addr_city: Option<String>, /// Business or contact state or province of the Seller. The value length is maximum 3 characters. Accepted values /// are: Country subdivision code defined in ISO 3166-2. For example, using the ISO entry US-CA (California, /// United States), the correct value for this field = CA. Note that the country and hyphen are not included in /// this value. This field is optional. seller_addr_state: Option<String>, /// Business or contact ZIP or other postal code of the Seller. The value length is maximum 16 characters. /// This field is optional. seller_addr_post_code: Option<String>, /// Business or contact country of the Seller. The accepted value length is 3 characters. Accepted values are /// ISO 3166-1 numeric three-digit country code, except 955-964 and 999. This field is optional. seller_addr_country: Option<String>, /// Business or contact email address of the Seller. The value length is maximum 254 characters. Accepted values /// shall meet requirements of Section 3.4 of IETF RFC 5322. This field is optional. seller_email: Option<String>, /// Business or contact phone number of the Seller. Country Code and Subscriber sections of the number represented /// by the following named fields: /// - cc -> Accepted value length is 1-3 characters. /// - subscriber -> Accepted value length is maximum 15 characters. /// This field is optional. seller_phone: Option<PhoneNumber>, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] 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>>, } // Split by comma and return the list of accept languages // If Accept-Language is : fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, List should be [fr-CH, fr, en, de] pub fn get_list_of_accept_languages(accept_language: String) -> Vec<String> { accept_language .split(',') .map(|lang| lang.split(';').next().unwrap_or(lang).trim().to_string()) .collect() } impl From<crate::types::BrowserInformation> for Browser { fn from(value: crate::types::BrowserInformation) -> Self { Self { browser_accept_header: value.accept_header, browser_ip: value .ip_address .map(|ip| masking::Secret::new(ip.to_string())), browser_java_enabled: value.java_enabled, browser_language: value.language, browser_color_depth: value.color_depth.map(|cd| cd.to_string()), browser_screen_height: value.screen_height, browser_screen_width: value.screen_width, browser_tz: value.time_zone, browser_user_agent: value.user_agent, challenge_window_size: Some(ChallengeWindowSizeEnum::FullScreen), browser_javascript_enabled: value.java_script_enabled, // Default to ["en"] locale if accept_language is not provided accept_language: value .accept_language .map(get_list_of_accept_languages) .or(Some(vec!["en".to_string()])), } } } #[derive(Serialize, Deserialize, Debug, Clone)] pub enum ChallengeWindowSizeEnum { #[serde(rename = "01")] Size250x400, #[serde(rename = "02")] Size390x400, #[serde(rename = "03")] Size500x600, #[serde(rename = "04")] Size600x400, #[serde(rename = "05")] FullScreen, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct Sdk { /// Universally unique ID created upon all installations and updates of the 3DS Requestor App on a Customer Device. /// This will be newly generated and stored by the 3DS SDK for each installation or update. The field is limited to 36 /// characters and it shall have a canonical format as defined in IETF RFC 4122. This may utilize any of the specified /// versions as long as the output meets specified requirements. /// /// Starting from EMV 3DS 2.3.1: /// In case of Browser-SDK, the SDK App ID value is not reliable, and may change for each transaction. #[serde(rename = "sdkAppID")] sdk_app_id: Option<String>, /// JWE Object as defined Section 6.2.2.1 containing data encrypted by the SDK for the DS to decrypt. This element is /// the only field encrypted in this version of the EMV 3-D Secure specification. The field is sent from the SDK and it /// is limited to 64.000 characters. The data will be present when sending to DS, but not present from DS to ACS. sdk_enc_data: Option<String>, /// Public key component of the ephemeral key pair generated by the 3DS SDK and used to establish session keys between /// the 3DS SDK and ACS. In AReq, this data element is contained within the ACS Signed Content JWS Object. The field is /// limited to maximum 256 characters. sdk_ephem_pub_key: Option<HashMap<String, String>>, /// Indicates the maximum amount of time (in minutes) for all exchanges. The field shall have value greater or equals /// than 05. sdk_max_timeout: Option<u8>, /// Identifies the vendor and version of the 3DS SDK that is integrated in a 3DS Requestor App, assigned by EMVCo when /// the 3DS SDK is approved. The field is limited to 32 characters. /// /// Starting from EMV 3DS 2.3.1: /// Identifies the vendor and version of the 3DS SDK that is utilised for a specific transaction. The value is /// assigned by EMVCo when the Letter of Approval of the specific 3DS SDK is issued. sdk_reference_number: Option<String>, /// Universally unique transaction identifier assigned by the 3DS SDK to identify a single transaction. The field is /// limited to 36 characters and it shall be in a canonical format as defined in IETF RFC 4122. This may utilize any of /// the specified versions as long as the output meets specific requirements. #[serde(rename = "sdkTransID")] sdk_trans_id: Option<String>, /// Contains the JWS object(represented as a string) created by the Split-SDK Server for the AReq message. A /// Split-SDK Server creates a time-stamped signature on certain transaction data that is sent to the DS for /// verification. As a prerequisite, the Split-SDK Server has a key pair PbSDK, PvSDK certificate Cert (PbSDK). This /// certificate is an X.509 certificate signed by a DS CA whose public key is known to the DS. /// /// The Split-SDK Server: /// Creates a JSON object of the following data as the JWS payload to be signed: /// /// - SDK Reference Number -> Identifies the vendor and version of the 3DS SDK that is utilised for a specific /// transaction. The value is assigned by EMVCo when the Letter of Approval of the /// specific 3DS SDK is issued. The field is limited to 32 characters. /// - SDK Signature Timestamp -> Date and time indicating when the 3DS SDK generated the Split-SDK Server Signed /// Content converted into UTC. The value is limited to 14 characters. Accepted /// format: YYYYMMDDHHMMSS. /// - SDK Transaction ID -> Universally unique transaction identifier assigned by the 3DS SDK to identify a /// single transaction. The field is limited to 36 characters and it shall be in a /// canonical format as defined in IETF RFC 4122. This may utilize any of the specified /// versions as long as the output meets specific requirements. /// - Split-SDK Server ID -> DS assigned Split-SDK Server identifier. Each DS can provide a unique ID to each /// Split-SDK Server on an individual basis. The field is limited to 32 characters. /// Any individual DS may impose specific formatting and character requirements on the /// contents of this field. /// /// Generates a digital signature of the full JSON object according to JWS (RFC 7515) using JWS Compact /// Serialization. The parameter values for this version of the specification and to be included in the JWS /// header are: /// /// - `alg`: PS2567 or ES256 /// - `x5c`: X.5C v3: Cert (PbSDK) and chaining certificates if present /// /// All other parameters: optional /// /// Includes the resulting JWS in the AReq message as SDK Server Signed Content /// /// This field is required if sdkType = 02 or 03 and deviceChannel = 01 (APP) /// Available for supporting EMV 3DS 2.3.1 and later versions. sdk_server_signed_content: Option<String>, /// Indicates the type of 3DS SDK. /// This data element provides additional information to the DS and ACS to determine the best approach for handling /// the transaction. Accepted values are: /// /// - 01 -> Default SDK /// - 02 -> Split-SDK /// - 03 -> Limited-SDK /// - 04 -> Browser-SDK /// - 05 -> Shell-SDK /// - 80-99 -> PS-specific value (dependent on the payment scheme type) /// /// This field is required for requests where deviceChannel = 01 (APP). /// Available for supporting EMV 3DS 2.3.1 and later versions. sdk_type: Option<SdkType>, /// Indicates the characteristics of a Default-SDK. /// /// This field is required for requests where deviceChannel = 01 (APP) and SDK Type = 01. /// Available for supporting EMV 3DS 2.3.1 and later versions. default_sdk_type: Option<DefaultSdkType>, /// Indicates the characteristics of a Split-SDK. /// /// This field is required for requests where deviceChannel = 01 (APP) and SDK Type = 02. /// Available for supporting EMV 3DS 2.3.1 and later versions. split_sdk_type: Option<SplitSdkType>, } impl From<api_models::payments::SdkInformation> for Sdk { fn from(sdk_info: api_models::payments::SdkInformation) -> Self { Self { sdk_app_id: Some(sdk_info.sdk_app_id), sdk_enc_data: Some(sdk_info.sdk_enc_data), sdk_ephem_pub_key: Some(sdk_info.sdk_ephem_pub_key), sdk_max_timeout: Some(sdk_info.sdk_max_timeout), sdk_reference_number: Some(sdk_info.sdk_reference_number), sdk_trans_id: Some(sdk_info.sdk_trans_id), sdk_server_signed_content: None, sdk_type: sdk_info .sdk_type .map(SdkType::from) .or(Some(SdkType::DefaultSdk)), default_sdk_type: Some(DefaultSdkType { // hardcoding this value because, it's the only value that is accepted sdk_variant: "01".to_string(), wrapped_ind: None, }), split_sdk_type: None, } } } impl From<api_models::payments::SdkType> for SdkType { fn from(sdk_type: api_models::payments::SdkType) -> Self { match sdk_type { api_models::payments::SdkType::DefaultSdk => Self::DefaultSdk, api_models::payments::SdkType::SplitSdk => Self::SplitSdk, api_models::payments::SdkType::LimitedSdk => Self::LimitedSdk, api_models::payments::SdkType::BrowserSdk => Self::BrowserSdk, api_models::payments::SdkType::ShellSdk => Self::ShellSdk, } } } /// Enum representing the type of 3DS SDK. #[derive(Serialize, Deserialize, Debug, Clone)] pub enum SdkType { #[serde(rename = "01")] DefaultSdk, #[serde(rename = "02")] SplitSdk, #[serde(rename = "03")] LimitedSdk, #[serde(rename = "04")] BrowserSdk, #[serde(rename = "05")] ShellSdk, /// - 80-99 -> PS-specific value (dependent on the payment scheme type) #[serde(untagged)] PsSpecific(String), } /// Struct representing characteristics of a Default-SDK. #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct DefaultSdkType { /// SDK Variant: SDK implementation characteristics /// - Length: 2 characters /// - Values accepted: /// - 01 = Native /// - 02–79 = Reserved for EMVCo future use (values invalid until defined by EMVCo) /// - 80–99 = Reserved for DS use sdk_variant: String, /// Wrapped Indicator: If the Default-SDK is embedded as a wrapped component in the 3DS Requestor App /// - Length: 1 character /// - Value accepted: Y = Wrapped /// - Only present if value = Y wrapped_ind: Option<String>, } /// Struct representing characteristics of a Split-SDK. #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct SplitSdkType { /// Split-SDK Variant: Implementation characteristics of the Split-SDK client /// - Length: 2 characters /// - Values accepted: /// - 01 = Native Client /// - 02 = Browser /// - 03 = Shell /// - 04–79 = Reserved for EMVCo future use (values invalid until defined by EMVCo) /// - 80–99 = Reserved for DS use sdk_variant: String, /// Limited Split-SDK Indicator: If the Split-SDK client has limited capabilities /// - Length: 1 character /// - Value accepted: /// • Y = Limited /// - Only present if value = Y limited_ind: Option<String>, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct MessageExtensionAttribute { id: String, name: String, criticality_indicator: bool, data: String, } #[derive(Serialize, Deserialize, Debug, Clone)] pub enum ThreeDSReqAuthMethod { /// No 3DS Requestor authentication occurred (i.e. cardholder "logged in" as guest) #[serde(rename = "01")] Guest, /// Login to the cardholder account at the 3DS Requestor system using 3DS Requestor's own credentials #[serde(rename = "02")] ThreeDsRequestorCredentials, /// Login to the cardholder account at the 3DS Requestor system using federated ID #[serde(rename = "03")] FederatedID, /// Login to the cardholder account at the 3DS Requestor system using issuer credentials #[serde(rename = "04")] IssuerCredentials, /// Login to the cardholder account at the 3DS Requestor system using third-party authentication #[serde(rename = "05")] ThirdPartyAuthentication, /// Login to the cardholder account at the 3DS Requestor system using FIDO Authenticator. #[serde(rename = "06")] FidoAuthenticator, /// Login to the cardholder account at the 3DS Requestor system using FIDO Authenticator(FIDO assurance data signed). #[serde(rename = "07")] FidoAssuranceData, /// SRC Assurance Data. #[serde(rename = "08")] SRCAssuranceData, /// Additionally, 80-99 can be used for PS-specific values, regardless of protocol version. #[serde(untagged)] PsSpecificValue(String), } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct DeviceRenderingOptionsSupported { pub sdk_interface: SdkInterface, /// For Native UI SDK Interface accepted values are 01-04 and for HTML UI accepted values are 01-05. pub sdk_ui_type: Vec<SdkUiType>, } #[derive(Serialize, Deserialize, Debug, Clone)] pub enum SdkInterface { #[serde(rename = "01")] Native, #[serde(rename = "02")] Html, #[serde(rename = "03")] Both, } #[derive(Serialize, Deserialize, Debug, Clone)] pub enum SdkUiType { #[serde(rename = "01")] Text, #[serde(rename = "02")] SingleSelect, #[serde(rename = "03")] MultiSelect, #[serde(rename = "04")] Oob, #[serde(rename = "05")] HtmlOther, }
19,893
1,515
hyperswitch
crates/router/src/connector/adyenplatform/transformers.rs
.rs
use common_utils::types::MinorUnit; use error_stack::Report; use masking::Secret; use serde::Serialize; #[cfg(feature = "payouts")] pub mod payouts; #[cfg(feature = "payouts")] pub use payouts::*; use crate::{core::errors, types}; // Error signature type Error = Report<errors::ConnectorError>; // Auth Struct pub struct AdyenplatformAuthType { pub(super) api_key: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for AdyenplatformAuthType { type Error = Error; fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self { api_key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Debug, Serialize)] pub struct AdyenPlatformRouterData<T> { pub amount: MinorUnit, pub router_data: T, } impl<T> TryFrom<(MinorUnit, T)> for AdyenPlatformRouterData<T> { type Error = Report<errors::ConnectorError>; fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> { Ok(Self { amount, router_data: item, }) } }
302
1,516
hyperswitch
crates/router/src/connector/adyenplatform/transformers/payouts.rs
.rs
#[cfg(feature = "payouts")] use api_models::webhooks; use common_utils::pii; use error_stack::{report, ResultExt}; use masking::Secret; use serde::{Deserialize, Serialize}; use super::{AdyenPlatformRouterData, Error}; use crate::{ connector::{ adyen::transformers as adyen, utils::{self, PayoutsData, RouterData}, }, core::errors, types::{self, api::payouts, storage::enums, transformers::ForeignFrom}, }; #[derive(Debug, Default, Serialize, Deserialize)] pub struct AdyenPlatformConnectorMetadataObject { source_balance_account: Option<Secret<String>>, } impl TryFrom<&Option<pii::SecretSerdeValue>> for AdyenPlatformConnectorMetadataObject { type Error = Error; fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> { let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone()) .change_context(errors::ConnectorError::InvalidConnectorConfig { config: "metadata", })?; Ok(metadata) } } #[serde_with::skip_serializing_none] #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct AdyenTransferRequest { amount: adyen::Amount, balance_account_id: Secret<String>, category: AdyenPayoutMethod, counterparty: AdyenPayoutMethodDetails, priority: AdyenPayoutPriority, reference: String, reference_for_beneficiary: String, description: Option<String>, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum AdyenPayoutMethod { Bank, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenPayoutMethodDetails { bank_account: AdyenBankAccountDetails, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenBankAccountDetails { account_holder: AdyenBankAccountHolder, account_identification: AdyenBankAccountIdentification, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenBankAccountHolder { address: Option<adyen::Address>, full_name: Secret<String>, #[serde(rename = "reference")] customer_id: Option<String>, #[serde(rename = "type")] entity_type: Option<EntityType>, } #[derive(Debug, Serialize, Deserialize)] pub struct AdyenBankAccountIdentification { #[serde(rename = "type")] bank_type: String, #[serde(flatten)] account_details: AdyenBankAccountIdentificationDetails, } #[derive(Debug, Serialize, Deserialize)] #[serde(untagged)] pub enum AdyenBankAccountIdentificationDetails { Sepa(SepaDetails), } #[derive(Debug, Serialize, Deserialize)] pub struct SepaDetails { iban: Secret<String>, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum AdyenPayoutPriority { Instant, Fast, Regular, Wire, CrossBorder, Internal, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum EntityType { Individual, Organization, Unknown, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenTransferResponse { id: String, account_holder: AdyenPlatformAccountHolder, amount: adyen::Amount, balance_account: AdyenBalanceAccount, category: AdyenPayoutMethod, category_data: AdyenCategoryData, direction: AdyenTransactionDirection, reference: String, reference_for_beneficiary: String, status: AdyenTransferStatus, #[serde(rename = "type")] transaction_type: AdyenTransactionType, reason: String, } #[derive(Debug, Serialize, Deserialize)] pub struct AdyenPlatformAccountHolder { description: String, id: String, } #[derive(Debug, Serialize, Deserialize)] pub struct AdyenCategoryData { priority: AdyenPayoutPriority, #[serde(rename = "type")] category: AdyenPayoutMethod, } #[derive(Debug, Serialize, Deserialize)] pub struct AdyenBalanceAccount { description: String, id: String, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum AdyenTransactionDirection { Incoming, Outgoing, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum AdyenTransferStatus { Authorised, Refused, Error, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum AdyenTransactionType { BankTransfer, InternalTransfer, Payment, Refund, } impl<F> TryFrom<&AdyenPlatformRouterData<&types::PayoutsRouterData<F>>> for AdyenTransferRequest { type Error = Error; fn try_from( item: &AdyenPlatformRouterData<&types::PayoutsRouterData<F>>, ) -> Result<Self, Self::Error> { let request = item.router_data.request.to_owned(); match item.router_data.get_payout_method_data()? { payouts::PayoutMethodData::Card(_) | payouts::PayoutMethodData::Wallet(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Adyenplatform"), ))? } payouts::PayoutMethodData::Bank(bd) => { let bank_details = match bd { payouts::BankPayout::Sepa(b) => AdyenBankAccountIdentification { bank_type: "iban".to_string(), account_details: AdyenBankAccountIdentificationDetails::Sepa(SepaDetails { iban: b.iban, }), }, payouts::BankPayout::Ach(..) => Err(errors::ConnectorError::NotSupported { message: "Bank transfer via ACH is not supported".to_string(), connector: "Adyenplatform", })?, payouts::BankPayout::Bacs(..) => Err(errors::ConnectorError::NotSupported { message: "Bank transfer via Bacs is not supported".to_string(), connector: "Adyenplatform", })?, payouts::BankPayout::Pix(..) => Err(errors::ConnectorError::NotSupported { message: "Bank transfer via Pix is not supported".to_string(), connector: "Adyenplatform", })?, }; let billing_address = item.router_data.get_optional_billing(); let address = adyen::get_address_info(billing_address).transpose()?; let account_holder = AdyenBankAccountHolder { address, full_name: item.router_data.get_billing_full_name()?, customer_id: Some( item.router_data .get_customer_id()? .get_string_repr() .to_owned(), ), entity_type: Some(EntityType::from(request.entity_type)), }; let counterparty = AdyenPayoutMethodDetails { bank_account: AdyenBankAccountDetails { account_holder, account_identification: bank_details, }, }; let adyen_connector_metadata_object = AdyenPlatformConnectorMetadataObject::try_from( &item.router_data.connector_meta_data, )?; let balance_account_id = adyen_connector_metadata_object .source_balance_account .ok_or(errors::ConnectorError::InvalidConnectorConfig { config: "metadata.source_balance_account", })?; let priority = request .priority .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "priority", })?; let payout_type = request.get_payout_type()?; Ok(Self { amount: adyen::Amount { value: item.amount, currency: request.destination_currency, }, balance_account_id, category: AdyenPayoutMethod::try_from(payout_type)?, counterparty, priority: AdyenPayoutPriority::from(priority), reference: item.router_data.connector_request_reference_id.clone(), reference_for_beneficiary: request.payout_id, description: item.router_data.description.clone(), }) } } } } impl<F> TryFrom<types::PayoutsResponseRouterData<F, AdyenTransferResponse>> for types::PayoutsRouterData<F> { type Error = Error; fn try_from( item: types::PayoutsResponseRouterData<F, AdyenTransferResponse>, ) -> Result<Self, Self::Error> { let response: AdyenTransferResponse = item.response; let status = enums::PayoutStatus::from(response.status); let error_code = match status { enums::PayoutStatus::Ineligible => Some(response.reason), _ => None, }; Ok(Self { response: Ok(types::PayoutsResponseData { status: Some(status), connector_payout_id: Some(response.id), payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code, error_message: None, }), ..item.data }) } } impl From<AdyenTransferStatus> for enums::PayoutStatus { fn from(adyen_status: AdyenTransferStatus) -> Self { match adyen_status { AdyenTransferStatus::Authorised => Self::Initiated, AdyenTransferStatus::Refused => Self::Ineligible, AdyenTransferStatus::Error => Self::Failed, } } } impl From<enums::PayoutEntityType> for EntityType { fn from(entity: enums::PayoutEntityType) -> Self { match entity { enums::PayoutEntityType::Individual | enums::PayoutEntityType::Personal | enums::PayoutEntityType::NaturalPerson => Self::Individual, enums::PayoutEntityType::Company | enums::PayoutEntityType::Business => { Self::Organization } _ => Self::Unknown, } } } impl From<enums::PayoutSendPriority> for AdyenPayoutPriority { fn from(entity: enums::PayoutSendPriority) -> Self { match entity { enums::PayoutSendPriority::Instant => Self::Instant, enums::PayoutSendPriority::Fast => Self::Fast, enums::PayoutSendPriority::Regular => Self::Regular, enums::PayoutSendPriority::Wire => Self::Wire, enums::PayoutSendPriority::CrossBorder => Self::CrossBorder, enums::PayoutSendPriority::Internal => Self::Internal, } } } impl TryFrom<enums::PayoutType> for AdyenPayoutMethod { type Error = Error; fn try_from(payout_type: enums::PayoutType) -> Result<Self, Self::Error> { match payout_type { enums::PayoutType::Bank => Ok(Self::Bank), enums::PayoutType::Card | enums::PayoutType::Wallet => { Err(report!(errors::ConnectorError::NotSupported { message: "Card or wallet payouts".to_string(), connector: "Adyenplatform", })) } } } } #[cfg(feature = "payouts")] #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenplatformIncomingWebhook { pub data: AdyenplatformIncomingWebhookData, #[serde(rename = "type")] pub webhook_type: AdyenplatformWebhookEventType, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenplatformIncomingWebhookData { pub status: AdyenplatformWebhookStatus, pub reference: String, pub tracking: Option<AdyenplatformInstantStatus>, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenplatformInstantStatus { status: Option<InstantPriorityStatus>, estimated_arrival_time: Option<String>, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum InstantPriorityStatus { Pending, Credited, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize, Deserialize)] pub enum AdyenplatformWebhookEventType { #[serde(rename = "balancePlatform.transfer.created")] PayoutCreated, #[serde(rename = "balancePlatform.transfer.updated")] PayoutUpdated, } #[cfg(feature = "payouts")] #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum AdyenplatformWebhookStatus { Authorised, Booked, Pending, Failed, Returned, Received, } #[cfg(feature = "payouts")] impl ForeignFrom<( AdyenplatformWebhookEventType, AdyenplatformWebhookStatus, Option<AdyenplatformInstantStatus>, )> for webhooks::IncomingWebhookEvent { fn foreign_from( (event_type, status, instant_status): ( AdyenplatformWebhookEventType, AdyenplatformWebhookStatus, Option<AdyenplatformInstantStatus>, ), ) -> Self { match (event_type, status, instant_status) { (AdyenplatformWebhookEventType::PayoutCreated, _, _) => Self::PayoutCreated, (AdyenplatformWebhookEventType::PayoutUpdated, _, Some(instant_status)) => { match (instant_status.status, instant_status.estimated_arrival_time) { (Some(InstantPriorityStatus::Credited), _) | (None, Some(_)) => { Self::PayoutSuccess } _ => Self::PayoutProcessing, } } (AdyenplatformWebhookEventType::PayoutUpdated, status, _) => match status { AdyenplatformWebhookStatus::Authorised | AdyenplatformWebhookStatus::Booked | AdyenplatformWebhookStatus::Received => Self::PayoutCreated, AdyenplatformWebhookStatus::Pending => Self::PayoutProcessing, AdyenplatformWebhookStatus::Failed => Self::PayoutFailure, AdyenplatformWebhookStatus::Returned => Self::PayoutReversed, }, } } } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenTransferErrorResponse { pub error_code: String, #[serde(rename = "type")] pub error_type: String, pub status: u16, pub title: String, pub detail: Option<String>, pub request_id: Option<String>, }
3,153
1,517
hyperswitch
crates/router/src/connector/plaid/transformers.rs
.rs
use common_enums::Currency; use common_utils::types::FloatMajorUnit; use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ connector::utils::is_payment_failure, core::errors, types::{self, api, domain, storage::enums}, }; pub struct PlaidRouterData<T> { pub amount: FloatMajorUnit, pub router_data: T, } impl<T> From<(FloatMajorUnit, T)> for PlaidRouterData<T> { fn from((amount, item): (FloatMajorUnit, T)) -> Self { Self { amount, router_data: item, } } } #[derive(Default, Debug, Serialize)] pub struct PlaidPaymentsRequest { amount: PlaidAmount, recipient_id: String, reference: String, #[serde(skip_serializing_if = "Option::is_none")] schedule: Option<PlaidSchedule>, #[serde(skip_serializing_if = "Option::is_none")] options: Option<PlaidOptions>, } #[derive(Default, Debug, Serialize, Deserialize)] pub struct PlaidAmount { currency: Currency, value: FloatMajorUnit, } #[derive(Default, Debug, Serialize, Deserialize)] pub struct PlaidSchedule { interval: String, interval_execution_day: String, start_date: String, end_date: Option<String>, adjusted_start_date: Option<String>, } #[derive(Default, Debug, Serialize, Deserialize)] pub struct PlaidOptions { request_refund_details: bool, iban: Option<Secret<String>>, bacs: Option<PlaidBacs>, scheme: String, } #[derive(Default, Debug, Serialize, Deserialize)] pub struct PlaidBacs { account: Secret<String>, sort_code: Secret<String>, } #[derive(Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct PlaidLinkTokenRequest { client_name: String, country_codes: Vec<String>, language: String, products: Vec<String>, user: User, payment_initiation: PlaidPaymentInitiation, redirect_uri: Option<String>, android_package_name: Option<String>, } #[derive(Default, Debug, Serialize, Deserialize)] pub struct User { pub client_user_id: String, } #[derive(Default, Debug, Serialize, Deserialize)] pub struct PlaidPaymentInitiation { payment_id: String, } impl TryFrom<&PlaidRouterData<&types::PaymentsAuthorizeRouterData>> for PlaidPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &PlaidRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { domain::PaymentMethodData::OpenBanking(ref data) => match data { domain::OpenBankingData::OpenBankingPIS { .. } => { let amount = item.amount; let currency = item.router_data.request.currency; let payment_id = item.router_data.payment_id.clone(); let id_len = payment_id.len(); let reference = if id_len > 18 { payment_id.get(id_len - 18..id_len).map(|id| id.to_string()) } else { Some(payment_id) } .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "payment_id", })?; let recipient_type = item .router_data .additional_merchant_data .as_ref() .map(|merchant_data| match merchant_data { api_models::admin::AdditionalMerchantData::OpenBankingRecipientData( data, ) => data.clone(), }) .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "additional_merchant_data", })?; let recipient_id = match recipient_type { api_models::admin::MerchantRecipientData::ConnectorRecipientId(id) => { Ok(id.peek().to_string()) } _ => Err(errors::ConnectorError::MissingRequiredField { field_name: "ConnectorRecipientId", }), }?; Ok(Self { amount: PlaidAmount { currency, value: amount, }, reference, recipient_id, schedule: None, options: None, }) } }, _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), } } } impl TryFrom<&types::PaymentsSyncRouterData> for PlaidSyncRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> { match item.request.connector_transaction_id { types::ResponseId::ConnectorTransactionId(ref id) => Ok(Self { payment_id: id.clone(), }), _ => Err((errors::ConnectorError::MissingConnectorTransactionID).into()), } } } impl TryFrom<&types::PaymentsPostProcessingRouterData> for PlaidLinkTokenRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsPostProcessingRouterData) -> Result<Self, Self::Error> { match item.request.payment_method_data { domain::PaymentMethodData::OpenBanking(ref data) => match data { domain::OpenBankingData::OpenBankingPIS { .. } => { let headers = item.header_payload.clone(); let platform = headers .as_ref() .and_then(|headers| headers.x_client_platform.clone()); let (is_android, is_ios) = match platform { Some(common_enums::ClientPlatform::Android) => (true, false), Some(common_enums::ClientPlatform::Ios) => (false, true), _ => (false, false), }; Ok(Self { client_name: "Hyperswitch".to_string(), country_codes: item .request .country .map(|code| vec![code.to_string()]) .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "billing.address.country", })?, language: "en".to_string(), products: vec!["payment_initiation".to_string()], user: User { client_user_id: item .request .customer_id .clone() .map(|id| id.get_string_repr().to_string()) .unwrap_or("default cust".to_string()), }, payment_initiation: PlaidPaymentInitiation { payment_id: item .request .connector_transaction_id .clone() .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?, }, android_package_name: if is_android { headers .as_ref() .and_then(|headers| headers.x_app_id.clone()) } else { None }, redirect_uri: if is_ios { headers .as_ref() .and_then(|headers| headers.x_redirect_uri.clone()) } else { None }, }) } }, _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), } } } pub struct PlaidAuthType { pub client_id: Secret<String>, pub secret: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for PlaidAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { client_id: api_key.to_owned(), secret: key1.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[derive(strum::Display)] pub enum PlaidPaymentStatus { PaymentStatusInputNeeded, PaymentStatusInitiated, PaymentStatusInsufficientFunds, PaymentStatusFailed, PaymentStatusBlocked, PaymentStatusCancelled, PaymentStatusExecuted, PaymentStatusSettled, PaymentStatusEstablished, PaymentStatusRejected, PaymentStatusAuthorising, } impl From<PlaidPaymentStatus> for enums::AttemptStatus { fn from(item: PlaidPaymentStatus) -> Self { match item { PlaidPaymentStatus::PaymentStatusAuthorising => Self::Authorizing, PlaidPaymentStatus::PaymentStatusBlocked | PlaidPaymentStatus::PaymentStatusInsufficientFunds | PlaidPaymentStatus::PaymentStatusRejected => Self::AuthorizationFailed, PlaidPaymentStatus::PaymentStatusCancelled => Self::Voided, PlaidPaymentStatus::PaymentStatusEstablished => Self::Authorized, PlaidPaymentStatus::PaymentStatusExecuted | PlaidPaymentStatus::PaymentStatusSettled | PlaidPaymentStatus::PaymentStatusInitiated => Self::Charged, PlaidPaymentStatus::PaymentStatusFailed => Self::Failure, PlaidPaymentStatus::PaymentStatusInputNeeded => Self::AuthenticationPending, } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PlaidPaymentsResponse { status: PlaidPaymentStatus, payment_id: String, } impl<F, T> TryFrom<types::ResponseRouterData<F, PlaidPaymentsResponse, T, types::PaymentsResponseData>> for types::RouterData<F, T, types::PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::ResponseRouterData<F, PlaidPaymentsResponse, T, types::PaymentsResponseData>, ) -> Result<Self, Self::Error> { let status = enums::AttemptStatus::from(item.response.status.clone()); Ok(Self { status, response: if is_payment_failure(status) { Err(types::ErrorResponse { // populating status everywhere as plaid only sends back a status code: item.response.status.clone().to_string(), message: item.response.status.clone().to_string(), reason: Some(item.response.status.to_string()), status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.payment_id), network_advice_code: None, network_decline_code: None, network_error_message: None, }) } else { Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId( item.response.payment_id.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.payment_id), incremental_authorization_allowed: None, charges: None, }) }, ..item.data }) } } #[derive(Default, Debug, Serialize, Deserialize)] pub struct PlaidLinkTokenResponse { link_token: String, } impl<F, T> TryFrom<types::ResponseRouterData<F, PlaidLinkTokenResponse, T, types::PaymentsResponseData>> for types::RouterData<F, T, types::PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::ResponseRouterData<F, PlaidLinkTokenResponse, T, types::PaymentsResponseData>, ) -> Result<Self, Self::Error> { let session_token = Some(api::OpenBankingSessionToken { open_banking_session_token: item.response.link_token, }); Ok(Self { status: enums::AttemptStatus::AuthenticationPending, response: Ok(types::PaymentsResponseData::PostProcessingResponse { session_token }), ..item.data }) } } #[derive(Default, Debug, Serialize, Deserialize)] pub struct PlaidSyncRequest { payment_id: String, } #[derive(Debug, Serialize, Deserialize)] pub struct PlaidSyncResponse { payment_id: String, amount: PlaidAmount, status: PlaidPaymentStatus, recipient_id: String, reference: String, last_status_update: String, adjusted_reference: Option<String>, schedule: Option<PlaidSchedule>, iban: Option<Secret<String>>, bacs: Option<PlaidBacs>, scheme: Option<String>, adjusted_scheme: Option<String>, request_id: String, } impl<F, T> TryFrom<types::ResponseRouterData<F, PlaidSyncResponse, T, types::PaymentsResponseData>> for types::RouterData<F, T, types::PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::ResponseRouterData<F, PlaidSyncResponse, T, types::PaymentsResponseData>, ) -> Result<Self, Self::Error> { let status = enums::AttemptStatus::from(item.response.status.clone()); Ok(Self { status, response: if is_payment_failure(status) { Err(types::ErrorResponse { // populating status everywhere as plaid only sends back a status code: item.response.status.clone().to_string(), message: item.response.status.clone().to_string(), reason: Some(item.response.status.to_string()), status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.payment_id), network_advice_code: None, network_decline_code: None, network_error_message: None, }) } else { Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId( item.response.payment_id.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.payment_id), incremental_authorization_allowed: None, charges: None, }) }, ..item.data }) } } #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub struct PlaidErrorResponse { pub display_message: Option<String>, pub error_code: Option<String>, pub error_message: String, pub error_type: Option<String>, }
3,099
1,518
hyperswitch
crates/router/src/connector/wellsfargopayout/transformers.rs
.rs
use common_utils::types::StringMinorUnit; use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ connector::utils::PaymentsAuthorizeRequestData, core::errors, types::{self, api, domain, storage::enums}, }; //TODO: Fill the struct with respective fields pub struct WellsfargopayoutRouterData<T> { pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. pub router_data: T, } impl<T> From<(StringMinorUnit, T)> for WellsfargopayoutRouterData<T> { fn from((amount, item): (StringMinorUnit, T)) -> Self { //Todo : use utils to convert the amount to the type of amount that a connector accepts Self { amount, router_data: item, } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Serialize, PartialEq)] pub struct WellsfargopayoutPaymentsRequest { amount: StringMinorUnit, card: WellsfargopayoutCard, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct WellsfargopayoutCard { number: cards::CardNumber, expiry_month: Secret<String>, expiry_year: Secret<String>, cvc: Secret<String>, complete: bool, } impl TryFrom<&WellsfargopayoutRouterData<&types::PaymentsAuthorizeRouterData>> for WellsfargopayoutPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &WellsfargopayoutRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { domain::PaymentMethodData::Card(req_card) => { let card = WellsfargopayoutCard { number: req_card.card_number, expiry_month: req_card.card_exp_month, expiry_year: req_card.card_exp_year, cvc: req_card.card_cvc, complete: item.router_data.request.is_auto_capture()?, }; Ok(Self { amount: item.amount.clone(), card, }) } _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), } } } //TODO: Fill the struct with respective fields // Auth Struct pub struct WellsfargopayoutAuthType { pub(super) api_key: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for WellsfargopayoutAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self { api_key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } // PaymentsResponse //TODO: Append the remaining status flags #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum WellsfargopayoutPaymentStatus { Succeeded, Failed, #[default] Processing, } impl From<WellsfargopayoutPaymentStatus> for enums::AttemptStatus { fn from(item: WellsfargopayoutPaymentStatus) -> Self { match item { WellsfargopayoutPaymentStatus::Succeeded => Self::Charged, WellsfargopayoutPaymentStatus::Failed => Self::Failure, WellsfargopayoutPaymentStatus::Processing => Self::Authorizing, } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct WellsfargopayoutPaymentsResponse { status: WellsfargopayoutPaymentStatus, id: String, } impl<F, T> TryFrom< types::ResponseRouterData< F, WellsfargopayoutPaymentsResponse, T, types::PaymentsResponseData, >, > for types::RouterData<F, T, types::PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::ResponseRouterData< F, WellsfargopayoutPaymentsResponse, T, types::PaymentsResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { status: enums::AttemptStatus::from(item.response.status), response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.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 }) } } //TODO: Fill the struct with respective fields // REFUND : // Type definition for RefundRequest #[derive(Default, Debug, Serialize)] pub struct WellsfargopayoutRefundRequest { pub amount: StringMinorUnit, } impl<F> TryFrom<&WellsfargopayoutRouterData<&types::RefundsRouterData<F>>> for WellsfargopayoutRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &WellsfargopayoutRouterData<&types::RefundsRouterData<F>>, ) -> Result<Self, Self::Error> { Ok(Self { amount: item.amount.to_owned(), }) } } // Type definition for Refund Response #[allow(dead_code)] #[derive(Debug, Serialize, Default, Deserialize, Clone)] pub enum RefundStatus { Succeeded, Failed, #[default] Processing, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Succeeded => Self::Success, RefundStatus::Failed => Self::Failure, RefundStatus::Processing => Self::Pending, //TODO: Review mapping } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse { id: String, status: RefundStatus, } impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> for types::RefundsRouterData<api::Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(types::RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> for types::RefundsRouterData<api::RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::RefundsResponseRouterData<api::RSync, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(types::RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct WellsfargopayoutErrorResponse { pub status_code: u16, pub code: String, pub message: String, pub reason: Option<String>, }
1,746
1,519
hyperswitch
crates/router/src/connector/stripe/transformers.rs
.rs
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; #[cfg(feature = "payouts")] pub mod connect; #[cfg(feature = "payouts")] 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, }; pub mod auth_headers { pub const STRIPE_API_VERSION: &str = "stripe-version"; pub const STRIPE_VERSION: &str = "2022-11-15"; } pub struct StripeAuthType { pub(super) api_key: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for StripeAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::ConnectorAuthType) -> Result<Self, Self::Error> { if let types::ConnectorAuthType::HeaderKey { api_key } = item { Ok(Self { api_key: api_key.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType.into()) } } } #[derive(Debug, Default, Eq, PartialEq, Serialize)] #[serde(rename_all = "lowercase")] pub enum StripeCaptureMethod { Manual, #[default] Automatic, } impl From<Option<enums::CaptureMethod>> for StripeCaptureMethod { fn from(item: Option<enums::CaptureMethod>) -> Self { match item { Some(p) => match p { enums::CaptureMethod::ManualMultiple => Self::Manual, enums::CaptureMethod::Manual => Self::Manual, enums::CaptureMethod::Automatic | enums::CaptureMethod::SequentialAutomatic => { Self::Automatic } enums::CaptureMethod::Scheduled => Self::Manual, }, None => Self::Automatic, } } } #[derive(Debug, Default, Eq, PartialEq, Serialize)] #[serde(rename_all = "lowercase")] pub enum Auth3ds { #[default] Automatic, Any, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] pub enum StripeCardNetwork { CartesBancaires, Mastercard, Visa, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde( rename_all = "snake_case", tag = "mandate_data[customer_acceptance][type]" )] pub enum StripeMandateType { Online { #[serde(rename = "mandate_data[customer_acceptance][online][ip_address]")] ip_address: Secret<String, pii::IpAddress>, #[serde(rename = "mandate_data[customer_acceptance][online][user_agent]")] user_agent: String, }, Offline, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripeMandateRequest { #[serde(flatten)] mandate_type: StripeMandateType, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] pub enum ExpandableObjects { LatestCharge, Customer, LatestAttempt, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripeBrowserInformation { #[serde(rename = "payment_method_data[ip]")] pub ip_address: Option<Secret<String, pii::IpAddress>>, #[serde(rename = "payment_method_data[user_agent]")] pub user_agent: Option<String>, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct PaymentIntentRequest { pub amount: MinorUnit, //amount in cents, hence passed as integer pub currency: String, pub statement_descriptor_suffix: Option<String>, pub statement_descriptor: Option<String>, #[serde(flatten)] pub meta_data: HashMap<String, String>, pub return_url: String, pub confirm: bool, pub payment_method: Option<String>, pub customer: Option<Secret<String>>, #[serde(flatten)] pub setup_mandate_details: Option<StripeMandateRequest>, pub description: Option<String>, #[serde(flatten)] pub shipping: Option<StripeShippingAddress>, #[serde(flatten)] pub billing: StripeBillingAddress, #[serde(flatten)] pub payment_data: Option<StripePaymentMethodData>, pub capture_method: StripeCaptureMethod, #[serde(flatten)] pub payment_method_options: Option<StripePaymentMethodOptions>, // For mandate txns using network_txns_id, needs to be validated pub setup_future_usage: Option<enums::FutureUsage>, pub off_session: Option<bool>, #[serde(rename = "payment_method_types[0]")] pub payment_method_types: Option<StripePaymentMethodType>, #[serde(rename = "expand[0]")] pub expand: Option<ExpandableObjects>, #[serde(flatten)] pub browser_info: Option<StripeBrowserInformation>, #[serde(flatten)] pub charges: Option<IntentCharges>, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct IntentCharges { pub application_fee_amount: MinorUnit, #[serde( rename = "transfer_data[destination]", skip_serializing_if = "Option::is_none" )] pub destination_account_id: Option<String>, } // Field rename is required only in case of serialization as it is passed in the request to the connector. // Deserialization is happening only in case of webhooks, where fields name should be used as defined in the struct. // Whenever adding new fields, Please ensure it doesn't break the webhook flow #[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] pub struct StripeMetadata { // merchant_reference_id #[serde(rename(serialize = "metadata[order_id]"))] pub order_id: Option<String>, // to check whether the order_id is refund_id or payment_id // before deployment, order id is set to payment_id in refunds but now it is set as refund_id // it is set as string instead of bool because stripe pass it as string even if we set it as bool #[serde(rename(serialize = "metadata[is_refund_id_as_reference]"))] pub is_refund_id_as_reference: Option<String>, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct SetupIntentRequest { pub confirm: bool, pub usage: Option<enums::FutureUsage>, pub customer: Option<Secret<String>>, pub off_session: Option<bool>, pub return_url: Option<String>, #[serde(flatten)] pub payment_data: StripePaymentMethodData, pub payment_method_options: Option<StripePaymentMethodOptions>, // For mandate txns using network_txns_id, needs to be validated #[serde(flatten)] pub meta_data: Option<HashMap<String, String>>, #[serde(rename = "payment_method_types[0]")] pub payment_method_types: Option<StripePaymentMethodType>, #[serde(rename = "expand[0]")] pub expand: Option<ExpandableObjects>, #[serde(flatten)] pub browser_info: Option<StripeBrowserInformation>, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripeCardData { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, #[serde(rename = "payment_method_data[card][number]")] pub payment_method_data_card_number: cards::CardNumber, #[serde(rename = "payment_method_data[card][exp_month]")] pub payment_method_data_card_exp_month: Secret<String>, #[serde(rename = "payment_method_data[card][exp_year]")] pub payment_method_data_card_exp_year: Secret<String>, #[serde(rename = "payment_method_data[card][cvc]")] pub payment_method_data_card_cvc: Option<Secret<String>>, #[serde(rename = "payment_method_options[card][request_three_d_secure]")] pub payment_method_auth_type: Option<Auth3ds>, #[serde(rename = "payment_method_options[card][network]")] pub payment_method_data_card_preferred_network: Option<StripeCardNetwork>, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripePayLaterData { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct TokenRequest { #[serde(flatten)] pub token_data: StripePaymentMethodData, } #[derive(Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct StripeTokenResponse { pub id: Secret<String>, pub object: String, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct CustomerRequest { pub description: Option<String>, pub email: Option<Email>, pub phone: Option<Secret<String>>, pub name: Option<Secret<String>>, pub source: Option<Secret<String>>, } #[derive(Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct StripeCustomerResponse { pub id: String, pub description: Option<String>, pub email: Option<Email>, pub phone: Option<Secret<String>>, pub name: Option<Secret<String>>, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct ChargesRequest { pub amount: MinorUnit, pub currency: String, pub customer: Secret<String>, pub source: Secret<String>, #[serde(flatten)] pub meta_data: Option<HashMap<String, String>>, } #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct ChargesResponse { pub id: String, pub amount: MinorUnit, pub amount_captured: MinorUnit, pub currency: String, pub status: StripePaymentStatus, pub source: StripeSourceResponse, pub failure_code: Option<String>, pub failure_message: Option<String>, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(untagged)] pub enum StripeBankName { Eps { #[serde(rename = "payment_method_data[eps][bank]")] bank_name: Option<StripeBankNames>, }, Ideal { #[serde(rename = "payment_method_data[ideal][bank]")] ideal_bank_name: Option<StripeBankNames>, }, Przelewy24 { #[serde(rename = "payment_method_data[p24][bank]")] bank_name: Option<StripeBankNames>, }, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(untagged)] pub enum BankSpecificData { Sofort { #[serde(rename = "payment_method_options[sofort][preferred_language]")] preferred_language: String, #[serde(rename = "payment_method_data[sofort][country]")] country: api_enums::CountryAlpha2, }, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(untagged)] pub enum StripeBankRedirectData { StripeGiropay(Box<StripeGiropay>), StripeIdeal(Box<StripeIdeal>), StripeSofort(Box<StripeSofort>), StripeBancontactCard(Box<StripeBancontactCard>), StripePrezelewy24(Box<StripePrezelewy24>), StripeEps(Box<StripeEps>), StripeBlik(Box<StripeBlik>), StripeOnlineBankingFpx(Box<StripeOnlineBankingFpx>), } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripeGiropay { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripeIdeal { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, #[serde(rename = "payment_method_data[ideal][bank]")] ideal_bank_name: Option<StripeBankNames>, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripeSofort { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, #[serde(rename = "payment_method_options[sofort][preferred_language]")] preferred_language: Option<String>, #[serde(rename = "payment_method_data[sofort][country]")] country: api_enums::CountryAlpha2, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripeBancontactCard { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripePrezelewy24 { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, #[serde(rename = "payment_method_data[p24][bank]")] bank_name: Option<StripeBankNames>, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripeEps { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, #[serde(rename = "payment_method_data[eps][bank]")] bank_name: Option<StripeBankNames>, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripeBlik { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, #[serde(rename = "payment_method_options[blik][code]")] pub code: Secret<String>, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripeOnlineBankingFpx { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct AchTransferData { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, #[serde(rename = "payment_method_options[customer_balance][bank_transfer][type]")] pub bank_transfer_type: StripeCreditTransferTypes, #[serde(rename = "payment_method_types[0]")] pub payment_method_type: StripePaymentMethodType, #[serde(rename = "payment_method_options[customer_balance][funding_type]")] pub balance_funding_type: BankTransferType, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct MultibancoTransferData { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripeCreditTransferTypes, #[serde(rename = "payment_method_types[0]")] pub payment_method_type: StripeCreditTransferTypes, #[serde(rename = "payment_method_data[billing_details][email]")] pub email: Email, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct BacsBankTransferData { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, #[serde(rename = "payment_method_options[customer_balance][bank_transfer][type]")] pub bank_transfer_type: BankTransferType, #[serde(rename = "payment_method_options[customer_balance][funding_type]")] pub balance_funding_type: BankTransferType, #[serde(rename = "payment_method_types[0]")] pub payment_method_type: StripePaymentMethodType, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct SepaBankTransferData { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, #[serde(rename = "payment_method_options[customer_balance][bank_transfer][type]")] pub bank_transfer_type: BankTransferType, #[serde(rename = "payment_method_options[customer_balance][funding_type]")] pub balance_funding_type: BankTransferType, #[serde(rename = "payment_method_types[0]")] pub payment_method_type: StripePaymentMethodType, #[serde( rename = "payment_method_options[customer_balance][bank_transfer][eu_bank_transfer][country]" )] pub country: api_models::enums::CountryAlpha2, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(untagged)] pub enum StripeCreditTransferSourceRequest { AchBankTansfer(AchCreditTransferSourceRequest), MultibancoBankTansfer(MultibancoCreditTransferSourceRequest), } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct AchCreditTransferSourceRequest { #[serde(rename = "type")] pub transfer_type: StripeCreditTransferTypes, #[serde(flatten)] pub payment_method_data: AchTransferData, pub currency: enums::Currency, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct MultibancoCreditTransferSourceRequest { #[serde(rename = "type")] pub transfer_type: StripeCreditTransferTypes, #[serde(flatten)] pub payment_method_data: MultibancoTransferData, pub currency: enums::Currency, pub amount: Option<MinorUnit>, #[serde(rename = "redirect[return_url]")] pub return_url: Option<String>, } // Remove untagged when Deserialize is added #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(untagged)] pub enum StripePaymentMethodData { CardToken(StripeCardToken), Card(StripeCardData), PayLater(StripePayLaterData), Wallet(StripeWallet), BankRedirect(StripeBankRedirectData), BankDebit(StripeBankDebitData), BankTransfer(StripeBankTransferData), } // Struct to call the Stripe tokens API to create a PSP token for the card details provided #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripeCardToken { #[serde(rename = "card[number]")] pub token_card_number: cards::CardNumber, #[serde(rename = "card[exp_month]")] pub token_card_exp_month: Secret<String>, #[serde(rename = "card[exp_year]")] pub token_card_exp_year: Secret<String>, #[serde(rename = "card[cvc]")] pub token_card_cvc: Secret<String>, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(tag = "payment_method_data[type]")] 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>, }, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripeBankDebitData { #[serde(flatten)] pub bank_specific_data: BankDebitData, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct BankTransferData { pub email: Email, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(untagged)] pub enum StripeBankTransferData { AchBankTransfer(Box<AchTransferData>), SepaBankTransfer(Box<SepaBankTransferData>), BacsBankTransfers(Box<BacsBankTransferData>), MultibancoBankTransfers(Box<MultibancoTransferData>), } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(untagged)] pub enum StripeWallet { ApplepayToken(StripeApplePay), GooglepayToken(GooglePayToken), ApplepayPayment(ApplepayPayment), AmazonpayPayment(AmazonpayPayment), WechatpayPayment(WechatpayPayment), AlipayPayment(AlipayPayment), Cashapp(CashappPayment), ApplePayPredecryptToken(Box<StripeApplePayPredecrypt>), } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripeApplePayPredecrypt { #[serde(rename = "card[number]")] number: Secret<String>, #[serde(rename = "card[exp_year]")] exp_year: Secret<String>, #[serde(rename = "card[exp_month]")] exp_month: Secret<String>, #[serde(rename = "card[cryptogram]")] cryptogram: Secret<String>, #[serde(rename = "card[eci]")] eci: Option<String>, #[serde(rename = "card[tokenization_method]")] tokenization_method: String, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripeApplePay { pub pk_token: Secret<String>, pub pk_token_instrument_name: String, pub pk_token_payment_network: String, pub pk_token_transaction_id: Secret<String>, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct GooglePayToken { #[serde(rename = "payment_method_data[type]")] pub payment_type: StripePaymentMethodType, #[serde(rename = "payment_method_data[card][token]")] pub token: Secret<String>, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct ApplepayPayment { #[serde(rename = "payment_method_data[card][token]")] pub token: Secret<String>, #[serde(rename = "payment_method_data[type]")] pub payment_method_types: StripePaymentMethodType, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct AmazonpayPayment { #[serde(rename = "payment_method_data[type]")] pub payment_method_types: StripePaymentMethodType, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct AlipayPayment { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct CashappPayment { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct WechatpayPayment { #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, #[serde(rename = "payment_method_options[wechat_pay][client]")] pub client: WechatClient, } #[derive(Debug, Eq, PartialEq, Serialize, Clone, Copy)] #[serde(rename_all = "snake_case")] pub enum WechatClient { Web, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct GooglepayPayment { #[serde(rename = "payment_method_data[card][token]")] pub token: Secret<String>, #[serde(rename = "payment_method_data[type]")] pub payment_method_types: StripePaymentMethodType, } // All supported payment_method_types in stripe // This enum goes in payment_method_types[] field in stripe request body // https://stripe.com/docs/api/payment_intents/create#create_payment_intent-payment_method_types #[derive(Eq, PartialEq, Serialize, Clone, Debug, Copy)] #[serde(rename_all = "snake_case")] 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, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] #[allow(dead_code)] pub enum StripeCreditTransferTypes { #[serde(rename = "us_bank_transfer")] AchCreditTransfer, Multibanco, Blik, } impl TryFrom<enums::PaymentMethodType> for StripePaymentMethodType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(value: enums::PaymentMethodType) -> Result<Self, Self::Error> { match value { enums::PaymentMethodType::Credit => Ok(Self::Card), enums::PaymentMethodType::Debit => Ok(Self::Card), #[cfg(feature = "v2")] enums::PaymentMethodType::Card => Ok(Self::Card), enums::PaymentMethodType::Klarna => Ok(Self::Klarna), enums::PaymentMethodType::Affirm => Ok(Self::Affirm), enums::PaymentMethodType::AfterpayClearpay => Ok(Self::AfterpayClearpay), enums::PaymentMethodType::Eps => Ok(Self::Eps), enums::PaymentMethodType::Giropay => Ok(Self::Giropay), enums::PaymentMethodType::Ideal => Ok(Self::Ideal), enums::PaymentMethodType::Sofort => Ok(Self::Sofort), enums::PaymentMethodType::AmazonPay => Ok(Self::AmazonPay), enums::PaymentMethodType::ApplePay => Ok(Self::Card), enums::PaymentMethodType::Ach => Ok(Self::Ach), enums::PaymentMethodType::Sepa => Ok(Self::Sepa), enums::PaymentMethodType::Becs => Ok(Self::Becs), enums::PaymentMethodType::Bacs => Ok(Self::Bacs), enums::PaymentMethodType::BancontactCard => Ok(Self::Bancontact), enums::PaymentMethodType::WeChatPay => Ok(Self::Wechatpay), enums::PaymentMethodType::Blik => Ok(Self::Blik), enums::PaymentMethodType::AliPay => Ok(Self::Alipay), enums::PaymentMethodType::Przelewy24 => Ok(Self::Przelewy24), // Stripe expects PMT as Card for Recurring Mandates Payments enums::PaymentMethodType::GooglePay => Ok(Self::Card), enums::PaymentMethodType::Boleto | enums::PaymentMethodType::CardRedirect | enums::PaymentMethodType::CryptoCurrency | enums::PaymentMethodType::Multibanco | enums::PaymentMethodType::OnlineBankingFpx | enums::PaymentMethodType::Paypal | enums::PaymentMethodType::Pix | enums::PaymentMethodType::UpiCollect | enums::PaymentMethodType::UpiIntent | enums::PaymentMethodType::Cashapp | enums::PaymentMethodType::Oxxo => Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) .into()), enums::PaymentMethodType::AliPayHk | enums::PaymentMethodType::Atome | enums::PaymentMethodType::Bizum | enums::PaymentMethodType::Alma | enums::PaymentMethodType::ClassicReward | enums::PaymentMethodType::Dana | enums::PaymentMethodType::DirectCarrierBilling | enums::PaymentMethodType::Efecty | enums::PaymentMethodType::Eft | enums::PaymentMethodType::Evoucher | enums::PaymentMethodType::GoPay | enums::PaymentMethodType::Gcash | enums::PaymentMethodType::Interac | enums::PaymentMethodType::KakaoPay | enums::PaymentMethodType::LocalBankRedirect | enums::PaymentMethodType::MbWay | enums::PaymentMethodType::MobilePay | enums::PaymentMethodType::Momo | enums::PaymentMethodType::MomoAtm | enums::PaymentMethodType::OnlineBankingThailand | enums::PaymentMethodType::OnlineBankingCzechRepublic | enums::PaymentMethodType::OnlineBankingFinland | enums::PaymentMethodType::OnlineBankingPoland | enums::PaymentMethodType::OnlineBankingSlovakia | enums::PaymentMethodType::OpenBankingUk | enums::PaymentMethodType::OpenBankingPIS | enums::PaymentMethodType::PagoEfectivo | enums::PaymentMethodType::PayBright | enums::PaymentMethodType::Pse | enums::PaymentMethodType::RedCompra | enums::PaymentMethodType::RedPagos | enums::PaymentMethodType::SamsungPay | enums::PaymentMethodType::Swish | enums::PaymentMethodType::TouchNGo | enums::PaymentMethodType::Trustly | enums::PaymentMethodType::Twint | enums::PaymentMethodType::Vipps | enums::PaymentMethodType::Venmo | enums::PaymentMethodType::Alfamart | enums::PaymentMethodType::BcaBankTransfer | enums::PaymentMethodType::BniVa | enums::PaymentMethodType::CimbVa | enums::PaymentMethodType::BriVa | enums::PaymentMethodType::DanamonVa | enums::PaymentMethodType::Indomaret | enums::PaymentMethodType::MandiriVa | enums::PaymentMethodType::PermataBankTransfer | enums::PaymentMethodType::PaySafeCard | enums::PaymentMethodType::Paze | enums::PaymentMethodType::Givex | enums::PaymentMethodType::Benefit | enums::PaymentMethodType::Knet | enums::PaymentMethodType::SevenEleven | enums::PaymentMethodType::Lawson | enums::PaymentMethodType::MiniStop | enums::PaymentMethodType::FamilyMart | enums::PaymentMethodType::Seicomart | enums::PaymentMethodType::PayEasy | enums::PaymentMethodType::LocalBankTransfer | enums::PaymentMethodType::InstantBankTransfer | enums::PaymentMethodType::SepaBankTransfer | enums::PaymentMethodType::Walley | enums::PaymentMethodType::Fps | enums::PaymentMethodType::DuitNow | enums::PaymentMethodType::PromptPay | enums::PaymentMethodType::VietQr | enums::PaymentMethodType::Mifinity => Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) .into()), } } } #[derive(Debug, Eq, PartialEq, Serialize, Clone)] #[serde(rename_all = "snake_case")] pub enum BankTransferType { GbBankTransfer, EuBankTransfer, #[serde(rename = "bank_transfer")] BankTransfers, } #[derive(Debug, Eq, PartialEq, Serialize, Clone)] #[serde(rename_all = "snake_case")] pub enum StripeBankNames { AbnAmro, ArzteUndApothekerBank, AsnBank, AustrianAnadiBankAg, BankAustria, BankhausCarlSpangler, BankhausSchelhammerUndSchatteraAg, BawagPskAg, BksBankAg, BrullKallmusBankAg, BtvVierLanderBank, Bunq, CapitalBankGraweGruppeAg, CitiHandlowy, Dolomitenbank, EasybankAg, ErsteBankUndSparkassen, Handelsbanken, HypoAlpeadriabankInternationalAg, HypoNoeLbFurNiederosterreichUWien, HypoOberosterreichSalzburgSteiermark, HypoTirolBankAg, HypoVorarlbergBankAg, HypoBankBurgenlandAktiengesellschaft, Ing, Knab, MarchfelderBank, OberbankAg, RaiffeisenBankengruppeOsterreich, SchoellerbankAg, SpardaBankWien, VolksbankGruppe, VolkskreditbankAg, VrBankBraunau, Moneyou, Rabobank, Regiobank, Revolut, SnsBank, TriodosBank, VanLanschot, PlusBank, EtransferPocztowy24, BankiSpbdzielcze, BankNowyBfgSa, GetinBank, Blik, NoblePay, #[serde(rename = "ideabank")] IdeaBank, #[serde(rename = "envelobank")] EnveloBank, NestPrzelew, MbankMtransfer, Inteligo, PbacZIpko, BnpParibas, BankPekaoSa, VolkswagenBank, AliorBank, Boz, } // This is used only for Disputes impl From<WebhookEventStatus> for api_models::webhooks::IncomingWebhookEvent { fn from(value: WebhookEventStatus) -> Self { match value { WebhookEventStatus::WarningNeedsResponse => Self::DisputeOpened, WebhookEventStatus::WarningClosed => Self::DisputeCancelled, WebhookEventStatus::WarningUnderReview => Self::DisputeChallenged, WebhookEventStatus::Won => Self::DisputeWon, WebhookEventStatus::Lost => Self::DisputeLost, WebhookEventStatus::NeedsResponse | WebhookEventStatus::UnderReview | WebhookEventStatus::ChargeRefunded | WebhookEventStatus::Succeeded | WebhookEventStatus::RequiresPaymentMethod | WebhookEventStatus::RequiresConfirmation | WebhookEventStatus::RequiresAction | WebhookEventStatus::Processing | WebhookEventStatus::RequiresCapture | WebhookEventStatus::Canceled | WebhookEventStatus::Chargeable | WebhookEventStatus::Failed | WebhookEventStatus::Unknown => Self::EventNotSupported, } } } impl TryFrom<&common_enums::enums::BankNames> for StripeBankNames { type Error = errors::ConnectorError; fn try_from(bank: &common_enums::enums::BankNames) -> Result<Self, Self::Error> { Ok(match bank { common_enums::enums::BankNames::AbnAmro => Self::AbnAmro, common_enums::enums::BankNames::ArzteUndApothekerBank => Self::ArzteUndApothekerBank, common_enums::enums::BankNames::AsnBank => Self::AsnBank, common_enums::enums::BankNames::AustrianAnadiBankAg => Self::AustrianAnadiBankAg, common_enums::enums::BankNames::BankAustria => Self::BankAustria, common_enums::enums::BankNames::BankhausCarlSpangler => Self::BankhausCarlSpangler, common_enums::enums::BankNames::BankhausSchelhammerUndSchatteraAg => { Self::BankhausSchelhammerUndSchatteraAg } common_enums::enums::BankNames::BawagPskAg => Self::BawagPskAg, common_enums::enums::BankNames::BksBankAg => Self::BksBankAg, common_enums::enums::BankNames::BrullKallmusBankAg => Self::BrullKallmusBankAg, common_enums::enums::BankNames::BtvVierLanderBank => Self::BtvVierLanderBank, common_enums::enums::BankNames::Bunq => Self::Bunq, common_enums::enums::BankNames::CapitalBankGraweGruppeAg => { Self::CapitalBankGraweGruppeAg } common_enums::enums::BankNames::Citi => Self::CitiHandlowy, common_enums::enums::BankNames::Dolomitenbank => Self::Dolomitenbank, common_enums::enums::BankNames::EasybankAg => Self::EasybankAg, common_enums::enums::BankNames::ErsteBankUndSparkassen => Self::ErsteBankUndSparkassen, common_enums::enums::BankNames::Handelsbanken => Self::Handelsbanken, common_enums::enums::BankNames::HypoAlpeadriabankInternationalAg => { Self::HypoAlpeadriabankInternationalAg } common_enums::enums::BankNames::HypoNoeLbFurNiederosterreichUWien => { Self::HypoNoeLbFurNiederosterreichUWien } common_enums::enums::BankNames::HypoOberosterreichSalzburgSteiermark => { Self::HypoOberosterreichSalzburgSteiermark } common_enums::enums::BankNames::HypoTirolBankAg => Self::HypoTirolBankAg, common_enums::enums::BankNames::HypoVorarlbergBankAg => Self::HypoVorarlbergBankAg, common_enums::enums::BankNames::HypoBankBurgenlandAktiengesellschaft => { Self::HypoBankBurgenlandAktiengesellschaft } common_enums::enums::BankNames::Ing => Self::Ing, common_enums::enums::BankNames::Knab => Self::Knab, common_enums::enums::BankNames::MarchfelderBank => Self::MarchfelderBank, common_enums::enums::BankNames::OberbankAg => Self::OberbankAg, common_enums::enums::BankNames::RaiffeisenBankengruppeOsterreich => { Self::RaiffeisenBankengruppeOsterreich } common_enums::enums::BankNames::Rabobank => Self::Rabobank, common_enums::enums::BankNames::Regiobank => Self::Regiobank, common_enums::enums::BankNames::Revolut => Self::Revolut, common_enums::enums::BankNames::SnsBank => Self::SnsBank, common_enums::enums::BankNames::TriodosBank => Self::TriodosBank, common_enums::enums::BankNames::VanLanschot => Self::VanLanschot, common_enums::enums::BankNames::Moneyou => Self::Moneyou, common_enums::enums::BankNames::SchoellerbankAg => Self::SchoellerbankAg, common_enums::enums::BankNames::SpardaBankWien => Self::SpardaBankWien, common_enums::enums::BankNames::VolksbankGruppe => Self::VolksbankGruppe, common_enums::enums::BankNames::VolkskreditbankAg => Self::VolkskreditbankAg, common_enums::enums::BankNames::VrBankBraunau => Self::VrBankBraunau, common_enums::enums::BankNames::PlusBank => Self::PlusBank, common_enums::enums::BankNames::EtransferPocztowy24 => Self::EtransferPocztowy24, common_enums::enums::BankNames::BankiSpbdzielcze => Self::BankiSpbdzielcze, common_enums::enums::BankNames::BankNowyBfgSa => Self::BankNowyBfgSa, common_enums::enums::BankNames::GetinBank => Self::GetinBank, common_enums::enums::BankNames::Blik => Self::Blik, common_enums::enums::BankNames::NoblePay => Self::NoblePay, common_enums::enums::BankNames::IdeaBank => Self::IdeaBank, common_enums::enums::BankNames::EnveloBank => Self::EnveloBank, common_enums::enums::BankNames::NestPrzelew => Self::NestPrzelew, common_enums::enums::BankNames::MbankMtransfer => Self::MbankMtransfer, common_enums::enums::BankNames::Inteligo => Self::Inteligo, common_enums::enums::BankNames::PbacZIpko => Self::PbacZIpko, common_enums::enums::BankNames::BnpParibas => Self::BnpParibas, common_enums::enums::BankNames::BankPekaoSa => Self::BankPekaoSa, common_enums::enums::BankNames::VolkswagenBank => Self::VolkswagenBank, common_enums::enums::BankNames::AliorBank => Self::AliorBank, common_enums::enums::BankNames::Boz => Self::Boz, _ => Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ))?, }) } } fn validate_shipping_address_against_payment_method( shipping_address: &Option<StripeShippingAddress>, payment_method: Option<&StripePaymentMethodType>, ) -> Result<(), error_stack::Report<errors::ConnectorError>> { match payment_method { Some(StripePaymentMethodType::AfterpayClearpay) => match shipping_address { Some(address) => { let missing_fields = collect_missing_value_keys!( ("shipping.address.line1", address.line1), ("shipping.address.country", address.country), ("shipping.address.zip", address.zip) ); if !missing_fields.is_empty() { return Err(errors::ConnectorError::MissingRequiredFields { field_names: missing_fields, } .into()); } Ok(()) } None => Err(errors::ConnectorError::MissingRequiredField { field_name: "shipping.address", } .into()), }, _ => Ok(()), } } impl TryFrom<&domain::payments::PayLaterData> for StripePaymentMethodType { type Error = errors::ConnectorError; fn try_from(pay_later_data: &domain::payments::PayLaterData) -> Result<Self, Self::Error> { match pay_later_data { domain::payments::PayLaterData::KlarnaRedirect { .. } => Ok(Self::Klarna), domain::payments::PayLaterData::AffirmRedirect {} => Ok(Self::Affirm), domain::payments::PayLaterData::AfterpayClearpayRedirect { .. } => { Ok(Self::AfterpayClearpay) } domain::PayLaterData::KlarnaSdk { .. } | domain::PayLaterData::PayBrightRedirect {} | domain::PayLaterData::WalleyRedirect {} | domain::PayLaterData::AlmaRedirect {} | domain::PayLaterData::AtomeRedirect {} => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), )) } } } } impl TryFrom<&domain::BankRedirectData> for StripePaymentMethodType { type Error = errors::ConnectorError; fn try_from(bank_redirect_data: &domain::BankRedirectData) -> Result<Self, Self::Error> { match bank_redirect_data { domain::BankRedirectData::Giropay { .. } => Ok(Self::Giropay), domain::BankRedirectData::Ideal { .. } => Ok(Self::Ideal), domain::BankRedirectData::Sofort { .. } => Ok(Self::Sofort), domain::BankRedirectData::BancontactCard { .. } => Ok(Self::Bancontact), domain::BankRedirectData::Przelewy24 { .. } => Ok(Self::Przelewy24), domain::BankRedirectData::Eps { .. } => Ok(Self::Eps), domain::BankRedirectData::Blik { .. } => Ok(Self::Blik), domain::BankRedirectData::OnlineBankingFpx { .. } => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), )) } domain::BankRedirectData::Bizum {} | domain::BankRedirectData::Interac { .. } | domain::BankRedirectData::Eft { .. } | domain::BankRedirectData::OnlineBankingCzechRepublic { .. } | domain::BankRedirectData::OnlineBankingFinland { .. } | domain::BankRedirectData::OnlineBankingPoland { .. } | domain::BankRedirectData::OnlineBankingSlovakia { .. } | domain::BankRedirectData::OnlineBankingThailand { .. } | domain::BankRedirectData::OpenBankingUk { .. } | domain::BankRedirectData::Trustly { .. } | domain::BankRedirectData::LocalBankRedirect {} => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), )) } } } } impl ForeignTryFrom<&domain::WalletData> for Option<StripePaymentMethodType> { type Error = errors::ConnectorError; 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"), )), } } } impl From<&domain::BankDebitData> for StripePaymentMethodType { 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, } } } 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) } } } 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()) } } } 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, } } impl TryFrom<(&domain::Card, Auth3ds)> for StripePaymentMethodData { type Error = errors::ConnectorError; fn try_from( (card, payment_method_auth_type): (&domain::Card, Auth3ds), ) -> Result<Self, Self::Error> { Ok(Self::Card(StripeCardData { payment_method_data_type: StripePaymentMethodType::Card, payment_method_data_card_number: card.card_number.clone(), payment_method_data_card_exp_month: card.card_exp_month.clone(), payment_method_data_card_exp_year: card.card_exp_year.clone(), payment_method_data_card_cvc: Some(card.card_cvc.clone()), payment_method_auth_type: Some(payment_method_auth_type), payment_method_data_card_preferred_network: card .card_network .clone() .and_then(get_stripe_card_network), })) } } impl TryFrom<(&domain::WalletData, Option<types::PaymentMethodToken>)> for StripePaymentMethodData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (wallet_data, payment_method_token): ( &domain::WalletData, Option<types::PaymentMethodToken>, ), ) -> Result<Self, Self::Error> { match wallet_data { domain::WalletData::ApplePay(applepay_data) => { let mut apple_pay_decrypt_data = if let Some(types::PaymentMethodToken::ApplePayDecrypt(decrypt_data)) = payment_method_token { let expiry_year_4_digit = decrypt_data.get_four_digit_expiry_year()?; let exp_month = decrypt_data.get_expiry_month()?; Some(Self::Wallet(StripeWallet::ApplePayPredecryptToken( Box::new(StripeApplePayPredecrypt { number: decrypt_data.clone().application_primary_account_number, exp_year: expiry_year_4_digit, exp_month, eci: decrypt_data.payment_data.eci_indicator, cryptogram: decrypt_data.payment_data.online_payment_cryptogram, tokenization_method: "apple_pay".to_string(), }), ))) } else { None }; if apple_pay_decrypt_data.is_none() { apple_pay_decrypt_data = Some(Self::Wallet(StripeWallet::ApplepayToken(StripeApplePay { pk_token: applepay_data.get_applepay_decoded_payment_data()?, pk_token_instrument_name: applepay_data .payment_method .pm_type .to_owned(), pk_token_payment_network: applepay_data .payment_method .network .to_owned(), pk_token_transaction_id: Secret::new( applepay_data.transaction_identifier.to_owned(), ), }))); }; let pmd = apple_pay_decrypt_data .ok_or(errors::ConnectorError::MissingApplePayTokenData)?; Ok(pmd) } domain::WalletData::WeChatPayQr(_) => Ok(Self::Wallet(StripeWallet::WechatpayPayment( WechatpayPayment { client: WechatClient::Web, payment_method_data_type: StripePaymentMethodType::Wechatpay, }, ))), domain::WalletData::AliPayRedirect(_) => { Ok(Self::Wallet(StripeWallet::AlipayPayment(AlipayPayment { payment_method_data_type: StripePaymentMethodType::Alipay, }))) } domain::WalletData::CashappQr(_) => { Ok(Self::Wallet(StripeWallet::Cashapp(CashappPayment { payment_method_data_type: StripePaymentMethodType::Cashapp, }))) } domain::WalletData::AmazonPayRedirect(_) => Ok(Self::Wallet( StripeWallet::AmazonpayPayment(AmazonpayPayment { payment_method_types: StripePaymentMethodType::AmazonPay, }), )), domain::WalletData::GooglePay(gpay_data) => Ok(Self::try_from(gpay_data)?), domain::WalletData::PaypalRedirect(_) | domain::WalletData::MobilePayRedirect(_) => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) .into()) } 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"), ) .into()), } } } impl TryFrom<(&domain::BankRedirectData, Option<StripeBillingAddress>)> for StripePaymentMethodData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (bank_redirect_data, billing_address): ( &domain::BankRedirectData, Option<StripeBillingAddress>, ), ) -> Result<Self, Self::Error> { let payment_method_data_type = StripePaymentMethodType::try_from(bank_redirect_data)?; match bank_redirect_data { domain::BankRedirectData::BancontactCard { .. } => Ok(Self::BankRedirect( StripeBankRedirectData::StripeBancontactCard(Box::new(StripeBancontactCard { payment_method_data_type, })), )), domain::BankRedirectData::Blik { blik_code } => Ok(Self::BankRedirect( StripeBankRedirectData::StripeBlik(Box::new(StripeBlik { payment_method_data_type, code: Secret::new(blik_code.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "blik_code", }, )?), })), )), domain::BankRedirectData::Eps { bank_name, .. } => Ok(Self::BankRedirect( StripeBankRedirectData::StripeEps(Box::new(StripeEps { payment_method_data_type, bank_name: bank_name .map(|bank_name| StripeBankNames::try_from(&bank_name)) .transpose()?, })), )), domain::BankRedirectData::Giropay { .. } => Ok(Self::BankRedirect( StripeBankRedirectData::StripeGiropay(Box::new(StripeGiropay { payment_method_data_type, })), )), domain::BankRedirectData::Ideal { bank_name, .. } => { let bank_name = bank_name .map(|bank_name| StripeBankNames::try_from(&bank_name)) .transpose()?; Ok(Self::BankRedirect(StripeBankRedirectData::StripeIdeal( Box::new(StripeIdeal { payment_method_data_type, ideal_bank_name: bank_name, }), ))) } domain::BankRedirectData::Przelewy24 { bank_name, .. } => { let bank_name = bank_name .map(|bank_name| StripeBankNames::try_from(&bank_name)) .transpose()?; Ok(Self::BankRedirect( StripeBankRedirectData::StripePrezelewy24(Box::new(StripePrezelewy24 { payment_method_data_type, bank_name, })), )) } domain::BankRedirectData::Sofort { preferred_language, .. } => Ok(Self::BankRedirect(StripeBankRedirectData::StripeSofort( Box::new(StripeSofort { payment_method_data_type, country: billing_address .and_then(|billing_data| billing_data.country) .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "billing_address.country", })?, preferred_language: preferred_language.clone(), }), ))), domain::BankRedirectData::OnlineBankingFpx { .. } => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) .into()) } domain::BankRedirectData::Bizum {} | domain::BankRedirectData::Eft { .. } | domain::BankRedirectData::Interac { .. } | domain::BankRedirectData::OnlineBankingCzechRepublic { .. } | domain::BankRedirectData::OnlineBankingFinland { .. } | domain::BankRedirectData::OnlineBankingPoland { .. } | domain::BankRedirectData::OnlineBankingSlovakia { .. } | domain::BankRedirectData::OnlineBankingThailand { .. } | domain::BankRedirectData::OpenBankingUk { .. } | domain::BankRedirectData::Trustly { .. } | domain::BankRedirectData::LocalBankRedirect {} => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) .into()) } } } } impl TryFrom<&domain::GooglePayWalletData> for StripePaymentMethodData { type Error = error_stack::Report<errors::ConnectorError>; 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, }))) } } impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntentRequest { type Error = error_stack::Report<errors::ConnectorError>; 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, }) } } 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)), } } } impl From<types::BrowserInformation> for StripeBrowserInformation { fn from(item: types::BrowserInformation) -> Self { Self { ip_address: item.ip_address.map(|ip| Secret::new(ip.to_string())), user_agent: item.user_agent, } } } impl TryFrom<&types::SetupMandateRouterData> for SetupIntentRequest { type Error = error_stack::Report<errors::ConnectorError>; 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, }) } } impl TryFrom<&types::TokenizationRouterData> for TokenRequest { type Error = error_stack::Report<errors::ConnectorError>; 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, }) } } impl TryFrom<&types::ConnectorCustomerRouterData> for CustomerRequest { type Error = error_stack::Report<errors::ConnectorError>; 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), }) } } #[derive(Clone, Default, Debug, Eq, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] pub enum StripePaymentStatus { Succeeded, Failed, #[default] Processing, #[serde(rename = "requires_action")] RequiresCustomerAction, #[serde(rename = "requires_payment_method")] RequiresPaymentMethod, RequiresConfirmation, Canceled, RequiresCapture, Chargeable, Consumed, Pending, } impl From<StripePaymentStatus> for enums::AttemptStatus { fn from(item: StripePaymentStatus) -> Self { match item { StripePaymentStatus::Succeeded => Self::Charged, StripePaymentStatus::Failed => Self::Failure, StripePaymentStatus::Processing => Self::Authorizing, StripePaymentStatus::RequiresCustomerAction => Self::AuthenticationPending, // Make the payment attempt status as failed StripePaymentStatus::RequiresPaymentMethod => Self::Failure, StripePaymentStatus::RequiresConfirmation => Self::ConfirmationAwaited, StripePaymentStatus::Canceled => Self::Voided, StripePaymentStatus::RequiresCapture => Self::Authorized, StripePaymentStatus::Chargeable => Self::Authorizing, StripePaymentStatus::Consumed => Self::Authorizing, StripePaymentStatus::Pending => Self::Pending, } } } #[derive(Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct PaymentIntentResponse { pub id: String, pub object: String, pub amount: MinorUnit, pub amount_received: Option<MinorUnit>, pub amount_capturable: Option<MinorUnit>, pub currency: String, pub status: StripePaymentStatus, pub client_secret: Option<Secret<String>>, pub created: i32, pub customer: Option<Secret<String>>, pub payment_method: Option<Secret<String>>, pub description: Option<String>, pub statement_descriptor: Option<String>, pub statement_descriptor_suffix: Option<String>, pub metadata: StripeMetadata, pub next_action: Option<StripeNextActionResponse>, pub payment_method_options: Option<StripePaymentMethodOptions>, pub last_payment_error: Option<ErrorDetails>, pub latest_attempt: Option<LatestAttempt>, //need a merchant to test this pub latest_charge: Option<StripeChargeEnum>, } #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct StripeSourceResponse { pub id: String, #[serde(skip_serializing_if = "Option::is_none")] pub ach_credit_transfer: Option<AchCreditTransferResponse>, #[serde(skip_serializing_if = "Option::is_none")] pub multibanco: Option<MultibancoCreditTansferResponse>, pub receiver: AchReceiverDetails, pub status: StripePaymentStatus, } #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct AchCreditTransferResponse { pub account_number: Secret<String>, pub bank_name: Secret<String>, pub routing_number: Secret<String>, pub swift_code: Secret<String>, } #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct MultibancoCreditTansferResponse { pub reference: Secret<String>, pub entity: Secret<String>, } #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct AchReceiverDetails { pub amount_received: MinorUnit, pub amount_charged: MinorUnit, } #[serde_with::skip_serializing_none] #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct SepaAndBacsBankTransferInstructions { pub bacs_bank_instructions: Option<BacsFinancialDetails>, pub sepa_bank_instructions: Option<SepaFinancialDetails>, pub receiver: SepaAndBacsReceiver, } #[serde_with::skip_serializing_none] #[derive(Clone, Debug, Serialize)] pub struct QrCodeNextInstructions { pub image_data_url: Url, pub display_to_timestamp: Option<i64>, } #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct SepaAndBacsReceiver { pub amount_received: MinorUnit, pub amount_remaining: MinorUnit, } #[derive(Debug, Default, Eq, PartialEq, Deserialize)] pub struct PaymentSyncResponse { #[serde(flatten)] pub intent_fields: PaymentIntentResponse, pub last_payment_error: Option<ErrorDetails>, } impl Deref for PaymentSyncResponse { type Target = PaymentIntentResponse; fn deref(&self) -> &Self::Target { &self.intent_fields } } #[derive(Deserialize, Debug, Serialize)] pub struct PaymentIntentSyncResponse { #[serde(flatten)] payment_intent_fields: PaymentIntentResponse, pub latest_charge: Option<StripeChargeEnum>, } #[derive(Debug, Eq, PartialEq, Deserialize, Clone, Serialize)] #[serde(untagged)] pub enum StripeChargeEnum { ChargeId(String), ChargeObject(StripeCharge), } #[derive(Deserialize, Clone, Debug, PartialEq, Eq, Serialize)] pub struct StripeCharge { pub id: String, pub payment_method_details: Option<StripePaymentMethodDetailsResponse>, } #[derive(Deserialize, Clone, Debug, PartialEq, Eq, Serialize)] pub struct StripeBankRedirectDetails { #[serde(rename = "generated_sepa_debit")] attached_payment_method: Option<Secret<String>>, } #[derive(Deserialize, Clone, Debug, PartialEq, Eq, Serialize)] pub struct StripeCashappDetails { buyer_id: Option<String>, cashtag: Option<String>, } impl Deref for PaymentIntentSyncResponse { type Target = PaymentIntentResponse; fn deref(&self) -> &Self::Target { &self.payment_intent_fields } } #[derive(Deserialize, Clone, Debug, PartialEq, Eq, Serialize)] pub struct StripeAdditionalCardDetails { checks: Option<Value>, three_d_secure: Option<Value>, network_transaction_id: Option<String>, } #[derive(Deserialize, Clone, Debug, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case", tag = "type")] pub enum StripePaymentMethodDetailsResponse { //only ideal, sofort and bancontact is supported by stripe for recurring payment in bank redirect Ideal { ideal: StripeBankRedirectDetails, }, Sofort { sofort: StripeBankRedirectDetails, }, Bancontact { bancontact: StripeBankRedirectDetails, }, //other payment method types supported by stripe. To avoid deserialization error. Blik, Eps, Fpx, Giropay, #[serde(rename = "p24")] Przelewy24, Card { card: StripeAdditionalCardDetails, }, Cashapp { cashapp: StripeCashappDetails, }, Klarna, Affirm, AfterpayClearpay, AmazonPay, ApplePay, #[serde(rename = "us_bank_account")] Ach, #[serde(rename = "sepa_debit")] Sepa, #[serde(rename = "au_becs_debit")] Becs, #[serde(rename = "bacs_debit")] Bacs, #[serde(rename = "wechat_pay")] Wechatpay, Alipay, CustomerBalance, } pub struct AdditionalPaymentMethodDetails { pub payment_checks: Option<Value>, pub authentication_details: Option<Value>, } impl From<AdditionalPaymentMethodDetails> for types::AdditionalPaymentMethodConnectorResponse { fn from(item: AdditionalPaymentMethodDetails) -> Self { Self::Card { authentication_data: item.authentication_details, payment_checks: item.payment_checks, card_network: None, domestic_network: None, } } } impl StripePaymentMethodDetailsResponse { pub fn get_additional_payment_method_data(&self) -> Option<AdditionalPaymentMethodDetails> { match self { Self::Card { card } => Some(AdditionalPaymentMethodDetails { payment_checks: card.checks.clone(), authentication_details: card.three_d_secure.clone(), }), Self::Ideal { .. } | Self::Sofort { .. } | Self::Bancontact { .. } | Self::Blik | Self::Eps | Self::Fpx | Self::Giropay | Self::Przelewy24 | Self::Klarna | Self::Affirm | Self::AfterpayClearpay | Self::AmazonPay | Self::ApplePay | Self::Ach | Self::Sepa | Self::Becs | Self::Bacs | Self::Wechatpay | Self::Alipay | Self::CustomerBalance | Self::Cashapp { .. } => None, } } } #[derive(Deserialize)] pub struct SetupIntentSyncResponse { #[serde(flatten)] setup_intent_fields: SetupIntentResponse, } impl Deref for SetupIntentSyncResponse { type Target = SetupIntentResponse; fn deref(&self) -> &Self::Target { &self.setup_intent_fields } } impl From<SetupIntentSyncResponse> for PaymentIntentSyncResponse { fn from(value: SetupIntentSyncResponse) -> Self { Self { payment_intent_fields: value.setup_intent_fields.into(), latest_charge: None, } } } impl From<SetupIntentResponse> for PaymentIntentResponse { fn from(value: SetupIntentResponse) -> Self { Self { id: value.id, object: value.object, status: value.status, client_secret: Some(value.client_secret), customer: value.customer, description: None, statement_descriptor: value.statement_descriptor, statement_descriptor_suffix: value.statement_descriptor_suffix, metadata: value.metadata, next_action: value.next_action, payment_method_options: value.payment_method_options, last_payment_error: value.last_setup_error, ..Default::default() } } } #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct SetupIntentResponse { pub id: String, pub object: String, pub status: StripePaymentStatus, // Change to SetupStatus pub client_secret: Secret<String>, pub customer: Option<Secret<String>>, pub payment_method: Option<String>, pub statement_descriptor: Option<String>, pub statement_descriptor_suffix: Option<String>, pub metadata: StripeMetadata, pub next_action: Option<StripeNextActionResponse>, pub payment_method_options: Option<StripePaymentMethodOptions>, pub latest_attempt: Option<LatestAttempt>, pub last_setup_error: Option<ErrorDetails>, } fn extract_payment_method_connector_response_from_latest_charge( stripe_charge_enum: &StripeChargeEnum, ) -> Option<types::ConnectorResponseData> { if let StripeChargeEnum::ChargeObject(charge_object) = stripe_charge_enum { charge_object .payment_method_details .as_ref() .and_then(StripePaymentMethodDetailsResponse::get_additional_payment_method_data) } else { None } .map(types::AdditionalPaymentMethodConnectorResponse::from) .map(types::ConnectorResponseData::with_additional_payment_method_data) } fn extract_payment_method_connector_response_from_latest_attempt( stripe_latest_attempt: &LatestAttempt, ) -> Option<types::ConnectorResponseData> { if let LatestAttempt::PaymentIntentAttempt(intent_attempt) = stripe_latest_attempt { intent_attempt .payment_method_details .as_ref() .and_then(StripePaymentMethodDetailsResponse::get_additional_payment_method_data) } else { None } .map(types::AdditionalPaymentMethodConnectorResponse::from) .map(types::ConnectorResponseData::with_additional_payment_method_data) } impl<F, T> TryFrom<types::ResponseRouterData<F, PaymentIntentResponse, T, types::PaymentsResponseData>> for types::RouterData<F, T, types::PaymentsResponseData> where T: connector_util::SplitPaymentData, { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::ResponseRouterData<F, PaymentIntentResponse, 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().expose()); let payment_method_id = Some(payment_method_id.expose()); types::MandateReference { connector_mandate_id, payment_method_id, mandate_metadata: None, connector_mandate_request_reference_id: None, } }); //Note: we might have to call retrieve_setup_intent to get the network_transaction_id in case its not sent in PaymentIntentResponse // Or we identify the mandate txns before hand and always call SetupIntent in case of mandate payment call let network_txn_id = match item.response.latest_charge.as_ref() { Some(StripeChargeEnum::ChargeObject(charge_object)) => charge_object .payment_method_details .as_ref() .and_then(|payment_method_details| match payment_method_details { StripePaymentMethodDetailsResponse::Card { card } => { card.network_transaction_id.clone() } _ => None, }), _ => None, }; let connector_metadata = get_connector_metadata(item.response.next_action.as_ref(), item.response.amount)?; let status = enums::AttemptStatus::from(item.response.status); let response = if connector_util::is_payment_failure(status) { types::PaymentsResponseData::foreign_try_from(( &item.response.last_payment_error, item.http_code, item.response.id.clone(), )) } else { 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, connector_response_reference_id: Some(item.response.id), incremental_authorization_allowed: None, charges, }) }; let connector_response_data = item .response .latest_charge .as_ref() .and_then(extract_payment_method_connector_response_from_latest_charge); Ok(Self { status, // client_secret: Some(item.response.client_secret.clone().as_str()), // description: item.response.description.map(|x| x.as_str()), // statement_descriptor_suffix: item.response.statement_descriptor_suffix.map(|x| x.as_str()), // three_ds_form, 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 }) } } 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) } impl<F, T> TryFrom<types::ResponseRouterData<F, PaymentIntentSyncResponse, T, types::PaymentsResponseData>> for types::RouterData<F, T, types::PaymentsResponseData> where T: connector_util::SplitPaymentData, { type Error = error_stack::Report<errors::ConnectorError>; 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 }) } } impl<F, T> TryFrom<types::ResponseRouterData<F, SetupIntentResponse, T, types::PaymentsResponseData>> for types::RouterData<F, T, types::PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; 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 }) } } impl ForeignFrom<Option<LatestAttempt>> for Option<String> { 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, } } } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "snake_case", remote = "Self")] pub enum StripeNextActionResponse { CashappHandleRedirectOrDisplayQrCode(StripeCashappQrResponse), RedirectToUrl(StripeRedirectToUrlResponse), AlipayHandleRedirect(StripeRedirectToUrlResponse), VerifyWithMicrodeposits(StripeVerifyWithMicroDepositsResponse), WechatPayDisplayQrCode(WechatPayRedirectToQr), DisplayBankTransferInstructions(StripeBankTransferDetails), MultibancoDisplayDetails(MultibancoCreditTansferResponse), NoNextActionBody, } impl StripeNextActionResponse { 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, } } } // This impl is required because Stripe's response is of the below format, which is externally // tagged, but also with an extra 'type' field specifying the enum variant name: // "next_action": { // "redirect_to_url": { "return_url": "...", "url": "..." }, // "type": "redirect_to_url" // }, // Reference: https://github.com/serde-rs/serde/issues/1343#issuecomment-409698470 impl<'de> Deserialize<'de> for StripeNextActionResponse { 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) } } impl Serialize for StripeNextActionResponse { 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), } } } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct StripeRedirectToUrlResponse { return_url: String, url: Url, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct WechatPayRedirectToQr { // This data contains url, it should be converted to QR code. // Note: The url in this data is not redirection url data: Url, // This is the image source, this image_data_url can directly be used by sdk to show the QR code image_data_url: Url, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct StripeVerifyWithMicroDepositsResponse { hosted_verification_url: Url, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] #[serde(untagged)] pub enum FinancialInformation { AchFinancialInformation(Vec<AchFinancialInformation>), StripeFinancialInformation(Vec<StripeFinancialInformation>), } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct StripeBankTransferDetails { pub amount_remaining: MinorUnit, pub currency: String, pub financial_addresses: FinancialInformation, pub hosted_instructions_url: Option<String>, pub reference: Option<String>, #[serde(rename = "type")] pub bank_transfer_type: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct StripeCashappQrResponse { pub mobile_auth_url: Url, pub qr_code: QrCodeResponse, pub hosted_instructions_url: Url, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct QrCodeResponse { pub expires_at: Option<i64>, pub image_url_png: Url, pub image_url_svg: Url, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct AbaDetails { pub account_number: Secret<String>, pub bank_name: Secret<String>, pub routing_number: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct SwiftDetails { pub account_number: Secret<String>, pub bank_name: Secret<String>, pub swift_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "lowercase")] pub enum AchFinancialDetails { Aba(AbaDetails), Swift(SwiftDetails), } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct StripeFinancialInformation { pub iban: Option<SepaFinancialDetails>, pub sort_code: Option<BacsFinancialDetails>, pub supported_networks: Vec<String>, #[serde(rename = "type")] pub financial_info_type: String, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct AchFinancialInformation { #[serde(flatten)] pub financial_details: AchFinancialDetails, pub supported_networks: Vec<String>, #[serde(rename = "type")] pub financial_info_type: String, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct SepaFinancialDetails { pub account_holder_name: Secret<String>, pub bic: Secret<String>, pub country: Secret<String>, pub iban: Secret<String>, pub reference: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct BacsFinancialDetails { pub account_holder_name: Secret<String>, pub account_number: Secret<String>, pub sort_code: Secret<String>, } // REFUND : // Type definition for Stripe RefundRequest #[derive(Debug, Serialize)] pub struct RefundRequest { pub amount: Option<MinorUnit>, //amount in cents, hence passed as integer pub payment_intent: String, #[serde(flatten)] pub meta_data: StripeMetadata, } impl<F> TryFrom<(&types::RefundsRouterData<F>, MinorUnit)> for RefundRequest { type Error = error_stack::Report<errors::ConnectorError>; 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()), }, }) } } #[derive(Debug, Serialize)] pub struct ChargeRefundRequest { pub charge: String, pub refund_application_fee: Option<bool>, pub reverse_transfer: Option<bool>, pub amount: Option<MinorUnit>, //amount in cents, hence passed as integer #[serde(flatten)] pub meta_data: StripeMetadata, } impl<F> TryFrom<&types::RefundsRouterData<F>> for ChargeRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; 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", })?, }, } } } // Type definition for Stripe Refund Response #[derive(Default, Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "snake_case")] pub enum RefundStatus { Succeeded, Failed, #[default] Pending, RequiresAction, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Succeeded => Self::Success, RefundStatus::Failed => Self::Failure, RefundStatus::Pending => Self::Pending, RefundStatus::RequiresAction => Self::ManualReview, } } } #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse { pub id: String, pub object: String, pub amount: MinorUnit, pub currency: String, pub metadata: StripeMetadata, pub payment_intent: String, pub status: RefundStatus, pub failure_reason: Option<String>, } impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> for types::RefundsRouterData<api::Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, ) -> Result<Self, Self::Error> { let refund_status = enums::RefundStatus::from(item.response.status); let response = if connector_util::is_refund_failure(refund_status) { Err(types::ErrorResponse { code: consts::NO_ERROR_CODE.to_string(), message: item .response .failure_reason .clone() .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), reason: item.response.failure_reason, status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.id), network_advice_code: None, network_decline_code: None, network_error_message: None, }) } else { Ok(types::RefundsResponseData { connector_refund_id: item.response.id, refund_status, }) }; Ok(Self { response, ..item.data }) } } impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> for types::RefundsRouterData<api::RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::RefundsResponseRouterData<api::RSync, RefundResponse>, ) -> Result<Self, Self::Error> { let refund_status = enums::RefundStatus::from(item.response.status); let response = if connector_util::is_refund_failure(refund_status) { Err(types::ErrorResponse { code: consts::NO_ERROR_CODE.to_string(), message: item .response .failure_reason .clone() .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), reason: item.response.failure_reason, status_code: item.http_code, attempt_status: None, connector_transaction_id: Some(item.response.id), network_advice_code: None, network_decline_code: None, network_error_message: None, }) } else { Ok(types::RefundsResponseData { connector_refund_id: item.response.id, refund_status, }) }; Ok(Self { response, ..item.data }) } } #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct ErrorDetails { pub code: Option<String>, #[serde(rename = "type")] pub error_type: Option<String>, pub message: Option<String>, pub param: Option<String>, pub decline_code: Option<String>, pub payment_intent: Option<PaymentIntentErrorResponse>, } #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct PaymentIntentErrorResponse { pub id: String, } #[derive(Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct ErrorResponse { pub error: ErrorDetails, } #[derive(Debug, Default, Eq, PartialEq, Serialize)] pub struct StripeShippingAddress { #[serde(rename = "shipping[address][city]")] pub city: Option<String>, #[serde(rename = "shipping[address][country]")] pub country: Option<api_enums::CountryAlpha2>, #[serde(rename = "shipping[address][line1]")] pub line1: Option<Secret<String>>, #[serde(rename = "shipping[address][line2]")] pub line2: Option<Secret<String>>, #[serde(rename = "shipping[address][postal_code]")] pub zip: Option<Secret<String>>, #[serde(rename = "shipping[address][state]")] pub state: Option<Secret<String>>, #[serde(rename = "shipping[name]")] pub name: Secret<String>, #[serde(rename = "shipping[phone]")] pub phone: Option<Secret<String>>, } #[derive(Debug, Clone, Default, Eq, PartialEq, Serialize)] pub struct StripeBillingAddress { #[serde(rename = "payment_method_data[billing_details][email]")] pub email: Option<Email>, #[serde(rename = "payment_method_data[billing_details][address][country]")] pub country: Option<api_enums::CountryAlpha2>, #[serde(rename = "payment_method_data[billing_details][name]")] pub name: Option<Secret<String>>, #[serde(rename = "payment_method_data[billing_details][address][city]")] pub city: Option<String>, #[serde(rename = "payment_method_data[billing_details][address][line1]")] pub address_line1: Option<Secret<String>>, #[serde(rename = "payment_method_data[billing_details][address][line2]")] pub address_line2: Option<Secret<String>>, #[serde(rename = "payment_method_data[billing_details][address][postal_code]")] pub zip_code: Option<Secret<String>>, #[serde(rename = "payment_method_data[billing_details][address][state]")] pub state: Option<Secret<String>>, #[serde(rename = "payment_method_data[billing_details][phone]")] pub phone: Option<Secret<String>>, } #[derive(Debug, Clone, serde::Deserialize, Eq, PartialEq)] pub struct StripeRedirectResponse { pub payment_intent: Option<String>, pub payment_intent_client_secret: Option<Secret<String>>, pub source_redirect_slug: Option<String>, pub redirect_status: Option<StripePaymentStatus>, pub source_type: Option<Secret<String>>, } #[derive(Debug, Serialize)] pub struct CancelRequest { cancellation_reason: Option<String>, } impl TryFrom<&types::PaymentsCancelRouterData> for CancelRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> { Ok(Self { cancellation_reason: item.request.cancellation_reason.clone(), }) } } #[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)] #[non_exhaustive] #[serde(rename_all = "snake_case")] #[serde(untagged)] pub enum StripePaymentMethodOptions { Card { mandate_options: Option<StripeMandateOptions>, #[serde(rename = "payment_method_options[card][network_transaction_id]")] network_transaction_id: Option<Secret<String>>, #[serde(flatten)] mit_exemption: Option<MitExemption>, // To be used for MIT mandate txns }, Klarna {}, Affirm {}, AfterpayClearpay {}, AmazonPay {}, Eps {}, Giropay {}, Ideal {}, Sofort {}, #[serde(rename = "us_bank_account")] Ach {}, #[serde(rename = "sepa_debit")] Sepa {}, #[serde(rename = "au_becs_debit")] Becs {}, #[serde(rename = "bacs_debit")] Bacs {}, Bancontact {}, WechatPay {}, Alipay {}, #[serde(rename = "p24")] Przelewy24 {}, CustomerBalance {}, Multibanco {}, Blik {}, Cashapp {}, } #[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] pub struct MitExemption { #[serde(rename = "payment_method_options[card][mit_exemption][network_transaction_id]")] pub network_transaction_id: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] #[serde(untagged)] pub enum LatestAttempt { PaymentIntentAttempt(Box<LatestPaymentAttempt>), SetupAttempt(String), } #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct LatestPaymentAttempt { pub payment_method_options: Option<StripePaymentMethodOptions>, pub payment_method_details: Option<StripePaymentMethodDetailsResponse>, } // #[derive(Deserialize, Debug, Clone, Eq, PartialEq)] // pub struct Card #[derive(serde::Serialize, serde::Deserialize, Clone, Debug, Default, Eq, PartialEq)] pub struct StripeMandateOptions { reference: Secret<String>, // Extendable, But only important field to be captured } /// Represents the capture request body for stripe connector. #[derive(Debug, Serialize, Clone, Copy)] pub struct CaptureRequest { /// If amount_to_capture is None stripe captures the amount in the payment intent. amount_to_capture: Option<MinorUnit>, } impl TryFrom<MinorUnit> for CaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(capture_amount: MinorUnit) -> Result<Self, Self::Error> { Ok(Self { amount_to_capture: Some(capture_amount), }) } } impl<F, T> TryFrom<types::ResponseRouterData<F, StripeSourceResponse, T, types::PaymentsResponseData>> for types::RouterData<F, T, types::PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::ResponseRouterData<F, StripeSourceResponse, T, types::PaymentsResponseData>, ) -> Result<Self, Self::Error> { let connector_source_response = item.response.to_owned(); let connector_metadata = connector_source_response .encode_to_value() .change_context(errors::ConnectorError::ResponseHandlingFailed)?; // We get pending as the status from stripe, but hyperswitch should give it as requires_customer_action as // customer has to make payment to the virtual account number given in the source response let status = match connector_source_response.status.clone().into() { diesel_models::enums::AttemptStatus::Pending => { diesel_models::enums::AttemptStatus::AuthenticationPending } _ => connector_source_response.status.into(), }; Ok(Self { response: Ok(types::PaymentsResponseData::PreProcessingResponse { pre_processing_id: types::PreprocessingResponseId::PreProcessingId( item.response.id, ), connector_metadata: Some(connector_metadata), session_token: None, connector_response_reference_id: None, }), status, ..item.data }) } } impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for ChargesRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( data: (&types::PaymentsAuthorizeRouterData, MinorUnit), ) -> Result<Self, Self::Error> { { let value = data.0; let amount = data.1; let order_id = value.connector_request_reference_id.clone(); let meta_data = Some(get_transaction_metadata( value.request.metadata.clone().map(Into::into), order_id, )); Ok(Self { amount, currency: value.request.currency.to_string(), customer: Secret::new(value.get_connector_customer_id()?), source: Secret::new(value.get_preprocessing_id()?), meta_data, }) } } } impl<F, T> TryFrom<types::ResponseRouterData<F, ChargesResponse, T, types::PaymentsResponseData>> for types::RouterData<F, T, types::PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::ResponseRouterData<F, ChargesResponse, T, types::PaymentsResponseData>, ) -> Result<Self, Self::Error> { let connector_source_response = item.response.to_owned(); let connector_metadata = connector_source_response .source .encode_to_value() .change_context(errors::ConnectorError::ResponseHandlingFailed)?; let status = enums::AttemptStatus::from(item.response.status); let response = if connector_util::is_payment_failure(status) { Err(types::ErrorResponse { code: item .response .failure_code .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), message: item .response .failure_message .clone() .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), reason: item.response.failure_message, status_code: item.http_code, attempt_status: Some(status), connector_transaction_id: Some(item.response.id), network_advice_code: None, network_decline_code: None, network_error_message: None, }) } else { Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: Some(connector_metadata), network_txn_id: None, connector_response_reference_id: Some(item.response.id.clone()), incremental_authorization_allowed: None, charges: None, }) }; Ok(Self { status, response, ..item.data }) } } impl<F, T> TryFrom<types::ResponseRouterData<F, StripeTokenResponse, T, types::PaymentsResponseData>> for types::RouterData<F, T, types::PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::ResponseRouterData<F, StripeTokenResponse, T, types::PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(types::PaymentsResponseData::TokenizationResponse { token: item.response.id.expose(), }), ..item.data }) } } impl<F, T> TryFrom<types::ResponseRouterData<F, StripeCustomerResponse, T, types::PaymentsResponseData>> for types::RouterData<F, T, types::PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::ResponseRouterData<F, StripeCustomerResponse, T, types::PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(types::PaymentsResponseData::ConnectorCustomerResponse { connector_customer_id: item.response.id, }), ..item.data }) } } // #[cfg(test)] // mod test_stripe_transformers { // use super::*; // #[test] // fn verify_transform_from_router_to_stripe_req() { // let router_req = PaymentsRequest { // amount: 100.0, // currency: "USD".to_string(), // ..Default::default() // }; // let stripe_req = PaymentIntentRequest::from(router_req); // //metadata is generated everytime. So use the transformed struct to copy uuid // let stripe_req_expected = PaymentIntentRequest { // amount: 10000, // currency: "USD".to_string(), // statement_descriptor_suffix: None, // metadata_order_id: "Auto generate Order ID".to_string(), // metadata_txn_id: "Fetch from Merchant Account_Auto generate Order ID_1".to_string(), // metadata_txn_uuid: stripe_req.metadata_txn_uuid.clone(), // return_url: "Fetch Url from Merchant Account".to_string(), // confirm: false, // payment_method_types: "card".to_string(), // payment_method_data_type: "card".to_string(), // payment_method_data_card_number: None, // payment_method_data_card_exp_month: None, // payment_method_data_card_exp_year: None, // payment_method_data_card_cvc: None, // description: None, // }; // assert_eq!(stripe_req_expected, stripe_req); // } // } #[derive(Debug, Deserialize)] pub struct WebhookEventDataResource { pub object: Value, } #[derive(Debug, Deserialize)] pub struct WebhookEventObjectResource { pub data: WebhookEventDataResource, } #[derive(Debug, Deserialize)] pub struct WebhookEvent { #[serde(rename = "type")] pub event_type: WebhookEventType, #[serde(rename = "data")] pub event_data: WebhookEventData, } #[derive(Debug, Deserialize)] pub struct WebhookEventTypeBody { #[serde(rename = "type")] pub event_type: WebhookEventType, #[serde(rename = "data")] pub event_data: WebhookStatusData, } #[derive(Debug, Deserialize)] pub struct WebhookEventData { #[serde(rename = "object")] pub event_object: WebhookEventObjectData, } #[derive(Debug, Deserialize)] pub struct WebhookStatusData { #[serde(rename = "object")] pub event_object: WebhookStatusObjectData, } #[derive(Debug, Deserialize)] pub struct WebhookStatusObjectData { pub status: Option<WebhookEventStatus>, pub payment_method_details: Option<WebhookPaymentMethodDetails>, } #[derive(Debug, Deserialize)] #[serde(rename_all = "snake_case")] pub enum WebhookPaymentMethodType { AchCreditTransfer, MultibancoBankTransfers, #[serde(other)] Unknown, } #[derive(Debug, Deserialize)] pub struct WebhookPaymentMethodDetails { #[serde(rename = "type")] pub payment_method: WebhookPaymentMethodType, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct WebhookEventObjectData { pub id: String, pub object: WebhookEventObjectType, pub amount: Option<i32>, #[serde(default, deserialize_with = "connector_util::convert_uppercase")] pub currency: enums::Currency, pub payment_intent: Option<String>, pub client_secret: Option<Secret<String>>, pub reason: Option<String>, #[serde(with = "common_utils::custom_serde::timestamp")] pub created: PrimitiveDateTime, pub evidence_details: Option<EvidenceDetails>, pub status: Option<WebhookEventStatus>, pub metadata: Option<StripeMetadata>, } #[derive(Debug, Clone, Serialize, Deserialize, strum::Display)] #[serde(rename_all = "snake_case")] pub enum WebhookEventObjectType { PaymentIntent, Dispute, Charge, Source, Refund, } #[derive(Debug, Deserialize)] pub enum WebhookEventType { #[serde(rename = "payment_intent.payment_failed")] PaymentIntentFailed, #[serde(rename = "payment_intent.succeeded")] PaymentIntentSucceed, #[serde(rename = "charge.dispute.created")] DisputeCreated, #[serde(rename = "charge.dispute.closed")] DisputeClosed, #[serde(rename = "charge.dispute.updated")] DisputeUpdated, #[serde(rename = "charge.dispute.funds_reinstated")] ChargeDisputeFundsReinstated, #[serde(rename = "charge.dispute.funds_withdrawn")] ChargeDisputeFundsWithdrawn, #[serde(rename = "charge.expired")] ChargeExpired, #[serde(rename = "charge.failed")] ChargeFailed, #[serde(rename = "charge.pending")] ChargePending, #[serde(rename = "charge.captured")] ChargeCaptured, #[serde(rename = "charge.refund.updated")] ChargeRefundUpdated, #[serde(rename = "charge.succeeded")] ChargeSucceeded, #[serde(rename = "charge.updated")] ChargeUpdated, #[serde(rename = "charge.refunded")] ChargeRefunded, #[serde(rename = "payment_intent.canceled")] PaymentIntentCanceled, #[serde(rename = "payment_intent.created")] PaymentIntentCreated, #[serde(rename = "payment_intent.processing")] PaymentIntentProcessing, #[serde(rename = "payment_intent.requires_action")] PaymentIntentRequiresAction, #[serde(rename = "payment_intent.amount_capturable_updated")] PaymentIntentAmountCapturableUpdated, #[serde(rename = "source.chargeable")] SourceChargeable, #[serde(rename = "source.transaction.created")] SourceTransactionCreated, #[serde(rename = "payment_intent.partially_funded")] PaymentIntentPartiallyFunded, #[serde(other)] Unknown, } #[derive(Debug, Clone, Serialize, strum::Display, Deserialize, PartialEq)] #[serde(rename_all = "snake_case")] pub enum WebhookEventStatus { WarningNeedsResponse, WarningClosed, WarningUnderReview, Won, Lost, NeedsResponse, UnderReview, ChargeRefunded, Succeeded, RequiresPaymentMethod, RequiresConfirmation, RequiresAction, Processing, RequiresCapture, Canceled, Chargeable, Failed, #[serde(other)] Unknown, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct EvidenceDetails { #[serde(with = "common_utils::custom_serde::timestamp")] pub due_by: PrimitiveDateTime, } impl TryFrom<( &types::SetupMandateRouterData, enums::AuthenticationType, StripePaymentMethodType, )> for StripePaymentMethodData { type Error = error_stack::Report<errors::ConnectorError>; 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"), ))? } } } } #[derive(Debug, Deserialize)] pub struct StripeGpayToken { pub id: String, } pub fn get_bank_transfer_request_data( req: &types::PaymentsAuthorizeRouterData, bank_transfer_data: &domain::BankTransferData, amount: MinorUnit, ) -> CustomResult<RequestContent, errors::ConnectorError> { match bank_transfer_data { domain::BankTransferData::AchBankTransfer { .. } | domain::BankTransferData::MultibancoBankTransfer { .. } => { let req = ChargesRequest::try_from((req, amount))?; Ok(RequestContent::FormUrlEncoded(Box::new(req))) } _ => { let req = PaymentIntentRequest::try_from((req, amount))?; Ok(RequestContent::FormUrlEncoded(Box::new(req))) } } } pub fn construct_file_upload_request( file_upload_router_data: types::UploadFileRouterData, ) -> CustomResult<reqwest::multipart::Form, errors::ConnectorError> { let request = file_upload_router_data.request; let mut multipart = reqwest::multipart::Form::new(); multipart = multipart.text("purpose", "dispute_evidence"); let file_data = reqwest::multipart::Part::bytes(request.file) .file_name(request.file_key) .mime_str(request.file_type.as_ref()) .map_err(|_| errors::ConnectorError::RequestEncodingFailed)?; multipart = multipart.part("file", file_data); Ok(multipart) } #[derive(Debug, Deserialize, Serialize)] pub struct FileUploadResponse { #[serde(rename = "id")] pub file_id: String, } #[derive(Debug, Serialize)] pub struct Evidence { #[serde(rename = "evidence[access_activity_log]")] pub access_activity_log: Option<String>, #[serde(rename = "evidence[billing_address]")] pub billing_address: Option<Secret<String>>, #[serde(rename = "evidence[cancellation_policy]")] pub cancellation_policy: Option<String>, #[serde(rename = "evidence[cancellation_policy_disclosure]")] pub cancellation_policy_disclosure: Option<String>, #[serde(rename = "evidence[cancellation_rebuttal]")] pub cancellation_rebuttal: Option<String>, #[serde(rename = "evidence[customer_communication]")] pub customer_communication: Option<String>, #[serde(rename = "evidence[customer_email_address]")] pub customer_email_address: Option<Secret<String, pii::EmailStrategy>>, #[serde(rename = "evidence[customer_name]")] pub customer_name: Option<Secret<String>>, #[serde(rename = "evidence[customer_purchase_ip]")] pub customer_purchase_ip: Option<Secret<String, pii::IpAddress>>, #[serde(rename = "evidence[customer_signature]")] pub customer_signature: Option<Secret<String>>, #[serde(rename = "evidence[product_description]")] pub product_description: Option<String>, #[serde(rename = "evidence[receipt]")] pub receipt: Option<Secret<String>>, #[serde(rename = "evidence[refund_policy]")] pub refund_policy: Option<String>, #[serde(rename = "evidence[refund_policy_disclosure]")] pub refund_policy_disclosure: Option<String>, #[serde(rename = "evidence[refund_refusal_explanation]")] pub refund_refusal_explanation: Option<String>, #[serde(rename = "evidence[service_date]")] pub service_date: Option<String>, #[serde(rename = "evidence[service_documentation]")] pub service_documentation: Option<String>, #[serde(rename = "evidence[shipping_address]")] pub shipping_address: Option<Secret<String>>, #[serde(rename = "evidence[shipping_carrier]")] pub shipping_carrier: Option<String>, #[serde(rename = "evidence[shipping_date]")] pub shipping_date: Option<String>, #[serde(rename = "evidence[shipping_documentation]")] pub shipping_documentation: Option<Secret<String>>, #[serde(rename = "evidence[shipping_tracking_number]")] pub shipping_tracking_number: Option<Secret<String>>, #[serde(rename = "evidence[uncategorized_file]")] pub uncategorized_file: Option<String>, #[serde(rename = "evidence[uncategorized_text]")] pub uncategorized_text: Option<String>, pub submit: bool, } // Mandates for bank redirects - ideal and sofort happens through sepa direct debit in stripe fn mandatory_parameters_for_sepa_bank_debit_mandates( billing_details: &Option<StripeBillingAddress>, is_customer_initiated_mandate_payment: Option<bool>, ) -> Result<StripeBillingAddress, errors::ConnectorError> { let billing_name = billing_details .clone() .and_then(|billing_data| billing_data.name.clone()); let billing_email = billing_details .clone() .and_then(|billing_data| billing_data.email.clone()); match is_customer_initiated_mandate_payment { Some(true) => Ok(StripeBillingAddress { name: Some( billing_name.ok_or(errors::ConnectorError::MissingRequiredField { field_name: "billing_name", })?, ), email: Some( billing_email.ok_or(errors::ConnectorError::MissingRequiredField { field_name: "billing_email", })?, ), ..StripeBillingAddress::default() }), Some(false) | None => Ok(StripeBillingAddress { name: billing_name, email: billing_email, ..StripeBillingAddress::default() }), } } impl TryFrom<&types::SubmitEvidenceRouterData> for Evidence { type Error = error_stack::Report<errors::ConnectorError>; 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, }) } } #[derive(Debug, Deserialize, Serialize)] pub struct DisputeObj { #[serde(rename = "id")] pub dispute_id: String, pub status: String, } 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 } impl ForeignTryFrom<(&Option<ErrorDetails>, u16, String)> for types::PaymentsResponseData { type Error = types::ErrorResponse; 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, }) } } pub(super) fn transform_headers_for_connect_platform( charge_type: api::enums::PaymentChargeType, transfer_account_id: String, header: &mut Vec<(String, services::request::Maskable<String>)>, ) { if let api::enums::PaymentChargeType::Stripe(api::enums::StripeChargeType::Direct) = charge_type { let mut customer_account_header = vec![( headers::STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(), transfer_account_id.into_masked(), )]; header.append(&mut customer_account_header); } } pub fn construct_charge_response<T>( charge_id: String, request: &T, ) -> Option<common_types::payments::ConnectorChargeResponseData> where T: connector_util::SplitPaymentData, { let charge_request = request.get_split_payment_data(); if let Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment( stripe_split_payment, )) = charge_request { let stripe_charge_response = common_types::payments::StripeChargeResponseData { charge_id: Some(charge_id), charge_type: stripe_split_payment.charge_type, application_fees: stripe_split_payment.application_fees, transfer_account_id: stripe_split_payment.transfer_account_id, }; Some( common_types::payments::ConnectorChargeResponseData::StripeSplitPayment( stripe_charge_response, ), ) } else { None } } #[cfg(test)] mod test_validate_shipping_address_against_payment_method { #![allow(clippy::unwrap_used)] use api_models::enums::CountryAlpha2; use masking::Secret; use crate::{ connector::stripe::transformers::{ validate_shipping_address_against_payment_method, StripePaymentMethodType, StripeShippingAddress, }, core::errors, }; #[test] fn should_return_ok() { // Arrange let stripe_shipping_address = create_stripe_shipping_address( "name".to_string(), Some("line1".to_string()), Some(CountryAlpha2::AD), Some("zip".to_string()), ); let payment_method = &StripePaymentMethodType::AfterpayClearpay; //Act let result = validate_shipping_address_against_payment_method( &Some(stripe_shipping_address), Some(payment_method), ); // Assert assert!(result.is_ok()); } #[test] fn should_return_err_for_empty_line1() { // Arrange let stripe_shipping_address = create_stripe_shipping_address( "name".to_string(), None, Some(CountryAlpha2::AD), Some("zip".to_string()), ); let payment_method = &StripePaymentMethodType::AfterpayClearpay; //Act let result = validate_shipping_address_against_payment_method( &Some(stripe_shipping_address), Some(payment_method), ); // Assert assert!(result.is_err()); let missing_fields = get_missing_fields(result.unwrap_err().current_context()).to_owned(); assert_eq!(missing_fields.len(), 1); assert_eq!(*missing_fields.first().unwrap(), "shipping.address.line1"); } #[test] fn should_return_err_for_empty_country() { // Arrange let stripe_shipping_address = create_stripe_shipping_address( "name".to_string(), Some("line1".to_string()), None, Some("zip".to_string()), ); let payment_method = &StripePaymentMethodType::AfterpayClearpay; //Act let result = validate_shipping_address_against_payment_method( &Some(stripe_shipping_address), Some(payment_method), ); // Assert assert!(result.is_err()); let missing_fields = get_missing_fields(result.unwrap_err().current_context()).to_owned(); assert_eq!(missing_fields.len(), 1); assert_eq!(*missing_fields.first().unwrap(), "shipping.address.country"); } #[test] fn should_return_err_for_empty_zip() { // Arrange let stripe_shipping_address = create_stripe_shipping_address( "name".to_string(), Some("line1".to_string()), Some(CountryAlpha2::AD), None, ); let payment_method = &StripePaymentMethodType::AfterpayClearpay; //Act let result = validate_shipping_address_against_payment_method( &Some(stripe_shipping_address), Some(payment_method), ); // Assert assert!(result.is_err()); let missing_fields = get_missing_fields(result.unwrap_err().current_context()).to_owned(); assert_eq!(missing_fields.len(), 1); assert_eq!(*missing_fields.first().unwrap(), "shipping.address.zip"); } #[test] fn should_return_error_when_missing_multiple_fields() { // Arrange let expected_missing_field_names: Vec<&'static str> = vec!["shipping.address.zip", "shipping.address.country"]; let stripe_shipping_address = create_stripe_shipping_address( "name".to_string(), Some("line1".to_string()), None, None, ); let payment_method = &StripePaymentMethodType::AfterpayClearpay; //Act let result = validate_shipping_address_against_payment_method( &Some(stripe_shipping_address), Some(payment_method), ); // Assert assert!(result.is_err()); let missing_fields = get_missing_fields(result.unwrap_err().current_context()).to_owned(); for field in missing_fields { assert!(expected_missing_field_names.contains(&field)); } } fn get_missing_fields(connector_error: &errors::ConnectorError) -> Vec<&'static str> { if let errors::ConnectorError::MissingRequiredFields { field_names } = connector_error { return field_names.to_vec(); } vec![] } fn create_stripe_shipping_address( name: String, line1: Option<String>, country: Option<CountryAlpha2>, zip: Option<String>, ) -> StripeShippingAddress { StripeShippingAddress { name: Secret::new(name), line1: line1.map(Secret::new), country, zip: zip.map(Secret::new), city: Some(String::from("city")), line2: Some(Secret::new(String::from("line2"))), state: Some(Secret::new(String::from("state"))), phone: Some(Secret::new(String::from("pbone number"))), } } }
36,937
1,520
hyperswitch
crates/router/src/connector/stripe/transformers/connect.rs
.rs
use api_models; use common_utils::pii::Email; use error_stack::ResultExt; use masking::Secret; use serde::{Deserialize, Serialize}; use super::ErrorDetails; use crate::{ connector::utils::{PayoutsData, RouterData}, core::{errors, payments::CustomerDetailsExt}, types::{self, storage::enums, PayoutIndividualDetailsExt}, utils::OptionExt, }; type Error = error_stack::Report<errors::ConnectorError>; #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] pub enum StripeConnectPayoutStatus { Canceled, Failed, InTransit, Paid, Pending, } #[derive(Debug, Deserialize, Serialize)] pub struct StripeConnectErrorResponse { pub error: ErrorDetails, } // Payouts #[derive(Clone, Debug, Serialize)] pub struct StripeConnectPayoutCreateRequest { amount: i64, currency: enums::Currency, destination: String, transfer_group: String, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct StripeConnectPayoutCreateResponse { id: String, description: Option<String>, source_transaction: Option<String>, } #[derive(Clone, Debug, Default, Serialize, Deserialize)] pub struct TransferReversals { object: String, has_more: bool, total_count: i32, url: String, } #[derive(Clone, Debug, Serialize)] pub struct StripeConnectPayoutFulfillRequest { amount: i64, currency: enums::Currency, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct StripeConnectPayoutFulfillResponse { id: String, currency: String, description: Option<String>, failure_balance_transaction: Option<String>, failure_code: Option<String>, failure_message: Option<String>, original_payout: Option<String>, reversed_by: Option<String>, statement_descriptor: Option<String>, status: StripeConnectPayoutStatus, } #[derive(Clone, Debug, Serialize)] pub struct StripeConnectReversalRequest { amount: i64, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct StripeConnectReversalResponse { id: String, source_refund: Option<String>, } #[derive(Clone, Debug, Serialize)] pub struct StripeConnectRecipientCreateRequest { #[serde(rename = "type")] account_type: String, country: Option<enums::CountryAlpha2>, email: Option<Email>, #[serde(rename = "capabilities[card_payments][requested]")] capabilities_card_payments: Option<bool>, #[serde(rename = "capabilities[transfers][requested]")] capabilities_transfers: Option<bool>, #[serde(rename = "tos_acceptance[date]")] tos_acceptance_date: Option<i64>, #[serde(rename = "tos_acceptance[ip]")] tos_acceptance_ip: Option<Secret<String>>, business_type: String, #[serde(rename = "business_profile[mcc]")] business_profile_mcc: Option<i32>, #[serde(rename = "business_profile[url]")] business_profile_url: Option<String>, #[serde(rename = "business_profile[name]")] business_profile_name: Option<Secret<String>>, #[serde(rename = "company[name]")] company_name: Option<Secret<String>>, #[serde(rename = "company[address][line1]")] company_address_line1: Option<Secret<String>>, #[serde(rename = "company[address][line2]")] company_address_line2: Option<Secret<String>>, #[serde(rename = "company[address][postal_code]")] company_address_postal_code: Option<Secret<String>>, #[serde(rename = "company[address][city]")] company_address_city: Option<Secret<String>>, #[serde(rename = "company[address][state]")] company_address_state: Option<Secret<String>>, #[serde(rename = "company[phone]")] company_phone: Option<Secret<String>>, #[serde(rename = "company[tax_id]")] company_tax_id: Option<Secret<String>>, #[serde(rename = "company[owners_provided]")] company_owners_provided: Option<bool>, #[serde(rename = "individual[first_name]")] individual_first_name: Option<Secret<String>>, #[serde(rename = "individual[last_name]")] individual_last_name: Option<Secret<String>>, #[serde(rename = "individual[dob][day]")] individual_dob_day: Option<Secret<String>>, #[serde(rename = "individual[dob][month]")] individual_dob_month: Option<Secret<String>>, #[serde(rename = "individual[dob][year]")] individual_dob_year: Option<Secret<String>>, #[serde(rename = "individual[address][line1]")] individual_address_line1: Option<Secret<String>>, #[serde(rename = "individual[address][line2]")] individual_address_line2: Option<Secret<String>>, #[serde(rename = "individual[address][postal_code]")] individual_address_postal_code: Option<Secret<String>>, #[serde(rename = "individual[address][city]")] individual_address_city: Option<String>, #[serde(rename = "individual[address][state]")] individual_address_state: Option<Secret<String>>, #[serde(rename = "individual[email]")] individual_email: Option<Email>, #[serde(rename = "individual[phone]")] individual_phone: Option<Secret<String>>, #[serde(rename = "individual[id_number]")] individual_id_number: Option<Secret<String>>, #[serde(rename = "individual[ssn_last_4]")] individual_ssn_last_4: Option<Secret<String>>, } #[derive(Clone, Debug, Default, Serialize, Deserialize)] pub struct StripeConnectRecipientCreateResponse { id: String, } #[derive(Clone, Debug, Serialize)] #[serde(untagged)] pub enum StripeConnectRecipientAccountCreateRequest { Bank(RecipientBankAccountRequest), Card(RecipientCardAccountRequest), Token(RecipientTokenRequest), } #[derive(Clone, Debug, Serialize)] pub struct RecipientTokenRequest { external_account: String, } #[derive(Clone, Debug, Serialize)] pub struct RecipientCardAccountRequest { #[serde(rename = "external_account[object]")] external_account_object: String, #[serde(rename = "external_account[number]")] external_account_number: Secret<String>, #[serde(rename = "external_account[exp_month]")] external_account_exp_month: Secret<String>, #[serde(rename = "external_account[exp_year]")] external_account_exp_year: Secret<String>, } #[derive(Clone, Debug, Serialize)] pub struct RecipientBankAccountRequest { #[serde(rename = "external_account[object]")] external_account_object: String, #[serde(rename = "external_account[country]")] external_account_country: enums::CountryAlpha2, #[serde(rename = "external_account[currency]")] external_account_currency: enums::Currency, #[serde(rename = "external_account[account_holder_name]")] external_account_account_holder_name: Secret<String>, #[serde(rename = "external_account[account_number]")] external_account_account_number: Secret<String>, #[serde(rename = "external_account[account_holder_type]")] external_account_account_holder_type: String, #[serde(rename = "external_account[routing_number]")] external_account_routing_number: Secret<String>, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct StripeConnectRecipientAccountCreateResponse { id: String, } // Payouts create/transfer request transform impl<F> TryFrom<&types::PayoutsRouterData<F>> for StripeConnectPayoutCreateRequest { type Error = Error; fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> { let request = item.request.to_owned(); let connector_customer_id = item.get_connector_customer_id()?; Ok(Self { amount: request.amount, currency: request.destination_currency, destination: connector_customer_id, transfer_group: request.payout_id, }) } } // Payouts create response transform impl<F> TryFrom<types::PayoutsResponseRouterData<F, StripeConnectPayoutCreateResponse>> for types::PayoutsRouterData<F> { type Error = Error; fn try_from( item: types::PayoutsResponseRouterData<F, StripeConnectPayoutCreateResponse>, ) -> Result<Self, Self::Error> { let response: StripeConnectPayoutCreateResponse = item.response; Ok(Self { response: Ok(types::PayoutsResponseData { status: Some(enums::PayoutStatus::RequiresFulfillment), connector_payout_id: Some(response.id), payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: None, error_message: None, }), ..item.data }) } } // Payouts fulfill request transform impl<F> TryFrom<&types::PayoutsRouterData<F>> for StripeConnectPayoutFulfillRequest { type Error = Error; fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> { let request = item.request.to_owned(); Ok(Self { amount: request.amount, currency: request.destination_currency, }) } } // Payouts fulfill response transform impl<F> TryFrom<types::PayoutsResponseRouterData<F, StripeConnectPayoutFulfillResponse>> for types::PayoutsRouterData<F> { type Error = Error; fn try_from( item: types::PayoutsResponseRouterData<F, StripeConnectPayoutFulfillResponse>, ) -> Result<Self, Self::Error> { let response: StripeConnectPayoutFulfillResponse = item.response; Ok(Self { response: Ok(types::PayoutsResponseData { status: Some(enums::PayoutStatus::from(response.status)), connector_payout_id: Some(response.id), payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: None, error_message: None, }), ..item.data }) } } // Payouts reversal request transform impl<F> TryFrom<&types::PayoutsRouterData<F>> for StripeConnectReversalRequest { type Error = Error; fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> { Ok(Self { amount: item.request.amount, }) } } // Payouts reversal response transform impl<F> TryFrom<types::PayoutsResponseRouterData<F, StripeConnectReversalResponse>> for types::PayoutsRouterData<F> { type Error = Error; fn try_from( item: types::PayoutsResponseRouterData<F, StripeConnectReversalResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(types::PayoutsResponseData { status: Some(enums::PayoutStatus::Cancelled), connector_payout_id: item.data.request.connector_payout_id.clone(), payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: None, error_message: None, }), ..item.data }) } } // Recipient creation request transform impl<F> TryFrom<&types::PayoutsRouterData<F>> for StripeConnectRecipientCreateRequest { type Error = Error; fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> { let request = item.request.to_owned(); let customer_details = request.get_customer_details()?; let customer_email = customer_details.get_email()?; let address = item.get_billing_address()?.clone(); let payout_vendor_details = request.get_vendor_details()?; let (vendor_details, individual_details) = ( payout_vendor_details.vendor_details, payout_vendor_details.individual_details, ); Ok(Self { account_type: vendor_details.account_type, country: address.country, email: Some(customer_email.clone()), capabilities_card_payments: vendor_details.capabilities_card_payments, capabilities_transfers: vendor_details.capabilities_transfers, tos_acceptance_date: individual_details.tos_acceptance_date, tos_acceptance_ip: individual_details.tos_acceptance_ip, business_type: vendor_details.business_type, business_profile_mcc: vendor_details.business_profile_mcc, business_profile_url: vendor_details.business_profile_url, business_profile_name: vendor_details.business_profile_name.clone(), company_name: vendor_details.business_profile_name, company_address_line1: vendor_details.company_address_line1, company_address_line2: vendor_details.company_address_line2, company_address_postal_code: vendor_details.company_address_postal_code, company_address_city: vendor_details.company_address_city, company_address_state: vendor_details.company_address_state, company_phone: vendor_details.company_phone, company_tax_id: vendor_details.company_tax_id, company_owners_provided: vendor_details.company_owners_provided, individual_first_name: address.first_name, individual_last_name: address.last_name, individual_dob_day: individual_details.individual_dob_day, individual_dob_month: individual_details.individual_dob_month, individual_dob_year: individual_details.individual_dob_year, individual_address_line1: address.line1, individual_address_line2: address.line2, individual_address_postal_code: address.zip, individual_address_city: address.city, individual_address_state: address.state, individual_email: Some(customer_email), individual_phone: customer_details.phone, individual_id_number: individual_details.individual_id_number, individual_ssn_last_4: individual_details.individual_ssn_last_4, }) } } // Recipient creation response transform impl<F> TryFrom<types::PayoutsResponseRouterData<F, StripeConnectRecipientCreateResponse>> for types::PayoutsRouterData<F> { type Error = Error; fn try_from( item: types::PayoutsResponseRouterData<F, StripeConnectRecipientCreateResponse>, ) -> Result<Self, Self::Error> { let response: StripeConnectRecipientCreateResponse = item.response; Ok(Self { response: Ok(types::PayoutsResponseData { status: Some(enums::PayoutStatus::RequiresVendorAccountCreation), connector_payout_id: Some(response.id), payout_eligible: None, should_add_next_step_to_process_tracker: true, error_code: None, error_message: None, }), ..item.data }) } } // Recipient account's creation request impl<F> TryFrom<&types::PayoutsRouterData<F>> for StripeConnectRecipientAccountCreateRequest { type Error = Error; fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> { let request = item.request.to_owned(); let payout_method_data = item.get_payout_method_data()?; let customer_details = request.get_customer_details()?; let customer_name = customer_details.get_name()?; let payout_vendor_details = request.get_vendor_details()?; match payout_method_data { api_models::payouts::PayoutMethodData::Card(_) => { Ok(Self::Token(RecipientTokenRequest { external_account: "tok_visa_debit".to_string(), })) } api_models::payouts::PayoutMethodData::Bank(bank) => match bank { api_models::payouts::Bank::Ach(bank_details) => { Ok(Self::Bank(RecipientBankAccountRequest { external_account_object: "bank_account".to_string(), external_account_country: bank_details .bank_country_code .get_required_value("bank_country_code") .change_context(errors::ConnectorError::MissingRequiredField { field_name: "bank_country_code", })?, external_account_currency: request.destination_currency.to_owned(), external_account_account_holder_name: customer_name, external_account_account_holder_type: payout_vendor_details .individual_details .get_external_account_account_holder_type()?, external_account_account_number: bank_details.bank_account_number, external_account_routing_number: bank_details.bank_routing_number, })) } api_models::payouts::Bank::Bacs(_) => Err(errors::ConnectorError::NotSupported { message: "BACS payouts are not supported".to_string(), connector: "stripe", } .into()), api_models::payouts::Bank::Sepa(_) => Err(errors::ConnectorError::NotSupported { message: "SEPA payouts are not supported".to_string(), connector: "stripe", } .into()), api_models::payouts::Bank::Pix(_) => Err(errors::ConnectorError::NotSupported { message: "PIX payouts are not supported".to_string(), connector: "stripe", } .into()), }, api_models::payouts::PayoutMethodData::Wallet(_) => { Err(errors::ConnectorError::NotSupported { message: "Payouts via wallets are not supported".to_string(), connector: "stripe", } .into()) } } } } // Recipient account's creation response impl<F> TryFrom<types::PayoutsResponseRouterData<F, StripeConnectRecipientAccountCreateResponse>> for types::PayoutsRouterData<F> { type Error = Error; fn try_from( item: types::PayoutsResponseRouterData<F, StripeConnectRecipientAccountCreateResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(types::PayoutsResponseData { status: Some(enums::PayoutStatus::RequiresCreation), connector_payout_id: item.data.request.connector_payout_id.clone(), payout_eligible: None, should_add_next_step_to_process_tracker: false, error_code: None, error_message: None, }), ..item.data }) } } impl From<StripeConnectPayoutStatus> for enums::PayoutStatus { fn from(stripe_connect_status: StripeConnectPayoutStatus) -> Self { match stripe_connect_status { StripeConnectPayoutStatus::Paid => Self::Success, StripeConnectPayoutStatus::Failed => Self::Failed, StripeConnectPayoutStatus::Canceled => Self::Cancelled, StripeConnectPayoutStatus::Pending | StripeConnectPayoutStatus::InTransit => { Self::Pending } } } }
3,955
1,521
hyperswitch
crates/router/src/connector/dummyconnector/transformers.rs
.rs
use diesel_models::enums::Currency; use masking::Secret; use serde::{Deserialize, Serialize}; use url::Url; use crate::{ connector::utils::RouterData, core::errors, services, types::{self, api, domain, storage::enums}, }; #[derive(Debug, Serialize, strum::Display, Eq, PartialEq)] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DummyConnectors { #[serde(rename = "phonypay")] #[strum(serialize = "phonypay")] PhonyPay, #[serde(rename = "fauxpay")] #[strum(serialize = "fauxpay")] FauxPay, #[serde(rename = "pretendpay")] #[strum(serialize = "pretendpay")] PretendPay, StripeTest, AdyenTest, CheckoutTest, PaypalTest, } impl DummyConnectors { pub fn get_dummy_connector_id(self) -> &'static str { match self { Self::PhonyPay => "phonypay", Self::FauxPay => "fauxpay", Self::PretendPay => "pretendpay", Self::StripeTest => "stripe_test", Self::AdyenTest => "adyen_test", Self::CheckoutTest => "checkout_test", Self::PaypalTest => "paypal_test", } } } impl From<u8> for DummyConnectors { fn from(value: u8) -> Self { match value { 1 => Self::PhonyPay, 2 => Self::FauxPay, 3 => Self::PretendPay, 4 => Self::StripeTest, 5 => Self::AdyenTest, 6 => Self::CheckoutTest, 7 => Self::PaypalTest, _ => Self::PhonyPay, } } } #[derive(Debug, Serialize, Eq, PartialEq)] pub struct DummyConnectorPaymentsRequest<const T: u8> { amount: i64, currency: Currency, payment_method_data: PaymentMethodData, return_url: Option<String>, connector: DummyConnectors, } #[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)] #[serde(rename_all = "lowercase")] pub enum PaymentMethodData { Card(DummyConnectorCard), Wallet(DummyConnectorWallet), PayLater(DummyConnectorPayLater), } #[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)] pub struct DummyConnectorCard { name: Secret<String>, number: cards::CardNumber, expiry_month: Secret<String>, expiry_year: Secret<String>, cvc: Secret<String>, } impl TryFrom<(domain::Card, Option<Secret<String>>)> for DummyConnectorCard { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (value, card_holder_name): (domain::Card, Option<Secret<String>>), ) -> Result<Self, Self::Error> { Ok(Self { name: card_holder_name.unwrap_or(Secret::new("".to_string())), number: value.card_number, expiry_month: value.card_exp_month, expiry_year: value.card_exp_year, cvc: value.card_cvc, }) } } #[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)] pub enum DummyConnectorWallet { GooglePay, Paypal, WeChatPay, MbWay, AliPay, AliPayHK, } impl TryFrom<domain::WalletData> for DummyConnectorWallet { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(value: domain::WalletData) -> Result<Self, Self::Error> { match value { domain::WalletData::GooglePayRedirect(_) => Ok(Self::GooglePay), domain::WalletData::PaypalRedirect(_) => Ok(Self::Paypal), domain::WalletData::WeChatPayRedirect(_) => Ok(Self::WeChatPay), domain::WalletData::MbWayRedirect(_) => Ok(Self::MbWay), domain::WalletData::AliPayRedirect(_) => Ok(Self::AliPay), domain::WalletData::AliPayHkRedirect(_) => Ok(Self::AliPayHK), _ => Err(errors::ConnectorError::NotImplemented("Dummy wallet".to_string()).into()), } } } #[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)] pub enum DummyConnectorPayLater { Klarna, Affirm, AfterPayClearPay, } impl TryFrom<domain::payments::PayLaterData> for DummyConnectorPayLater { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(value: domain::payments::PayLaterData) -> Result<Self, Self::Error> { match value { domain::payments::PayLaterData::KlarnaRedirect { .. } => Ok(Self::Klarna), domain::payments::PayLaterData::AffirmRedirect {} => Ok(Self::Affirm), domain::payments::PayLaterData::AfterpayClearpayRedirect { .. } => { Ok(Self::AfterPayClearPay) } _ => Err(errors::ConnectorError::NotImplemented("Dummy pay later".to_string()).into()), } } } impl<const T: u8> TryFrom<&types::PaymentsAuthorizeRouterData> for DummyConnectorPaymentsRequest<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { let payment_method_data: Result<PaymentMethodData, Self::Error> = match item .request .payment_method_data { domain::PaymentMethodData::Card(ref req_card) => { let card_holder_name = item.get_optional_billing_full_name(); Ok(PaymentMethodData::Card(DummyConnectorCard::try_from(( req_card.clone(), card_holder_name, ))?)) } domain::PaymentMethodData::Wallet(ref wallet_data) => { Ok(PaymentMethodData::Wallet(wallet_data.clone().try_into()?)) } domain::PaymentMethodData::PayLater(ref pay_later_data) => Ok( PaymentMethodData::PayLater(pay_later_data.clone().try_into()?), ), _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), }; Ok(Self { amount: item.request.amount, currency: item.request.currency, payment_method_data: payment_method_data?, return_url: item.request.router_return_url.clone(), connector: Into::<DummyConnectors>::into(T), }) } } // Auth Struct pub struct DummyConnectorAuthType { pub(super) api_key: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for DummyConnectorAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self { api_key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } // PaymentsResponse //TODO: Append the remaining status flags #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum DummyConnectorPaymentStatus { Succeeded, Failed, #[default] Processing, } impl From<DummyConnectorPaymentStatus> for enums::AttemptStatus { fn from(item: DummyConnectorPaymentStatus) -> Self { match item { DummyConnectorPaymentStatus::Succeeded => Self::Charged, DummyConnectorPaymentStatus::Failed => Self::Failure, DummyConnectorPaymentStatus::Processing => Self::AuthenticationPending, } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PaymentsResponse { status: DummyConnectorPaymentStatus, id: String, amount: i64, currency: Currency, created: String, payment_method_type: PaymentMethodType, next_action: Option<DummyConnectorNextAction>, } #[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)] #[serde(rename_all = "lowercase")] pub enum PaymentMethodType { Card, Wallet(DummyConnectorWallet), PayLater(DummyConnectorPayLater), } impl<F, T> TryFrom<types::ResponseRouterData<F, PaymentsResponse, T, types::PaymentsResponseData>> for types::RouterData<F, T, types::PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::ResponseRouterData<F, PaymentsResponse, T, types::PaymentsResponseData>, ) -> Result<Self, Self::Error> { let redirection_data = item .response .next_action .and_then(|redirection_data| redirection_data.get_url()) .map(|redirection_url| { services::RedirectForm::from((redirection_url, services::Method::Get)) }); Ok(Self { status: enums::AttemptStatus::from(item.response.status), response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), redirection_data: Box::new(redirection_data), 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 }) } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "snake_case")] pub enum DummyConnectorNextAction { RedirectToUrl(Url), } impl DummyConnectorNextAction { fn get_url(&self) -> Option<Url> { match self { Self::RedirectToUrl(redirect_to_url) => Some(redirect_to_url.to_owned()), } } } // REFUND : // Type definition for RefundRequest #[derive(Default, Debug, Serialize)] pub struct DummyConnectorRefundRequest { pub amount: i64, } impl<F> TryFrom<&types::RefundsRouterData<F>> for DummyConnectorRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { Ok(Self { amount: item.request.refund_amount, }) } } // Type definition for Refund Response #[allow(dead_code)] #[derive(Debug, Serialize, Default, Deserialize, Clone)] #[serde(rename_all = "lowercase")] pub enum RefundStatus { Succeeded, Failed, #[default] Processing, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Succeeded => Self::Success, RefundStatus::Failed => Self::Failure, RefundStatus::Processing => Self::Pending, //TODO: Review mapping } } } #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse { id: String, status: RefundStatus, currency: Currency, created: String, payment_amount: i64, refund_amount: i64, } impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> for types::RefundsRouterData<api::Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(types::RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> for types::RefundsRouterData<api::RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::RefundsResponseRouterData<api::RSync, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(types::RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct DummyConnectorErrorResponse { pub error: ErrorData, } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct ErrorData { pub code: String, pub message: String, pub reason: Option<String>, }
2,806
1,522
hyperswitch
crates/router/src/connector/threedsecureio/transformers.rs
.rs
use std::str::FromStr; use api_models::payments::{DeviceChannel, ThreeDsCompletionIndicator}; use base64::Engine; use common_utils::date_time; use error_stack::ResultExt; use hyperswitch_connectors::utils::AddressDetailsData; use iso_currency::Currency; use isocountry; use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use serde_json::{json, to_string}; use crate::{ connector::utils::{get_card_details, to_connector_meta, CardData}, consts::{BASE64_ENGINE, NO_ERROR_MESSAGE}, core::errors, types::{ self, api::{self, MessageCategory}, authentication::ChallengeParams, }, utils::OptionExt, }; pub struct ThreedsecureioRouterData<T> { pub amount: String, pub router_data: T, } impl<T> TryFrom<(&api::CurrencyUnit, types::storage::enums::Currency, i64, T)> for ThreedsecureioRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (_currency_unit, _currency, amount, item): ( &api::CurrencyUnit, types::storage::enums::Currency, i64, T, ), ) -> Result<Self, Self::Error> { Ok(Self { amount: amount.to_string(), router_data: item, }) } } impl<T> TryFrom<(i64, T)> for ThreedsecureioRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from((amount, router_data): (i64, T)) -> Result<Self, Self::Error> { Ok(Self { amount: amount.to_string(), router_data, }) } } impl TryFrom< types::ResponseRouterData< api::PreAuthentication, ThreedsecureioPreAuthenticationResponse, types::authentication::PreAuthNRequestData, types::authentication::AuthenticationResponseData, >, > for types::authentication::PreAuthNRouterData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::ResponseRouterData< api::PreAuthentication, ThreedsecureioPreAuthenticationResponse, types::authentication::PreAuthNRequestData, types::authentication::AuthenticationResponseData, >, ) -> Result<Self, Self::Error> { let response = match item.response { ThreedsecureioPreAuthenticationResponse::Success(pre_authn_response) => { let three_ds_method_data = json!({ "threeDSServerTransID": pre_authn_response.threeds_server_trans_id, }); let three_ds_method_data_str = to_string(&three_ds_method_data) .change_context(errors::ConnectorError::ResponseDeserializationFailed) .attach_printable("error while constructing three_ds_method_data_str")?; let three_ds_method_data_base64 = BASE64_ENGINE.encode(three_ds_method_data_str); let connector_metadata = serde_json::json!(ThreeDSecureIoConnectorMetaData { ds_start_protocol_version: pre_authn_response.ds_start_protocol_version, ds_end_protocol_version: pre_authn_response.ds_end_protocol_version, acs_start_protocol_version: pre_authn_response.acs_start_protocol_version, acs_end_protocol_version: pre_authn_response.acs_end_protocol_version.clone(), }); Ok( types::authentication::AuthenticationResponseData::PreAuthNResponse { threeds_server_transaction_id: pre_authn_response .threeds_server_trans_id .clone(), maximum_supported_3ds_version: common_utils::types::SemanticVersion::from_str( &pre_authn_response.acs_end_protocol_version, ) .change_context(errors::ConnectorError::ParsingFailed)?, connector_authentication_id: pre_authn_response.threeds_server_trans_id, three_ds_method_data: Some(three_ds_method_data_base64), three_ds_method_url: pre_authn_response.threeds_method_url, message_version: common_utils::types::SemanticVersion::from_str( &pre_authn_response.acs_end_protocol_version, ) .change_context(errors::ConnectorError::ParsingFailed)?, connector_metadata: Some(connector_metadata), directory_server_id: None, }, ) } ThreedsecureioPreAuthenticationResponse::Failure(error_response) => { Err(types::ErrorResponse { code: error_response.error_code, message: error_response .error_description .clone() .unwrap_or(NO_ERROR_MESSAGE.to_owned()), reason: error_response.error_description, status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, }) } }; Ok(Self { response, ..item.data.clone() }) } } impl TryFrom< types::ResponseRouterData< api::Authentication, ThreedsecureioAuthenticationResponse, types::authentication::ConnectorAuthenticationRequestData, types::authentication::AuthenticationResponseData, >, > for types::authentication::ConnectorAuthenticationRouterData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::ResponseRouterData< api::Authentication, ThreedsecureioAuthenticationResponse, types::authentication::ConnectorAuthenticationRequestData, types::authentication::AuthenticationResponseData, >, ) -> Result<Self, Self::Error> { let response = match item.response { ThreedsecureioAuthenticationResponse::Success(response) => { let creq = serde_json::json!({ "threeDSServerTransID": response.three_dsserver_trans_id, "acsTransID": response.acs_trans_id, "messageVersion": response.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(); Ok( types::authentication::AuthenticationResponseData::AuthNResponse { trans_status: response.trans_status.clone().into(), authn_flow_type: if response.trans_status == ThreedsecureioTransStatus::C { types::authentication::AuthNFlowType::Challenge(Box::new( ChallengeParams { acs_url: response.acs_url, challenge_request: Some(creq_base64), acs_reference_number: Some( response.acs_reference_number.clone(), ), acs_trans_id: Some(response.acs_trans_id.clone()), three_dsserver_trans_id: Some(response.three_dsserver_trans_id), acs_signed_content: response.acs_signed_content, }, )) } else { types::authentication::AuthNFlowType::Frictionless }, authentication_value: response.authentication_value, connector_metadata: None, ds_trans_id: Some(response.ds_trans_id), }, ) } ThreedsecureioAuthenticationResponse::Error(err_response) => match *err_response { ThreedsecureioErrorResponseWrapper::ErrorResponse(resp) => { Err(types::ErrorResponse { code: resp.error_code, message: resp .error_description .clone() .unwrap_or(NO_ERROR_MESSAGE.to_owned()), reason: resp.error_description, status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, }) } ThreedsecureioErrorResponseWrapper::ErrorString(error) => { Err(types::ErrorResponse { code: error.clone(), message: error.clone(), reason: Some(error), status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, }) } }, }; Ok(Self { response, ..item.data.clone() }) } } pub struct ThreedsecureioAuthType { pub(super) api_key: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for ThreedsecureioAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self { api_key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } impl TryFrom<&ThreedsecureioRouterData<&types::authentication::ConnectorAuthenticationRouterData>> for ThreedsecureioAuthenticationRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &ThreedsecureioRouterData<&types::authentication::ConnectorAuthenticationRouterData>, ) -> Result<Self, Self::Error> { let request = &item.router_data.request; //browser_details are mandatory for Browser flows 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(), "threedsecureio")?; let currency = request .currency .map(|currency| currency.to_string()) .ok_or(errors::ConnectorError::RequestEncodingFailed) .attach_printable("missing field currency")?; let purchase_currency: Currency = Currency::from_code(&currency) .ok_or(errors::ConnectorError::RequestEncodingFailed) .attach_printable("error while parsing Currency")?; let billing_address = request.billing_address.address.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "billing_address.address", }, )?; let billing_state = billing_address.clone().to_state_code()?; let billing_country = isocountry::CountryCode::for_alpha2( &billing_address .country .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "billing_address.address.country", })? .to_string(), ) .change_context(errors::ConnectorError::RequestEncodingFailed) .attach_printable("Error parsing billing_address.address.country")?; let connector_meta_data: ThreeDSecureIoMetaData = item .router_data .connector_meta_data .clone() .parse_value("ThreeDSecureIoMetaData") .change_context(errors::ConnectorError::RequestEncodingFailed)?; let pre_authentication_data = &request.pre_authentication_data; let sdk_information = match request.device_channel { DeviceChannel::App => Some(item.router_data.request.sdk_information.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "sdk_information", }, )?), DeviceChannel::Browser => None, }; let (acquirer_bin, acquirer_merchant_id) = pre_authentication_data .acquirer_bin .clone() .zip(pre_authentication_data.acquirer_merchant_id.clone()) .get_required_value("acquirer_details") .change_context(errors::ConnectorError::MissingRequiredField { field_name: "acquirer_details", })?; let meta: ThreeDSecureIoConnectorMetaData = to_connector_meta(request.pre_authentication_data.connector_metadata.clone())?; let card_holder_name = billing_address.get_optional_full_name(); Ok(Self { ds_start_protocol_version: meta.ds_start_protocol_version.clone(), ds_end_protocol_version: meta.ds_end_protocol_version.clone(), acs_start_protocol_version: meta.acs_start_protocol_version.clone(), acs_end_protocol_version: meta.acs_end_protocol_version.clone(), three_dsserver_trans_id: pre_authentication_data .threeds_server_transaction_id .clone(), acct_number: card_details.card_number.clone(), notification_url: request .return_url .clone() .ok_or(errors::ConnectorError::RequestEncodingFailed) .attach_printable("missing return_url")?, three_dscomp_ind: ThreeDSecureIoThreeDsCompletionIndicator::from( request.threeds_method_comp_ind.clone(), ), three_dsrequestor_url: request.three_ds_requestor_url.clone(), acquirer_bin, acquirer_merchant_id, card_expiry_date: card_details.get_expiry_date_as_yymm()?.expose(), bill_addr_city: billing_address .city .clone() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "billing_address.address.city", })? .to_string(), bill_addr_country: billing_country.numeric_id().to_string().into(), bill_addr_line1: billing_address.line1.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "billing_address.address.line1", }, )?, bill_addr_post_code: billing_address.zip.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "billing_address.address.zip", }, )?, bill_addr_state: billing_state, // Indicates the type of Authentication request, "01" for Payment transaction three_dsrequestor_authentication_ind: "01".to_string(), device_channel: match item.router_data.request.device_channel.clone() { DeviceChannel::App => "01", DeviceChannel::Browser => "02", } .to_string(), message_category: match item.router_data.request.message_category.clone() { MessageCategory::Payment => "01", MessageCategory::NonPayment => "02", } .to_string(), 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())), mcc: connector_meta_data.mcc, merchant_country_code: connector_meta_data.merchant_country_code, merchant_name: connector_meta_data.merchant_name, message_type: "AReq".to_string(), message_version: pre_authentication_data.message_version.to_string(), purchase_amount: item.amount.clone(), purchase_currency: purchase_currency.numeric().to_string(), trans_type: "01".to_string(), purchase_exponent: purchase_currency .exponent() .ok_or(errors::ConnectorError::RequestEncodingFailed) .attach_printable("missing purchase_exponent")? .to_string(), purchase_date: date_time::DateTime::<date_time::YYYYMMDDHHmmss>::from(date_time::now()) .to_string(), sdk_app_id: sdk_information .as_ref() .map(|sdk_info| sdk_info.sdk_app_id.clone()), sdk_enc_data: sdk_information .as_ref() .map(|sdk_info| sdk_info.sdk_enc_data.clone()), sdk_ephem_pub_key: sdk_information .as_ref() .map(|sdk_info| sdk_info.sdk_ephem_pub_key.clone()), sdk_reference_number: sdk_information .as_ref() .map(|sdk_info| sdk_info.sdk_reference_number.clone()), sdk_trans_id: sdk_information .as_ref() .map(|sdk_info| sdk_info.sdk_trans_id.clone()), sdk_max_timeout: sdk_information .as_ref() .map(|sdk_info| sdk_info.sdk_max_timeout.to_string()), device_render_options: match request.device_channel { DeviceChannel::App => Some(DeviceRenderOptions { // SDK Interface types that the device supports for displaying specific challenge user interfaces within the SDK, 01 for Native sdk_interface: "01".to_string(), // UI types that the device supports for displaying specific challenge user interfaces within the SDK, 01 for Text sdk_ui_type: vec!["01".to_string()], }), DeviceChannel::Browser => None, }, cardholder_name: card_holder_name, email: request.email.clone(), }) } } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ThreedsecureioErrorResponse { pub error_code: String, pub error_component: Option<String>, pub error_description: Option<String>, pub error_detail: Option<String>, pub error_message_type: Option<String>, pub message_type: Option<String>, pub message_version: Option<String>, pub three_dsserver_trans_id: Option<String>, } #[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum ThreedsecureioErrorResponseWrapper { ErrorResponse(ThreedsecureioErrorResponse), ErrorString(String), } #[derive(Debug, Serialize, Deserialize)] #[serde(untagged)] pub enum ThreedsecureioAuthenticationResponse { Success(Box<ThreedsecureioAuthenticationSuccessResponse>), Error(Box<ThreedsecureioErrorResponseWrapper>), } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ThreedsecureioAuthenticationSuccessResponse { #[serde(rename = "acsChallengeMandated")] pub acs_challenge_mandated: Option<String>, #[serde(rename = "acsOperatorID")] pub acs_operator_id: Option<String>, #[serde(rename = "acsReferenceNumber")] pub acs_reference_number: String, #[serde(rename = "acsTransID")] pub acs_trans_id: String, #[serde(rename = "acsURL")] pub acs_url: Option<url::Url>, #[serde(rename = "authenticationType")] pub authentication_type: Option<String>, #[serde(rename = "dsReferenceNumber")] pub ds_reference_number: String, #[serde(rename = "dsTransID")] pub ds_trans_id: String, #[serde(rename = "messageType")] pub message_type: Option<String>, #[serde(rename = "messageVersion")] pub message_version: String, #[serde(rename = "threeDSServerTransID")] pub three_dsserver_trans_id: String, #[serde(rename = "transStatus")] pub trans_status: ThreedsecureioTransStatus, #[serde(rename = "acsSignedContent")] pub acs_signed_content: Option<String>, #[serde(rename = "authenticationValue")] pub authentication_value: Option<String>, } #[derive(Debug, Serialize, Deserialize)] pub enum ThreeDSecureIoThreeDsCompletionIndicator { Y, N, U, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ThreedsecureioAuthenticationRequest { pub ds_start_protocol_version: String, pub ds_end_protocol_version: String, pub acs_start_protocol_version: String, pub acs_end_protocol_version: String, pub three_dsserver_trans_id: String, pub acct_number: cards::CardNumber, pub notification_url: String, pub three_dscomp_ind: ThreeDSecureIoThreeDsCompletionIndicator, pub three_dsrequestor_url: String, pub acquirer_bin: String, pub acquirer_merchant_id: String, pub card_expiry_date: String, pub bill_addr_city: String, pub bill_addr_country: Secret<String>, pub bill_addr_line1: Secret<String>, pub bill_addr_post_code: Secret<String>, pub bill_addr_state: Secret<String>, pub email: Option<common_utils::pii::Email>, pub three_dsrequestor_authentication_ind: String, pub cardholder_name: Option<Secret<String>>, pub device_channel: String, pub browser_javascript_enabled: Option<bool>, pub browser_accept_header: Option<String>, pub browser_ip: Option<Secret<String, common_utils::pii::IpAddress>>, pub browser_java_enabled: Option<bool>, pub browser_language: Option<String>, pub browser_color_depth: Option<String>, pub browser_screen_height: Option<String>, pub browser_screen_width: Option<String>, pub browser_tz: Option<String>, pub browser_user_agent: Option<String>, pub sdk_app_id: Option<String>, pub sdk_enc_data: Option<String>, pub sdk_ephem_pub_key: Option<std::collections::HashMap<String, String>>, pub sdk_reference_number: Option<String>, pub sdk_trans_id: Option<String>, pub mcc: String, pub merchant_country_code: String, pub merchant_name: String, pub message_category: String, pub message_type: String, pub message_version: String, pub purchase_amount: String, pub purchase_currency: String, pub purchase_exponent: String, pub purchase_date: String, pub trans_type: String, pub sdk_max_timeout: Option<String>, pub device_render_options: Option<DeviceRenderOptions>, } #[derive(Debug, Serialize, Deserialize)] pub struct ThreeDSecureIoMetaData { pub mcc: String, pub merchant_country_code: String, pub merchant_name: String, } #[derive(Debug, Serialize, Deserialize)] pub struct ThreeDSecureIoConnectorMetaData { pub ds_start_protocol_version: String, pub ds_end_protocol_version: String, pub acs_start_protocol_version: String, pub acs_end_protocol_version: String, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct DeviceRenderOptions { pub sdk_interface: String, pub sdk_ui_type: Vec<String>, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ThreedsecureioPreAuthenticationRequest { acct_number: cards::CardNumber, ds: Option<DirectoryServer>, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ThreedsecureioPostAuthenticationRequest { pub three_ds_server_trans_id: String, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ThreedsecureioPostAuthenticationResponse { pub authentication_value: Option<String>, pub trans_status: ThreedsecureioTransStatus, pub eci: Option<String>, } #[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)] pub enum ThreedsecureioTransStatus { /// Authentication/ Account Verification Successful Y, /// Not Authenticated /Account Not Verified; Transaction denied N, /// Authentication/ Account Verification Could Not Be Performed; Technical or other problem, as indicated in ARes or RReq U, /// Attempts Processing Performed; Not Authenticated/Verified , but a proof of attempted authentication/verification is provided A, /// Authentication/ Account Verification Rejected; Issuer is rejecting authentication/verification and request that authorisation not be attempted. R, C, } impl From<ThreeDsCompletionIndicator> for ThreeDSecureIoThreeDsCompletionIndicator { fn from(value: ThreeDsCompletionIndicator) -> Self { match value { ThreeDsCompletionIndicator::Success => Self::Y, ThreeDsCompletionIndicator::Failure => Self::N, ThreeDsCompletionIndicator::NotAvailable => Self::U, } } } impl From<ThreedsecureioTransStatus> for common_enums::TransactionStatus { fn from(value: ThreedsecureioTransStatus) -> Self { match value { ThreedsecureioTransStatus::Y => Self::Success, ThreedsecureioTransStatus::N => Self::Failure, ThreedsecureioTransStatus::U => Self::VerificationNotPerformed, ThreedsecureioTransStatus::A => Self::NotVerified, ThreedsecureioTransStatus::R => Self::Rejected, ThreedsecureioTransStatus::C => Self::ChallengeRequired, } } } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum DirectoryServer { Standin, Visa, Mastercard, Jcb, Upi, Amex, Protectbuy, Sbn, } #[derive(Debug, Deserialize, Serialize)] #[serde(untagged)] pub enum ThreedsecureioPreAuthenticationResponse { Success(Box<ThreedsecureioPreAuthenticationResponseData>), Failure(Box<ThreedsecureioErrorResponse>), } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ThreedsecureioPreAuthenticationResponseData { pub ds_start_protocol_version: String, pub ds_end_protocol_version: String, pub acs_start_protocol_version: String, pub acs_end_protocol_version: String, #[serde(rename = "threeDSMethodURL")] pub threeds_method_url: Option<String>, #[serde(rename = "threeDSServerTransID")] pub threeds_server_trans_id: String, pub scheme: Option<String>, pub message_type: Option<String>, } impl TryFrom<&ThreedsecureioRouterData<&types::authentication::PreAuthNRouterData>> for ThreedsecureioPreAuthenticationRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( value: &ThreedsecureioRouterData<&types::authentication::PreAuthNRouterData>, ) -> Result<Self, Self::Error> { let router_data = value.router_data; Ok(Self { acct_number: router_data.request.card.card_number.clone(), ds: None, }) } }
5,782
1,523
hyperswitch
crates/router/src/connector/riskified/transformers.rs
.rs
#[cfg(feature = "frm")] pub mod api; pub mod auth; #[cfg(feature = "frm")] pub use self::api::*; pub use self::auth::*;
34
1,524
hyperswitch
crates/router/src/connector/riskified/transformers/api.rs
.rs
use api_models::payments::AdditionalPaymentData; use common_utils::{ ext_traits::ValueExt, id_type, pii::Email, types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector}, }; use error_stack::{self, ResultExt}; use masking::Secret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{ connector::utils::{ convert_amount, AddressDetailsData, FraudCheckCheckoutRequest, FraudCheckTransactionRequest, RouterData, }, core::{errors, fraud_check::types as core_types}, types::{ self, api::{self, Fulfillment}, fraud_check as frm_types, storage::enums as storage_enums, ResponseId, ResponseRouterData, }, }; type Error = error_stack::Report<errors::ConnectorError>; pub struct RiskifiedRouterData<T> { pub amount: StringMajorUnit, pub router_data: T, amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), } impl<T> From<(StringMajorUnit, T)> for RiskifiedRouterData<T> { fn from((amount, router_data): (StringMajorUnit, T)) -> Self { Self { amount, router_data, amount_converter: &StringMajorUnitForConnector, } } } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct RiskifiedPaymentsCheckoutRequest { order: CheckoutRequest, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct CheckoutRequest { id: String, note: Option<String>, email: Option<Email>, #[serde(with = "common_utils::custom_serde::iso8601")] created_at: PrimitiveDateTime, currency: Option<common_enums::Currency>, #[serde(with = "common_utils::custom_serde::iso8601")] updated_at: PrimitiveDateTime, gateway: Option<String>, browser_ip: Option<std::net::IpAddr>, total_price: StringMajorUnit, total_discounts: i64, cart_token: String, referring_site: String, line_items: Vec<LineItem>, discount_codes: Vec<DiscountCodes>, shipping_lines: Vec<ShippingLines>, payment_details: Option<PaymentDetails>, customer: RiskifiedCustomer, billing_address: Option<OrderAddress>, shipping_address: Option<OrderAddress>, source: Source, client_details: ClientDetails, vendor_name: String, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct PaymentDetails { credit_card_bin: Option<Secret<String>>, credit_card_number: Option<Secret<String>>, credit_card_company: Option<api_models::enums::CardNetwork>, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct ShippingLines { price: StringMajorUnit, title: Option<String>, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct DiscountCodes { amount: StringMajorUnit, code: Option<String>, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct ClientDetails { user_agent: Option<String>, accept_language: Option<String>, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct RiskifiedCustomer { email: Option<Email>, first_name: Option<Secret<String>>, last_name: Option<Secret<String>>, #[serde(with = "common_utils::custom_serde::iso8601")] created_at: PrimitiveDateTime, verified_email: bool, id: id_type::CustomerId, account_type: CustomerAccountType, orders_count: i32, phone: Option<Secret<String>>, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] #[serde(rename_all = "lowercase")] pub enum CustomerAccountType { Guest, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct OrderAddress { first_name: Option<Secret<String>>, last_name: Option<Secret<String>>, address1: Option<Secret<String>>, country_code: Option<common_enums::CountryAlpha2>, city: Option<String>, province: Option<Secret<String>>, phone: Option<Secret<String>>, zip: Option<Secret<String>>, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct LineItem { price: StringMajorUnit, quantity: i32, title: String, product_type: Option<common_enums::ProductType>, requires_shipping: Option<bool>, product_id: Option<String>, category: Option<String>, brand: Option<String>, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] #[serde(rename_all = "snake_case")] pub enum Source { DesktopWeb, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct RiskifiedMetadata { vendor_name: String, shipping_lines: Vec<ShippingLines>, } impl TryFrom<&RiskifiedRouterData<&frm_types::FrmCheckoutRouterData>> for RiskifiedPaymentsCheckoutRequest { type Error = Error; fn try_from( payment: &RiskifiedRouterData<&frm_types::FrmCheckoutRouterData>, ) -> Result<Self, Self::Error> { let payment_data = payment.router_data.clone(); let metadata: RiskifiedMetadata = payment_data .frm_metadata .clone() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "frm_metadata", })? .parse_value("Riskified Metadata") .change_context(errors::ConnectorError::InvalidDataFormat { field_name: "frm_metadata", })?; let billing_address = payment_data.get_billing()?; let shipping_address = payment_data.get_shipping_address_with_phone_number()?; let address = payment_data.get_billing_address()?; let line_items = payment_data .request .get_order_details()? .iter() .map(|order_detail| { let price = convert_amount( payment.amount_converter, order_detail.amount, payment_data.request.currency.ok_or_else(|| { errors::ConnectorError::MissingRequiredField { field_name: "currency", } })?, )?; Ok(LineItem { price, quantity: i32::from(order_detail.quantity), title: order_detail.product_name.clone(), product_type: order_detail.product_type.clone(), requires_shipping: order_detail.requires_shipping, product_id: order_detail.product_id.clone(), category: order_detail.category.clone(), brand: order_detail.brand.clone(), }) }) .collect::<Result<Vec<_>, Self::Error>>()?; Ok(Self { order: CheckoutRequest { id: payment_data.attempt_id.clone(), email: payment_data.request.email.clone(), created_at: common_utils::date_time::now(), updated_at: common_utils::date_time::now(), gateway: payment_data.request.gateway.clone(), total_price: payment.amount.clone(), cart_token: payment_data.attempt_id.clone(), line_items, source: Source::DesktopWeb, billing_address: OrderAddress::try_from(billing_address).ok(), shipping_address: OrderAddress::try_from(shipping_address).ok(), total_discounts: 0, currency: payment_data.request.currency, referring_site: "hyperswitch.io".to_owned(), discount_codes: Vec::new(), shipping_lines: metadata.shipping_lines, customer: RiskifiedCustomer { email: payment_data.request.email.clone(), first_name: address.get_first_name().ok().cloned(), last_name: address.get_last_name().ok().cloned(), created_at: common_utils::date_time::now(), verified_email: false, id: payment_data.get_customer_id()?, account_type: CustomerAccountType::Guest, orders_count: 0, phone: billing_address .clone() .phone .and_then(|phone_data| phone_data.number), }, browser_ip: payment_data .request .browser_info .as_ref() .and_then(|browser_info| browser_info.ip_address), client_details: ClientDetails { user_agent: payment_data .request .browser_info .as_ref() .and_then(|browser_info| browser_info.user_agent.clone()), accept_language: payment_data.request.browser_info.as_ref().and_then( |browser_info: &types::BrowserInformation| browser_info.language.clone(), ), }, note: payment_data.description.clone(), vendor_name: metadata.vendor_name, payment_details: match payment_data.request.payment_method_data.as_ref() { Some(AdditionalPaymentData::Card(card_info)) => Some(PaymentDetails { credit_card_bin: card_info.card_isin.clone().map(Secret::new), credit_card_number: card_info .last4 .clone() .map(|last_four| format!("XXXX-XXXX-XXXX-{}", last_four)) .map(Secret::new), credit_card_company: card_info.card_network.clone(), }), Some(_) | None => None, }, }, }) } } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct RiskifiedPaymentsResponse { order: OrderResponse, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct OrderResponse { id: String, status: PaymentStatus, description: Option<String>, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct RiskifiedFulfilmentResponse { order: OrderFulfilmentResponse, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct OrderFulfilmentResponse { id: String, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] #[serde(rename_all = "lowercase")] pub enum FulfilmentStatus { Fulfilled, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] #[serde(rename_all = "lowercase")] pub enum PaymentStatus { Captured, Created, Submitted, Approved, Declined, Processing, } impl<F, T> TryFrom<ResponseRouterData<F, RiskifiedPaymentsResponse, T, frm_types::FraudCheckResponseData>> for types::RouterData<F, T, frm_types::FraudCheckResponseData> { type Error = Error; fn try_from( item: ResponseRouterData< F, RiskifiedPaymentsResponse, T, frm_types::FraudCheckResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(frm_types::FraudCheckResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.order.id), status: storage_enums::FraudCheckStatus::from(item.response.order.status), connector_metadata: None, score: None, reason: item.response.order.description.map(serde_json::Value::from), }), ..item.data }) } } impl From<PaymentStatus> for storage_enums::FraudCheckStatus { fn from(item: PaymentStatus) -> Self { match item { PaymentStatus::Approved => Self::Legit, PaymentStatus::Declined => Self::Fraud, _ => Self::Pending, } } } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct TransactionFailedRequest { checkout: FailedTransactionData, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct FailedTransactionData { id: String, payment_details: Vec<DeclinedPaymentDetails>, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct DeclinedPaymentDetails { authorization_error: AuthorizationError, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct AuthorizationError { #[serde(with = "common_utils::custom_serde::iso8601")] created_at: PrimitiveDateTime, error_code: Option<String>, message: Option<String>, } impl TryFrom<&frm_types::FrmTransactionRouterData> for TransactionFailedRequest { type Error = Error; fn try_from(item: &frm_types::FrmTransactionRouterData) -> Result<Self, Self::Error> { Ok(Self { checkout: FailedTransactionData { id: item.attempt_id.clone(), payment_details: [DeclinedPaymentDetails { authorization_error: AuthorizationError { created_at: common_utils::date_time::now(), error_code: item.request.error_code.clone(), message: item.request.error_message.clone(), }, }] .to_vec(), }, }) } } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct RiskifiedFailedTransactionResponse { checkout: OrderResponse, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] #[serde(untagged)] pub enum RiskifiedTransactionResponse { FailedResponse(RiskifiedFailedTransactionResponse), SuccessResponse(RiskifiedPaymentsResponse), } impl<F, T> TryFrom< ResponseRouterData< F, RiskifiedFailedTransactionResponse, T, frm_types::FraudCheckResponseData, >, > for types::RouterData<F, T, frm_types::FraudCheckResponseData> { type Error = Error; fn try_from( item: ResponseRouterData< F, RiskifiedFailedTransactionResponse, T, frm_types::FraudCheckResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(frm_types::FraudCheckResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.checkout.id), status: storage_enums::FraudCheckStatus::from(item.response.checkout.status), connector_metadata: None, score: None, reason: item .response .checkout .description .map(serde_json::Value::from), }), ..item.data }) } } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct TransactionSuccessRequest { order: SuccessfulTransactionData, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct SuccessfulTransactionData { id: String, decision: TransactionDecisionData, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct TransactionDecisionData { external_status: TransactionStatus, reason: Option<String>, amount: StringMajorUnit, currency: storage_enums::Currency, #[serde(with = "common_utils::custom_serde::iso8601")] decided_at: PrimitiveDateTime, payment_details: Vec<TransactionPaymentDetails>, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct TransactionPaymentDetails { authorization_id: Option<String>, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] #[serde(rename_all = "lowercase")] pub enum TransactionStatus { Approved, } impl TryFrom<&RiskifiedRouterData<&frm_types::FrmTransactionRouterData>> for TransactionSuccessRequest { type Error = Error; fn try_from( item_data: &RiskifiedRouterData<&frm_types::FrmTransactionRouterData>, ) -> Result<Self, Self::Error> { let item = item_data.router_data.clone(); Ok(Self { order: SuccessfulTransactionData { id: item.attempt_id.clone(), decision: TransactionDecisionData { external_status: TransactionStatus::Approved, reason: None, amount: item_data.amount.clone(), currency: item.request.get_currency()?, decided_at: common_utils::date_time::now(), payment_details: [TransactionPaymentDetails { authorization_id: item.request.connector_transaction_id.clone(), }] .to_vec(), }, }, }) } } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct RiskifiedFulfillmentRequest { order: OrderFulfillment, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] #[serde(rename_all = "lowercase")] pub enum FulfillmentRequestStatus { Success, Cancelled, Error, Failure, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct OrderFulfillment { id: String, fulfillments: FulfilmentData, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct FulfilmentData { fulfillment_id: String, #[serde(with = "common_utils::custom_serde::iso8601")] created_at: PrimitiveDateTime, status: Option<FulfillmentRequestStatus>, tracking_company: String, tracking_number: String, tracking_url: Option<String>, } impl TryFrom<&frm_types::FrmFulfillmentRouterData> for RiskifiedFulfillmentRequest { type Error = Error; fn try_from(item: &frm_types::FrmFulfillmentRouterData) -> Result<Self, Self::Error> { let tracking_number = item .request .fulfillment_req .tracking_numbers .as_ref() .and_then(|numbers| numbers.first().cloned()) .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "tracking_number", })?; let tracking_url = item .request .fulfillment_req .tracking_urls .as_ref() .and_then(|urls| urls.first().cloned().map(|url| url.to_string())); Ok(Self { order: OrderFulfillment { id: item.attempt_id.clone(), fulfillments: FulfilmentData { fulfillment_id: item.payment_id.clone(), created_at: common_utils::date_time::now(), status: item .request .fulfillment_req .fulfillment_status .clone() .and_then(get_fulfillment_status), tracking_company: item .request .fulfillment_req .tracking_company .clone() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "tracking_company", })?, tracking_number, tracking_url, }, }, }) } } impl TryFrom< ResponseRouterData< Fulfillment, RiskifiedFulfilmentResponse, frm_types::FraudCheckFulfillmentData, frm_types::FraudCheckResponseData, >, > for types::RouterData< Fulfillment, frm_types::FraudCheckFulfillmentData, frm_types::FraudCheckResponseData, > { type Error = Error; fn try_from( item: ResponseRouterData< Fulfillment, RiskifiedFulfilmentResponse, frm_types::FraudCheckFulfillmentData, frm_types::FraudCheckResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(frm_types::FraudCheckResponseData::FulfillmentResponse { order_id: item.response.order.id, shipment_ids: Vec::new(), }), ..item.data }) } } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct ErrorResponse { pub error: ErrorData, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct ErrorData { pub message: String, } impl TryFrom<&hyperswitch_domain_models::address::Address> for OrderAddress { type Error = Error; fn try_from( address_info: &hyperswitch_domain_models::address::Address, ) -> Result<Self, Self::Error> { let address = address_info .clone() .address .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "address", })?; Ok(Self { first_name: address.first_name.clone(), last_name: address.last_name.clone(), address1: address.line1.clone(), country_code: address.country, city: address.city.clone(), province: address.state.clone(), zip: address.zip.clone(), phone: address_info .phone .clone() .and_then(|phone_data| phone_data.number), }) } } fn get_fulfillment_status( status: core_types::FulfillmentStatus, ) -> Option<FulfillmentRequestStatus> { match status { core_types::FulfillmentStatus::COMPLETE => Some(FulfillmentRequestStatus::Success), core_types::FulfillmentStatus::CANCELED => Some(FulfillmentRequestStatus::Cancelled), core_types::FulfillmentStatus::PARTIAL | core_types::FulfillmentStatus::REPLACEMENT => None, } } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct RiskifiedWebhookBody { pub id: String, pub status: RiskifiedWebhookStatus, } #[derive(Debug, Clone, Deserialize, Serialize)] pub enum RiskifiedWebhookStatus { Approved, Declined, } impl From<RiskifiedWebhookStatus> for api::IncomingWebhookEvent { fn from(value: RiskifiedWebhookStatus) -> Self { match value { RiskifiedWebhookStatus::Declined => Self::FrmRejected, RiskifiedWebhookStatus::Approved => Self::FrmApproved, } } }
4,621
1,525
hyperswitch
crates/router/src/connector/riskified/transformers/auth.rs
.rs
use error_stack; use masking::{ExposeInterface, Secret}; use crate::{core::errors, types}; pub struct RiskifiedAuthType { pub secret_token: Secret<String>, pub domain_name: String, } impl TryFrom<&types::ConnectorAuthType> for RiskifiedAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { secret_token: api_key.to_owned(), domain_name: key1.to_owned().expose(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } }
167
1,526
hyperswitch
crates/router/src/connector/gpayments/gpayments_types.rs
.rs
use api_models::payments::ThreeDsCompletionIndicator; use cards::CardNumber; use common_utils::types; use masking::{Deserialize, Secret, Serialize}; #[derive(Debug, Serialize, Deserialize)] pub struct GpaymentsConnectorMetaData { pub authentication_url: String, pub three_ds_requestor_trans_id: Option<String>, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct GpaymentsPreAuthVersionCallRequest { pub acct_number: CardNumber, pub merchant_id: common_utils::id_type::MerchantId, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct GpaymentsPreAuthVersionCallResponse { pub enrolment_status: EnrollmentStatus, pub supported_message_versions: Option<Vec<types::SemanticVersion>>, } #[derive(Serialize, Deserialize, Debug, Clone)] pub enum EnrollmentStatus { #[serde(rename = "00")] NotEnrolled, #[serde(rename = "01")] Enrolled, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct TDS2ApiError { pub error_code: String, pub error_component: Option<String>, pub error_description: String, pub error_detail: Option<String>, pub error_message_type: Option<String>, /// Always returns 'Error' to indicate that this message is an error. /// /// Example: "Error" pub message_type: String, pub message_version: Option<String>, #[serde(rename = "sdkTransID")] pub sdk_trans_id: Option<String>, #[serde(rename = "threeDSServerTransID")] pub three_ds_server_trans_id: Option<String>, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct GpaymentsPreAuthenticationRequest { pub acct_number: CardNumber, pub card_scheme: Option<CardScheme>, pub challenge_window_size: Option<ChallengeWindowSize>, /// URL where the 3DS requestor receives events during authentication. /// ActiveServer calls this URL through the iframe to notify events occurring during authentication. /// /// Example: "https://example.requestor.com/3ds-notify" /// Length: Maximum 2000 characters pub event_callback_url: String, /// Merchant identifier assigned by the acquirer. /// This may be the same value used in authorization requests sent on behalf of the 3DS Requestor. /// /// Example: "1234567890123456789012345678901234" /// Length: Maximum 35 characters pub merchant_id: common_utils::id_type::MerchantId, /// Optional boolean. If set to true, ActiveServer will not collect the browser information automatically. /// The requestor must have a backend implementation to collect browser information. pub skip_auto_browser_info_collect: Option<bool>, /// Universal unique transaction identifier assigned by the 3DS Requestor to identify a single transaction. /// /// Example: "6afa6072-9412-446b-9673-2f98b3ee98a2" /// Length: 36 characters #[serde(rename = "threeDSRequestorTransID")] pub three_ds_requestor_trans_id: String, } #[derive(Serialize, Deserialize, Debug, Clone)] pub enum ChallengeWindowSize { #[serde(rename = "01")] Size250x400, #[serde(rename = "02")] Size390x400, #[serde(rename = "03")] Size500x600, #[serde(rename = "04")] Size600x400, #[serde(rename = "05")] FullScreen, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "UPPERCASE")] pub enum CardScheme { Visa, MasterCard, AmericanExpress, JCB, Discover, UnionPay, Mir, Eftpos, BCard, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct GpaymentsPreAuthenticationResponse { pub auth_url: String, pub mon_url: Option<String>, pub resolved_card_scheme: Option<CardScheme>, #[serde(rename = "threeDSMethodAvailable")] pub three_ds_method_available: Option<bool>, #[serde(rename = "threeDSMethodUrl")] pub three_ds_method_url: Option<String>, #[serde(rename = "threeDSServerCallbackUrl")] pub three_ds_server_callback_url: Option<String>, #[serde(rename = "threeDSServerTransID")] pub three_ds_server_trans_id: String, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct GpaymentsAuthenticationRequest { pub acct_number: CardNumber, pub authentication_ind: String, pub browser_info_collected: BrowserInfoCollected, pub card_expiry_date: String, #[serde(rename = "notificationURL")] pub notification_url: String, pub merchant_id: common_utils::id_type::MerchantId, #[serde(rename = "threeDSCompInd")] pub three_ds_comp_ind: ThreeDsCompletionIndicator, pub message_category: String, pub purchase_amount: String, pub purchase_date: String, #[serde(rename = "threeDSServerTransID")] pub three_ds_server_trans_id: String, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct BrowserInfoCollected { pub browser_accept_header: Option<String>, pub browser_color_depth: Option<String>, #[serde(rename = "browserIP")] pub browser_ip: Option<Secret<String, common_utils::pii::IpAddress>>, pub browser_javascript_enabled: Option<bool>, pub browser_java_enabled: Option<bool>, pub browser_language: Option<String>, pub browser_screen_height: Option<String>, pub browser_screen_width: Option<String>, #[serde(rename = "browserTZ")] pub browser_tz: Option<String>, pub browser_user_agent: Option<String>, } #[derive(Serialize, Deserialize, Debug, Clone)] pub enum AuthenticationInd { #[serde(rename = "01")] PaymentTransaction, #[serde(rename = "02")] RecurringTransaction, #[serde(rename = "03")] InstalmentTransaction, #[serde(rename = "04")] AddCard, #[serde(rename = "05")] MaintainCard, #[serde(rename = "06")] CardholderVerification, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct GpaymentsAuthenticationSuccessResponse { #[serde(rename = "dsReferenceNumber")] pub ds_reference_number: String, #[serde(rename = "dsTransID")] pub ds_trans_id: String, #[serde(rename = "threeDSServerTransID")] pub three_ds_server_trans_id: String, #[serde(rename = "messageVersion")] pub message_version: String, #[serde(rename = "transStatus")] pub trans_status: AuthStatus, #[serde(rename = "acsTransID")] pub acs_trans_id: String, #[serde(rename = "challengeUrl")] pub acs_url: Option<url::Url>, #[serde(rename = "acsReferenceNumber")] pub acs_reference_number: String, pub authentication_value: Option<String>, } #[derive(Deserialize, Debug, Clone, Serialize, PartialEq)] pub enum AuthStatus { /// Authentication/ Account Verification Successful Y, /// Not Authenticated /Account Not Verified; Transaction denied N, /// Authentication/ Account Verification Could Not Be Performed; Technical or other problem, as indicated in ARes or RReq U, /// Attempts Processing Performed; Not Authenticated/Verified , but a proof of attempted authentication/verification is provided A, /// Authentication/ Account Verification Rejected; Issuer is rejecting authentication/verification and request that authorisation not be attempted. R, /// Challenge required C, } impl From<AuthStatus> for common_enums::TransactionStatus { fn from(value: AuthStatus) -> Self { match value { AuthStatus::Y => Self::Success, AuthStatus::N => Self::Failure, AuthStatus::U => Self::VerificationNotPerformed, AuthStatus::A => Self::NotVerified, AuthStatus::R => Self::Rejected, AuthStatus::C => Self::ChallengeRequired, } } } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct GpaymentsPostAuthenticationResponse { pub authentication_value: Option<String>, pub trans_status: AuthStatus, pub eci: Option<String>, }
1,925
1,527
hyperswitch
crates/router/src/connector/gpayments/transformers.rs
.rs
use api_models::payments::DeviceChannel; use base64::Engine; use common_utils::{date_time, types::MinorUnit}; use error_stack::ResultExt; use masking::{ExposeInterface, Secret}; use serde::Deserialize; use serde_json::to_string; use super::gpayments_types; 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}, }; pub struct GpaymentsRouterData<T> { pub amount: MinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. pub router_data: T, } impl<T> From<(MinorUnit, T)> for GpaymentsRouterData<T> { fn from((amount, item): (MinorUnit, T)) -> Self { Self { amount, router_data: item, } } } // Auth Struct pub struct GpaymentsAuthType { /// base64 encoded certificate pub certificate: Secret<String>, /// base64 encoded private_key pub private_key: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for GpaymentsAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type.to_owned() { types::ConnectorAuthType::CertificateAuth { certificate, private_key, } => Ok(Self { certificate, private_key, }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } impl TryFrom<&GpaymentsRouterData<&types::authentication::PreAuthNVersionCallRouterData>> for gpayments_types::GpaymentsPreAuthVersionCallRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( value: &GpaymentsRouterData<&types::authentication::PreAuthNVersionCallRouterData>, ) -> 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(), merchant_id: metadata.merchant_id, }) } } #[derive(Deserialize, PartialEq)] pub struct GpaymentsMetaData { pub endpoint_prefix: String, pub merchant_id: common_utils::id_type::MerchantId, } impl TryFrom<&Option<common_utils::pii::SecretSerdeValue>> for GpaymentsMetaData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( meta_data: &Option<common_utils::pii::SecretSerdeValue>, ) -> Result<Self, Self::Error> { let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone()) .change_context(errors::ConnectorError::InvalidConnectorConfig { config: "metadata", })?; Ok(metadata) } } impl TryFrom< types::ResponseRouterData< api::PreAuthenticationVersionCall, gpayments_types::GpaymentsPreAuthVersionCallResponse, types::authentication::PreAuthNRequestData, types::authentication::AuthenticationResponseData, >, > for types::authentication::PreAuthNVersionCallRouterData { type Error = error_stack::Report<errors::ConnectorError>; 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() }) } } impl TryFrom<&GpaymentsRouterData<&types::authentication::PreAuthNRouterData>> for gpayments_types::GpaymentsPreAuthenticationRequest { type Error = error_stack::Report<errors::ConnectorError>; 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(), }) } } impl TryFrom<&GpaymentsRouterData<&types::authentication::ConnectorAuthenticationRouterData>> for gpayments_types::GpaymentsAuthenticationRequest { type Error = error_stack::Report<errors::ConnectorError>; 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())), }, }) } } impl TryFrom< types::ResponseRouterData< api::Authentication, GpaymentsAuthenticationSuccessResponse, types::authentication::ConnectorAuthenticationRequestData, types::authentication::AuthenticationResponseData, >, > for types::authentication::ConnectorAuthenticationRouterData { type Error = error_stack::Report<errors::ConnectorError>; 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() }) } } impl TryFrom< types::ResponseRouterData< api::PreAuthentication, gpayments_types::GpaymentsPreAuthenticationResponse, types::authentication::PreAuthNRequestData, types::authentication::AuthenticationResponseData, >, > for types::authentication::PreAuthNRouterData { type Error = error_stack::Report<errors::ConnectorError>; 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() }) } }
2,978
1,528
hyperswitch
crates/router/src/utils/storage_partitioning.rs
.rs
pub use storage_impl::redis::kv_store::{KvStorePartition, PartitionKey};
18
1,529
hyperswitch
crates/router/src/utils/connector_onboarding.rs
.rs
use diesel_models::{ConfigNew, ConfigUpdate}; use error_stack::ResultExt; use super::errors::StorageErrorExt; use crate::{ consts, core::errors::{ApiErrorResponse, NotImplementedMessage, RouterResult}, routes::{app::settings, SessionState}, types::{self, api::enums}, }; pub mod paypal; pub fn get_connector_auth( connector: enums::Connector, connector_data: &settings::ConnectorOnboarding, ) -> RouterResult<types::ConnectorAuthType> { match connector { enums::Connector::Paypal => Ok(types::ConnectorAuthType::BodyKey { api_key: connector_data.paypal.client_secret.clone(), key1: connector_data.paypal.client_id.clone(), }), _ => Err(ApiErrorResponse::NotImplemented { message: NotImplementedMessage::Reason(format!( "Onboarding is not implemented for {}", connector )), } .into()), } } pub fn is_enabled( connector: types::Connector, conf: &settings::ConnectorOnboarding, ) -> Option<bool> { match connector { enums::Connector::Paypal => Some(conf.paypal.enabled), _ => None, } } pub async fn check_if_connector_exists( state: &SessionState, connector_id: &common_utils::id_type::MerchantConnectorAccountId, merchant_id: &common_utils::id_type::MerchantId, ) -> RouterResult<()> { let key_manager_state = &state.into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .to_not_found_response(ApiErrorResponse::MerchantAccountNotFound)?; #[cfg(feature = "v1")] let _connector = state .store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_id, connector_id, &key_store, ) .await .to_not_found_response(ApiErrorResponse::MerchantConnectorAccountNotFound { id: connector_id.get_string_repr().to_string(), })?; #[cfg(feature = "v2")] { let _ = connector_id; let _ = key_store; todo!() }; Ok(()) } pub async fn set_tracking_id_in_configs( state: &SessionState, connector_id: &common_utils::id_type::MerchantConnectorAccountId, connector: enums::Connector, ) -> RouterResult<()> { let timestamp = common_utils::date_time::now_unix_timestamp().to_string(); let find_config = state .store .find_config_by_key(&build_key(connector_id, connector)) .await; if find_config.is_ok() { state .store .update_config_by_key( &build_key(connector_id, connector), ConfigUpdate::Update { config: Some(timestamp), }, ) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Error updating data in configs table")?; } else if find_config .as_ref() .map_err(|e| e.current_context().is_db_not_found()) .err() .unwrap_or(false) { state .store .insert_config(ConfigNew { key: build_key(connector_id, connector), config: timestamp, }) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Error inserting data in configs table")?; } else { find_config.change_context(ApiErrorResponse::InternalServerError)?; } Ok(()) } pub async fn get_tracking_id_from_configs( state: &SessionState, connector_id: &common_utils::id_type::MerchantConnectorAccountId, connector: enums::Connector, ) -> RouterResult<String> { let timestamp = state .store .find_config_by_key_unwrap_or( &build_key(connector_id, connector), Some(common_utils::date_time::now_unix_timestamp().to_string()), ) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Error getting data from configs table")? .config; Ok(format!("{}_{}", connector_id.get_string_repr(), timestamp)) } fn build_key( connector_id: &common_utils::id_type::MerchantConnectorAccountId, connector: enums::Connector, ) -> String { format!( "{}_{}_{}", consts::CONNECTOR_ONBOARDING_CONFIG_PREFIX, connector, connector_id.get_string_repr(), ) }
985
1,530
hyperswitch
crates/router/src/utils/currency.rs
.rs
use std::{collections::HashMap, ops::Deref, str::FromStr, sync::Arc}; use api_models::enums; use common_utils::{date_time, errors::CustomResult, events::ApiEventMetric, ext_traits::AsyncExt}; use currency_conversion::types::{CurrencyFactors, ExchangeRates}; use error_stack::ResultExt; use masking::PeekInterface; use once_cell::sync::Lazy; use redis_interface::DelReply; use router_env::{instrument, tracing}; use rust_decimal::Decimal; use strum::IntoEnumIterator; use tokio::sync::RwLock; use tracing_futures::Instrument; use crate::{ logger, routes::app::settings::{Conversion, DefaultExchangeRates}, services, SessionState, }; const REDIX_FOREX_CACHE_KEY: &str = "{forex_cache}_lock"; const REDIX_FOREX_CACHE_DATA: &str = "{forex_cache}_data"; const FOREX_API_TIMEOUT: u64 = 5; const FOREX_BASE_URL: &str = "https://openexchangerates.org/api/latest.json?app_id="; const FOREX_BASE_CURRENCY: &str = "&base=USD"; const FALLBACK_FOREX_BASE_URL: &str = "http://apilayer.net/api/live?access_key="; const FALLBACK_FOREX_API_CURRENCY_PREFIX: &str = "USD"; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct FxExchangeRatesCacheEntry { pub data: Arc<ExchangeRates>, timestamp: i64, } static FX_EXCHANGE_RATES_CACHE: Lazy<RwLock<Option<FxExchangeRatesCacheEntry>>> = Lazy::new(|| RwLock::new(None)); impl ApiEventMetric for FxExchangeRatesCacheEntry {} #[derive(Debug, Clone, thiserror::Error)] pub enum ForexError { #[error("API error")] ApiError, #[error("API timeout")] ApiTimeout, #[error("API unresponsive")] ApiUnresponsive, #[error("Conversion error")] ConversionError, #[error("Could not acquire the lock for cache entry")] CouldNotAcquireLock, #[error("Provided currency not acceptable")] CurrencyNotAcceptable, #[error("Forex configuration error: {0}")] ConfigurationError(String), #[error("Incorrect entries in default Currency response")] DefaultCurrencyParsingError, #[error("Entry not found in cache")] EntryNotFound, #[error("Forex data unavailable")] ForexDataUnavailable, #[error("Expiration time invalid")] InvalidLogExpiry, #[error("Error reading local")] LocalReadError, #[error("Error writing to local cache")] LocalWriteError, #[error("Json Parsing error")] ParsingError, #[error("Aws Kms decryption error")] AwsKmsDecryptionFailed, #[error("Error connecting to redis")] RedisConnectionError, #[error("Not able to release write lock")] RedisLockReleaseFailed, #[error("Error writing to redis")] RedisWriteError, #[error("Not able to acquire write lock")] WriteLockNotAcquired, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] struct ForexResponse { pub rates: HashMap<String, FloatDecimal>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] struct FallbackForexResponse { pub quotes: HashMap<String, FloatDecimal>, } #[derive(Debug, Copy, Clone, serde::Serialize, serde::Deserialize)] #[serde(transparent)] struct FloatDecimal(#[serde(with = "rust_decimal::serde::float")] Decimal); impl Deref for FloatDecimal { type Target = Decimal; fn deref(&self) -> &Self::Target { &self.0 } } impl FxExchangeRatesCacheEntry { fn new(exchange_rate: ExchangeRates) -> Self { Self { data: Arc::new(exchange_rate), timestamp: date_time::now_unix_timestamp(), } } fn is_expired(&self, data_expiration_delay: u32) -> bool { self.timestamp + i64::from(data_expiration_delay) < date_time::now_unix_timestamp() } } async fn retrieve_forex_from_local_cache() -> Option<FxExchangeRatesCacheEntry> { FX_EXCHANGE_RATES_CACHE.read().await.clone() } async fn save_forex_data_to_local_cache( exchange_rates_cache_entry: FxExchangeRatesCacheEntry, ) -> CustomResult<(), ForexError> { let mut local = FX_EXCHANGE_RATES_CACHE.write().await; *local = Some(exchange_rates_cache_entry); logger::debug!("forex_log: forex saved in cache"); Ok(()) } impl TryFrom<DefaultExchangeRates> for ExchangeRates { type Error = error_stack::Report<ForexError>; fn try_from(value: DefaultExchangeRates) -> Result<Self, Self::Error> { let mut conversion_usable: HashMap<enums::Currency, CurrencyFactors> = HashMap::new(); for (curr, conversion) in value.conversion { let enum_curr = enums::Currency::from_str(curr.as_str()) .change_context(ForexError::ConversionError) .attach_printable("Unable to Convert currency received")?; conversion_usable.insert(enum_curr, CurrencyFactors::from(conversion)); } let base_curr = enums::Currency::from_str(value.base_currency.as_str()) .change_context(ForexError::ConversionError) .attach_printable("Unable to convert base currency")?; Ok(Self { base_currency: base_curr, conversion: conversion_usable, }) } } impl From<Conversion> for CurrencyFactors { fn from(value: Conversion) -> Self { Self { to_factor: value.to_factor, from_factor: value.from_factor, } } } #[instrument(skip_all)] pub async fn get_forex_rates( state: &SessionState, data_expiration_delay: u32, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> { if let Some(local_rates) = retrieve_forex_from_local_cache().await { if local_rates.is_expired(data_expiration_delay) { // expired local data logger::debug!("forex_log: Forex stored in cache is expired"); call_forex_api_and_save_data_to_cache_and_redis(state, Some(local_rates)).await } else { // Valid data present in local logger::debug!("forex_log: forex found in cache"); Ok(local_rates) } } else { // No data in local call_api_if_redis_forex_data_expired(state, data_expiration_delay).await } } async fn call_api_if_redis_forex_data_expired( state: &SessionState, data_expiration_delay: u32, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> { match retrieve_forex_data_from_redis(state).await { Ok(Some(data)) => { call_forex_api_if_redis_data_expired(state, data, data_expiration_delay).await } Ok(None) => { // No data in local as well as redis call_forex_api_and_save_data_to_cache_and_redis(state, None).await?; Err(ForexError::ForexDataUnavailable.into()) } Err(error) => { // Error in deriving forex rates from redis logger::error!("forex_error: {:?}", error); call_forex_api_and_save_data_to_cache_and_redis(state, None).await?; Err(ForexError::ForexDataUnavailable.into()) } } } async fn call_forex_api_and_save_data_to_cache_and_redis( state: &SessionState, stale_redis_data: Option<FxExchangeRatesCacheEntry>, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> { // spawn a new thread and do the api fetch and write operations on redis. let forex_api_key = state.conf.forex_api.get_inner().api_key.peek(); if forex_api_key.is_empty() { Err(ForexError::ConfigurationError("api_keys not provided".into()).into()) } else { let state = state.clone(); tokio::spawn( async move { acquire_redis_lock_and_call_forex_api(&state) .await .map_err(|err| { logger::error!(forex_error=?err); }) .ok(); } .in_current_span(), ); stale_redis_data.ok_or(ForexError::EntryNotFound.into()) } } async fn acquire_redis_lock_and_call_forex_api( state: &SessionState, ) -> CustomResult<(), ForexError> { let lock_acquired = acquire_redis_lock(state).await?; if !lock_acquired { Err(ForexError::CouldNotAcquireLock.into()) } else { logger::debug!("forex_log: redis lock acquired"); let api_rates = fetch_forex_rates_from_primary_api(state).await; match api_rates { Ok(rates) => save_forex_data_to_cache_and_redis(state, rates).await, Err(error) => { logger::error!(forex_error=?error,"primary_forex_error"); // API not able to fetch data call secondary service let secondary_api_rates = fetch_forex_rates_from_fallback_api(state).await; match secondary_api_rates { Ok(rates) => save_forex_data_to_cache_and_redis(state, rates).await, Err(error) => { release_redis_lock(state).await?; Err(error) } } } } } } async fn save_forex_data_to_cache_and_redis( state: &SessionState, forex: FxExchangeRatesCacheEntry, ) -> CustomResult<(), ForexError> { save_forex_data_to_redis(state, &forex) .await .async_and_then(|_rates| release_redis_lock(state)) .await .async_and_then(|_val| save_forex_data_to_local_cache(forex.clone())) .await } async fn call_forex_api_if_redis_data_expired( state: &SessionState, redis_data: FxExchangeRatesCacheEntry, data_expiration_delay: u32, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> { match is_redis_expired(Some(redis_data.clone()).as_ref(), data_expiration_delay).await { Some(redis_forex) => { // Valid data present in redis let exchange_rates = FxExchangeRatesCacheEntry::new(redis_forex.as_ref().clone()); logger::debug!("forex_log: forex response found in redis"); save_forex_data_to_local_cache(exchange_rates.clone()).await?; Ok(exchange_rates) } None => { // redis expired call_forex_api_and_save_data_to_cache_and_redis(state, Some(redis_data)).await } } } async fn fetch_forex_rates_from_primary_api( state: &SessionState, ) -> Result<FxExchangeRatesCacheEntry, error_stack::Report<ForexError>> { let forex_api_key = state.conf.forex_api.get_inner().api_key.peek(); logger::debug!("forex_log: Primary api call for forex fetch"); let forex_url: String = format!("{}{}{}", FOREX_BASE_URL, forex_api_key, FOREX_BASE_CURRENCY); let forex_request = services::RequestBuilder::new() .method(services::Method::Get) .url(&forex_url) .build(); logger::info!(primary_forex_request=?forex_request,"forex_log: Primary api call for forex fetch"); let response = state .api_client .send_request( &state.clone(), forex_request, Some(FOREX_API_TIMEOUT), false, ) .await .change_context(ForexError::ApiUnresponsive) .attach_printable("Primary forex fetch api unresponsive")?; let forex_response = response .json::<ForexResponse>() .await .change_context(ForexError::ParsingError) .attach_printable( "Unable to parse response received from primary api into ForexResponse", )?; logger::info!(primary_forex_response=?forex_response,"forex_log"); let mut conversions: HashMap<enums::Currency, CurrencyFactors> = HashMap::new(); for enum_curr in enums::Currency::iter() { match forex_response.rates.get(&enum_curr.to_string()) { Some(rate) => { let from_factor = match Decimal::new(1, 0).checked_div(**rate) { Some(rate) => rate, None => { logger::error!( "forex_error: Rates for {} not received from API", &enum_curr ); continue; } }; let currency_factors = CurrencyFactors::new(**rate, from_factor); conversions.insert(enum_curr, currency_factors); } None => { logger::error!( "forex_error: Rates for {} not received from API", &enum_curr ); } }; } Ok(FxExchangeRatesCacheEntry::new(ExchangeRates::new( enums::Currency::USD, conversions, ))) } pub async fn fetch_forex_rates_from_fallback_api( state: &SessionState, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> { let fallback_forex_api_key = state.conf.forex_api.get_inner().fallback_api_key.peek(); let fallback_forex_url: String = format!("{}{}", FALLBACK_FOREX_BASE_URL, fallback_forex_api_key,); let fallback_forex_request = services::RequestBuilder::new() .method(services::Method::Get) .url(&fallback_forex_url) .build(); logger::info!(fallback_forex_request=?fallback_forex_request,"forex_log: Fallback api call for forex fetch"); let response = state .api_client .send_request( &state.clone(), fallback_forex_request, Some(FOREX_API_TIMEOUT), false, ) .await .change_context(ForexError::ApiUnresponsive) .attach_printable("Fallback forex fetch api unresponsive")?; let fallback_forex_response = response .json::<FallbackForexResponse>() .await .change_context(ForexError::ParsingError) .attach_printable( "Unable to parse response received from falback api into ForexResponse", )?; logger::info!(fallback_forex_response=?fallback_forex_response,"forex_log"); let mut conversions: HashMap<enums::Currency, CurrencyFactors> = HashMap::new(); for enum_curr in enums::Currency::iter() { match fallback_forex_response.quotes.get( format!( "{}{}", FALLBACK_FOREX_API_CURRENCY_PREFIX, &enum_curr.to_string() ) .as_str(), ) { Some(rate) => { let from_factor = match Decimal::new(1, 0).checked_div(**rate) { Some(rate) => rate, None => { logger::error!( "forex_error: Rates for {} not received from API", &enum_curr ); continue; } }; let currency_factors = CurrencyFactors::new(**rate, from_factor); conversions.insert(enum_curr, currency_factors); } None => { if enum_curr == enums::Currency::USD { let currency_factors = CurrencyFactors::new(Decimal::new(1, 0), Decimal::new(1, 0)); conversions.insert(enum_curr, currency_factors); } else { logger::error!( "forex_error: Rates for {} not received from API", &enum_curr ); } } }; } let rates = FxExchangeRatesCacheEntry::new(ExchangeRates::new(enums::Currency::USD, conversions)); match acquire_redis_lock(state).await { Ok(_) => { save_forex_data_to_cache_and_redis(state, rates.clone()).await?; Ok(rates) } Err(e) => Err(e), } } async fn release_redis_lock( state: &SessionState, ) -> Result<DelReply, error_stack::Report<ForexError>> { logger::debug!("forex_log: Releasing redis lock"); state .store .get_redis_conn() .change_context(ForexError::RedisConnectionError)? .delete_key(&REDIX_FOREX_CACHE_KEY.into()) .await .change_context(ForexError::RedisLockReleaseFailed) .attach_printable("Unable to release redis lock") } async fn acquire_redis_lock(state: &SessionState) -> CustomResult<bool, ForexError> { let forex_api = state.conf.forex_api.get_inner(); logger::debug!("forex_log: Acquiring redis lock"); state .store .get_redis_conn() .change_context(ForexError::RedisConnectionError)? .set_key_if_not_exists_with_expiry( &REDIX_FOREX_CACHE_KEY.into(), "", Some(i64::from(forex_api.redis_lock_timeout_in_seconds)), ) .await .map(|val| matches!(val, redis_interface::SetnxReply::KeySet)) .change_context(ForexError::CouldNotAcquireLock) .attach_printable("Unable to acquire redis lock") } async fn save_forex_data_to_redis( app_state: &SessionState, forex_exchange_cache_entry: &FxExchangeRatesCacheEntry, ) -> CustomResult<(), ForexError> { let forex_api = app_state.conf.forex_api.get_inner(); logger::debug!("forex_log: Saving forex to redis"); app_state .store .get_redis_conn() .change_context(ForexError::RedisConnectionError)? .serialize_and_set_key_with_expiry( &REDIX_FOREX_CACHE_DATA.into(), forex_exchange_cache_entry, i64::from(forex_api.redis_ttl_in_seconds), ) .await .change_context(ForexError::RedisWriteError) .attach_printable("Unable to save forex data to redis") } async fn retrieve_forex_data_from_redis( app_state: &SessionState, ) -> CustomResult<Option<FxExchangeRatesCacheEntry>, ForexError> { logger::debug!("forex_log: Retrieving forex from redis"); app_state .store .get_redis_conn() .change_context(ForexError::RedisConnectionError)? .get_and_deserialize_key(&REDIX_FOREX_CACHE_DATA.into(), "FxExchangeRatesCache") .await .change_context(ForexError::EntryNotFound) .attach_printable("Forex entry not found in redis") } async fn is_redis_expired( redis_cache: Option<&FxExchangeRatesCacheEntry>, data_expiration_delay: u32, ) -> Option<Arc<ExchangeRates>> { redis_cache.and_then(|cache| { if cache.timestamp + i64::from(data_expiration_delay) > date_time::now_unix_timestamp() { Some(cache.data.clone()) } else { logger::debug!("forex_log: Forex stored in redis is expired"); None } }) } #[instrument(skip_all)] pub async fn convert_currency( state: SessionState, amount: i64, to_currency: String, from_currency: String, ) -> CustomResult<api_models::currency::CurrencyConversionResponse, ForexError> { let forex_api = state.conf.forex_api.get_inner(); let rates = get_forex_rates(&state, forex_api.data_expiration_delay_in_seconds) .await .change_context(ForexError::ApiError)?; let to_currency = enums::Currency::from_str(to_currency.as_str()) .change_context(ForexError::CurrencyNotAcceptable) .attach_printable("The provided currency is not acceptable")?; let from_currency = enums::Currency::from_str(from_currency.as_str()) .change_context(ForexError::CurrencyNotAcceptable) .attach_printable("The provided currency is not acceptable")?; let converted_amount = currency_conversion::conversion::convert(&rates.data, from_currency, to_currency, amount) .change_context(ForexError::ConversionError) .attach_printable("Unable to perform currency conversion")?; Ok(api_models::currency::CurrencyConversionResponse { converted_amount: converted_amount.to_string(), currency: to_currency.to_string(), }) }
4,421
1,531
hyperswitch
crates/router/src/utils/user.rs
.rs
use std::sync::Arc; use api_models::user as user_api; use common_enums::UserAuthType; use common_utils::{ encryption::Encryption, errors::CustomResult, id_type, type_name, types::keymanager::Identifier, }; use diesel_models::organization::{self, OrganizationBridge}; use error_stack::ResultExt; use masking::{ExposeInterface, Secret}; use redis_interface::RedisConnectionPool; use router_env::env; 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, }, }; pub mod dashboard_metadata; pub mod password; #[cfg(feature = "dummy_connector")] pub mod sample_data; pub mod theme; pub mod two_factor_auth; impl UserFromToken { pub async fn get_merchant_account_from_db( &self, state: SessionState, ) -> UserResult<MerchantAccount> { let key_manager_state = &(&state).into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, &self.merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .map_err(|e| { if e.current_context().is_db_not_found() { e.change_context(UserErrors::MerchantIdNotFound) } else { e.change_context(UserErrors::InternalServerError) } })?; let merchant_account = state .store .find_merchant_account_by_merchant_id(key_manager_state, &self.merchant_id, &key_store) .await .map_err(|e| { if e.current_context().is_db_not_found() { e.change_context(UserErrors::MerchantIdNotFound) } else { e.change_context(UserErrors::InternalServerError) } })?; Ok(merchant_account) } pub async fn get_user_from_db(&self, state: &SessionState) -> UserResult<UserFromStorage> { let user = state .global_store .find_user_by_id(&self.user_id) .await .change_context(UserErrors::InternalServerError)?; Ok(user.into()) } pub async fn get_role_info_from_db(&self, state: &SessionState) -> UserResult<RoleInfo> { RoleInfo::from_role_id_org_id_tenant_id( state, &self.role_id, &self.org_id, self.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError) } } pub async fn generate_jwt_auth_token_with_attributes( state: &SessionState, user_id: String, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, role_id: String, profile_id: id_type::ProfileId, tenant_id: Option<id_type::TenantId>, ) -> UserResult<Secret<String>> { let token = AuthToken::new_token( user_id, merchant_id, role_id, &state.conf, org_id, profile_id, tenant_id, ) .await?; Ok(Secret::new(token)) } #[allow(unused_variables)] pub fn get_verification_days_left( state: &SessionState, user: &UserFromStorage, ) -> UserResult<Option<i64>> { #[cfg(feature = "email")] return user.get_verification_days_left(state); #[cfg(not(feature = "email"))] return Ok(None); } pub async fn get_user_from_db_by_email( state: &SessionState, email: domain::UserEmail, ) -> CustomResult<UserFromStorage, StorageError> { state .global_store .find_user_by_email(&email) .await .map(UserFromStorage::from) } pub fn get_redis_connection(state: &SessionState) -> UserResult<Arc<RedisConnectionPool>> { state .store .get_redis_conn() .change_context(UserErrors::InternalServerError) .attach_printable("Failed to get redis connection") } impl ForeignFrom<&user_api::AuthConfig> for UserAuthType { fn foreign_from(from: &user_api::AuthConfig) -> Self { match *from { user_api::AuthConfig::OpenIdConnect { .. } => Self::OpenIdConnect, user_api::AuthConfig::Password => Self::Password, user_api::AuthConfig::MagicLink => Self::MagicLink, } } } pub async fn construct_public_and_private_db_configs( state: &SessionState, auth_config: &user_api::AuthConfig, encryption_key: &[u8], id: String, ) -> UserResult<(Option<Encryption>, Option<serde_json::Value>)> { match auth_config { user_api::AuthConfig::OpenIdConnect { private_config, public_config, } => { let private_config_value = serde_json::to_value(private_config.clone()) .change_context(UserErrors::InternalServerError) .attach_printable("Failed to convert auth config to json")?; let encrypted_config = domain::types::crypto_operation::<serde_json::Value, masking::WithType>( &state.into(), type_name!(diesel_models::user::User), domain::types::CryptoOperation::Encrypt(private_config_value.into()), Identifier::UserAuth(id), encryption_key, ) .await .and_then(|val| val.try_into_operation()) .change_context(UserErrors::InternalServerError) .attach_printable("Failed to encrypt auth config")?; Ok(( Some(encrypted_config.into()), Some( serde_json::to_value(public_config.clone()) .change_context(UserErrors::InternalServerError) .attach_printable("Failed to convert auth config to json")?, ), )) } user_api::AuthConfig::Password | user_api::AuthConfig::MagicLink => Ok((None, None)), } } pub fn parse_value<T>(value: serde_json::Value, type_name: &str) -> UserResult<T> where T: serde::de::DeserializeOwned, { serde_json::from_value::<T>(value) .change_context(UserErrors::InternalServerError) .attach_printable(format!("Unable to parse {}", type_name)) } pub async fn decrypt_oidc_private_config( state: &SessionState, encrypted_config: Option<Encryption>, id: String, ) -> UserResult<user_api::OpenIdConnectPrivateConfig> { let user_auth_key = hex::decode( state .conf .user_auth_methods .get_inner() .encryption_key .clone() .expose(), ) .change_context(UserErrors::InternalServerError) .attach_printable("Failed to decode DEK")?; let private_config = domain::types::crypto_operation::<serde_json::Value, masking::WithType>( &state.into(), type_name!(diesel_models::user::User), domain::types::CryptoOperation::DecryptOptional(encrypted_config), Identifier::UserAuth(id), &user_auth_key, ) .await .and_then(|val| val.try_into_optionaloperation()) .change_context(UserErrors::InternalServerError) .attach_printable("Failed to decrypt private config")? .ok_or(UserErrors::InternalServerError) .attach_printable("Private config not found")? .into_inner() .expose(); serde_json::from_value::<user_api::OpenIdConnectPrivateConfig>(private_config) .change_context(UserErrors::InternalServerError) .attach_printable("unable to parse OpenIdConnectPrivateConfig") } 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") } 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") } fn get_oidc_key(oidc_state: &str) -> String { format!("{}{oidc_state}", REDIS_SSO_PREFIX) } pub fn get_oidc_sso_redirect_url(state: &SessionState, provider: &str) -> String { format!("{}/redirect/oidc/{}", state.conf.user.base_url, provider) } pub fn is_sso_auth_type(auth_type: UserAuthType) -> bool { match auth_type { UserAuthType::OpenIdConnect => true, UserAuthType::Password | UserAuthType::MagicLink => false, } } #[cfg(feature = "v1")] pub fn create_merchant_account_request_for_org( req: user_api::UserOrgMerchantCreateRequest, org: organization::Organization, product_type: common_enums::MerchantProductType, ) -> UserResult<api_models::admin::MerchantAccountCreate> { let merchant_id = if matches!(env::which(), env::Env::Production) { id_type::MerchantId::try_from(domain::MerchantId::new(req.merchant_name.clone().expose())?)? } else { id_type::MerchantId::new_from_unix_timestamp() }; let company_name = domain::UserCompanyName::new(req.merchant_name.expose())?; Ok(api_models::admin::MerchantAccountCreate { merchant_id, metadata: None, locker_id: None, return_url: None, merchant_name: Some(Secret::new(company_name.get_secret())), webhook_details: None, publishable_key: None, organization_id: Some(org.get_organization_id()), merchant_details: None, routing_algorithm: None, parent_merchant_id: None, sub_merchants_enabled: None, frm_routing_algorithm: None, #[cfg(feature = "payouts")] payout_routing_algorithm: None, primary_business_details: None, payment_response_hash_key: None, enable_payment_response_hash: None, redirect_to_merchant_with_http_post: None, pm_collect_link_config: None, product_type: Some(product_type), }) } pub async fn validate_email_domain_auth_type_using_db( state: &SessionState, email: &domain::UserEmail, required_auth_type: UserAuthType, ) -> UserResult<()> { let domain = email.extract_domain()?; let user_auth_methods = state .store .list_user_authentication_methods_for_email_domain(domain) .await .change_context(UserErrors::InternalServerError)?; (user_auth_methods.is_empty() || user_auth_methods .iter() .any(|auth_method| auth_method.auth_type == required_auth_type)) .then_some(()) .ok_or(UserErrors::InvalidUserAuthMethodOperation.into()) }
2,542
1,532
hyperswitch
crates/router/src/utils/verify_connector.rs
.rs
use api_models::enums::Connector; use error_stack::ResultExt; use crate::{core::errors, types::domain}; pub fn generate_card_from_details( card_number: String, card_exp_year: String, card_exp_month: String, card_cvv: String, ) -> errors::RouterResult<domain::Card> { Ok(domain::Card { card_number: card_number .parse::<cards::CardNumber>() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while parsing card number")?, card_issuer: None, card_cvc: masking::Secret::new(card_cvv), card_network: None, card_exp_year: masking::Secret::new(card_exp_year), card_exp_month: masking::Secret::new(card_exp_month), nick_name: None, card_type: None, card_issuing_country: None, bank_code: None, card_holder_name: None, }) } pub fn get_test_card_details( connector_name: Connector, ) -> errors::RouterResult<Option<domain::Card>> { match connector_name { Connector::Stripe => Some(generate_card_from_details( "4242424242424242".to_string(), "2025".to_string(), "12".to_string(), "100".to_string(), )) .transpose(), Connector::Paypal => Some(generate_card_from_details( "4111111111111111".to_string(), "2025".to_string(), "02".to_string(), "123".to_string(), )) .transpose(), _ => Ok(None), } }
385
1,533
hyperswitch
crates/router/src/utils/ext_traits.rs
.rs
use common_utils::ext_traits::ValueExt; use error_stack::{Report, ResultExt}; use crate::{ core::errors::{self, ApiErrorResponse, CustomResult, RouterResult}, utils::when, }; pub trait OptionExt<T> { fn check_value_present(&self, field_name: &'static str) -> RouterResult<()>; fn get_required_value(self, field_name: &'static str) -> RouterResult<T>; fn parse_enum<E>(self, enum_name: &'static str) -> CustomResult<E, errors::ParsingError> where T: AsRef<str>, E: std::str::FromStr, // Requirement for converting the `Err` variant of `FromStr` to `Report<Err>` <E as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static; fn parse_value<U>(self, type_name: &'static str) -> CustomResult<U, errors::ParsingError> where T: ValueExt, U: serde::de::DeserializeOwned; fn update_value(&mut self, value: Option<T>); } impl<T> OptionExt<T> for Option<T> { fn check_value_present(&self, field_name: &'static str) -> RouterResult<()> { when(self.is_none(), || { Err( Report::new(ApiErrorResponse::MissingRequiredField { field_name }) .attach_printable(format!("Missing required field {field_name}")), ) }) } // This will allow the error message that was generated in this function to point to the call site #[track_caller] fn get_required_value(self, field_name: &'static str) -> RouterResult<T> { match self { Some(v) => Ok(v), None => Err( Report::new(ApiErrorResponse::MissingRequiredField { field_name }) .attach_printable(format!("Missing required field {field_name}")), ), } } fn parse_enum<E>(self, enum_name: &'static str) -> CustomResult<E, errors::ParsingError> where T: AsRef<str>, E: std::str::FromStr, <E as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static, { let value = self .get_required_value(enum_name) .change_context(errors::ParsingError::UnknownError)?; E::from_str(value.as_ref()) .change_context(errors::ParsingError::UnknownError) .attach_printable_lazy(|| format!("Invalid {{ {enum_name} }} ")) } fn parse_value<U>(self, type_name: &'static str) -> CustomResult<U, errors::ParsingError> where T: ValueExt, U: serde::de::DeserializeOwned, { let value = self .get_required_value(type_name) .change_context(errors::ParsingError::UnknownError)?; value.parse_value(type_name) } fn update_value(&mut self, value: Self) { if let Some(a) = value { *self = Some(a) } } } pub trait ValidateCall<T, F> { fn validate_opt(self, func: F) -> CustomResult<(), errors::ValidationError>; } impl<T, F> ValidateCall<T, F> for Option<&T> where F: Fn(&T) -> CustomResult<(), errors::ValidationError>, { fn validate_opt(self, func: F) -> CustomResult<(), errors::ValidationError> { match self { Some(val) => func(val), None => Ok(()), } } }
778
1,534
hyperswitch
crates/router/src/utils/db_utils.rs
.rs
use crate::{ core::errors::{self, utils::RedisErrorExt}, routes::metrics, }; /// Generates hscan field pattern. Suppose the field is pa_1234_ref_1211 it will generate /// pa_1234_ref_* pub fn generate_hscan_pattern_for_refund(sk: &str) -> String { sk.split('_') .take(3) .chain(["*"]) .collect::<Vec<&str>>() .join("_") } // The first argument should be a future while the second argument should be a closure that returns a future for a database call pub async fn try_redis_get_else_try_database_get<F, RFut, DFut, T>( redis_fut: RFut, database_call_closure: F, ) -> error_stack::Result<T, errors::StorageError> where F: FnOnce() -> DFut, RFut: futures::Future<Output = error_stack::Result<T, redis_interface::errors::RedisError>>, DFut: futures::Future<Output = error_stack::Result<T, errors::StorageError>>, { let redis_output = redis_fut.await; match redis_output { Ok(output) => Ok(output), Err(redis_error) => match redis_error.current_context() { redis_interface::errors::RedisError::NotFound => { metrics::KV_MISS.add(1, &[]); database_call_closure().await } // Keeping the key empty here since the error would never go here. _ => Err(redis_error.to_redis_failed_response("")), }, } }
339
1,535
hyperswitch
crates/router/src/utils/user_role.rs
.rs
use std::{cmp, collections::HashSet}; use common_enums::{EntityType, PermissionGroup}; use common_utils::id_type; use diesel_models::{ enums::{UserRoleVersion, UserStatus}, role::ListRolesByEntityPayload, user_role::{UserRole, UserRoleUpdate}, }; use error_stack::{report, Report, ResultExt}; use router_env::logger; use storage_impl::errors::StorageError; use crate::{ consts, core::errors::{UserErrors, UserResult}, db::{ errors::StorageErrorExt, user_role::{ListUserRolesByOrgIdPayload, ListUserRolesByUserIdPayload}, }, routes::SessionState, services::authorization::{self as authz, roles}, types::domain, }; pub fn validate_role_groups(groups: &[PermissionGroup]) -> UserResult<()> { if groups.is_empty() { return Err(report!(UserErrors::InvalidRoleOperation)) .attach_printable("Role groups cannot be empty"); } let unique_groups: HashSet<_> = groups.iter().copied().collect(); if unique_groups.contains(&PermissionGroup::OrganizationManage) { return Err(report!(UserErrors::InvalidRoleOperation)) .attach_printable("Organization manage group cannot be added to role"); } if unique_groups.len() != groups.len() { return Err(report!(UserErrors::InvalidRoleOperation)) .attach_printable("Duplicate permission group found"); } Ok(()) } pub async fn validate_role_name( state: &SessionState, role_name: &domain::RoleName, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, tenant_id: &id_type::TenantId, profile_id: &id_type::ProfileId, entity_type: &EntityType, ) -> UserResult<()> { let role_name_str = role_name.clone().get_role_name(); let is_present_in_predefined_roles = roles::predefined_roles::PREDEFINED_ROLES .iter() .any(|(_, role_info)| role_info.get_role_name() == role_name_str); let entity_type_for_role = match entity_type { EntityType::Tenant | EntityType::Organization => ListRolesByEntityPayload::Organization, EntityType::Merchant => ListRolesByEntityPayload::Merchant(merchant_id.to_owned()), EntityType::Profile => { ListRolesByEntityPayload::Profile(merchant_id.to_owned(), profile_id.to_owned()) } }; let is_present_in_custom_role = match state .global_store .generic_list_roles_by_entity_type( entity_type_for_role, false, tenant_id.to_owned(), org_id.to_owned(), ) .await { Ok(roles_list) => roles_list .iter() .any(|role| role.role_name == role_name_str), Err(e) => { if e.current_context().is_db_not_found() { false } else { return Err(UserErrors::InternalServerError.into()); } } }; if is_present_in_predefined_roles || is_present_in_custom_role { return Err(UserErrors::RoleNameAlreadyExists.into()); } Ok(()) } pub async fn set_role_info_in_cache_by_user_role( state: &SessionState, user_role: &UserRole, ) -> bool { let Some(ref org_id) = user_role.org_id else { return false; }; set_role_info_in_cache_if_required( state, user_role.role_id.as_str(), org_id, &user_role.tenant_id, ) .await .map_err(|e| logger::error!("Error setting permissions in cache {:?}", e)) .is_ok() } pub async fn set_role_info_in_cache_by_role_id_org_id( state: &SessionState, role_id: &str, org_id: &id_type::OrganizationId, tenant_id: &id_type::TenantId, ) -> bool { set_role_info_in_cache_if_required(state, role_id, org_id, tenant_id) .await .map_err(|e| logger::error!("Error setting permissions in cache {:?}", e)) .is_ok() } pub async fn set_role_info_in_cache_if_required( state: &SessionState, role_id: &str, org_id: &id_type::OrganizationId, tenant_id: &id_type::TenantId, ) -> UserResult<()> { if roles::predefined_roles::PREDEFINED_ROLES.contains_key(role_id) { return Ok(()); } let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id(state, role_id, org_id, tenant_id) .await .change_context(UserErrors::InternalServerError) .attach_printable("Error getting role_info from role_id")?; authz::set_role_info_in_cache( state, role_id, &role_info, i64::try_from(consts::JWT_TOKEN_TIME_IN_SECS) .change_context(UserErrors::InternalServerError)?, ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Error setting permissions in redis") } pub async fn update_v1_and_v2_user_roles_in_db( state: &SessionState, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, profile_id: Option<&id_type::ProfileId>, update: UserRoleUpdate, ) -> ( Result<UserRole, Report<StorageError>>, Result<UserRole, Report<StorageError>>, ) { let updated_v1_role = state .global_store .update_user_role_by_user_id_and_lineage( user_id, tenant_id, org_id, merchant_id, profile_id, update.clone(), UserRoleVersion::V1, ) .await .map_err(|e| { logger::error!("Error updating user_role {e:?}"); e }); let updated_v2_role = state .global_store .update_user_role_by_user_id_and_lineage( user_id, tenant_id, org_id, merchant_id, profile_id, update, UserRoleVersion::V2, ) .await .map_err(|e| { logger::error!("Error updating user_role {e:?}"); e }); (updated_v1_role, updated_v2_role) } pub async fn get_single_org_id( state: &SessionState, user_role: &UserRole, ) -> UserResult<id_type::OrganizationId> { let (_, entity_type) = user_role .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError)?; match entity_type { EntityType::Tenant => Ok(state .store .list_merchant_and_org_ids(&state.into(), 1, None) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to get merchants list for org")? .pop() .ok_or(UserErrors::InternalServerError) .attach_printable("No merchants to get merchant or org id")? .1), EntityType::Organization | EntityType::Merchant | EntityType::Profile => user_role .org_id .clone() .ok_or(UserErrors::InternalServerError) .attach_printable("Org_id not found"), } } pub async fn get_single_merchant_id( state: &SessionState, user_role: &UserRole, org_id: &id_type::OrganizationId, ) -> UserResult<id_type::MerchantId> { let (_, entity_type) = user_role .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError)?; match entity_type { EntityType::Tenant | EntityType::Organization => Ok(state .store .list_merchant_accounts_by_organization_id(&state.into(), org_id) .await .to_not_found_response(UserErrors::InvalidRoleOperationWithMessage( "Invalid Org Id".to_string(), ))? .first() .ok_or(UserErrors::InternalServerError) .attach_printable("No merchants found for org_id")? .get_id() .clone()), EntityType::Merchant | EntityType::Profile => user_role .merchant_id .clone() .ok_or(UserErrors::InternalServerError) .attach_printable("merchant_id not found"), } } pub async fn get_single_profile_id( state: &SessionState, user_role: &UserRole, merchant_id: &id_type::MerchantId, ) -> UserResult<id_type::ProfileId> { let (_, entity_type) = user_role .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError)?; match entity_type { EntityType::Tenant | EntityType::Organization | EntityType::Merchant => { let key_store = state .store .get_merchant_key_store_by_merchant_id( &state.into(), merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .change_context(UserErrors::InternalServerError)?; Ok(state .store .list_profile_by_merchant_id(&state.into(), &key_store, merchant_id) .await .change_context(UserErrors::InternalServerError)? .pop() .ok_or(UserErrors::InternalServerError)? .get_id() .to_owned()) } EntityType::Profile => user_role .profile_id .clone() .ok_or(UserErrors::InternalServerError) .attach_printable("profile_id not found"), } } pub async fn get_lineage_for_user_id_and_entity_for_accepting_invite( state: &SessionState, user_id: &str, tenant_id: &id_type::TenantId, entity_id: String, entity_type: EntityType, ) -> UserResult< Option<( id_type::OrganizationId, Option<id_type::MerchantId>, Option<id_type::ProfileId>, )>, > { match entity_type { EntityType::Tenant => Err(UserErrors::InvalidRoleOperationWithMessage( "Tenant roles are not allowed for this operation".to_string(), ) .into()), EntityType::Organization => { let Ok(org_id) = id_type::OrganizationId::try_from(std::borrow::Cow::from(entity_id.clone())) else { return Ok(None); }; let user_roles = state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id, tenant_id, org_id: Some(&org_id), merchant_id: None, profile_id: None, entity_id: None, version: None, status: Some(UserStatus::InvitationSent), limit: None, }) .await .change_context(UserErrors::InternalServerError)? .into_iter() .collect::<HashSet<_>>(); if user_roles.len() > 1 { return Ok(None); } if let Some(user_role) = user_roles.into_iter().next() { let (_entity_id, entity_type) = user_role .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError)?; if entity_type != EntityType::Organization { return Ok(None); } return Ok(Some(( user_role.org_id.ok_or(UserErrors::InternalServerError)?, None, None, ))); } Ok(None) } EntityType::Merchant => { let Ok(merchant_id) = id_type::MerchantId::wrap(entity_id) else { return Ok(None); }; let user_roles = state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id, tenant_id, org_id: None, merchant_id: Some(&merchant_id), profile_id: None, entity_id: None, version: None, status: Some(UserStatus::InvitationSent), limit: None, }) .await .change_context(UserErrors::InternalServerError)? .into_iter() .collect::<HashSet<_>>(); if user_roles.len() > 1 { return Ok(None); } if let Some(user_role) = user_roles.into_iter().next() { let (_entity_id, entity_type) = user_role .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError)?; if entity_type != EntityType::Merchant { return Ok(None); } return Ok(Some(( user_role.org_id.ok_or(UserErrors::InternalServerError)?, Some(merchant_id), None, ))); } Ok(None) } EntityType::Profile => { let Ok(profile_id) = id_type::ProfileId::try_from(std::borrow::Cow::from(entity_id)) else { return Ok(None); }; let user_roles = state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id, tenant_id: &state.tenant.tenant_id, org_id: None, merchant_id: None, profile_id: Some(&profile_id), entity_id: None, version: None, status: Some(UserStatus::InvitationSent), limit: None, }) .await .change_context(UserErrors::InternalServerError)? .into_iter() .collect::<HashSet<_>>(); if user_roles.len() > 1 { return Ok(None); } if let Some(user_role) = user_roles.into_iter().next() { let (_entity_id, entity_type) = user_role .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError)?; if entity_type != EntityType::Profile { return Ok(None); } return Ok(Some(( user_role.org_id.ok_or(UserErrors::InternalServerError)?, Some( user_role .merchant_id .ok_or(UserErrors::InternalServerError)?, ), Some(profile_id), ))); } Ok(None) } } } pub async fn get_single_merchant_id_and_profile_id( state: &SessionState, user_role: &UserRole, ) -> UserResult<(id_type::MerchantId, id_type::ProfileId)> { let org_id = get_single_org_id(state, user_role).await?; let merchant_id = get_single_merchant_id(state, user_role, &org_id).await?; let profile_id = get_single_profile_id(state, user_role, &merchant_id).await?; Ok((merchant_id, profile_id)) } pub async fn fetch_user_roles_by_payload( state: &SessionState, payload: ListUserRolesByOrgIdPayload<'_>, request_entity_type: Option<EntityType>, ) -> UserResult<HashSet<UserRole>> { Ok(state .global_store .list_user_roles_by_org_id(payload) .await .change_context(UserErrors::InternalServerError)? .into_iter() .filter_map(|user_role| { let (_entity_id, entity_type) = user_role.get_entity_id_and_type()?; request_entity_type .map_or(true, |req_entity_type| entity_type == req_entity_type) .then_some(user_role) }) .collect::<HashSet<_>>()) } pub fn get_min_entity( user_entity: EntityType, filter_entity: Option<EntityType>, ) -> UserResult<EntityType> { let Some(filter_entity) = filter_entity else { return Ok(user_entity); }; if user_entity < filter_entity { return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( "{} level user requesting data for {:?} level", user_entity, filter_entity )); } Ok(cmp::min(user_entity, filter_entity)) }
3,405
1,536
hyperswitch
crates/router/src/utils/connector_onboarding/paypal.rs
.rs
use common_utils::request::{Method, Request, RequestBuilder, RequestContent}; use error_stack::ResultExt; use http::header; use crate::{ connector, core::errors::{ApiErrorResponse, RouterResult}, routes::SessionState, types, types::api::{ enums, verify_connector::{self as verify_connector_types, VerifyConnector}, }, utils::verify_connector as verify_connector_utils, }; pub async fn generate_access_token(state: SessionState) -> RouterResult<types::AccessToken> { let connector = enums::Connector::Paypal; let boxed_connector = types::api::ConnectorData::convert_connector(connector.to_string().as_str())?; let connector_auth = super::get_connector_auth(connector, state.conf.connector_onboarding.get_inner())?; connector::Paypal::get_access_token( &state, verify_connector_types::VerifyConnectorData { connector: boxed_connector, connector_auth, card_details: verify_connector_utils::get_test_card_details(connector)?.ok_or( ApiErrorResponse::FlowNotSupported { flow: "Connector onboarding".to_string(), connector: connector.to_string(), }, )?, }, ) .await? .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("Error occurred while retrieving access token") } pub fn build_paypal_post_request<T>( url: String, body: T, access_token: String, ) -> RouterResult<Request> where T: serde::Serialize + Send + 'static, { Ok(RequestBuilder::new() .method(Method::Post) .url(&url) .attach_default_headers() .header( header::AUTHORIZATION.to_string().as_str(), format!("Bearer {}", access_token).as_str(), ) .header( header::CONTENT_TYPE.to_string().as_str(), "application/json", ) .set_body(RequestContent::Json(Box::new(body))) .build()) } pub fn build_paypal_get_request(url: String, access_token: String) -> RouterResult<Request> { Ok(RequestBuilder::new() .method(Method::Get) .url(&url) .attach_default_headers() .header( header::AUTHORIZATION.to_string().as_str(), format!("Bearer {}", access_token).as_str(), ) .build()) }
502
1,537
hyperswitch
crates/router/src/utils/user/two_factor_auth.rs
.rs
use common_utils::pii; use error_stack::ResultExt; use masking::{ExposeInterface, PeekInterface}; use totp_rs::{Algorithm, TOTP}; use crate::{ consts, core::errors::{UserErrors, UserResult}, routes::SessionState, }; pub fn generate_default_totp( email: pii::Email, secret: Option<masking::Secret<String>>, issuer: String, ) -> UserResult<TOTP> { let secret = secret .map(|sec| totp_rs::Secret::Encoded(sec.expose())) .unwrap_or_else(totp_rs::Secret::generate_secret) .to_bytes() .change_context(UserErrors::InternalServerError)?; TOTP::new( Algorithm::SHA1, consts::user::TOTP_DIGITS, consts::user::TOTP_TOLERANCE, consts::user::TOTP_VALIDITY_DURATION_IN_SECONDS, secret, Some(issuer), email.expose().expose(), ) .change_context(UserErrors::InternalServerError) } pub async fn check_totp_in_redis(state: &SessionState, user_id: &str) -> UserResult<bool> { let redis_conn = super::get_redis_connection(state)?; let key = format!("{}{}", consts::user::REDIS_TOTP_PREFIX, user_id); redis_conn .exists::<()>(&key.into()) .await .change_context(UserErrors::InternalServerError) } pub async fn check_recovery_code_in_redis(state: &SessionState, user_id: &str) -> UserResult<bool> { let redis_conn = super::get_redis_connection(state)?; let key = format!("{}{}", consts::user::REDIS_RECOVERY_CODE_PREFIX, user_id); redis_conn .exists::<()>(&key.into()) .await .change_context(UserErrors::InternalServerError) } pub async fn insert_totp_in_redis(state: &SessionState, user_id: &str) -> UserResult<()> { let redis_conn = super::get_redis_connection(state)?; let key = format!("{}{}", consts::user::REDIS_TOTP_PREFIX, user_id); redis_conn .set_key_with_expiry( &key.as_str().into(), common_utils::date_time::now_unix_timestamp(), state.conf.user.two_factor_auth_expiry_in_secs, ) .await .change_context(UserErrors::InternalServerError) } pub async fn insert_totp_secret_in_redis( state: &SessionState, user_id: &str, secret: &masking::Secret<String>, ) -> UserResult<()> { let redis_conn = super::get_redis_connection(state)?; redis_conn .set_key_with_expiry( &get_totp_secret_key(user_id).into(), secret.peek(), consts::user::REDIS_TOTP_SECRET_TTL_IN_SECS, ) .await .change_context(UserErrors::InternalServerError) } pub async fn get_totp_secret_from_redis( state: &SessionState, user_id: &str, ) -> UserResult<Option<masking::Secret<String>>> { let redis_conn = super::get_redis_connection(state)?; redis_conn .get_key::<Option<String>>(&get_totp_secret_key(user_id).into()) .await .change_context(UserErrors::InternalServerError) .map(|secret| secret.map(Into::into)) } pub async fn delete_totp_secret_from_redis(state: &SessionState, user_id: &str) -> UserResult<()> { let redis_conn = super::get_redis_connection(state)?; redis_conn .delete_key(&get_totp_secret_key(user_id).into()) .await .change_context(UserErrors::InternalServerError) .map(|_| ()) } fn get_totp_secret_key(user_id: &str) -> String { format!("{}{}", consts::user::REDIS_TOTP_SECRET_PREFIX, user_id) } pub async fn insert_recovery_code_in_redis(state: &SessionState, user_id: &str) -> UserResult<()> { let redis_conn = super::get_redis_connection(state)?; let key = format!("{}{}", consts::user::REDIS_RECOVERY_CODE_PREFIX, user_id); redis_conn .set_key_with_expiry( &key.as_str().into(), common_utils::date_time::now_unix_timestamp(), state.conf.user.two_factor_auth_expiry_in_secs, ) .await .change_context(UserErrors::InternalServerError) } pub async fn delete_totp_from_redis(state: &SessionState, user_id: &str) -> UserResult<()> { let redis_conn = super::get_redis_connection(state)?; let key = format!("{}{}", consts::user::REDIS_TOTP_PREFIX, user_id); redis_conn .delete_key(&key.into()) .await .change_context(UserErrors::InternalServerError) .map(|_| ()) } pub async fn delete_recovery_code_from_redis( state: &SessionState, user_id: &str, ) -> UserResult<()> { let redis_conn = super::get_redis_connection(state)?; let key = format!("{}{}", consts::user::REDIS_RECOVERY_CODE_PREFIX, user_id); redis_conn .delete_key(&key.into()) .await .change_context(UserErrors::InternalServerError) .map(|_| ()) } fn get_totp_attempts_key(user_id: &str) -> String { format!("{}{}", consts::user::REDIS_TOTP_ATTEMPTS_PREFIX, user_id) } fn get_recovery_code_attempts_key(user_id: &str) -> String { format!( "{}{}", consts::user::REDIS_RECOVERY_CODE_ATTEMPTS_PREFIX, user_id ) } pub async fn insert_totp_attempts_in_redis( state: &SessionState, user_id: &str, user_totp_attempts: u8, ) -> UserResult<()> { let redis_conn = super::get_redis_connection(state)?; redis_conn .set_key_with_expiry( &get_totp_attempts_key(user_id).into(), user_totp_attempts, consts::user::REDIS_TOTP_ATTEMPTS_TTL_IN_SECS, ) .await .change_context(UserErrors::InternalServerError) } pub async fn get_totp_attempts_from_redis(state: &SessionState, user_id: &str) -> UserResult<u8> { let redis_conn = super::get_redis_connection(state)?; redis_conn .get_key::<Option<u8>>(&get_totp_attempts_key(user_id).into()) .await .change_context(UserErrors::InternalServerError) .map(|v| v.unwrap_or(0)) } pub async fn insert_recovery_code_attempts_in_redis( state: &SessionState, user_id: &str, user_recovery_code_attempts: u8, ) -> UserResult<()> { let redis_conn = super::get_redis_connection(state)?; redis_conn .set_key_with_expiry( &get_recovery_code_attempts_key(user_id).into(), user_recovery_code_attempts, consts::user::REDIS_RECOVERY_CODE_ATTEMPTS_TTL_IN_SECS, ) .await .change_context(UserErrors::InternalServerError) } pub async fn get_recovery_code_attempts_from_redis( state: &SessionState, user_id: &str, ) -> UserResult<u8> { let redis_conn = super::get_redis_connection(state)?; redis_conn .get_key::<Option<u8>>(&get_recovery_code_attempts_key(user_id).into()) .await .change_context(UserErrors::InternalServerError) .map(|v| v.unwrap_or(0)) } pub async fn delete_totp_attempts_from_redis( state: &SessionState, user_id: &str, ) -> UserResult<()> { let redis_conn = super::get_redis_connection(state)?; redis_conn .delete_key(&get_totp_attempts_key(user_id).into()) .await .change_context(UserErrors::InternalServerError) .map(|_| ()) } pub async fn delete_recovery_code_attempts_from_redis( state: &SessionState, user_id: &str, ) -> UserResult<()> { let redis_conn = super::get_redis_connection(state)?; redis_conn .delete_key(&get_recovery_code_attempts_key(user_id).into()) .await .change_context(UserErrors::InternalServerError) .map(|_| ()) }
1,774
1,538
hyperswitch
crates/router/src/utils/user/sample_data.rs
.rs
use api_models::{ enums::Connector::{DummyConnector4, DummyConnector7}, user::sample_data::SampleDataRequest, }; use common_utils::{ id_type, types::{ConnectorTransactionId, MinorUnit}, }; #[cfg(feature = "v1")] use diesel_models::user::sample_data::PaymentAttemptBatchNew; use diesel_models::{enums as storage_enums, DisputeNew, RefundNew}; use error_stack::ResultExt; use hyperswitch_domain_models::payments::PaymentIntent; use rand::{prelude::SliceRandom, thread_rng, Rng}; use time::OffsetDateTime; use crate::{ consts, core::errors::sample_data::{SampleDataError, SampleDataResult}, SessionState, }; #[cfg(feature = "v1")] #[allow(clippy::type_complexity)] pub async fn generate_sample_data( state: &SessionState, req: SampleDataRequest, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, ) -> SampleDataResult< Vec<( PaymentIntent, PaymentAttemptBatchNew, Option<RefundNew>, Option<DisputeNew>, )>, > { let sample_data_size: usize = req.record.unwrap_or(100); let key_manager_state = &state.into(); if !(10..=100).contains(&sample_data_size) { return Err(SampleDataError::InvalidRange.into()); } let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .change_context(SampleDataError::InternalServerError)?; let merchant_from_db = state .store .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) .await .change_context::<SampleDataError>(SampleDataError::DataDoesNotExist)?; #[cfg(feature = "v1")] let (profile_id_result, business_country_default, business_label_default) = { let merchant_parsed_details: Vec<api_models::admin::PrimaryBusinessDetails> = serde_json::from_value(merchant_from_db.primary_business_details.clone()) .change_context(SampleDataError::InternalServerError) .attach_printable("Error while parsing primary business details")?; let business_country_default = merchant_parsed_details.first().map(|x| x.country); let business_label_default = merchant_parsed_details.first().map(|x| x.business.clone()); let profile_id = crate::core::utils::get_profile_id_from_business_details( key_manager_state, &key_store, business_country_default, business_label_default.as_ref(), &merchant_from_db, req.profile_id.as_ref(), &*state.store, false, ) .await; (profile_id, business_country_default, business_label_default) }; #[cfg(feature = "v2")] let (profile_id_result, business_country_default, business_label_default) = { let profile_id = req .profile_id.clone() .ok_or(hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse::MissingRequiredField { field_name: "profile_id", }); (profile_id, None, None) }; let profile_id = match profile_id_result { Ok(id) => id.clone(), Err(error) => { router_env::logger::error!( "Profile ID not found in business details. Attempting to fetch from the database {error:?}" ); state .store .list_profile_by_merchant_id(key_manager_state, &key_store, merchant_id) .await .change_context(SampleDataError::InternalServerError) .attach_printable("Failed to get business profile")? .first() .ok_or(SampleDataError::InternalServerError)? .get_id() .to_owned() } }; // 10 percent payments should be failed #[allow(clippy::as_conversions)] let failure_attempts = usize::try_from((sample_data_size as f32 / 10.0).round() as i64) .change_context(SampleDataError::InvalidParameters)?; let failure_after_attempts = sample_data_size / failure_attempts; // 20 percent refunds for payments #[allow(clippy::as_conversions)] let number_of_refunds = usize::try_from((sample_data_size as f32 / 5.0).round() as i64) .change_context(SampleDataError::InvalidParameters)?; let mut refunds_count = 0; // 2 disputes if generated data size is between 50 and 100, 1 dispute if it is less than 50. let number_of_disputes: usize = if sample_data_size >= 50 { 2 } else { 1 }; let mut disputes_count = 0; let mut random_array: Vec<usize> = (1..=sample_data_size).collect(); // Shuffle the array let mut rng = thread_rng(); random_array.shuffle(&mut rng); let mut res: Vec<( PaymentIntent, PaymentAttemptBatchNew, Option<RefundNew>, Option<DisputeNew>, )> = Vec::new(); let start_time = req .start_time .unwrap_or(common_utils::date_time::now() - time::Duration::days(7)) .assume_utc() .unix_timestamp(); let end_time = req .end_time .unwrap_or_else(common_utils::date_time::now) .assume_utc() .unix_timestamp(); let current_time = common_utils::date_time::now().assume_utc().unix_timestamp(); let min_amount = req.min_amount.unwrap_or(100); let max_amount = req.max_amount.unwrap_or(min_amount + 100); if min_amount > max_amount || start_time > end_time || start_time > current_time || end_time > current_time { return Err(SampleDataError::InvalidParameters.into()); }; let currency_vec = req.currency.unwrap_or(vec![common_enums::Currency::USD]); let currency_vec_len = currency_vec.len(); let connector_vec = req .connector .unwrap_or(vec![DummyConnector4, DummyConnector7]); let connector_vec_len = connector_vec.len(); let auth_type = req.auth_type.unwrap_or(vec![ common_enums::AuthenticationType::ThreeDs, common_enums::AuthenticationType::NoThreeDs, ]); let auth_type_len = auth_type.len(); if currency_vec_len == 0 || connector_vec_len == 0 || auth_type_len == 0 { return Err(SampleDataError::InvalidParameters.into()); } // This has to be an internal server error because, this function failing means that the intended functionality is not working as expected let dashboard_customer_id = id_type::CustomerId::try_from(std::borrow::Cow::from("hs-dashboard-user")) .change_context(SampleDataError::InternalServerError)?; for num in 1..=sample_data_size { let payment_id = id_type::PaymentId::generate_test_payment_id_for_sample_data(); let attempt_id = payment_id.get_attempt_id(1); let client_secret = payment_id.generate_client_secret(); let amount = thread_rng().gen_range(min_amount..=max_amount); let created_at @ modified_at @ last_synced = OffsetDateTime::from_unix_timestamp(thread_rng().gen_range(start_time..=end_time)) .map(common_utils::date_time::convert_to_pdt) .unwrap_or( req.start_time.unwrap_or_else(|| { common_utils::date_time::now() - time::Duration::days(7) }), ); let session_expiry = created_at.saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)); // After some set of payments sample data will have a failed attempt let is_failed_payment = (random_array.get(num - 1).unwrap_or(&0) % failure_after_attempts) == 0; let payment_intent = PaymentIntent { payment_id: payment_id.clone(), merchant_id: merchant_id.clone(), status: match is_failed_payment { true => common_enums::IntentStatus::Failed, _ => common_enums::IntentStatus::Succeeded, }, amount: MinorUnit::new(amount * 100), currency: Some( *currency_vec .get((num - 1) % currency_vec_len) .unwrap_or(&common_enums::Currency::USD), ), description: Some("This is a sample payment".to_string()), created_at, modified_at, last_synced: Some(last_synced), client_secret: Some(client_secret), business_country: business_country_default, business_label: business_label_default.clone(), active_attempt: hyperswitch_domain_models::RemoteStorageObject::ForeignID( attempt_id.clone(), ), attempt_count: 1, customer_id: Some(dashboard_customer_id.clone()), amount_captured: Some(MinorUnit::new(amount * 100)), profile_id: Some(profile_id.clone()), return_url: Default::default(), metadata: Default::default(), connector_id: Default::default(), shipping_address_id: Default::default(), billing_address_id: Default::default(), statement_descriptor_name: Default::default(), statement_descriptor_suffix: Default::default(), setup_future_usage: Default::default(), off_session: Default::default(), order_details: Default::default(), allowed_payment_method_types: Default::default(), connector_metadata: Default::default(), feature_metadata: Default::default(), merchant_decision: Default::default(), payment_link_id: Default::default(), payment_confirm_source: Default::default(), updated_by: merchant_from_db.storage_scheme.to_string(), surcharge_applicable: Default::default(), request_incremental_authorization: Default::default(), incremental_authorization_allowed: Default::default(), authorization_count: Default::default(), fingerprint_id: None, session_expiry: Some(session_expiry), request_external_three_ds_authentication: None, split_payments: None, frm_metadata: Default::default(), customer_details: None, billing_details: None, merchant_order_reference_id: Default::default(), shipping_details: None, is_payment_processor_token_flow: None, organization_id: org_id.clone(), shipping_cost: None, tax_details: None, skip_external_tax_calculation: None, request_extended_authorization: None, psd2_sca_exemption_type: None, platform_merchant_id: None, force_3ds_challenge: None, force_3ds_challenge_trigger: None, }; let (connector_transaction_id, processor_transaction_data) = ConnectorTransactionId::form_id_and_data(attempt_id.clone()); let payment_attempt = PaymentAttemptBatchNew { attempt_id: attempt_id.clone(), payment_id: payment_id.clone(), connector_transaction_id: Some(connector_transaction_id), merchant_id: merchant_id.clone(), status: match is_failed_payment { true => common_enums::AttemptStatus::Failure, _ => common_enums::AttemptStatus::Charged, }, amount: MinorUnit::new(amount * 100), currency: payment_intent.currency, connector: Some( (*connector_vec .get((num - 1) % connector_vec_len) .unwrap_or(&DummyConnector4)) .to_string(), ), payment_method: Some(common_enums::PaymentMethod::Card), payment_method_type: Some(get_payment_method_type(thread_rng().gen_range(1..=2))), authentication_type: Some( *auth_type .get((num - 1) % auth_type_len) .unwrap_or(&common_enums::AuthenticationType::NoThreeDs), ), error_message: match is_failed_payment { true => Some("This is a test payment which has a failed status".to_string()), _ => None, }, error_code: match is_failed_payment { true => Some("HS001".to_string()), _ => None, }, confirm: true, created_at, modified_at, last_synced: Some(last_synced), amount_to_capture: Some(MinorUnit::new(amount * 100)), connector_response_reference_id: Some(attempt_id.clone()), updated_by: merchant_from_db.storage_scheme.to_string(), save_to_locker: None, offer_amount: None, surcharge_amount: None, tax_amount: None, payment_method_id: None, capture_method: None, capture_on: None, cancellation_reason: None, mandate_id: None, browser_info: None, payment_token: None, connector_metadata: None, payment_experience: None, payment_method_data: None, business_sub_label: None, straight_through_algorithm: None, preprocessing_step_id: None, mandate_details: None, error_reason: None, multiple_capture_count: None, amount_capturable: MinorUnit::new(i64::default()), merchant_connector_id: None, authentication_data: None, encoded_data: None, unified_code: None, unified_message: None, net_amount: None, external_three_ds_authentication_attempted: None, authentication_connector: None, authentication_id: None, mandate_data: None, payment_method_billing_address_id: None, fingerprint_id: None, charge_id: None, client_source: None, client_version: None, customer_acceptance: None, profile_id: profile_id.clone(), organization_id: org_id.clone(), shipping_cost: None, order_tax_amount: None, processor_transaction_data, connector_mandate_detail: None, request_extended_authorization: None, extended_authorization_applied: None, capture_before: None, card_discovery: None, }; let refund = if refunds_count < number_of_refunds && !is_failed_payment { refunds_count += 1; let (connector_transaction_id, processor_transaction_data) = ConnectorTransactionId::form_id_and_data(attempt_id.clone()); Some(RefundNew { refund_id: common_utils::generate_id_with_default_len("test"), internal_reference_id: common_utils::generate_id_with_default_len("test"), external_reference_id: None, payment_id: payment_id.clone(), attempt_id: attempt_id.clone(), merchant_id: merchant_id.clone(), connector_transaction_id, connector_refund_id: None, description: Some("This is a sample refund".to_string()), created_at, modified_at, refund_reason: Some("Sample Refund".to_string()), connector: payment_attempt .connector .clone() .unwrap_or(DummyConnector4.to_string()), currency: *currency_vec .get((num - 1) % currency_vec_len) .unwrap_or(&common_enums::Currency::USD), total_amount: MinorUnit::new(amount * 100), refund_amount: MinorUnit::new(amount * 100), refund_status: common_enums::RefundStatus::Success, sent_to_gateway: true, refund_type: diesel_models::enums::RefundType::InstantRefund, metadata: None, refund_arn: None, profile_id: payment_intent.profile_id.clone(), updated_by: merchant_from_db.storage_scheme.to_string(), merchant_connector_id: payment_attempt.merchant_connector_id.clone(), charges: None, split_refunds: None, organization_id: org_id.clone(), processor_refund_data: None, processor_transaction_data, }) } else { None }; let dispute = if disputes_count < number_of_disputes && !is_failed_payment && refund.is_none() { disputes_count += 1; Some(DisputeNew { dispute_id: common_utils::generate_id_with_default_len("test"), amount: (amount * 100).to_string(), currency: payment_intent .currency .unwrap_or(common_enums::Currency::USD) .to_string(), dispute_stage: storage_enums::DisputeStage::Dispute, dispute_status: storage_enums::DisputeStatus::DisputeOpened, payment_id: payment_id.clone(), attempt_id: attempt_id.clone(), merchant_id: merchant_id.clone(), connector_status: "Sample connector status".into(), connector_dispute_id: common_utils::generate_id_with_default_len("test"), connector_reason: Some("Sample Dispute".into()), connector_reason_code: Some("123".into()), challenge_required_by: None, connector_created_at: None, connector_updated_at: None, connector: payment_attempt .connector .clone() .unwrap_or(DummyConnector4.to_string()), evidence: None, profile_id: payment_intent.profile_id.clone(), merchant_connector_id: payment_attempt.merchant_connector_id.clone(), dispute_amount: amount * 100, organization_id: org_id.clone(), dispute_currency: Some(payment_intent.currency.unwrap_or_default()), }) } else { None }; res.push((payment_intent, payment_attempt, refund, dispute)); } Ok(res) } fn get_payment_method_type(num: u8) -> common_enums::PaymentMethodType { let rem: u8 = (num) % 2; match rem { 0 => common_enums::PaymentMethodType::Debit, _ => common_enums::PaymentMethodType::Credit, } }
3,835
1,539
hyperswitch
crates/router/src/utils/user/password.rs
.rs
use argon2::{ password_hash::{ rand_core::OsRng, Error as argon2Err, PasswordHash, PasswordHasher, PasswordVerifier, SaltString, }, Argon2, }; use common_utils::errors::CustomResult; use error_stack::ResultExt; use masking::{ExposeInterface, PeekInterface, Secret}; use rand::{seq::SliceRandom, Rng}; use crate::core::errors::UserErrors; pub fn generate_password_hash( password: Secret<String>, ) -> CustomResult<Secret<String>, UserErrors> { let salt = SaltString::generate(&mut OsRng); let argon2 = Argon2::default(); let password_hash = argon2 .hash_password(password.expose().as_bytes(), &salt) .change_context(UserErrors::InternalServerError)?; Ok(Secret::new(password_hash.to_string())) } pub fn is_correct_password( candidate: &Secret<String>, password: &Secret<String>, ) -> CustomResult<bool, UserErrors> { let password = password.peek(); let parsed_hash = PasswordHash::new(password).change_context(UserErrors::InternalServerError)?; let result = Argon2::default().verify_password(candidate.peek().as_bytes(), &parsed_hash); match result { Ok(_) => Ok(true), Err(argon2Err::Password) => Ok(false), Err(e) => Err(e), } .change_context(UserErrors::InternalServerError) } pub fn get_index_for_correct_recovery_code( candidate: &Secret<String>, recovery_codes: &[Secret<String>], ) -> CustomResult<Option<usize>, UserErrors> { for (index, recovery_code) in recovery_codes.iter().enumerate() { let is_match = is_correct_password(candidate, recovery_code)?; if is_match { return Ok(Some(index)); } } Ok(None) } pub fn get_temp_password() -> Secret<String> { let uuid_pass = uuid::Uuid::new_v4().to_string(); let mut rng = rand::thread_rng(); let special_chars: Vec<char> = "!@#$%^&*()-_=+[]{}|;:,.<>?".chars().collect(); let special_char = special_chars.choose(&mut rng).unwrap_or(&'@'); Secret::new(format!( "{}{}{}{}{}", uuid_pass, rng.gen_range('A'..='Z'), special_char, rng.gen_range('a'..='z'), rng.gen_range('0'..='9'), )) }
537
1,541
hyperswitch
crates/router/src/utils/user/dashboard_metadata.rs
.rs
use std::{net::IpAddr, ops::Not, str::FromStr}; use actix_web::http::header::HeaderMap; use api_models::user::dashboard_metadata::{ GetMetaDataRequest, GetMultipleMetaDataPayload, ProdIntent, SetMetaDataRequest, }; use common_utils::id_type; use diesel_models::{ enums::DashboardMetadata as DBEnum, user::dashboard_metadata::{DashboardMetadata, DashboardMetadataNew, DashboardMetadataUpdate}, }; use error_stack::{report, ResultExt}; use masking::{ExposeInterface, PeekInterface, Secret}; use router_env::logger; use crate::{ core::errors::{UserErrors, UserResult}, headers, SessionState, }; pub async fn insert_merchant_scoped_metadata_to_db( state: &SessionState, user_id: String, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, metadata_key: DBEnum, metadata_value: impl serde::Serialize, ) -> UserResult<DashboardMetadata> { let now = common_utils::date_time::now(); let data_value = serde_json::to_value(metadata_value) .change_context(UserErrors::InternalServerError) .attach_printable("Error Converting Struct To Serde Value")?; state .store .insert_metadata(DashboardMetadataNew { user_id: None, merchant_id, org_id, data_key: metadata_key, data_value: Secret::from(data_value), created_by: user_id.clone(), created_at: now, last_modified_by: user_id, last_modified_at: now, }) .await .map_err(|e| { if e.current_context().is_db_unique_violation() { return e.change_context(UserErrors::MetadataAlreadySet); } e.change_context(UserErrors::InternalServerError) }) } pub async fn insert_user_scoped_metadata_to_db( state: &SessionState, user_id: String, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, metadata_key: DBEnum, metadata_value: impl serde::Serialize, ) -> UserResult<DashboardMetadata> { let now = common_utils::date_time::now(); let data_value = serde_json::to_value(metadata_value) .change_context(UserErrors::InternalServerError) .attach_printable("Error Converting Struct To Serde Value")?; state .store .insert_metadata(DashboardMetadataNew { user_id: Some(user_id.clone()), merchant_id, org_id, data_key: metadata_key, data_value: Secret::from(data_value), created_by: user_id.clone(), created_at: now, last_modified_by: user_id, last_modified_at: now, }) .await .map_err(|e| { if e.current_context().is_db_unique_violation() { return e.change_context(UserErrors::MetadataAlreadySet); } e.change_context(UserErrors::InternalServerError) }) } pub async fn get_merchant_scoped_metadata_from_db( state: &SessionState, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, metadata_keys: Vec<DBEnum>, ) -> UserResult<Vec<DashboardMetadata>> { state .store .find_merchant_scoped_dashboard_metadata(&merchant_id, &org_id, metadata_keys) .await .change_context(UserErrors::InternalServerError) .attach_printable("DB Error Fetching DashboardMetaData") } pub async fn get_user_scoped_metadata_from_db( state: &SessionState, user_id: String, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, metadata_keys: Vec<DBEnum>, ) -> UserResult<Vec<DashboardMetadata>> { match state .store .find_user_scoped_dashboard_metadata(&user_id, &merchant_id, &org_id, metadata_keys) .await { Ok(data) => Ok(data), Err(e) => { if e.current_context().is_db_not_found() { return Ok(Vec::with_capacity(0)); } Err(e .change_context(UserErrors::InternalServerError) .attach_printable("DB Error Fetching DashboardMetaData")) } } } pub async fn update_merchant_scoped_metadata( state: &SessionState, user_id: String, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, metadata_key: DBEnum, metadata_value: impl serde::Serialize, ) -> UserResult<DashboardMetadata> { let data_value = serde_json::to_value(metadata_value) .change_context(UserErrors::InternalServerError) .attach_printable("Error Converting Struct To Serde Value")?; state .store .update_metadata( None, merchant_id, org_id, metadata_key, DashboardMetadataUpdate::UpdateData { data_key: metadata_key, data_value: Secret::from(data_value), last_modified_by: user_id, }, ) .await .change_context(UserErrors::InternalServerError) } pub async fn update_user_scoped_metadata( state: &SessionState, user_id: String, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, metadata_key: DBEnum, metadata_value: impl serde::Serialize, ) -> UserResult<DashboardMetadata> { let data_value = serde_json::to_value(metadata_value) .change_context(UserErrors::InternalServerError) .attach_printable("Error Converting Struct To Serde Value")?; state .store .update_metadata( Some(user_id.clone()), merchant_id, org_id, metadata_key, DashboardMetadataUpdate::UpdateData { data_key: metadata_key, data_value: Secret::from(data_value), last_modified_by: user_id, }, ) .await .change_context(UserErrors::InternalServerError) } pub fn deserialize_to_response<T>(data: Option<&DashboardMetadata>) -> UserResult<Option<T>> where T: serde::de::DeserializeOwned, { data.map(|metadata| serde_json::from_value(metadata.data_value.clone().expose())) .transpose() .change_context(UserErrors::InternalServerError) .attach_printable("Error Serializing Metadata from DB") } pub fn separate_metadata_type_based_on_scope( metadata_keys: Vec<DBEnum>, ) -> (Vec<DBEnum>, Vec<DBEnum>) { let (mut merchant_scoped, mut user_scoped) = ( Vec::with_capacity(metadata_keys.len()), Vec::with_capacity(metadata_keys.len()), ); for key in metadata_keys { match key { DBEnum::ProductionAgreement | DBEnum::SetupProcessor | DBEnum::ConfigureEndpoint | DBEnum::SetupComplete | DBEnum::FirstProcessorConnected | DBEnum::SecondProcessorConnected | DBEnum::ConfiguredRouting | DBEnum::TestPayment | DBEnum::IntegrationMethod | DBEnum::ConfigurationType | DBEnum::IntegrationCompleted | DBEnum::StripeConnected | DBEnum::PaypalConnected | DBEnum::SpRoutingConfigured | DBEnum::SpTestPayment | DBEnum::DownloadWoocom | DBEnum::ConfigureWoocom | DBEnum::SetupWoocomWebhook | DBEnum::OnboardingSurvey | DBEnum::IsMultipleConfiguration | DBEnum::ReconStatus | DBEnum::ProdIntent => merchant_scoped.push(key), DBEnum::Feedback | DBEnum::IsChangePasswordRequired => user_scoped.push(key), } } (merchant_scoped, user_scoped) } pub fn is_update_required(metadata: &UserResult<DashboardMetadata>) -> bool { match metadata { Ok(_) => false, Err(e) => matches!(e.current_context(), UserErrors::MetadataAlreadySet), } } pub fn is_backfill_required(metadata_key: DBEnum) -> bool { matches!( metadata_key, DBEnum::StripeConnected | DBEnum::PaypalConnected ) } pub fn set_ip_address_if_required( request: &mut SetMetaDataRequest, headers: &HeaderMap, ) -> UserResult<()> { if let SetMetaDataRequest::ProductionAgreement(req) = request { let ip_address_from_request: Secret<String, common_utils::pii::IpAddress> = headers .get(headers::X_FORWARDED_FOR) .ok_or(report!(UserErrors::IpAddressParsingFailed)) .attach_printable("X-Forwarded-For header not found")? .to_str() .change_context(UserErrors::IpAddressParsingFailed) .attach_printable("Error converting Header Value to Str")? .split(',') .next() .and_then(|ip| { let ip_addr: Result<IpAddr, _> = ip.parse(); ip_addr.ok() }) .ok_or(report!(UserErrors::IpAddressParsingFailed)) .attach_printable("Error Parsing header value to ip")? .to_string() .into(); req.ip_address = Some(ip_address_from_request) } Ok(()) } pub fn parse_string_to_enums(query: String) -> UserResult<GetMultipleMetaDataPayload> { Ok(GetMultipleMetaDataPayload { results: query .split(',') .map(GetMetaDataRequest::from_str) .collect::<Result<Vec<GetMetaDataRequest>, _>>() .change_context(UserErrors::InvalidMetadataRequest) .attach_printable("Error Parsing to DashboardMetadata enums")?, }) } fn not_contains_string(value: Option<&str>, value_to_be_checked: &str) -> bool { value.is_some_and(|mail| !mail.contains(value_to_be_checked)) } pub fn is_prod_email_required(data: &ProdIntent, user_email: String) -> bool { let poc_email_check = not_contains_string( data.poc_email.as_ref().map(|email| email.peek().as_str()), "juspay", ); let business_website_check = not_contains_string(data.business_website.as_deref(), "juspay") && not_contains_string(data.business_website.as_deref(), "hyperswitch"); let user_email_check = not_contains_string(Some(&user_email), "juspay"); if (poc_email_check && business_website_check && user_email_check).not() { logger::info!(prod_intent_email = poc_email_check); logger::info!(prod_intent_email = business_website_check); logger::info!(prod_intent_email = user_email_check); } poc_email_check && business_website_check && user_email_check }
2,311
1,542
hyperswitch
crates/router/src/utils/user/theme.rs
.rs
use std::path::PathBuf; use common_enums::EntityType; use common_utils::{ext_traits::AsyncExt, id_type, types::theme::ThemeLineage}; use diesel_models::user::theme::Theme; use error_stack::ResultExt; use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore; use crate::{ core::errors::{StorageErrorExt, UserErrors, UserResult}, routes::SessionState, services::authentication::UserFromToken, }; fn get_theme_dir_key(theme_id: &str) -> PathBuf { ["themes", theme_id].iter().collect() } 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 } pub fn get_theme_file_key(theme_id: &str) -> PathBuf { get_specific_file_key(theme_id, "theme.json") } 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)) } 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) } 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) } pub async fn validate_lineage(state: &SessionState, lineage: &ThemeLineage) -> UserResult<()> { match lineage { ThemeLineage::Tenant { tenant_id } => { validate_tenant(state, tenant_id)?; Ok(()) } ThemeLineage::Organization { tenant_id, org_id } => { validate_tenant(state, tenant_id)?; validate_org(state, org_id).await?; Ok(()) } ThemeLineage::Merchant { tenant_id, org_id, merchant_id, } => { validate_tenant(state, tenant_id)?; validate_org(state, org_id).await?; validate_merchant(state, org_id, merchant_id).await?; Ok(()) } ThemeLineage::Profile { tenant_id, org_id, merchant_id, profile_id, } => { validate_tenant(state, tenant_id)?; validate_org(state, org_id).await?; let key_store = validate_merchant_and_get_key_store(state, org_id, merchant_id).await?; validate_profile(state, profile_id, merchant_id, &key_store).await?; Ok(()) } } } fn validate_tenant(state: &SessionState, tenant_id: &id_type::TenantId) -> UserResult<()> { if &state.tenant.tenant_id != tenant_id { return Err(UserErrors::InvalidThemeLineage("tenant_id".to_string()).into()); } Ok(()) } async fn validate_org(state: &SessionState, org_id: &id_type::OrganizationId) -> UserResult<()> { state .accounts_store .find_organization_by_org_id(org_id) .await .to_not_found_response(UserErrors::InvalidThemeLineage("org_id".to_string())) .map(|_| ()) } async fn validate_merchant_and_get_key_store( state: &SessionState, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, ) -> UserResult<MerchantKeyStore> { let key_store = state .store .get_merchant_key_store_by_merchant_id( &state.into(), merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .to_not_found_response(UserErrors::InvalidThemeLineage("merchant_id".to_string()))?; let merchant_account = state .store .find_merchant_account_by_merchant_id(&state.into(), merchant_id, &key_store) .await .to_not_found_response(UserErrors::InvalidThemeLineage("merchant_id".to_string()))?; if &merchant_account.organization_id != org_id { return Err(UserErrors::InvalidThemeLineage("merchant_id".to_string()).into()); } Ok(key_store) } async fn validate_merchant( state: &SessionState, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, ) -> UserResult<()> { validate_merchant_and_get_key_store(state, org_id, merchant_id) .await .map(|_| ()) } async fn validate_profile( state: &SessionState, profile_id: &id_type::ProfileId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, ) -> UserResult<()> { state .store .find_business_profile_by_merchant_id_profile_id( &state.into(), key_store, merchant_id, profile_id, ) .await .to_not_found_response(UserErrors::InvalidThemeLineage("profile_id".to_string())) .map(|_| ()) } pub async fn get_most_specific_theme_using_token_and_min_entity( state: &SessionState, user_from_token: &UserFromToken, min_entity: EntityType, ) -> UserResult<Option<Theme>> { get_most_specific_theme_using_lineage( state, ThemeLineage::new( min_entity, user_from_token .tenant_id .clone() .unwrap_or(state.tenant.tenant_id.clone()), user_from_token.org_id.clone(), user_from_token.merchant_id.clone(), user_from_token.profile_id.clone(), ), ) .await } pub async fn get_most_specific_theme_using_lineage( state: &SessionState, lineage: ThemeLineage, ) -> UserResult<Option<Theme>> { match state .store .find_most_specific_theme_in_lineage(lineage) .await { Ok(theme) => Ok(Some(theme)), Err(e) => { if e.current_context().is_db_not_found() { Ok(None) } else { Err(e.change_context(UserErrors::InternalServerError)) } } } } pub async fn get_theme_using_optional_theme_id( state: &SessionState, theme_id: Option<String>, ) -> UserResult<Option<Theme>> { match theme_id .async_map(|theme_id| state.store.find_theme_by_theme_id(theme_id)) .await .transpose() { Ok(theme) => Ok(theme), Err(e) => { if e.current_context().is_db_not_found() { Ok(None) } else { Err(e.change_context(UserErrors::InternalServerError)) } } } }
1,541
1,543
hyperswitch
crates/router/src/core/apple_pay_certificates_migration.rs
.rs
use api_models::apple_pay_certificates_migration; use common_utils::{errors::CustomResult, type_name, types::keymanager::Identifier}; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; use super::{ errors::{self, StorageErrorExt}, payments::helpers, }; use crate::{ routes::SessionState, services::{self, logger}, types::{domain::types as domain_types, storage}, }; #[cfg(feature = "v1")] pub async fn apple_pay_certificates_migration( state: SessionState, req: &apple_pay_certificates_migration::ApplePayCertificatesMigrationRequest, ) -> CustomResult< services::ApplicationResponse< apple_pay_certificates_migration::ApplePayCertificatesMigrationResponse, >, errors::ApiErrorResponse, > { let db = state.store.as_ref(); let merchant_id_list = &req.merchant_ids; let mut migration_successful_merchant_ids = vec![]; let mut migration_failed_merchant_ids = vec![]; let key_manager_state = &(&state).into(); for merchant_id in merchant_id_list { let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; let merchant_connector_accounts = db .find_merchant_connector_account_by_merchant_id_and_disabled_list( key_manager_state, merchant_id, true, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; let mut mca_to_update = vec![]; for connector_account in merchant_connector_accounts { let connector_apple_pay_metadata = helpers::get_applepay_metadata(connector_account.clone().metadata) .map_err(|error| { logger::error!( "Apple pay metadata parsing failed for {:?} in certificates migrations api {:?}", connector_account.clone().connector_name, error ) }) .ok(); if let Some(apple_pay_metadata) = connector_apple_pay_metadata { let encrypted_apple_pay_metadata = domain_types::crypto_operation( &(&state).into(), type_name!(storage::MerchantConnectorAccount), domain_types::CryptoOperation::Encrypt(Secret::new( serde_json::to_value(apple_pay_metadata) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize apple pay metadata as JSON")?, )), Identifier::Merchant(merchant_id.clone()), key_store.key.get_inner().peek(), ) .await .and_then(|val| val.try_into_operation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt connector apple pay metadata")?; let updated_mca = storage::MerchantConnectorAccountUpdate::ConnectorWalletDetailsUpdate { connector_wallets_details: encrypted_apple_pay_metadata, }; mca_to_update.push((connector_account, updated_mca.into())); } } let merchant_connector_accounts_update = db .update_multiple_merchant_connector_accounts(mca_to_update) .await; match merchant_connector_accounts_update { Ok(_) => { logger::debug!( "Merchant connector accounts updated for merchant id {merchant_id:?}" ); migration_successful_merchant_ids.push(merchant_id.clone()); } Err(error) => { logger::debug!( "Merchant connector accounts update failed with error {error} for merchant id {merchant_id:?}"); migration_failed_merchant_ids.push(merchant_id.clone()); } }; } Ok(services::api::ApplicationResponse::Json( apple_pay_certificates_migration::ApplePayCertificatesMigrationResponse { migration_successful: migration_successful_merchant_ids, migration_failed: migration_failed_merchant_ids, }, )) }
832
1,544
hyperswitch
crates/router/src/core/payment_link.rs
.rs
pub mod validator; use actix_web::http::header; use api_models::{ admin::PaymentLinkConfig, payments::{PaymentLinkData, PaymentLinkStatusWrap}, }; use common_utils::{ consts::{DEFAULT_LOCALE, DEFAULT_SESSION_EXPIRY}, ext_traits::{OptionExt, ValueExt}, types::{AmountConvertor, StringMajorUnitForCore}, }; use error_stack::{report, ResultExt}; use futures::future; use hyperswitch_domain_models::api::{GenericLinks, GenericLinksData}; use masking::{PeekInterface, Secret}; use router_env::logger; use time::PrimitiveDateTime; use super::{ errors::{self, RouterResult, StorageErrorExt}, payments::helpers, }; use crate::{ consts::{ self, DEFAULT_ALLOWED_DOMAINS, DEFAULT_BACKGROUND_COLOR, DEFAULT_DISPLAY_SDK_ONLY, DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY, DEFAULT_ENABLE_SAVED_PAYMENT_METHOD, DEFAULT_HIDE_CARD_NICKNAME_FIELD, DEFAULT_MERCHANT_LOGO, DEFAULT_PRODUCT_IMG, DEFAULT_SDK_LAYOUT, DEFAULT_SHOW_CARD_FORM, }, errors::RouterResponse, get_payment_link_config_value, get_payment_link_config_value_based_on_priority, routes::SessionState, services, types::{ api::payment_link::PaymentLinkResponseExt, domain, storage::{enums as storage_enums, payment_link::PaymentLink}, transformers::{ForeignFrom, ForeignInto}, }, }; pub async fn retrieve_payment_link( state: SessionState, payment_link_id: String, ) -> RouterResponse<api_models::payments::RetrievePaymentLinkResponse> { let db = &*state.store; let payment_link_config = db .find_payment_link_by_payment_link_id(&payment_link_id) .await .to_not_found_response(errors::ApiErrorResponse::PaymentLinkNotFound)?; let session_expiry = payment_link_config.fulfilment_time.unwrap_or_else(|| { common_utils::date_time::now() .saturating_add(time::Duration::seconds(DEFAULT_SESSION_EXPIRY)) }); let status = check_payment_link_status(session_expiry); let response = api_models::payments::RetrievePaymentLinkResponse::foreign_from(( payment_link_config, status, )); Ok(services::ApplicationResponse::Json(response)) } #[cfg(feature = "v2")] pub async fn form_payment_link_data( state: &SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, merchant_id: common_utils::id_type::MerchantId, payment_id: common_utils::id_type::PaymentId, ) -> RouterResult<(PaymentLink, PaymentLinkData, PaymentLinkConfig)> { todo!() } #[cfg(feature = "v1")] pub async fn form_payment_link_data( state: &SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, merchant_id: common_utils::id_type::MerchantId, payment_id: common_utils::id_type::PaymentId, ) -> RouterResult<(PaymentLink, PaymentLinkData, PaymentLinkConfig)> { let db = &*state.store; let key_manager_state = &state.into(); let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &(state).into(), &payment_id, &merchant_id, &key_store, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let payment_link_id = payment_intent .payment_link_id .get_required_value("payment_link_id") .change_context(errors::ApiErrorResponse::PaymentLinkNotFound)?; let merchant_name_from_merchant_account = merchant_account .merchant_name .clone() .map(|merchant_name| merchant_name.into_inner().peek().to_owned()) .unwrap_or_default(); let payment_link = db .find_payment_link_by_payment_link_id(&payment_link_id) .await .to_not_found_response(errors::ApiErrorResponse::PaymentLinkNotFound)?; let payment_link_config = if let Some(pl_config_value) = payment_link.payment_link_config.clone() { extract_payment_link_config(pl_config_value)? } else { PaymentLinkConfig { theme: DEFAULT_BACKGROUND_COLOR.to_string(), logo: DEFAULT_MERCHANT_LOGO.to_string(), seller_name: merchant_name_from_merchant_account, sdk_layout: DEFAULT_SDK_LAYOUT.to_owned(), display_sdk_only: DEFAULT_DISPLAY_SDK_ONLY, enabled_saved_payment_method: DEFAULT_ENABLE_SAVED_PAYMENT_METHOD, hide_card_nickname_field: DEFAULT_HIDE_CARD_NICKNAME_FIELD, show_card_form_by_default: DEFAULT_SHOW_CARD_FORM, allowed_domains: DEFAULT_ALLOWED_DOMAINS, transaction_details: None, background_image: None, details_layout: None, branding_visibility: None, payment_button_text: None, custom_message_for_card_terms: None, payment_button_colour: None, skip_status_screen: None, background_colour: None, payment_button_text_colour: None, sdk_ui_rules: None, payment_link_ui_rules: None, enable_button_only_on_form_ready: DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY, } }; let profile_id = payment_link .profile_id .clone() .or(payment_intent.profile_id) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Profile id missing in payment link and payment intent")?; let business_profile = db .find_business_profile_by_profile_id(key_manager_state, &key_store, &profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let return_url = if let Some(payment_create_return_url) = payment_intent.return_url.clone() { payment_create_return_url } else { business_profile .return_url .ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "return_url", })? }; let (currency, client_secret) = validate_sdk_requirements( payment_intent.currency, payment_intent.client_secret.clone(), )?; let required_conversion_type = StringMajorUnitForCore; let amount = required_conversion_type .convert(payment_intent.amount, currency) .change_context(errors::ApiErrorResponse::AmountConversionFailed { amount_type: "StringMajorUnit", })?; let order_details = validate_order_details(payment_intent.order_details.clone(), currency)?; let session_expiry = payment_link.fulfilment_time.unwrap_or_else(|| { payment_intent .created_at .saturating_add(time::Duration::seconds(DEFAULT_SESSION_EXPIRY)) }); // converting first letter of merchant name to upperCase let merchant_name = capitalize_first_char(&payment_link_config.seller_name); let payment_link_status = check_payment_link_status(session_expiry); let is_payment_link_terminal_state = check_payment_link_invalid_conditions( payment_intent.status, &[ storage_enums::IntentStatus::Cancelled, storage_enums::IntentStatus::Failed, storage_enums::IntentStatus::Processing, storage_enums::IntentStatus::RequiresCapture, storage_enums::IntentStatus::RequiresMerchantAction, storage_enums::IntentStatus::Succeeded, storage_enums::IntentStatus::PartiallyCaptured, storage_enums::IntentStatus::RequiresCustomerAction, ], ); if is_payment_link_terminal_state || payment_link_status == api_models::payments::PaymentLinkStatus::Expired { let status = match payment_link_status { api_models::payments::PaymentLinkStatus::Active => { logger::info!("displaying status page as the requested payment link has reached terminal state with payment status as {:?}", payment_intent.status); PaymentLinkStatusWrap::IntentStatus(payment_intent.status) } api_models::payments::PaymentLinkStatus::Expired => { if is_payment_link_terminal_state { logger::info!("displaying status page as the requested payment link has reached terminal state with payment status as {:?}", payment_intent.status); PaymentLinkStatusWrap::IntentStatus(payment_intent.status) } else { logger::info!( "displaying status page as the requested payment link has expired" ); PaymentLinkStatusWrap::PaymentLinkStatus( api_models::payments::PaymentLinkStatus::Expired, ) } } }; let attempt_id = payment_intent.active_attempt.get_id().clone(); let payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, &merchant_id, &attempt_id.clone(), merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let payment_details = api_models::payments::PaymentLinkStatusDetails { amount, currency, payment_id: payment_intent.payment_id, merchant_name, merchant_logo: payment_link_config.logo.clone(), created: payment_link.created_at, status, error_code: payment_attempt.error_code, error_message: payment_attempt.error_message, redirect: false, theme: payment_link_config.theme.clone(), return_url: return_url.clone(), locale: Some(state.clone().locale), transaction_details: payment_link_config.transaction_details.clone(), unified_code: payment_attempt.unified_code, unified_message: payment_attempt.unified_message, }; return Ok(( payment_link, PaymentLinkData::PaymentLinkStatusDetails(Box::new(payment_details)), payment_link_config, )); }; let payment_link_details = api_models::payments::PaymentLinkDetails { amount, currency, payment_id: payment_intent.payment_id, merchant_name, order_details, return_url, session_expiry, pub_key: merchant_account.publishable_key, client_secret, merchant_logo: payment_link_config.logo.clone(), max_items_visible_after_collapse: 3, theme: payment_link_config.theme.clone(), merchant_description: payment_intent.description, sdk_layout: payment_link_config.sdk_layout.clone(), display_sdk_only: payment_link_config.display_sdk_only, hide_card_nickname_field: payment_link_config.hide_card_nickname_field, show_card_form_by_default: payment_link_config.show_card_form_by_default, locale: Some(state.clone().locale), transaction_details: payment_link_config.transaction_details.clone(), background_image: payment_link_config.background_image.clone(), details_layout: payment_link_config.details_layout, branding_visibility: payment_link_config.branding_visibility, payment_button_text: payment_link_config.payment_button_text.clone(), custom_message_for_card_terms: payment_link_config.custom_message_for_card_terms.clone(), payment_button_colour: payment_link_config.payment_button_colour.clone(), skip_status_screen: payment_link_config.skip_status_screen, background_colour: payment_link_config.background_colour.clone(), payment_button_text_colour: payment_link_config.payment_button_text_colour.clone(), sdk_ui_rules: payment_link_config.sdk_ui_rules.clone(), payment_link_ui_rules: payment_link_config.payment_link_ui_rules.clone(), status: payment_intent.status, enable_button_only_on_form_ready: payment_link_config.enable_button_only_on_form_ready, }; Ok(( payment_link, PaymentLinkData::PaymentLinkDetails(Box::new(payment_link_details)), payment_link_config, )) } pub async fn initiate_secure_payment_link_flow( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, merchant_id: common_utils::id_type::MerchantId, payment_id: common_utils::id_type::PaymentId, request_headers: &header::HeaderMap, ) -> RouterResponse<services::PaymentLinkFormData> { let (payment_link, payment_link_details, payment_link_config) = form_payment_link_data(&state, merchant_account, key_store, merchant_id, payment_id) .await?; validator::validate_secure_payment_link_render_request( request_headers, &payment_link, &payment_link_config, )?; let css_script = get_color_scheme_css(&payment_link_config); match payment_link_details { PaymentLinkData::PaymentLinkStatusDetails(ref status_details) => { let js_script = get_js_script(&payment_link_details)?; let payment_link_error_data = services::PaymentLinkStatusData { js_script, css_script, }; logger::info!( "payment link data, for building payment link status page {:?}", status_details ); Ok(services::ApplicationResponse::PaymentLinkForm(Box::new( services::api::PaymentLinkAction::PaymentLinkStatus(payment_link_error_data), ))) } PaymentLinkData::PaymentLinkDetails(link_details) => { let secure_payment_link_details = api_models::payments::SecurePaymentLinkDetails { enabled_saved_payment_method: payment_link_config.enabled_saved_payment_method, hide_card_nickname_field: payment_link_config.hide_card_nickname_field, show_card_form_by_default: payment_link_config.show_card_form_by_default, payment_link_details: *link_details.to_owned(), payment_button_text: payment_link_config.payment_button_text, custom_message_for_card_terms: payment_link_config.custom_message_for_card_terms, payment_button_colour: payment_link_config.payment_button_colour, skip_status_screen: payment_link_config.skip_status_screen, background_colour: payment_link_config.background_colour, payment_button_text_colour: payment_link_config.payment_button_text_colour, sdk_ui_rules: payment_link_config.sdk_ui_rules, payment_link_ui_rules: payment_link_config.payment_link_ui_rules, enable_button_only_on_form_ready: payment_link_config .enable_button_only_on_form_ready, }; let js_script = format!( "window.__PAYMENT_DETAILS = {}", serde_json::to_string(&secure_payment_link_details) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize PaymentLinkData")? ); let html_meta_tags = get_meta_tags_html(&link_details); let payment_link_data = services::PaymentLinkFormData { js_script, sdk_url: state.conf.payment_link.sdk_url.clone(), css_script, html_meta_tags, }; let allowed_domains = payment_link_config .allowed_domains .clone() .ok_or(report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| { format!( "Invalid list of allowed_domains found - {:?}", payment_link_config.allowed_domains.clone() ) })?; if allowed_domains.is_empty() { return Err(report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| { format!( "Invalid list of allowed_domains found - {:?}", payment_link_config.allowed_domains.clone() ) }); } let link_data = GenericLinks { allowed_domains, data: GenericLinksData::SecurePaymentLink(payment_link_data), locale: DEFAULT_LOCALE.to_string(), }; logger::info!( "payment link data, for building secure payment link {:?}", link_data ); Ok(services::ApplicationResponse::GenericLinkForm(Box::new( link_data, ))) } } } pub async fn initiate_payment_link_flow( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, merchant_id: common_utils::id_type::MerchantId, payment_id: common_utils::id_type::PaymentId, ) -> RouterResponse<services::PaymentLinkFormData> { let (_, payment_details, payment_link_config) = form_payment_link_data(&state, merchant_account, key_store, merchant_id, payment_id) .await?; let css_script = get_color_scheme_css(&payment_link_config); let js_script = get_js_script(&payment_details)?; match payment_details { PaymentLinkData::PaymentLinkStatusDetails(status_details) => { let payment_link_error_data = services::PaymentLinkStatusData { js_script, css_script, }; logger::info!( "payment link data, for building payment link status page {:?}", status_details ); Ok(services::ApplicationResponse::PaymentLinkForm(Box::new( services::api::PaymentLinkAction::PaymentLinkStatus(payment_link_error_data), ))) } PaymentLinkData::PaymentLinkDetails(payment_details) => { let html_meta_tags = get_meta_tags_html(&payment_details); let payment_link_data = services::PaymentLinkFormData { js_script, sdk_url: state.conf.payment_link.sdk_url.clone(), css_script, html_meta_tags, }; logger::info!( "payment link data, for building open payment link {:?}", payment_link_data ); Ok(services::ApplicationResponse::PaymentLinkForm(Box::new( services::api::PaymentLinkAction::PaymentLinkFormData(payment_link_data), ))) } } } /* The get_js_script function is used to inject dynamic value to payment_link sdk, which is unique to every payment. */ fn get_js_script(payment_details: &PaymentLinkData) -> RouterResult<String> { let payment_details_str = serde_json::to_string(payment_details) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize PaymentLinkData")?; Ok(format!("window.__PAYMENT_DETAILS = {payment_details_str};")) } fn get_color_scheme_css(payment_link_config: &PaymentLinkConfig) -> String { let background_primary_color = payment_link_config .background_colour .clone() .unwrap_or(payment_link_config.theme.clone()); format!( ":root {{ --primary-color: {background_primary_color}; }}" ) } fn get_meta_tags_html(payment_details: &api_models::payments::PaymentLinkDetails) -> String { format!( r#"<meta property="og:title" content="Payment request from {0}"/> <meta property="og:description" content="{1}"/>"#, payment_details.merchant_name.clone(), payment_details .merchant_description .clone() .unwrap_or_default() ) } fn validate_sdk_requirements( currency: Option<api_models::enums::Currency>, client_secret: Option<String>, ) -> Result<(api_models::enums::Currency, String), errors::ApiErrorResponse> { let currency = currency.ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "currency", })?; let client_secret = client_secret.ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "client_secret", })?; Ok((currency, client_secret)) } pub async fn list_payment_link( state: SessionState, merchant: domain::MerchantAccount, constraints: api_models::payments::PaymentLinkListConstraints, ) -> RouterResponse<Vec<api_models::payments::RetrievePaymentLinkResponse>> { let db = state.store.as_ref(); let payment_link = db .list_payment_link_by_merchant_id(merchant.get_id(), constraints) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to retrieve payment link")?; let payment_link_list = future::try_join_all(payment_link.into_iter().map(|payment_link| { api_models::payments::RetrievePaymentLinkResponse::from_db_payment_link(payment_link) })) .await?; Ok(services::ApplicationResponse::Json(payment_link_list)) } pub fn check_payment_link_status( payment_link_expiry: PrimitiveDateTime, ) -> api_models::payments::PaymentLinkStatus { let curr_time = common_utils::date_time::now(); if curr_time > payment_link_expiry { api_models::payments::PaymentLinkStatus::Expired } else { api_models::payments::PaymentLinkStatus::Active } } fn validate_order_details( order_details: Option<Vec<Secret<serde_json::Value>>>, currency: api_models::enums::Currency, ) -> Result< Option<Vec<api_models::payments::OrderDetailsWithStringAmount>>, error_stack::Report<errors::ApiErrorResponse>, > { let required_conversion_type = StringMajorUnitForCore; let order_details = order_details .map(|order_details| { order_details .iter() .map(|data| { data.to_owned() .parse_value("OrderDetailsWithAmount") .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "OrderDetailsWithAmount", }) .attach_printable("Unable to parse OrderDetailsWithAmount") }) .collect::<Result<Vec<api_models::payments::OrderDetailsWithAmount>, _>>() }) .transpose()?; let updated_order_details = match order_details { Some(mut order_details) => { let mut order_details_amount_string_array: Vec< api_models::payments::OrderDetailsWithStringAmount, > = Vec::new(); for order in order_details.iter_mut() { let mut order_details_amount_string : api_models::payments::OrderDetailsWithStringAmount = Default::default(); if order.product_img_link.is_none() { order_details_amount_string.product_img_link = Some(DEFAULT_PRODUCT_IMG.to_string()) } else { order_details_amount_string .product_img_link .clone_from(&order.product_img_link) }; order_details_amount_string.amount = required_conversion_type .convert(order.amount, currency) .change_context(errors::ApiErrorResponse::AmountConversionFailed { amount_type: "StringMajorUnit", })?; order_details_amount_string.product_name = capitalize_first_char(&order.product_name.clone()); order_details_amount_string.quantity = order.quantity; order_details_amount_string_array.push(order_details_amount_string) } Some(order_details_amount_string_array) } None => None, }; Ok(updated_order_details) } pub fn extract_payment_link_config( pl_config: serde_json::Value, ) -> Result<PaymentLinkConfig, error_stack::Report<errors::ApiErrorResponse>> { serde_json::from_value::<PaymentLinkConfig>(pl_config).change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "payment_link_config", }, ) } pub fn get_payment_link_config_based_on_priority( payment_create_link_config: Option<api_models::payments::PaymentCreatePaymentLinkConfig>, business_link_config: Option<diesel_models::business_profile::BusinessPaymentLinkConfig>, merchant_name: String, default_domain_name: String, payment_link_config_id: Option<String>, ) -> Result<(PaymentLinkConfig, String), error_stack::Report<errors::ApiErrorResponse>> { let (domain_name, business_theme_configs, allowed_domains, branding_visibility) = if let Some(business_config) = business_link_config { ( business_config .domain_name .clone() .map(|d_name| { logger::info!("domain name set to custom domain https://{:?}", d_name); format!("https://{}", d_name) }) .unwrap_or_else(|| default_domain_name.clone()), payment_link_config_id .and_then(|id| { business_config .business_specific_configs .as_ref() .and_then(|specific_configs| specific_configs.get(&id).cloned()) }) .or(business_config.default_config), business_config.allowed_domains, business_config.branding_visibility, ) } else { (default_domain_name, None, None, None) }; let ( theme, logo, seller_name, sdk_layout, display_sdk_only, enabled_saved_payment_method, hide_card_nickname_field, show_card_form_by_default, enable_button_only_on_form_ready, ) = get_payment_link_config_value!( payment_create_link_config, business_theme_configs, (theme, DEFAULT_BACKGROUND_COLOR.to_string()), (logo, DEFAULT_MERCHANT_LOGO.to_string()), (seller_name, merchant_name.clone()), (sdk_layout, DEFAULT_SDK_LAYOUT.to_owned()), (display_sdk_only, DEFAULT_DISPLAY_SDK_ONLY), ( enabled_saved_payment_method, DEFAULT_ENABLE_SAVED_PAYMENT_METHOD ), (hide_card_nickname_field, DEFAULT_HIDE_CARD_NICKNAME_FIELD), (show_card_form_by_default, DEFAULT_SHOW_CARD_FORM), ( enable_button_only_on_form_ready, DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY ) ); let ( details_layout, background_image, payment_button_text, custom_message_for_card_terms, payment_button_colour, skip_status_screen, background_colour, payment_button_text_colour, sdk_ui_rules, payment_link_ui_rules, ) = get_payment_link_config_value!( payment_create_link_config, business_theme_configs, (details_layout), (background_image, |background_image| background_image .foreign_into()), (payment_button_text), (custom_message_for_card_terms), (payment_button_colour), (skip_status_screen), (background_colour), (payment_button_text_colour), (sdk_ui_rules), (payment_link_ui_rules), ); let payment_link_config = PaymentLinkConfig { theme, logo, seller_name, sdk_layout, display_sdk_only, enabled_saved_payment_method, hide_card_nickname_field, show_card_form_by_default, allowed_domains, branding_visibility, skip_status_screen, transaction_details: payment_create_link_config.as_ref().and_then( |payment_link_config| payment_link_config.theme_config.transaction_details.clone(), ), details_layout, background_image, payment_button_text, custom_message_for_card_terms, payment_button_colour, background_colour, payment_button_text_colour, sdk_ui_rules, payment_link_ui_rules, enable_button_only_on_form_ready, }; Ok((payment_link_config, domain_name)) } fn capitalize_first_char(s: &str) -> String { if let Some(first_char) = s.chars().next() { let capitalized = first_char.to_uppercase(); let mut result = capitalized.to_string(); if let Some(remaining) = s.get(1..) { result.push_str(remaining); } result } else { s.to_owned() } } fn check_payment_link_invalid_conditions( intent_status: storage_enums::IntentStatus, not_allowed_statuses: &[storage_enums::IntentStatus], ) -> bool { not_allowed_statuses.contains(&intent_status) } #[cfg(feature = "v2")] pub async fn get_payment_link_status( _state: SessionState, _merchant_account: domain::MerchantAccount, _key_store: domain::MerchantKeyStore, _merchant_id: common_utils::id_type::MerchantId, _payment_id: common_utils::id_type::PaymentId, ) -> RouterResponse<services::PaymentLinkFormData> { todo!() } #[cfg(feature = "v1")] pub async fn get_payment_link_status( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, merchant_id: common_utils::id_type::MerchantId, payment_id: common_utils::id_type::PaymentId, ) -> RouterResponse<services::PaymentLinkFormData> { let db = &*state.store; let key_manager_state = &(&state).into(); let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( key_manager_state, &payment_id, &merchant_id, &key_store, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let attempt_id = payment_intent.active_attempt.get_id().clone(); let payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, &merchant_id, &attempt_id.clone(), merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let payment_link_id = payment_intent .payment_link_id .get_required_value("payment_link_id") .change_context(errors::ApiErrorResponse::PaymentLinkNotFound)?; let merchant_name_from_merchant_account = merchant_account .merchant_name .clone() .map(|merchant_name| merchant_name.into_inner().peek().to_owned()) .unwrap_or_default(); let payment_link = db .find_payment_link_by_payment_link_id(&payment_link_id) .await .to_not_found_response(errors::ApiErrorResponse::PaymentLinkNotFound)?; let payment_link_config = if let Some(pl_config_value) = payment_link.payment_link_config { extract_payment_link_config(pl_config_value)? } else { PaymentLinkConfig { theme: DEFAULT_BACKGROUND_COLOR.to_string(), logo: DEFAULT_MERCHANT_LOGO.to_string(), seller_name: merchant_name_from_merchant_account, sdk_layout: DEFAULT_SDK_LAYOUT.to_owned(), display_sdk_only: DEFAULT_DISPLAY_SDK_ONLY, enabled_saved_payment_method: DEFAULT_ENABLE_SAVED_PAYMENT_METHOD, hide_card_nickname_field: DEFAULT_HIDE_CARD_NICKNAME_FIELD, show_card_form_by_default: DEFAULT_SHOW_CARD_FORM, allowed_domains: DEFAULT_ALLOWED_DOMAINS, transaction_details: None, background_image: None, details_layout: None, branding_visibility: None, payment_button_text: None, custom_message_for_card_terms: None, payment_button_colour: None, skip_status_screen: None, background_colour: None, payment_button_text_colour: None, sdk_ui_rules: None, payment_link_ui_rules: None, enable_button_only_on_form_ready: DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY, } }; let currency = payment_intent .currency .ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "currency", })?; let required_conversion_type = StringMajorUnitForCore; let amount = required_conversion_type .convert(payment_attempt.get_total_amount(), currency) .change_context(errors::ApiErrorResponse::AmountConversionFailed { amount_type: "StringMajorUnit", })?; // converting first letter of merchant name to upperCase let merchant_name = capitalize_first_char(&payment_link_config.seller_name); let css_script = get_color_scheme_css(&payment_link_config); let profile_id = payment_link .profile_id .or(payment_intent.profile_id) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Profile id missing in payment link and payment intent")?; let business_profile = db .find_business_profile_by_profile_id(key_manager_state, &key_store, &profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let return_url = if let Some(payment_create_return_url) = payment_intent.return_url.clone() { payment_create_return_url } else { business_profile .return_url .ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "return_url", })? }; let (unified_code, unified_message) = if let Some((code, message)) = payment_attempt .unified_code .as_ref() .zip(payment_attempt.unified_message.as_ref()) { (code.to_owned(), message.to_owned()) } else { ( consts::DEFAULT_UNIFIED_ERROR_CODE.to_owned(), consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_owned(), ) }; let unified_translated_message = helpers::get_unified_translation( &state, unified_code.to_owned(), unified_message.to_owned(), state.locale.clone(), ) .await .or(Some(unified_message)); let payment_details = api_models::payments::PaymentLinkStatusDetails { amount, currency, payment_id: payment_intent.payment_id, merchant_name, merchant_logo: payment_link_config.logo.clone(), created: payment_link.created_at, status: PaymentLinkStatusWrap::IntentStatus(payment_intent.status), error_code: payment_attempt.error_code, error_message: payment_attempt.error_message, redirect: true, theme: payment_link_config.theme.clone(), return_url, locale: Some(state.locale.clone()), transaction_details: payment_link_config.transaction_details, unified_code: Some(unified_code), unified_message: unified_translated_message, }; let js_script = get_js_script(&PaymentLinkData::PaymentLinkStatusDetails(Box::new( payment_details, )))?; let payment_link_status_data = services::PaymentLinkStatusData { js_script, css_script, }; Ok(services::ApplicationResponse::PaymentLinkForm(Box::new( services::api::PaymentLinkAction::PaymentLinkStatus(payment_link_status_data), ))) }
6,983
1,545
hyperswitch
crates/router/src/core/metrics.rs
.rs
use router_env::{counter_metric, global_meter}; global_meter!(GLOBAL_METER, "ROUTER_API"); counter_metric!(INCOMING_DISPUTE_WEBHOOK_METRIC, GLOBAL_METER); // No. of incoming dispute webhooks counter_metric!( INCOMING_DISPUTE_WEBHOOK_SIGNATURE_FAILURE_METRIC, GLOBAL_METER ); // No. of incoming dispute webhooks for which signature verification failed counter_metric!( INCOMING_DISPUTE_WEBHOOK_VALIDATION_FAILURE_METRIC, GLOBAL_METER ); // No. of incoming dispute webhooks for which validation failed counter_metric!(INCOMING_DISPUTE_WEBHOOK_NEW_RECORD_METRIC, GLOBAL_METER); // No. of incoming dispute webhooks for which new record is created in our db counter_metric!(INCOMING_DISPUTE_WEBHOOK_UPDATE_RECORD_METRIC, GLOBAL_METER); // No. of incoming dispute webhooks for which we have updated the details to existing record counter_metric!( INCOMING_DISPUTE_WEBHOOK_MERCHANT_NOTIFIED_METRIC, GLOBAL_METER ); // No. of incoming dispute webhooks which are notified to merchant counter_metric!( ACCEPT_DISPUTE_STATUS_VALIDATION_FAILURE_METRIC, GLOBAL_METER ); //No. of status validation failures while accepting a dispute counter_metric!( EVIDENCE_SUBMISSION_DISPUTE_STATUS_VALIDATION_FAILURE_METRIC, GLOBAL_METER ); //No. of status validation failures while submitting evidence for a dispute //No. of status validation failures while attaching evidence for a dispute counter_metric!( ATTACH_EVIDENCE_DISPUTE_STATUS_VALIDATION_FAILURE_METRIC, GLOBAL_METER ); counter_metric!(INCOMING_PAYOUT_WEBHOOK_METRIC, GLOBAL_METER); // No. of incoming payout webhooks counter_metric!( INCOMING_PAYOUT_WEBHOOK_SIGNATURE_FAILURE_METRIC, GLOBAL_METER ); // No. of incoming payout webhooks for which signature verification failed counter_metric!(WEBHOOK_INCOMING_COUNT, GLOBAL_METER); counter_metric!(WEBHOOK_INCOMING_FILTERED_COUNT, GLOBAL_METER); counter_metric!(WEBHOOK_SOURCE_VERIFIED_COUNT, GLOBAL_METER); counter_metric!(WEBHOOK_OUTGOING_COUNT, GLOBAL_METER); counter_metric!(WEBHOOK_OUTGOING_RECEIVED_COUNT, GLOBAL_METER); counter_metric!(WEBHOOK_OUTGOING_NOT_RECEIVED_COUNT, GLOBAL_METER); counter_metric!(WEBHOOK_PAYMENT_NOT_FOUND, GLOBAL_METER); counter_metric!( WEBHOOK_EVENT_TYPE_IDENTIFICATION_FAILURE_COUNT, GLOBAL_METER ); counter_metric!(ROUTING_CREATE_REQUEST_RECEIVED, GLOBAL_METER); counter_metric!(ROUTING_CREATE_SUCCESS_RESPONSE, GLOBAL_METER); counter_metric!(ROUTING_MERCHANT_DICTIONARY_RETRIEVE, GLOBAL_METER); counter_metric!( ROUTING_MERCHANT_DICTIONARY_RETRIEVE_SUCCESS_RESPONSE, GLOBAL_METER ); counter_metric!(ROUTING_LINK_CONFIG, GLOBAL_METER); counter_metric!(ROUTING_LINK_CONFIG_SUCCESS_RESPONSE, GLOBAL_METER); counter_metric!(ROUTING_RETRIEVE_CONFIG, GLOBAL_METER); counter_metric!(ROUTING_RETRIEVE_CONFIG_SUCCESS_RESPONSE, GLOBAL_METER); counter_metric!(ROUTING_RETRIEVE_DEFAULT_CONFIG, GLOBAL_METER); counter_metric!( ROUTING_RETRIEVE_DEFAULT_CONFIG_SUCCESS_RESPONSE, GLOBAL_METER ); counter_metric!(ROUTING_RETRIEVE_LINK_CONFIG, GLOBAL_METER); counter_metric!(ROUTING_RETRIEVE_LINK_CONFIG_SUCCESS_RESPONSE, GLOBAL_METER); counter_metric!(ROUTING_UNLINK_CONFIG, GLOBAL_METER); counter_metric!(ROUTING_UNLINK_CONFIG_SUCCESS_RESPONSE, GLOBAL_METER); counter_metric!(ROUTING_UPDATE_CONFIG, GLOBAL_METER); counter_metric!(ROUTING_UPDATE_CONFIG_SUCCESS_RESPONSE, GLOBAL_METER); counter_metric!(ROUTING_UPDATE_CONFIG_FOR_PROFILE, GLOBAL_METER); counter_metric!( ROUTING_UPDATE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE, GLOBAL_METER ); counter_metric!(ROUTING_RETRIEVE_CONFIG_FOR_PROFILE, GLOBAL_METER); counter_metric!( ROUTING_RETRIEVE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE, GLOBAL_METER ); counter_metric!(DYNAMIC_SUCCESS_BASED_ROUTING, GLOBAL_METER); counter_metric!(DYNAMIC_CONTRACT_BASED_ROUTING, GLOBAL_METER); #[cfg(feature = "partial-auth")] counter_metric!(PARTIAL_AUTH_FAILURE, GLOBAL_METER); counter_metric!(API_KEY_REQUEST_INITIATED, GLOBAL_METER); counter_metric!(API_KEY_REQUEST_COMPLETED, GLOBAL_METER);
926
1,546
hyperswitch
crates/router/src/core/external_service_auth.rs
.rs
use api_models::external_service_auth as external_service_auth_api; use common_utils::fp_utils; use error_stack::ResultExt; use masking::ExposeInterface; use crate::{ core::errors::{self, RouterResponse}, services::{ api as service_api, authentication::{self, ExternalServiceType, ExternalToken}, }, SessionState, }; pub async fn generate_external_token( state: SessionState, user: authentication::UserFromToken, external_service_type: ExternalServiceType, ) -> RouterResponse<external_service_auth_api::ExternalTokenResponse> { let token = ExternalToken::new_token( user.user_id.clone(), user.merchant_id.clone(), &state.conf, external_service_type.clone(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed to create external token for params [user_id, mid, external_service_type] [{}, {:?}, {:?}]", user.user_id, user.merchant_id, external_service_type, ) })?; Ok(service_api::ApplicationResponse::Json( external_service_auth_api::ExternalTokenResponse { token: token.into(), }, )) } pub async fn signout_external_token( state: SessionState, json_payload: external_service_auth_api::ExternalSignoutTokenRequest, ) -> RouterResponse<()> { let token = authentication::decode_jwt::<ExternalToken>(&json_payload.token.expose(), &state) .await .change_context(errors::ApiErrorResponse::Unauthorized)?; authentication::blacklist::insert_user_in_blacklist(&state, &token.user_id) .await .change_context(errors::ApiErrorResponse::InvalidJwtToken)?; Ok(service_api::ApplicationResponse::StatusOk) } pub async fn verify_external_token( state: SessionState, json_payload: external_service_auth_api::ExternalVerifyTokenRequest, external_service_type: ExternalServiceType, ) -> RouterResponse<external_service_auth_api::ExternalVerifyTokenResponse> { let token_from_payload = json_payload.token.expose(); let token = authentication::decode_jwt::<ExternalToken>(&token_from_payload, &state) .await .change_context(errors::ApiErrorResponse::Unauthorized)?; fp_utils::when( authentication::blacklist::check_user_in_blacklist(&state, &token.user_id, token.exp) .await?, || Err(errors::ApiErrorResponse::InvalidJwtToken), )?; token.check_service_type(&external_service_type)?; let user_in_db = state .global_store .find_user_by_id(&token.user_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("User not found in database")?; let email = user_in_db.email.clone(); let name = user_in_db.name; Ok(service_api::ApplicationResponse::Json( external_service_auth_api::ExternalVerifyTokenResponse::Hypersense { user_id: user_in_db.user_id, merchant_id: token.merchant_id, name, email, }, )) }
661
1,547
hyperswitch
crates/router/src/core/conditional_config.rs
.rs
#[cfg(feature = "v2")] use api_models::conditional_configs::DecisionManagerRequest; use api_models::conditional_configs::{ DecisionManager, DecisionManagerRecord, DecisionManagerResponse, }; use common_utils::ext_traits::StringExt; #[cfg(feature = "v2")] use common_utils::types::keymanager::KeyManagerState; use error_stack::ResultExt; use crate::{ core::errors::{self, RouterResponse}, routes::SessionState, services::api as service_api, types::domain, }; #[cfg(feature = "v2")] pub async fn upsert_conditional_config( state: SessionState, key_store: domain::MerchantKeyStore, request: DecisionManagerRequest, profile: domain::Profile, ) -> RouterResponse<common_types::payments::DecisionManagerRecord> { use common_utils::ext_traits::OptionExt; let key_manager_state: &KeyManagerState = &(&state).into(); let db = &*state.store; let name = request.name; let program = request.program; let timestamp = common_utils::date_time::now_unix_timestamp(); euclid::frontend::ast::lowering::lower_program(program.clone()) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid Request Data".to_string(), }) .attach_printable("The Request has an Invalid Comparison")?; let decision_manager_record = common_types::payments::DecisionManagerRecord { name, program, created_at: timestamp, }; let business_profile_update = domain::ProfileUpdate::DecisionManagerRecordUpdate { three_ds_decision_manager_config: decision_manager_record, }; let updated_profile = db .update_profile_by_profile_id( key_manager_state, &key_store, profile, business_profile_update, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update decision manager record in business profile")?; Ok(service_api::ApplicationResponse::Json( updated_profile .three_ds_decision_manager_config .clone() .get_required_value("three_ds_decision_manager_config") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to get updated decision manager record in business profile", )?, )) } #[cfg(feature = "v1")] pub async fn upsert_conditional_config( state: SessionState, key_store: domain::MerchantKeyStore, merchant_account: domain::MerchantAccount, request: DecisionManager, ) -> RouterResponse<DecisionManagerRecord> { use common_utils::ext_traits::{Encode, OptionExt, ValueExt}; use diesel_models::configs; use storage_impl::redis::cache; use super::routing::helpers::update_merchant_active_algorithm_ref; let db = state.store.as_ref(); let (name, prog) = match request { DecisionManager::DecisionManagerv0(ccr) => { let name = ccr.name; let prog = ccr .algorithm .get_required_value("algorithm") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "algorithm", }) .attach_printable("Algorithm for config not given")?; (name, prog) } DecisionManager::DecisionManagerv1(dmr) => { let name = dmr.name; let prog = dmr .program .get_required_value("program") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "program", }) .attach_printable("Program for config not given")?; (name, prog) } }; let timestamp = common_utils::date_time::now_unix_timestamp(); let mut algo_id: api_models::routing::RoutingAlgorithmRef = merchant_account .routing_algorithm .clone() .map(|val| val.parse_value("routing algorithm")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not decode the routing algorithm")? .unwrap_or_default(); let key = merchant_account.get_id().get_payment_config_routing_id(); let read_config_key = db.find_config_by_key(&key).await; euclid::frontend::ast::lowering::lower_program(prog.clone()) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid Request Data".to_string(), }) .attach_printable("The Request has an Invalid Comparison")?; match read_config_key { Ok(config) => { let previous_record: DecisionManagerRecord = config .config .parse_struct("DecisionManagerRecord") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("The Payment Config Key Not Found")?; let new_algo = DecisionManagerRecord { name: previous_record.name, program: prog, modified_at: timestamp, created_at: previous_record.created_at, }; let serialize_updated_str = new_algo .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to serialize config to string")?; let updated_config = configs::ConfigUpdate::Update { config: Some(serialize_updated_str), }; db.update_config_by_key(&key, updated_config) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error serializing the config")?; algo_id.update_conditional_config_id(key.clone()); let config_key = cache::CacheKind::DecisionManager(key.into()); update_merchant_active_algorithm_ref(&state, &key_store, config_key, algo_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update routing algorithm ref")?; Ok(service_api::ApplicationResponse::Json(new_algo)) } Err(e) if e.current_context().is_db_not_found() => { let new_rec = DecisionManagerRecord { name: name .get_required_value("name") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "name", }) .attach_printable("name of the config not found")?, program: prog, modified_at: timestamp, created_at: timestamp, }; let serialized_str = new_rec .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error serializing the config")?; let new_config = configs::ConfigNew { key: key.clone(), config: serialized_str, }; db.insert_config(new_config) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error fetching the config")?; algo_id.update_conditional_config_id(key.clone()); let config_key = cache::CacheKind::DecisionManager(key.into()); update_merchant_active_algorithm_ref(&state, &key_store, config_key, algo_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update routing algorithm ref")?; Ok(service_api::ApplicationResponse::Json(new_rec)) } Err(e) => Err(e) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error fetching payment config"), } } #[cfg(feature = "v2")] pub async fn delete_conditional_config( _state: SessionState, _key_store: domain::MerchantKeyStore, _merchant_account: domain::MerchantAccount, ) -> RouterResponse<()> { todo!() } #[cfg(feature = "v1")] pub async fn delete_conditional_config( state: SessionState, key_store: domain::MerchantKeyStore, merchant_account: domain::MerchantAccount, ) -> RouterResponse<()> { use common_utils::ext_traits::ValueExt; use storage_impl::redis::cache; use super::routing::helpers::update_merchant_active_algorithm_ref; let db = state.store.as_ref(); let key = merchant_account.get_id().get_payment_config_routing_id(); let mut algo_id: api_models::routing::RoutingAlgorithmRef = merchant_account .routing_algorithm .clone() .map(|value| value.parse_value("routing algorithm")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not decode the conditional_config algorithm")? .unwrap_or_default(); algo_id.config_algo_id = None; let config_key = cache::CacheKind::DecisionManager(key.clone().into()); update_merchant_active_algorithm_ref(&state, &key_store, config_key, algo_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update deleted algorithm ref")?; db.delete_config_by_key(&key) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to delete routing config from DB")?; Ok(service_api::ApplicationResponse::StatusOk) } #[cfg(feature = "v1")] pub async fn retrieve_conditional_config( state: SessionState, merchant_account: domain::MerchantAccount, ) -> RouterResponse<DecisionManagerResponse> { let db = state.store.as_ref(); let algorithm_id = merchant_account.get_id().get_payment_config_routing_id(); let algo_config = db .find_config_by_key(&algorithm_id) .await .change_context(errors::ApiErrorResponse::ResourceIdNotFound) .attach_printable("The conditional config was not found in the DB")?; let record: DecisionManagerRecord = algo_config .config .parse_struct("ConditionalConfigRecord") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("The Conditional Config Record was not found")?; let response = DecisionManagerRecord { name: record.name, program: record.program, created_at: record.created_at, modified_at: record.modified_at, }; Ok(service_api::ApplicationResponse::Json(response)) } #[cfg(feature = "v2")] pub async fn retrieve_conditional_config( state: SessionState, key_store: domain::MerchantKeyStore, profile: domain::Profile, ) -> RouterResponse<common_types::payments::DecisionManagerResponse> { let db = state.store.as_ref(); let key_manager_state: &KeyManagerState = &(&state).into(); let profile_id = profile.get_id(); let record = profile .three_ds_decision_manager_config .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("The Conditional Config Record was not found")?; let response = common_types::payments::DecisionManagerRecord { name: record.name, program: record.program, created_at: record.created_at, }; Ok(service_api::ApplicationResponse::Json(response)) }
2,328
1,548
hyperswitch
crates/router/src/core/disputes.rs
.rs
use std::collections::HashMap; use api_models::{ admin::MerchantConnectorInfo, disputes as dispute_models, files as files_api_models, }; use common_utils::ext_traits::{Encode, ValueExt}; use error_stack::ResultExt; use router_env::{instrument, tracing}; use strum::IntoEnumIterator; pub mod transformers; use super::{ errors::{self, ConnectorErrorExt, RouterResponse, StorageErrorExt}, metrics, }; use crate::{ core::{files, payments, utils as core_utils}, routes::SessionState, services, types::{ api::{self, disputes}, domain, storage::enums as storage_enums, transformers::ForeignFrom, AcceptDisputeRequestData, AcceptDisputeResponse, DefendDisputeRequestData, DefendDisputeResponse, SubmitEvidenceRequestData, SubmitEvidenceResponse, }, }; #[instrument(skip(state))] pub async fn retrieve_dispute( state: SessionState, merchant_account: domain::MerchantAccount, profile_id: Option<common_utils::id_type::ProfileId>, req: disputes::DisputeId, ) -> RouterResponse<api_models::disputes::DisputeResponse> { let dispute = state .store .find_dispute_by_merchant_id_dispute_id(merchant_account.get_id(), &req.dispute_id) .await .to_not_found_response(errors::ApiErrorResponse::DisputeNotFound { dispute_id: req.dispute_id, })?; core_utils::validate_profile_id_from_auth_layer(profile_id, &dispute)?; let dispute_response = api_models::disputes::DisputeResponse::foreign_from(dispute); Ok(services::ApplicationResponse::Json(dispute_response)) } #[instrument(skip(state))] pub async fn retrieve_disputes_list( state: SessionState, merchant_account: domain::MerchantAccount, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, constraints: api_models::disputes::DisputeListGetConstraints, ) -> RouterResponse<Vec<api_models::disputes::DisputeResponse>> { let dispute_list_constraints = &(constraints.clone(), profile_id_list.clone()).try_into()?; let disputes = state .store .find_disputes_by_constraints(merchant_account.get_id(), dispute_list_constraints) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to retrieve disputes")?; let disputes_list = disputes .into_iter() .map(api_models::disputes::DisputeResponse::foreign_from) .collect(); Ok(services::ApplicationResponse::Json(disputes_list)) } #[cfg(feature = "v2")] #[instrument(skip(state))] pub async fn accept_dispute( state: SessionState, merchant_account: domain::MerchantAccount, profile_id: Option<common_utils::id_type::ProfileId>, key_store: domain::MerchantKeyStore, req: disputes::DisputeId, ) -> RouterResponse<dispute_models::DisputeResponse> { todo!() } #[cfg(feature = "v1")] #[instrument(skip(state))] pub async fn get_filters_for_disputes( state: SessionState, merchant_account: domain::MerchantAccount, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, ) -> RouterResponse<api_models::disputes::DisputeListFilters> { let merchant_connector_accounts = if let services::ApplicationResponse::Json(data) = super::admin::list_payment_connectors( state, merchant_account.get_id().to_owned(), profile_id_list, ) .await? { data } else { return Err(error_stack::report!( errors::ApiErrorResponse::InternalServerError )) .attach_printable( "Failed to retrieve merchant connector accounts while fetching dispute list filters.", ); }; let connector_map = merchant_connector_accounts .into_iter() .filter_map(|merchant_connector_account| { merchant_connector_account .connector_label .clone() .map(|label| { let info = merchant_connector_account.to_merchant_connector_info(&label); (merchant_connector_account.connector_name, info) }) }) .fold( HashMap::new(), |mut map: HashMap<String, Vec<MerchantConnectorInfo>>, (connector_name, info)| { map.entry(connector_name).or_default().push(info); map }, ); Ok(services::ApplicationResponse::Json( api_models::disputes::DisputeListFilters { connector: connector_map, currency: storage_enums::Currency::iter().collect(), dispute_status: storage_enums::DisputeStatus::iter().collect(), dispute_stage: storage_enums::DisputeStage::iter().collect(), }, )) } #[cfg(feature = "v1")] #[instrument(skip(state))] pub async fn accept_dispute( state: SessionState, merchant_account: domain::MerchantAccount, profile_id: Option<common_utils::id_type::ProfileId>, key_store: domain::MerchantKeyStore, req: disputes::DisputeId, ) -> RouterResponse<dispute_models::DisputeResponse> { let db = &state.store; let dispute = state .store .find_dispute_by_merchant_id_dispute_id(merchant_account.get_id(), &req.dispute_id) .await .to_not_found_response(errors::ApiErrorResponse::DisputeNotFound { dispute_id: req.dispute_id, })?; core_utils::validate_profile_id_from_auth_layer(profile_id, &dispute)?; let dispute_id = dispute.dispute_id.clone(); common_utils::fp_utils::when( !(dispute.dispute_stage == storage_enums::DisputeStage::Dispute && dispute.dispute_status == storage_enums::DisputeStatus::DisputeOpened), || { metrics::ACCEPT_DISPUTE_STATUS_VALIDATION_FAILURE_METRIC.add(1, &[]); Err(errors::ApiErrorResponse::DisputeStatusValidationFailed { reason: format!( "This dispute cannot be accepted because the dispute is in {} stage and has {} status", dispute.dispute_stage, dispute.dispute_status ), }) }, )?; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &(&state).into(), &dispute.payment_id, merchant_account.get_id(), &key_store, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let payment_attempt = db .find_payment_attempt_by_attempt_id_merchant_id( &dispute.attempt_id, merchant_account.get_id(), merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &dispute.connector, api::GetToken::Connector, dispute.merchant_connector_id.clone(), )?; let connector_integration: services::BoxedDisputeConnectorIntegrationInterface< api::Accept, AcceptDisputeRequestData, AcceptDisputeResponse, > = connector_data.connector.get_connector_integration(); let router_data = core_utils::construct_accept_dispute_router_data( &state, &payment_intent, &payment_attempt, &merchant_account, &key_store, &dispute, ) .await?; let response = services::execute_connector_processing_step( &state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, ) .await .to_dispute_failed_response() .attach_printable("Failed while calling accept dispute connector api")?; let accept_dispute_response = response .response .map_err(|err| errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: dispute.connector.clone(), status_code: err.status_code, reason: err.reason, })?; let update_dispute = diesel_models::dispute::DisputeUpdate::StatusUpdate { dispute_status: accept_dispute_response.dispute_status, connector_status: accept_dispute_response.connector_status.clone(), }; let updated_dispute = db .update_dispute(dispute.clone(), update_dispute) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!("Unable to update dispute with dispute_id: {dispute_id}") })?; let dispute_response = api_models::disputes::DisputeResponse::foreign_from(updated_dispute); Ok(services::ApplicationResponse::Json(dispute_response)) } #[cfg(feature = "v2")] #[instrument(skip(state))] pub async fn submit_evidence( state: SessionState, merchant_account: domain::MerchantAccount, profile_id: Option<common_utils::id_type::ProfileId>, key_store: domain::MerchantKeyStore, req: dispute_models::SubmitEvidenceRequest, ) -> RouterResponse<dispute_models::DisputeResponse> { todo!() } #[cfg(feature = "v1")] #[instrument(skip(state))] pub async fn submit_evidence( state: SessionState, merchant_account: domain::MerchantAccount, profile_id: Option<common_utils::id_type::ProfileId>, key_store: domain::MerchantKeyStore, req: dispute_models::SubmitEvidenceRequest, ) -> RouterResponse<dispute_models::DisputeResponse> { let db = &state.store; let dispute = state .store .find_dispute_by_merchant_id_dispute_id(merchant_account.get_id(), &req.dispute_id) .await .to_not_found_response(errors::ApiErrorResponse::DisputeNotFound { dispute_id: req.dispute_id.clone(), })?; core_utils::validate_profile_id_from_auth_layer(profile_id, &dispute)?; let dispute_id = dispute.dispute_id.clone(); common_utils::fp_utils::when( !(dispute.dispute_stage == storage_enums::DisputeStage::Dispute && dispute.dispute_status == storage_enums::DisputeStatus::DisputeOpened), || { metrics::EVIDENCE_SUBMISSION_DISPUTE_STATUS_VALIDATION_FAILURE_METRIC.add(1, &[]); Err(errors::ApiErrorResponse::DisputeStatusValidationFailed { reason: format!( "Evidence cannot be submitted because the dispute is in {} stage and has {} status", dispute.dispute_stage, dispute.dispute_status ), }) }, )?; let submit_evidence_request_data = transformers::get_evidence_request_data( &state, &merchant_account, &key_store, req, &dispute, ) .await?; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &(&state).into(), &dispute.payment_id, merchant_account.get_id(), &key_store, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let payment_attempt = db .find_payment_attempt_by_attempt_id_merchant_id( &dispute.attempt_id, merchant_account.get_id(), merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &dispute.connector, api::GetToken::Connector, dispute.merchant_connector_id.clone(), )?; let connector_integration: services::BoxedDisputeConnectorIntegrationInterface< api::Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse, > = connector_data.connector.get_connector_integration(); let router_data = core_utils::construct_submit_evidence_router_data( &state, &payment_intent, &payment_attempt, &merchant_account, &key_store, &dispute, submit_evidence_request_data, ) .await?; let response = services::execute_connector_processing_step( &state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, ) .await .to_dispute_failed_response() .attach_printable("Failed while calling submit evidence connector api")?; let submit_evidence_response = response .response .map_err(|err| errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: dispute.connector.clone(), status_code: err.status_code, reason: err.reason, })?; //Defend Dispute Optionally if connector expects to defend / submit evidence in a separate api call let (dispute_status, connector_status) = if connector_data .connector_name .requires_defend_dispute() { let connector_integration_defend_dispute: services::BoxedDisputeConnectorIntegrationInterface< api::Defend, DefendDisputeRequestData, DefendDisputeResponse, > = connector_data.connector.get_connector_integration(); let defend_dispute_router_data = core_utils::construct_defend_dispute_router_data( &state, &payment_intent, &payment_attempt, &merchant_account, &key_store, &dispute, ) .await?; let defend_response = services::execute_connector_processing_step( &state, connector_integration_defend_dispute, &defend_dispute_router_data, payments::CallConnectorAction::Trigger, None, ) .await .to_dispute_failed_response() .attach_printable("Failed while calling defend dispute connector api")?; let defend_dispute_response = defend_response.response.map_err(|err| { errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: dispute.connector.clone(), status_code: err.status_code, reason: err.reason, } })?; ( defend_dispute_response.dispute_status, defend_dispute_response.connector_status, ) } else { ( submit_evidence_response.dispute_status, submit_evidence_response.connector_status, ) }; let update_dispute = diesel_models::dispute::DisputeUpdate::StatusUpdate { dispute_status, connector_status, }; let updated_dispute = db .update_dispute(dispute.clone(), update_dispute) .await .to_not_found_response(errors::ApiErrorResponse::DisputeNotFound { dispute_id: dispute_id.to_owned(), }) .attach_printable_lazy(|| { format!("Unable to update dispute with dispute_id: {dispute_id}") })?; let dispute_response = api_models::disputes::DisputeResponse::foreign_from(updated_dispute); Ok(services::ApplicationResponse::Json(dispute_response)) } pub async fn attach_evidence( state: SessionState, merchant_account: domain::MerchantAccount, profile_id: Option<common_utils::id_type::ProfileId>, key_store: domain::MerchantKeyStore, attach_evidence_request: api::AttachEvidenceRequest, ) -> RouterResponse<files_api_models::CreateFileResponse> { let db = &state.store; let dispute_id = attach_evidence_request .create_file_request .dispute_id .clone() .ok_or(errors::ApiErrorResponse::MissingDisputeId)?; let dispute = db .find_dispute_by_merchant_id_dispute_id(merchant_account.get_id(), &dispute_id) .await .to_not_found_response(errors::ApiErrorResponse::DisputeNotFound { dispute_id: dispute_id.clone(), })?; core_utils::validate_profile_id_from_auth_layer(profile_id, &dispute)?; common_utils::fp_utils::when( !(dispute.dispute_stage == storage_enums::DisputeStage::Dispute && dispute.dispute_status == storage_enums::DisputeStatus::DisputeOpened), || { metrics::ATTACH_EVIDENCE_DISPUTE_STATUS_VALIDATION_FAILURE_METRIC.add(1, &[]); Err(errors::ApiErrorResponse::DisputeStatusValidationFailed { reason: format!( "Evidence cannot be attached because the dispute is in {} stage and has {} status", dispute.dispute_stage, dispute.dispute_status ), }) }, )?; let create_file_response = Box::pin(files::files_create_core( state.clone(), merchant_account, key_store, attach_evidence_request.create_file_request, )) .await?; let file_id = match &create_file_response { services::ApplicationResponse::Json(res) => res.file_id.clone(), _ => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unexpected response received from files create core")?, }; let dispute_evidence: api::DisputeEvidence = dispute .evidence .clone() .parse_value("DisputeEvidence") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while parsing dispute evidence record")?; let updated_dispute_evidence = transformers::update_dispute_evidence( dispute_evidence, attach_evidence_request.evidence_type, file_id, ); let update_dispute = diesel_models::dispute::DisputeUpdate::EvidenceUpdate { evidence: updated_dispute_evidence .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while encoding dispute evidence")? .into(), }; db.update_dispute(dispute, update_dispute) .await .to_not_found_response(errors::ApiErrorResponse::DisputeNotFound { dispute_id: dispute_id.to_owned(), }) .attach_printable_lazy(|| { format!("Unable to update dispute with dispute_id: {dispute_id}") })?; Ok(create_file_response) } #[instrument(skip(state))] pub async fn retrieve_dispute_evidence( state: SessionState, merchant_account: domain::MerchantAccount, profile_id: Option<common_utils::id_type::ProfileId>, req: disputes::DisputeId, ) -> RouterResponse<Vec<api_models::disputes::DisputeEvidenceBlock>> { let dispute = state .store .find_dispute_by_merchant_id_dispute_id(merchant_account.get_id(), &req.dispute_id) .await .to_not_found_response(errors::ApiErrorResponse::DisputeNotFound { dispute_id: req.dispute_id, })?; core_utils::validate_profile_id_from_auth_layer(profile_id, &dispute)?; let dispute_evidence: api::DisputeEvidence = dispute .evidence .clone() .parse_value("DisputeEvidence") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while parsing dispute evidence record")?; let dispute_evidence_vec = transformers::get_dispute_evidence_vec(&state, merchant_account, dispute_evidence).await?; Ok(services::ApplicationResponse::Json(dispute_evidence_vec)) } pub async fn delete_evidence( state: SessionState, merchant_account: domain::MerchantAccount, delete_evidence_request: dispute_models::DeleteEvidenceRequest, ) -> RouterResponse<serde_json::Value> { let dispute_id = delete_evidence_request.dispute_id.clone(); let dispute = state .store .find_dispute_by_merchant_id_dispute_id(merchant_account.get_id(), &dispute_id) .await .to_not_found_response(errors::ApiErrorResponse::DisputeNotFound { dispute_id: dispute_id.clone(), })?; let dispute_evidence: api::DisputeEvidence = dispute .evidence .clone() .parse_value("DisputeEvidence") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while parsing dispute evidence record")?; let updated_dispute_evidence = transformers::delete_evidence_file(dispute_evidence, delete_evidence_request.evidence_type); let update_dispute = diesel_models::dispute::DisputeUpdate::EvidenceUpdate { evidence: updated_dispute_evidence .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while encoding dispute evidence")? .into(), }; state .store .update_dispute(dispute, update_dispute) .await .to_not_found_response(errors::ApiErrorResponse::DisputeNotFound { dispute_id: dispute_id.to_owned(), }) .attach_printable_lazy(|| { format!("Unable to update dispute with dispute_id: {dispute_id}") })?; Ok(services::ApplicationResponse::StatusOk) } #[instrument(skip(state))] pub async fn get_aggregates_for_disputes( state: SessionState, merchant: domain::MerchantAccount, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: common_utils::types::TimeRange, ) -> RouterResponse<dispute_models::DisputesAggregateResponse> { let db = state.store.as_ref(); let dispute_status_with_count = db .get_dispute_status_with_count(merchant.get_id(), profile_id_list, &time_range) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to retrieve disputes aggregate")?; let mut status_map: HashMap<storage_enums::DisputeStatus, i64> = dispute_status_with_count.into_iter().collect(); for status in storage_enums::DisputeStatus::iter() { status_map.entry(status).or_default(); } Ok(services::ApplicationResponse::Json( dispute_models::DisputesAggregateResponse { status_with_count: status_map, }, )) }
4,718
1,549
hyperswitch
crates/router/src/core/encryption.rs
.rs
use api_models::admin::MerchantKeyTransferRequest; use base64::Engine; use common_utils::{ keymanager::transfer_key_to_key_manager, types::keymanager::{EncryptionTransferRequest, Identifier}, }; use error_stack::ResultExt; use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore; use masking::ExposeInterface; use crate::{consts::BASE64_ENGINE, errors, types::domain::UserKeyStore, SessionState}; pub async fn transfer_encryption_key( state: &SessionState, req: MerchantKeyTransferRequest, ) -> errors::CustomResult<usize, errors::ApiErrorResponse> { let db = &*state.store; let key_stores = db .get_all_key_stores( &state.into(), &db.get_master_key().to_vec().into(), req.from, req.limit, ) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; send_request_to_key_service_for_merchant(state, key_stores).await } pub async fn send_request_to_key_service_for_merchant( state: &SessionState, keys: Vec<MerchantKeyStore>, ) -> errors::CustomResult<usize, errors::ApiErrorResponse> { let total = keys.len(); for key in keys { let key_encoded = BASE64_ENGINE.encode(key.key.clone().into_inner().expose()); let req = EncryptionTransferRequest { identifier: Identifier::Merchant(key.merchant_id.clone()), key: key_encoded, }; transfer_key_to_key_manager(&state.into(), req) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; } Ok(total) } pub async fn send_request_to_key_service_for_user( state: &SessionState, keys: Vec<UserKeyStore>, ) -> errors::CustomResult<usize, errors::ApiErrorResponse> { futures::future::try_join_all(keys.into_iter().map(|key| async move { let key_encoded = BASE64_ENGINE.encode(key.key.clone().into_inner().expose()); let req = EncryptionTransferRequest { identifier: Identifier::User(key.user_id.clone()), key: key_encoded, }; transfer_key_to_key_manager(&state.into(), req).await })) .await .change_context(errors::ApiErrorResponse::InternalServerError) .map(|v| v.len()) }
501
1,550
hyperswitch
crates/router/src/core/authentication.rs
.rs
pub(crate) mod utils; pub mod transformers; pub mod types; use api_models::payments; use common_enums::Currency; use common_utils::errors::CustomResult; use error_stack::ResultExt; use masking::ExposeInterface; use super::errors::StorageErrorExt; use crate::{ core::{errors::ApiErrorResponse, payments as payments_core}, routes::SessionState, types::{self as core_types, api, domain, storage}, utils::check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata, }; #[allow(clippy::too_many_arguments)] pub async fn perform_authentication( state: &SessionState, merchant_id: common_utils::id_type::MerchantId, authentication_connector: String, payment_method_data: domain::PaymentMethodData, payment_method: common_enums::PaymentMethod, billing_address: hyperswitch_domain_models::address::Address, shipping_address: Option<hyperswitch_domain_models::address::Address>, browser_details: Option<core_types::BrowserInformation>, merchant_connector_account: payments_core::helpers::MerchantConnectorAccountType, amount: Option<common_utils::types::MinorUnit>, currency: Option<Currency>, message_category: api::authentication::MessageCategory, device_channel: payments::DeviceChannel, authentication_data: storage::Authentication, return_url: Option<String>, sdk_information: Option<payments::SdkInformation>, threeds_method_comp_ind: payments::ThreeDsCompletionIndicator, email: Option<common_utils::pii::Email>, webhook_url: String, three_ds_requestor_url: String, psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>, payment_id: common_utils::id_type::PaymentId, force_3ds_challenge: bool, ) -> CustomResult<api::authentication::AuthenticationResponse, ApiErrorResponse> { let router_data = transformers::construct_authentication_router_data( state, merchant_id, authentication_connector.clone(), payment_method_data, payment_method, billing_address, shipping_address, browser_details, amount, currency, message_category, device_channel, merchant_connector_account, authentication_data.clone(), return_url, sdk_information, threeds_method_comp_ind, email, webhook_url, three_ds_requestor_url, psd2_sca_exemption_type, payment_id, force_3ds_challenge, )?; let response = Box::pin(utils::do_auth_connector_call( state, authentication_connector.clone(), router_data, )) .await?; let authentication = utils::update_trackers(state, response.clone(), authentication_data, None).await?; response .response .map_err(|err| ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: authentication_connector, status_code: err.status_code, reason: err.reason, })?; api::authentication::AuthenticationResponse::try_from(authentication) } pub async fn perform_post_authentication( state: &SessionState, key_store: &domain::MerchantKeyStore, business_profile: domain::Profile, authentication_id: String, payment_id: &common_utils::id_type::PaymentId, ) -> CustomResult<storage::Authentication, ApiErrorResponse> { let (authentication_connector, three_ds_connector_account) = utils::get_authentication_connector_data(state, key_store, &business_profile).await?; let is_pull_mechanism_enabled = check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata( three_ds_connector_account .get_metadata() .map(|metadata| metadata.expose()), ); let authentication = state .store .find_authentication_by_merchant_id_authentication_id( &business_profile.merchant_id, authentication_id.clone(), ) .await .to_not_found_response(ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| format!("Error while fetching authentication record with authentication_id {authentication_id}"))?; if !authentication.authentication_status.is_terminal_status() && is_pull_mechanism_enabled { let router_data = transformers::construct_post_authentication_router_data( state, authentication_connector.to_string(), business_profile, three_ds_connector_account, &authentication, payment_id, )?; let router_data = utils::do_auth_connector_call(state, authentication_connector.to_string(), router_data) .await?; utils::update_trackers(state, router_data, authentication, None).await } else { Ok(authentication) } } #[allow(clippy::too_many_arguments)] pub async fn perform_pre_authentication( state: &SessionState, key_store: &domain::MerchantKeyStore, card: hyperswitch_domain_models::payment_method_data::Card, token: String, business_profile: &domain::Profile, acquirer_details: Option<types::AcquirerDetails>, payment_id: common_utils::id_type::PaymentId, organization_id: common_utils::id_type::OrganizationId, ) -> CustomResult<storage::Authentication, ApiErrorResponse> { let (authentication_connector, three_ds_connector_account) = utils::get_authentication_connector_data(state, key_store, business_profile).await?; let authentication_connector_name = authentication_connector.to_string(); let authentication = utils::create_new_authentication( state, business_profile.merchant_id.clone(), authentication_connector_name.clone(), token, business_profile.get_id().to_owned(), payment_id.clone(), three_ds_connector_account .get_mca_id() .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("Error while finding mca_id from merchant_connector_account")?, organization_id, ) .await?; let authentication = if authentication_connector.is_separate_version_call_required() { let router_data: core_types::authentication::PreAuthNVersionCallRouterData = transformers::construct_pre_authentication_router_data( state, authentication_connector_name.clone(), card.clone(), &three_ds_connector_account, business_profile.merchant_id.clone(), payment_id.clone(), )?; let router_data = utils::do_auth_connector_call( state, authentication_connector_name.clone(), router_data, ) .await?; let updated_authentication = utils::update_trackers(state, router_data, authentication, acquirer_details.clone()) .await?; // from version call response, we will get to know the maximum supported 3ds version. // If the version is not greater than or equal to 3DS 2.0, We should not do the successive pre authentication call. if !updated_authentication.is_separate_authn_required() { return Ok(updated_authentication); } updated_authentication } else { authentication }; let router_data: core_types::authentication::PreAuthNRouterData = transformers::construct_pre_authentication_router_data( state, authentication_connector_name.clone(), card, &three_ds_connector_account, business_profile.merchant_id.clone(), payment_id, )?; let router_data = utils::do_auth_connector_call(state, authentication_connector_name, router_data).await?; utils::update_trackers(state, router_data, authentication, acquirer_details).await }
1,554
1,551
hyperswitch
crates/router/src/core/connector_onboarding.rs
.rs
use api_models::{connector_onboarding as api, enums}; use masking::Secret; use crate::{ core::errors::{ApiErrorResponse, RouterResponse, RouterResult}, routes::app::ReqState, services::{authentication as auth, ApplicationResponse}, types as oss_types, utils::connector_onboarding as utils, SessionState, }; pub mod paypal; #[async_trait::async_trait] pub trait AccessToken { async fn access_token(state: &SessionState) -> RouterResult<oss_types::AccessToken>; } pub async fn get_action_url( state: SessionState, user_from_token: auth::UserFromToken, request: api::ActionUrlRequest, _req_state: ReqState, ) -> RouterResponse<api::ActionUrlResponse> { utils::check_if_connector_exists(&state, &request.connector_id, &user_from_token.merchant_id) .await?; let connector_onboarding_conf = state.conf.connector_onboarding.get_inner(); let is_enabled = utils::is_enabled(request.connector, connector_onboarding_conf); let tracking_id = utils::get_tracking_id_from_configs(&state, &request.connector_id, request.connector) .await?; match (is_enabled, request.connector) { (Some(true), enums::Connector::Paypal) => { let action_url = Box::pin(paypal::get_action_url_from_paypal( state, tracking_id, request.return_url, )) .await?; Ok(ApplicationResponse::Json(api::ActionUrlResponse::PayPal( api::PayPalActionUrlResponse { action_url }, ))) } _ => Err(ApiErrorResponse::FlowNotSupported { flow: "Connector onboarding".to_string(), connector: request.connector.to_string(), } .into()), } } pub async fn sync_onboarding_status( state: SessionState, user_from_token: auth::UserFromToken, request: api::OnboardingSyncRequest, _req_state: ReqState, ) -> RouterResponse<api::OnboardingStatus> { utils::check_if_connector_exists(&state, &request.connector_id, &user_from_token.merchant_id) .await?; let connector_onboarding_conf = state.conf.connector_onboarding.get_inner(); let is_enabled = utils::is_enabled(request.connector, connector_onboarding_conf); let tracking_id = utils::get_tracking_id_from_configs(&state, &request.connector_id, request.connector) .await?; match (is_enabled, request.connector) { (Some(true), enums::Connector::Paypal) => { let status = Box::pin(paypal::sync_merchant_onboarding_status( state.clone(), tracking_id, )) .await?; if let api::OnboardingStatus::PayPal(api::PayPalOnboardingStatus::Success( ref paypal_onboarding_data, )) = status { let connector_onboarding_conf = state.conf.connector_onboarding.get_inner(); let auth_details = oss_types::ConnectorAuthType::SignatureKey { api_key: connector_onboarding_conf.paypal.client_secret.clone(), key1: connector_onboarding_conf.paypal.client_id.clone(), api_secret: Secret::new( paypal_onboarding_data.payer_id.get_string_repr().to_owned(), ), }; let update_mca_data = paypal::update_mca( &state, user_from_token.merchant_id, request.connector_id.to_owned(), auth_details, ) .await?; return Ok(ApplicationResponse::Json(api::OnboardingStatus::PayPal( api::PayPalOnboardingStatus::ConnectorIntegrated(Box::new(update_mca_data)), ))); } Ok(ApplicationResponse::Json(status)) } _ => Err(ApiErrorResponse::FlowNotSupported { flow: "Connector onboarding".to_string(), connector: request.connector.to_string(), } .into()), } } pub async fn reset_tracking_id( state: SessionState, user_from_token: auth::UserFromToken, request: api::ResetTrackingIdRequest, _req_state: ReqState, ) -> RouterResponse<()> { utils::check_if_connector_exists(&state, &request.connector_id, &user_from_token.merchant_id) .await?; utils::set_tracking_id_in_configs(&state, &request.connector_id, request.connector).await?; Ok(ApplicationResponse::StatusOk) }
934
1,552
hyperswitch
crates/router/src/core/cache.rs
.rs
use common_utils::errors::CustomResult; use error_stack::{report, ResultExt}; use storage_impl::redis::cache::{redact_from_redis_and_publish, CacheKind}; use super::errors; use crate::{routes::SessionState, services}; pub async fn invalidate( state: SessionState, key: &str, ) -> CustomResult<services::api::ApplicationResponse<serde_json::Value>, errors::ApiErrorResponse> { let store = state.store.as_ref(); let result = redact_from_redis_and_publish( store.get_cache_store().as_ref(), [CacheKind::All(key.into())], ) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; // If the message was published to atleast one channel // then return status Ok if result > 0 { Ok(services::api::ApplicationResponse::StatusOk) } else { Err(report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to invalidate cache")) } }
215
1,553
hyperswitch
crates/router/src/core/api_keys.rs
.rs
use common_utils::date_time; #[cfg(feature = "email")] use diesel_models::{api_keys::ApiKey, enums as storage_enums}; use error_stack::{report, ResultExt}; use masking::{PeekInterface, StrongSecret}; use router_env::{instrument, tracing}; use crate::{ configs::settings, consts, core::errors::{self, RouterResponse, StorageErrorExt}, db::domain, routes::{metrics, SessionState}, services::{authentication, ApplicationResponse}, types::{api, storage, transformers::ForeignInto}, }; #[cfg(feature = "email")] const API_KEY_EXPIRY_TAG: &str = "API_KEY"; #[cfg(feature = "email")] const API_KEY_EXPIRY_NAME: &str = "API_KEY_EXPIRY"; #[cfg(feature = "email")] const API_KEY_EXPIRY_RUNNER: diesel_models::ProcessTrackerRunner = diesel_models::ProcessTrackerRunner::ApiKeyExpiryWorkflow; static HASH_KEY: once_cell::sync::OnceCell<StrongSecret<[u8; PlaintextApiKey::HASH_KEY_LEN]>> = once_cell::sync::OnceCell::new(); impl settings::ApiKeys { pub fn get_hash_key( &self, ) -> errors::RouterResult<&'static StrongSecret<[u8; PlaintextApiKey::HASH_KEY_LEN]>> { HASH_KEY.get_or_try_init(|| { <[u8; PlaintextApiKey::HASH_KEY_LEN]>::try_from( hex::decode(self.hash_key.peek()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("API key hash key has invalid hexadecimal data")? .as_slice(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("The API hashing key has incorrect length") .map(StrongSecret::new) }) } } // Defining new types `PlaintextApiKey` and `HashedApiKey` in the hopes of reducing the possibility // of plaintext API key being stored in the data store. pub struct PlaintextApiKey(StrongSecret<String>); #[derive(Debug, PartialEq, Eq)] pub struct HashedApiKey(String); impl PlaintextApiKey { const HASH_KEY_LEN: usize = 32; const PREFIX_LEN: usize = 12; pub fn new(length: usize) -> Self { let env = router_env::env::prefix_for_env(); let key = common_utils::crypto::generate_cryptographically_secure_random_string(length); Self(format!("{env}_{key}").into()) } pub fn new_key_id() -> common_utils::id_type::ApiKeyId { let env = router_env::env::prefix_for_env(); common_utils::id_type::ApiKeyId::generate_key_id(env) } pub fn prefix(&self) -> String { self.0.peek().chars().take(Self::PREFIX_LEN).collect() } pub fn peek(&self) -> &str { self.0.peek() } pub fn keyed_hash(&self, key: &[u8; Self::HASH_KEY_LEN]) -> HashedApiKey { /* Decisions regarding API key hashing algorithm chosen: - Since API key hash verification would be done for each request, there is a requirement for the hashing to be quick. - Password hashing algorithms would not be suitable for this purpose as they're designed to prevent brute force attacks, considering that the same password could be shared across multiple sites by the user. - Moreover, password hash verification happens once per user session, so the delay involved is negligible, considering the security benefits it provides. While with API keys (assuming uniqueness of keys across the application), the delay involved in hashing (with the use of a password hashing algorithm) becomes significant, considering that it must be done per request. - Since we are the only ones generating API keys and are able to guarantee their uniqueness, a simple hash algorithm is sufficient for this purpose. Hash algorithms considered: - Password hashing algorithms: Argon2id and PBKDF2 - Simple hashing algorithms: HMAC-SHA256, HMAC-SHA512, BLAKE3 After benchmarking the simple hashing algorithms, we decided to go with the BLAKE3 keyed hashing algorithm, with a randomly generated key for the hash key. */ HashedApiKey( blake3::keyed_hash(key, self.0.peek().as_bytes()) .to_hex() .to_string(), ) } } #[instrument(skip_all)] pub async fn create_api_key( state: SessionState, api_key: api::CreateApiKeyRequest, key_store: domain::MerchantKeyStore, ) -> RouterResponse<api::CreateApiKeyResponse> { let api_key_config = state.conf.api_keys.get_inner(); let store = state.store.as_ref(); let merchant_id = key_store.merchant_id.clone(); let hash_key = api_key_config.get_hash_key()?; let plaintext_api_key = PlaintextApiKey::new(consts::API_KEY_LENGTH); let api_key = storage::ApiKeyNew { key_id: PlaintextApiKey::new_key_id(), merchant_id: merchant_id.to_owned(), name: api_key.name, description: api_key.description, hashed_api_key: plaintext_api_key.keyed_hash(hash_key.peek()).into(), prefix: plaintext_api_key.prefix(), created_at: date_time::now(), expires_at: api_key.expiration.into(), last_used: None, }; let api_key = store .insert_api_key(api_key) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to insert new API key")?; let state_inner = state.clone(); let hashed_api_key = api_key.hashed_api_key.clone(); let merchant_id_inner = merchant_id.clone(); let key_id = api_key.key_id.clone(); let expires_at = api_key.expires_at; authentication::decision::spawn_tracked_job( async move { authentication::decision::add_api_key( &state_inner, hashed_api_key.into_inner().into(), merchant_id_inner, key_id, expires_at.map(authentication::decision::convert_expiry), ) .await }, authentication::decision::ADD, ); metrics::API_KEY_CREATED.add( 1, router_env::metric_attributes!(("merchant", merchant_id.clone())), ); // Add process to process_tracker for email reminder, only if expiry is set to future date // If the `api_key` is set to expire in less than 7 days, the merchant is not notified about it's expiry #[cfg(feature = "email")] { if api_key.expires_at.is_some() { let expiry_reminder_days = state.conf.api_keys.get_inner().expiry_reminder_days.clone(); add_api_key_expiry_task(store, &api_key, expiry_reminder_days) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to insert API key expiry reminder to process tracker")?; } } Ok(ApplicationResponse::Json( (api_key, plaintext_api_key).foreign_into(), )) } // Add api_key_expiry task to the process_tracker table. // Construct ProcessTrackerNew struct with all required fields, and schedule the first email. // After first email has been sent, update the schedule_time based on retry_count in execute_workflow(). // A task is not scheduled if the time for the first email is in the past. #[cfg(feature = "email")] #[instrument(skip_all)] pub async fn add_api_key_expiry_task( store: &dyn crate::db::StorageInterface, api_key: &ApiKey, expiry_reminder_days: Vec<u8>, ) -> Result<(), errors::ProcessTrackerError> { let current_time = date_time::now(); let schedule_time = expiry_reminder_days .first() .and_then(|expiry_reminder_day| { api_key.expires_at.map(|expires_at| { expires_at.saturating_sub(time::Duration::days(i64::from(*expiry_reminder_day))) }) }) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to obtain initial process tracker schedule time")?; if schedule_time <= current_time { return Ok(()); } let api_key_expiry_tracker = storage::ApiKeyExpiryTrackingData { key_id: api_key.key_id.clone(), merchant_id: api_key.merchant_id.clone(), api_key_name: api_key.name.clone(), prefix: api_key.prefix.clone(), // We need API key expiry too, because we need to decide on the schedule_time in // execute_workflow() where we won't be having access to the Api key object. api_key_expiry: api_key.expires_at, expiry_reminder_days: expiry_reminder_days.clone(), }; let process_tracker_id = generate_task_id_for_api_key_expiry_workflow(&api_key.key_id); let process_tracker_entry = storage::ProcessTrackerNew::new( process_tracker_id, API_KEY_EXPIRY_NAME, API_KEY_EXPIRY_RUNNER, [API_KEY_EXPIRY_TAG], api_key_expiry_tracker, None, schedule_time, common_types::consts::API_VERSION, ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct API key expiry process tracker task")?; store .insert_process(process_tracker_entry) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed while inserting API key expiry reminder to process_tracker: {:?}", api_key.key_id ) })?; metrics::TASKS_ADDED_COUNT.add(1, router_env::metric_attributes!(("flow", "ApiKeyExpiry"))); Ok(()) } #[instrument(skip_all)] pub async fn retrieve_api_key( state: SessionState, merchant_id: common_utils::id_type::MerchantId, key_id: common_utils::id_type::ApiKeyId, ) -> RouterResponse<api::RetrieveApiKeyResponse> { let store = state.store.as_ref(); let api_key = store .find_api_key_by_merchant_id_key_id_optional(&merchant_id, &key_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed .attach_printable("Failed to retrieve API key")? .ok_or(report!(errors::ApiErrorResponse::ApiKeyNotFound))?; // If retrieve returned `None` Ok(ApplicationResponse::Json(api_key.foreign_into())) } #[instrument(skip_all)] pub async fn update_api_key( state: SessionState, api_key: api::UpdateApiKeyRequest, ) -> RouterResponse<api::RetrieveApiKeyResponse> { let merchant_id = api_key.merchant_id.clone(); let key_id = api_key.key_id.clone(); let store = state.store.as_ref(); let api_key = store .update_api_key( merchant_id.to_owned(), key_id.to_owned(), api_key.foreign_into(), ) .await .to_not_found_response(errors::ApiErrorResponse::ApiKeyNotFound)?; let state_inner = state.clone(); let hashed_api_key = api_key.hashed_api_key.clone(); let key_id_inner = api_key.key_id.clone(); let expires_at = api_key.expires_at; authentication::decision::spawn_tracked_job( async move { authentication::decision::add_api_key( &state_inner, hashed_api_key.into_inner().into(), merchant_id.clone(), key_id_inner, expires_at.map(authentication::decision::convert_expiry), ) .await }, authentication::decision::ADD, ); #[cfg(feature = "email")] { let expiry_reminder_days = state.conf.api_keys.get_inner().expiry_reminder_days.clone(); let task_id = generate_task_id_for_api_key_expiry_workflow(&key_id); // In order to determine how to update the existing process in the process_tracker table, // we need access to the current entry in the table. let existing_process_tracker_task = store .find_process_by_id(task_id.as_str()) .await .change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed .attach_printable( "Failed to retrieve API key expiry reminder task from process tracker", )?; // If process exist if existing_process_tracker_task.is_some() { if api_key.expires_at.is_some() { // Process exist in process, update the process with new schedule_time update_api_key_expiry_task(store, &api_key, expiry_reminder_days) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to update API key expiry reminder task in process tracker", )?; } // If an expiry is set to 'never' else { // Process exist in process, revoke it revoke_api_key_expiry_task(store, &key_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to revoke API key expiry reminder task in process tracker", )?; } } // This case occurs if the expiry for an API key is set to 'never' during its creation. If so, // process in tracker was not created. else if api_key.expires_at.is_some() { // Process doesn't exist in process_tracker table, so create new entry with // schedule_time based on new expiry set. add_api_key_expiry_task(store, &api_key, expiry_reminder_days) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to insert API key expiry reminder task to process tracker", )?; } } Ok(ApplicationResponse::Json(api_key.foreign_into())) } // Update api_key_expiry task in the process_tracker table. // Construct Update variant of ProcessTrackerUpdate with new tracking_data. // A task is not scheduled if the time for the first email is in the past. #[cfg(feature = "email")] #[instrument(skip_all)] pub async fn update_api_key_expiry_task( store: &dyn crate::db::StorageInterface, api_key: &ApiKey, expiry_reminder_days: Vec<u8>, ) -> Result<(), errors::ProcessTrackerError> { let current_time = date_time::now(); let schedule_time = expiry_reminder_days .first() .and_then(|expiry_reminder_day| { api_key.expires_at.map(|expires_at| { expires_at.saturating_sub(time::Duration::days(i64::from(*expiry_reminder_day))) }) }); if let Some(schedule_time) = schedule_time { if schedule_time <= current_time { return Ok(()); } } let task_id = generate_task_id_for_api_key_expiry_workflow(&api_key.key_id); let task_ids = vec![task_id.clone()]; let updated_tracking_data = &storage::ApiKeyExpiryTrackingData { key_id: api_key.key_id.clone(), merchant_id: api_key.merchant_id.clone(), api_key_name: api_key.name.clone(), prefix: api_key.prefix.clone(), api_key_expiry: api_key.expires_at, expiry_reminder_days, }; let updated_api_key_expiry_workflow_model = serde_json::to_value(updated_tracking_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!("unable to serialize API key expiry tracker: {updated_tracking_data:?}") })?; let updated_process_tracker_data = storage::ProcessTrackerUpdate::Update { name: None, retry_count: Some(0), schedule_time, tracking_data: Some(updated_api_key_expiry_workflow_model), business_status: Some(String::from( diesel_models::process_tracker::business_status::PENDING, )), status: Some(storage_enums::ProcessTrackerStatus::New), updated_at: Some(current_time), }; store .process_tracker_update_process_status_by_ids(task_ids, updated_process_tracker_data) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; Ok(()) } #[instrument(skip_all)] pub async fn revoke_api_key( state: SessionState, merchant_id: &common_utils::id_type::MerchantId, key_id: &common_utils::id_type::ApiKeyId, ) -> RouterResponse<api::RevokeApiKeyResponse> { let store = state.store.as_ref(); let api_key = store .find_api_key_by_merchant_id_key_id_optional(merchant_id, key_id) .await .to_not_found_response(errors::ApiErrorResponse::ApiKeyNotFound)?; let revoked = store .revoke_api_key(merchant_id, key_id) .await .to_not_found_response(errors::ApiErrorResponse::ApiKeyNotFound)?; if let Some(api_key) = api_key { let hashed_api_key = api_key.hashed_api_key; let state = state.clone(); authentication::decision::spawn_tracked_job( async move { authentication::decision::revoke_api_key(&state, hashed_api_key.into_inner().into()) .await }, authentication::decision::REVOKE, ); } metrics::API_KEY_REVOKED.add(1, &[]); #[cfg(feature = "email")] { let task_id = generate_task_id_for_api_key_expiry_workflow(key_id); // In order to determine how to update the existing process in the process_tracker table, // we need access to the current entry in the table. let existing_process_tracker_task = store .find_process_by_id(task_id.as_str()) .await .change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed .attach_printable( "Failed to retrieve API key expiry reminder task from process tracker", )?; // If process exist, then revoke it if existing_process_tracker_task.is_some() { revoke_api_key_expiry_task(store, key_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to revoke API key expiry reminder task in process tracker", )?; } } Ok(ApplicationResponse::Json(api::RevokeApiKeyResponse { merchant_id: merchant_id.to_owned(), key_id: key_id.to_owned(), revoked, })) } // Function to revoke api_key_expiry task in the process_tracker table when API key is revoked. // Construct StatusUpdate variant of ProcessTrackerUpdate by setting status to 'finish'. #[cfg(feature = "email")] #[instrument(skip_all)] pub async fn revoke_api_key_expiry_task( store: &dyn crate::db::StorageInterface, key_id: &common_utils::id_type::ApiKeyId, ) -> Result<(), errors::ProcessTrackerError> { let task_id = generate_task_id_for_api_key_expiry_workflow(key_id); let task_ids = vec![task_id]; let updated_process_tracker_data = storage::ProcessTrackerUpdate::StatusUpdate { status: storage_enums::ProcessTrackerStatus::Finish, business_status: Some(String::from(diesel_models::business_status::REVOKED)), }; store .process_tracker_update_process_status_by_ids(task_ids, updated_process_tracker_data) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; Ok(()) } #[instrument(skip_all)] pub async fn list_api_keys( state: SessionState, merchant_id: common_utils::id_type::MerchantId, limit: Option<i64>, offset: Option<i64>, ) -> RouterResponse<Vec<api::RetrieveApiKeyResponse>> { let store = state.store.as_ref(); let api_keys = store .list_api_keys_by_merchant_id(&merchant_id, limit, offset) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to list merchant API keys")?; let api_keys = api_keys .into_iter() .map(ForeignInto::foreign_into) .collect(); Ok(ApplicationResponse::Json(api_keys)) } #[cfg(feature = "email")] fn generate_task_id_for_api_key_expiry_workflow( key_id: &common_utils::id_type::ApiKeyId, ) -> String { format!( "{API_KEY_EXPIRY_RUNNER}_{API_KEY_EXPIRY_NAME}_{}", key_id.get_string_repr() ) } impl From<&str> for PlaintextApiKey { fn from(s: &str) -> Self { Self(s.to_owned().into()) } } impl From<String> for PlaintextApiKey { fn from(s: String) -> Self { Self(s.into()) } } impl From<HashedApiKey> for storage::HashedApiKey { fn from(hashed_api_key: HashedApiKey) -> Self { hashed_api_key.0.into() } } impl From<storage::HashedApiKey> for HashedApiKey { fn from(hashed_api_key: storage::HashedApiKey) -> Self { Self(hashed_api_key.into_inner()) } } #[cfg(test)] mod tests { #![allow(clippy::expect_used, clippy::unwrap_used)] use super::*; #[tokio::test] async fn test_hashing_and_verification() { let settings = settings::Settings::new().expect("invalid settings"); let plaintext_api_key = PlaintextApiKey::new(consts::API_KEY_LENGTH); let hash_key = settings.api_keys.get_inner().get_hash_key().unwrap(); let hashed_api_key = plaintext_api_key.keyed_hash(hash_key.peek()); assert_ne!( plaintext_api_key.0.peek().as_bytes(), hashed_api_key.0.as_bytes() ); let new_hashed_api_key = plaintext_api_key.keyed_hash(hash_key.peek()); assert_eq!(hashed_api_key, new_hashed_api_key) } }
4,680
1,554
hyperswitch
crates/router/src/core/relay.rs
.rs
use std::marker::PhantomData; use api_models::relay as relay_api_models; use async_trait::async_trait; use common_enums::RelayStatus; use common_utils::{ self, fp_utils, id_type::{self, GenerateId}, }; use error_stack::ResultExt; use hyperswitch_domain_models::relay; use super::errors::{self, ConnectorErrorExt, RouterResponse, RouterResult, StorageErrorExt}; use crate::{ core::payments, routes::SessionState, services, types::{ api::{self}, domain, }, utils::OptionExt, }; pub mod utils; pub trait Validate { type Error: error_stack::Context; fn validate(&self) -> Result<(), Self::Error>; } impl Validate for relay_api_models::RelayRefundRequestData { type Error = errors::ApiErrorResponse; fn validate(&self) -> Result<(), Self::Error> { fp_utils::when(self.amount.get_amount_as_i64() <= 0, || { Err(errors::ApiErrorResponse::PreconditionFailed { message: "Amount should be greater than 0".to_string(), }) })?; Ok(()) } } #[async_trait] pub trait RelayInterface { type Request: Validate; fn validate_relay_request(req: &Self::Request) -> RouterResult<()> { req.validate() .change_context(errors::ApiErrorResponse::PreconditionFailed { message: "Invalid relay request".to_string(), }) } fn get_domain_models( relay_request: RelayRequestInner<Self>, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, ) -> relay::Relay; async fn process_relay( state: &SessionState, merchant_account: domain::MerchantAccount, connector_account: domain::MerchantConnectorAccount, relay_record: &relay::Relay, ) -> RouterResult<relay::RelayUpdate>; fn generate_response(value: relay::Relay) -> RouterResult<api_models::relay::RelayResponse>; } pub struct RelayRequestInner<T: RelayInterface + ?Sized> { pub connector_resource_id: String, pub connector_id: id_type::MerchantConnectorAccountId, pub relay_type: PhantomData<T>, pub data: T::Request, } impl RelayRequestInner<RelayRefund> { pub fn from_relay_request(relay_request: relay_api_models::RelayRequest) -> RouterResult<Self> { match relay_request.data { Some(relay_api_models::RelayData::Refund(ref_data)) => Ok(Self { connector_resource_id: relay_request.connector_resource_id, connector_id: relay_request.connector_id, relay_type: PhantomData, data: ref_data, }), None => Err(errors::ApiErrorResponse::InvalidRequestData { message: "Relay data is required for relay type refund".to_string(), })?, } } } pub struct RelayRefund; #[async_trait] impl RelayInterface for RelayRefund { type Request = relay_api_models::RelayRefundRequestData; fn get_domain_models( relay_request: RelayRequestInner<Self>, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, ) -> relay::Relay { let relay_id = id_type::RelayId::generate(); let relay_refund: relay::RelayRefundData = relay_request.data.into(); relay::Relay { id: relay_id.clone(), connector_resource_id: relay_request.connector_resource_id.clone(), connector_id: relay_request.connector_id.clone(), profile_id: profile_id.clone(), merchant_id: merchant_id.clone(), relay_type: common_enums::RelayType::Refund, request_data: Some(relay::RelayData::Refund(relay_refund)), status: RelayStatus::Created, connector_reference_id: None, error_code: None, error_message: None, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), response_data: None, } } async fn process_relay( state: &SessionState, merchant_account: domain::MerchantAccount, connector_account: domain::MerchantConnectorAccount, relay_record: &relay::Relay, ) -> RouterResult<relay::RelayUpdate> { let connector_id = &relay_record.connector_id; let merchant_id = merchant_account.get_id(); let connector_name = &connector_account.get_connector_name_as_string(); let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, connector_name, api::GetToken::Connector, Some(connector_id.clone()), )?; let connector_integration: services::BoxedRefundConnectorIntegrationInterface< api::Execute, hyperswitch_domain_models::router_request_types::RefundsData, hyperswitch_domain_models::router_response_types::RefundsResponseData, > = connector_data.connector.get_connector_integration(); let router_data = utils::construct_relay_refund_router_data( state, merchant_id, &connector_account, relay_record, ) .await?; let router_data_res = services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, ) .await .to_refund_failed_response()?; let relay_update = relay::RelayUpdate::from(router_data_res.response); Ok(relay_update) } fn generate_response(value: relay::Relay) -> RouterResult<api_models::relay::RelayResponse> { let error = value .error_code .zip(value.error_message) .map( |(error_code, error_message)| api_models::relay::RelayError { code: error_code, message: error_message, }, ); let data = api_models::relay::RelayData::from(value.request_data.get_required_value("RelayData")?); Ok(api_models::relay::RelayResponse { id: value.id, status: value.status, error, connector_resource_id: value.connector_resource_id, connector_id: value.connector_id, profile_id: value.profile_id, relay_type: value.relay_type, data: Some(data), connector_reference_id: value.connector_reference_id, }) } } pub async fn relay_flow_decider( state: SessionState, merchant_account: domain::MerchantAccount, profile_id_optional: Option<id_type::ProfileId>, key_store: domain::MerchantKeyStore, request: relay_api_models::RelayRequest, ) -> RouterResponse<relay_api_models::RelayResponse> { let relay_flow_request = match request.relay_type { common_enums::RelayType::Refund => { RelayRequestInner::<RelayRefund>::from_relay_request(request)? } }; relay( state, merchant_account, profile_id_optional, key_store, relay_flow_request, ) .await } pub async fn relay<T: RelayInterface>( state: SessionState, merchant_account: domain::MerchantAccount, profile_id_optional: Option<id_type::ProfileId>, key_store: domain::MerchantKeyStore, req: RelayRequestInner<T>, ) -> RouterResponse<relay_api_models::RelayResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let merchant_id = merchant_account.get_id(); let connector_id = &req.connector_id; let profile_id_from_auth_layer = profile_id_optional.get_required_value("ProfileId")?; let profile = db .find_business_profile_by_merchant_id_profile_id( key_manager_state, &key_store, merchant_id, &profile_id_from_auth_layer, ) .await .change_context(errors::ApiErrorResponse::ProfileNotFound { id: profile_id_from_auth_layer.get_string_repr().to_owned(), })?; #[cfg(feature = "v1")] let connector_account = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_id, connector_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: connector_id.get_string_repr().to_string(), })?; #[cfg(feature = "v2")] let connector_account = db .find_merchant_connector_account_by_id(key_manager_state, connector_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: connector_id.get_string_repr().to_string(), })?; T::validate_relay_request(&req.data)?; let relay_domain = T::get_domain_models(req, merchant_id, profile.get_id()); let relay_record = db .insert_relay(key_manager_state, &key_store, relay_domain) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to insert a relay record in db")?; let relay_response = T::process_relay(&state, merchant_account, connector_account, &relay_record) .await .attach_printable("Failed to process relay")?; let relay_update_record = db .update_relay(key_manager_state, &key_store, relay_record, relay_response) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; let response = T::generate_response(relay_update_record) .attach_printable("Failed to generate relay response")?; Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( response, )) } pub async fn relay_retrieve( state: SessionState, merchant_account: domain::MerchantAccount, profile_id_optional: Option<id_type::ProfileId>, key_store: domain::MerchantKeyStore, req: relay_api_models::RelayRetrieveRequest, ) -> RouterResponse<relay_api_models::RelayResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let merchant_id = merchant_account.get_id(); let relay_id = &req.id; let profile_id_from_auth_layer = profile_id_optional.get_required_value("ProfileId")?; db.find_business_profile_by_merchant_id_profile_id( key_manager_state, &key_store, merchant_id, &profile_id_from_auth_layer, ) .await .change_context(errors::ApiErrorResponse::ProfileNotFound { id: profile_id_from_auth_layer.get_string_repr().to_owned(), })?; let relay_record_result = db .find_relay_by_id(key_manager_state, &key_store, relay_id) .await; let relay_record = match relay_record_result { Err(error) => { if error.current_context().is_db_not_found() { Err(error).change_context(errors::ApiErrorResponse::GenericNotFoundError { message: "relay not found".to_string(), })? } else { Err(error) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error while fetch relay record")? } } Ok(relay) => relay, }; #[cfg(feature = "v1")] let connector_account = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_id, &relay_record.connector_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: relay_record.connector_id.get_string_repr().to_string(), })?; #[cfg(feature = "v2")] let connector_account = db .find_merchant_connector_account_by_id( key_manager_state, &relay_record.connector_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: relay_record.connector_id.get_string_repr().to_string(), })?; let relay_response = match relay_record.relay_type { common_enums::RelayType::Refund => { if should_call_connector_for_relay_refund_status(&relay_record, req.force_sync) { let relay_response = sync_relay_refund_with_gateway( &state, &merchant_account, &relay_record, connector_account, ) .await?; db.update_relay(key_manager_state, &key_store, relay_record, relay_response) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update the relay record")? } else { relay_record } } }; let response = relay_api_models::RelayResponse::from(relay_response); Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( response, )) } fn should_call_connector_for_relay_refund_status(relay: &relay::Relay, force_sync: bool) -> bool { // This allows refund sync at connector level if force_sync is enabled, or // check if the refund is in terminal state !matches!(relay.status, RelayStatus::Failure | RelayStatus::Success) && force_sync } pub async fn sync_relay_refund_with_gateway( state: &SessionState, merchant_account: &domain::MerchantAccount, relay_record: &relay::Relay, connector_account: domain::MerchantConnectorAccount, ) -> RouterResult<relay::RelayUpdate> { let connector_id = &relay_record.connector_id; let merchant_id = merchant_account.get_id(); #[cfg(feature = "v1")] let connector_name = &connector_account.connector_name; #[cfg(feature = "v2")] let connector_name = &connector_account.connector_name.to_string(); let connector_data: api::ConnectorData = api::ConnectorData::get_connector_by_name( &state.conf.connectors, connector_name, api::GetToken::Connector, Some(connector_id.clone()), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the connector")?; let router_data = utils::construct_relay_refund_router_data( state, merchant_id, &connector_account, relay_record, ) .await?; let connector_integration: services::BoxedRefundConnectorIntegrationInterface< api::RSync, hyperswitch_domain_models::router_request_types::RefundsData, hyperswitch_domain_models::router_response_types::RefundsResponseData, > = connector_data.connector.get_connector_integration(); let router_data_res = services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, ) .await .to_refund_failed_response()?; let relay_response = relay::RelayUpdate::from(router_data_res.response); Ok(relay_response) }
3,245
1,555
hyperswitch
crates/router/src/core/currency.rs
.rs
use analytics::errors::AnalyticsError; use common_utils::errors::CustomResult; use currency_conversion::types::ExchangeRates; use error_stack::ResultExt; use router_env::logger; use crate::{ consts::DEFAULT_ANALYTICS_FOREX_RETRY_ATTEMPTS, core::errors::ApiErrorResponse, services::ApplicationResponse, utils::currency::{self, convert_currency, get_forex_rates, ForexError as ForexCacheError}, SessionState, }; pub async fn retrieve_forex( state: SessionState, ) -> CustomResult<ApplicationResponse<currency::FxExchangeRatesCacheEntry>, ApiErrorResponse> { let forex_api = state.conf.forex_api.get_inner(); Ok(ApplicationResponse::Json( get_forex_rates(&state, forex_api.data_expiration_delay_in_seconds) .await .change_context(ApiErrorResponse::GenericNotFoundError { message: "Unable to fetch forex rates".to_string(), })?, )) } pub async fn convert_forex( state: SessionState, amount: i64, to_currency: String, from_currency: String, ) -> CustomResult< ApplicationResponse<api_models::currency::CurrencyConversionResponse>, ApiErrorResponse, > { Ok(ApplicationResponse::Json( Box::pin(convert_currency( state.clone(), amount, to_currency, from_currency, )) .await .change_context(ApiErrorResponse::InternalServerError)?, )) } pub async fn get_forex_exchange_rates( state: SessionState, ) -> CustomResult<ExchangeRates, AnalyticsError> { let forex_api = state.conf.forex_api.get_inner(); let mut attempt = 1; logger::info!("Starting forex exchange rates fetch"); loop { logger::info!("Attempting to fetch forex rates - Attempt {attempt} of {DEFAULT_ANALYTICS_FOREX_RETRY_ATTEMPTS}"); match get_forex_rates(&state, forex_api.data_expiration_delay_in_seconds).await { Ok(rates) => { logger::info!("Successfully fetched forex rates"); return Ok((*rates.data).clone()); } Err(error) => { let is_retryable = matches!( error.current_context(), ForexCacheError::CouldNotAcquireLock | ForexCacheError::EntryNotFound | ForexCacheError::ForexDataUnavailable | ForexCacheError::LocalReadError | ForexCacheError::LocalWriteError | ForexCacheError::RedisConnectionError | ForexCacheError::RedisLockReleaseFailed | ForexCacheError::RedisWriteError | ForexCacheError::WriteLockNotAcquired ); if !is_retryable { return Err(error.change_context(AnalyticsError::ForexFetchFailed)); } if attempt >= DEFAULT_ANALYTICS_FOREX_RETRY_ATTEMPTS { logger::error!("Failed to fetch forex rates after {DEFAULT_ANALYTICS_FOREX_RETRY_ATTEMPTS} attempts"); return Err(error.change_context(AnalyticsError::ForexFetchFailed)); } logger::warn!( "Forex rates fetch failed with retryable error, retrying in {attempt} seconds" ); tokio::time::sleep(std::time::Duration::from_secs(attempt * 2)).await; attempt += 1; } } } }
700
1,556
hyperswitch
crates/router/src/core/user.rs
.rs
use std::{ collections::{HashMap, HashSet}, ops::Not, }; use api_models::{ payments::RedirectionResponse, user::{self as user_api, InviteMultipleUserResponse, NameIdUnit}, }; use common_enums::{EntityType, UserAuthType}; use common_utils::{type_name, types::keymanager::Identifier}; #[cfg(feature = "email")] use diesel_models::user_role::UserRoleUpdate; use diesel_models::{ enums::{TotpStatus, UserRoleVersion, UserStatus}, organization::OrganizationBridge, user as storage_user, user_authentication_method::{UserAuthenticationMethodNew, UserAuthenticationMethodUpdate}, }; use error_stack::{report, ResultExt}; use masking::{ExposeInterface, PeekInterface, Secret}; #[cfg(feature = "email")] use router_env::env; use router_env::logger; use storage_impl::errors::StorageError; #[cfg(not(feature = "email"))] use user_api::dashboard_metadata::SetMetaDataRequest; #[cfg(feature = "v1")] use super::admin; use super::errors::{StorageErrorExt, UserErrors, UserResponse, UserResult}; #[cfg(feature = "email")] use crate::services::email::types as email_types; #[cfg(feature = "v1")] use crate::types::transformers::ForeignFrom; use crate::{ consts, core::encryption::send_request_to_key_service_for_user, db::{ domain::user_authentication_method::DEFAULT_USER_AUTH_METHOD, user_role::ListUserRolesByUserIdPayload, }, routes::{app::ReqState, SessionState}, services::{authentication as auth, authorization::roles, openidconnect, ApplicationResponse}, types::{domain, transformers::ForeignInto}, utils::{ self, user::{theme as theme_utils, two_factor_auth as tfa_utils}, }, }; pub mod dashboard_metadata; #[cfg(feature = "dummy_connector")] pub mod sample_data; pub mod theme; #[cfg(feature = "email")] pub async fn signup_with_merchant_id( state: SessionState, request: user_api::SignUpWithMerchantIdRequest, auth_id: Option<String>, theme_id: Option<String>, ) -> UserResponse<user_api::SignUpWithMerchantIdResponse> { let new_user = domain::NewUser::try_from(request.clone())?; new_user .get_new_merchant() .get_new_organization() .insert_org_in_db(state.clone()) .await?; let user_from_db = new_user .insert_user_and_merchant_in_db(state.clone()) .await?; let _user_role = new_user .insert_org_level_user_role_in_db( state.clone(), common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(), UserStatus::Active, ) .await?; let theme = theme_utils::get_theme_using_optional_theme_id(&state, theme_id).await?; let email_contents = email_types::ResetPassword { recipient_email: user_from_db.get_email().try_into()?, user_name: domain::UserName::new(user_from_db.get_name())?, settings: state.conf.clone(), auth_id, theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()), theme_config: theme .map(|theme| theme.email_config()) .unwrap_or(state.conf.theme.email_config.clone()), }; let send_email_result = state .email_client .compose_and_send_email( email_types::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) .await; logger::info!(?send_email_result); Ok(ApplicationResponse::Json(user_api::AuthorizeResponse { is_email_sent: send_email_result.is_ok(), user_id: user_from_db.get_user_id().to_string(), })) } pub async fn get_user_details( state: SessionState, user_from_token: auth::UserFromToken, ) -> UserResponse<user_api::GetUserDetailsResponse> { let user = user_from_token.get_user_from_db(&state).await?; let verification_days_left = utils::user::get_verification_days_left(&state, &user)?; let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; let key_manager_state = &(&state).into(); let merchant_key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, &user_from_token.merchant_id, &state.store.get_master_key().to_vec().into(), ) .await; let version = if let Ok(merchant_key_store) = merchant_key_store { let merchant_account = state .store .find_merchant_account_by_merchant_id( key_manager_state, &user_from_token.merchant_id, &merchant_key_store, ) .await; if let Ok(merchant_account) = merchant_account { merchant_account.version } else if merchant_account .as_ref() .map_err(|e| e.current_context().is_db_not_found()) .err() .unwrap_or(false) { common_enums::ApiVersion::V2 } else { Err(merchant_account .err() .map(|e| e.change_context(UserErrors::InternalServerError)) .unwrap_or(UserErrors::InternalServerError.into()))? } } else if merchant_key_store .as_ref() .map_err(|e| e.current_context().is_db_not_found()) .err() .unwrap_or(false) { common_enums::ApiVersion::V2 } else { Err(merchant_key_store .err() .map(|e| e.change_context(UserErrors::InternalServerError)) .unwrap_or(UserErrors::InternalServerError.into()))? }; let theme = theme_utils::get_most_specific_theme_using_token_and_min_entity( &state, &user_from_token, EntityType::Profile, ) .await?; Ok(ApplicationResponse::Json( user_api::GetUserDetailsResponse { merchant_id: user_from_token.merchant_id, name: user.get_name(), email: user.get_email(), user_id: user.get_user_id().to_string(), verification_days_left, role_id: user_from_token.role_id, org_id: user_from_token.org_id, is_two_factor_auth_setup: user.get_totp_status() == TotpStatus::Set, recovery_codes_left: user.get_recovery_codes().map(|codes| codes.len()), profile_id: user_from_token.profile_id, entity_type: role_info.get_entity_type(), theme_id: theme.map(|theme| theme.theme_id), version, }, )) } pub async fn signup_token_only_flow( state: SessionState, request: user_api::SignUpRequest, ) -> UserResponse<user_api::TokenResponse> { let user_email = domain::UserEmail::from_pii_email(request.email.clone())?; utils::user::validate_email_domain_auth_type_using_db( &state, &user_email, UserAuthType::Password, ) .await?; let new_user = domain::NewUser::try_from(request)?; new_user .get_new_merchant() .get_new_organization() .insert_org_in_db(state.clone()) .await?; let user_from_db = new_user .insert_user_and_merchant_in_db(state.clone()) .await?; let user_role = new_user .insert_org_level_user_role_in_db( state.clone(), common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(), UserStatus::Active, ) .await?; let next_flow = domain::NextFlow::from_origin(domain::Origin::SignUp, user_from_db.clone(), &state).await?; let token = next_flow .get_token_with_user_role(&state, &user_role) .await?; let response = user_api::TokenResponse { token: token.clone(), token_type: next_flow.get_flow().into(), }; auth::cookies::set_cookie_response(response, token) } pub async fn signin_token_only_flow( state: SessionState, request: user_api::SignInRequest, ) -> UserResponse<user_api::TokenResponse> { let user_email = domain::UserEmail::from_pii_email(request.email)?; utils::user::validate_email_domain_auth_type_using_db( &state, &user_email, UserAuthType::Password, ) .await?; let user_from_db: domain::UserFromStorage = state .global_store .find_user_by_email(&user_email) .await .to_not_found_response(UserErrors::InvalidCredentials)? .into(); user_from_db.compare_password(&request.password)?; let next_flow = domain::NextFlow::from_origin(domain::Origin::SignIn, user_from_db.clone(), &state).await?; let token = next_flow.get_token(&state).await?; let response = user_api::TokenResponse { token: token.clone(), token_type: next_flow.get_flow().into(), }; auth::cookies::set_cookie_response(response, token) } #[cfg(feature = "email")] pub async fn connect_account( state: SessionState, request: user_api::ConnectAccountRequest, auth_id: Option<String>, theme_id: Option<String>, ) -> UserResponse<user_api::ConnectAccountResponse> { let user_email = domain::UserEmail::from_pii_email(request.email.clone())?; utils::user::validate_email_domain_auth_type_using_db( &state, &user_email, UserAuthType::MagicLink, ) .await?; let find_user = state.global_store.find_user_by_email(&user_email).await; if let Ok(found_user) = find_user { let user_from_db: domain::UserFromStorage = found_user.into(); let theme = theme_utils::get_theme_using_optional_theme_id(&state, theme_id).await?; let email_contents = email_types::MagicLink { recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?, settings: state.conf.clone(), user_name: domain::UserName::new(user_from_db.get_name())?, auth_id, theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()), theme_config: theme .map(|theme| theme.email_config()) .unwrap_or(state.conf.theme.email_config.clone()), }; let send_email_result = state .email_client .compose_and_send_email( email_types::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) .await; logger::info!(?send_email_result); Ok(ApplicationResponse::Json( user_api::ConnectAccountResponse { is_email_sent: send_email_result.is_ok(), user_id: user_from_db.get_user_id().to_string(), }, )) } else if find_user .as_ref() .map_err(|e| e.current_context().is_db_not_found()) .err() .unwrap_or(false) { if matches!(env::which(), env::Env::Production) { return Err(report!(UserErrors::InvalidCredentials)); } let new_user = domain::NewUser::try_from(request)?; let _ = new_user .get_new_merchant() .get_new_organization() .insert_org_in_db(state.clone()) .await?; let user_from_db = new_user .insert_user_and_merchant_in_db(state.clone()) .await?; let _user_role = new_user .insert_org_level_user_role_in_db( state.clone(), common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(), UserStatus::Active, ) .await?; let theme = theme_utils::get_theme_using_optional_theme_id(&state, theme_id).await?; let magic_link_email = email_types::VerifyEmail { recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?, settings: state.conf.clone(), auth_id, theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()), theme_config: theme .map(|theme| theme.email_config()) .unwrap_or(state.conf.theme.email_config.clone()), }; let magic_link_result = state .email_client .compose_and_send_email( email_types::get_base_url(&state), Box::new(magic_link_email), state.conf.proxy.https_url.as_ref(), ) .await; logger::info!(?magic_link_result); if state.tenant.tenant_id.get_string_repr() == common_utils::consts::DEFAULT_TENANT { let welcome_to_community_email = email_types::WelcomeToCommunity { recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?, }; let welcome_email_result = state .email_client .compose_and_send_email( email_types::get_base_url(&state), Box::new(welcome_to_community_email), state.conf.proxy.https_url.as_ref(), ) .await; logger::info!(?welcome_email_result); } return Ok(ApplicationResponse::Json( user_api::ConnectAccountResponse { is_email_sent: magic_link_result.is_ok(), user_id: user_from_db.get_user_id().to_string(), }, )); } else { Err(find_user .err() .map(|e| e.change_context(UserErrors::InternalServerError)) .unwrap_or(UserErrors::InternalServerError.into())) } } pub async fn signout( state: SessionState, user_from_token: auth::UserIdFromAuth, ) -> UserResponse<()> { tfa_utils::delete_totp_from_redis(&state, &user_from_token.user_id).await?; tfa_utils::delete_recovery_code_from_redis(&state, &user_from_token.user_id).await?; tfa_utils::delete_totp_secret_from_redis(&state, &user_from_token.user_id).await?; auth::blacklist::insert_user_in_blacklist(&state, &user_from_token.user_id).await?; auth::cookies::remove_cookie_response() } pub async fn change_password( state: SessionState, request: user_api::ChangePasswordRequest, user_from_token: auth::UserFromToken, ) -> UserResponse<()> { let user: domain::UserFromStorage = state .global_store .find_user_by_id(&user_from_token.user_id) .await .change_context(UserErrors::InternalServerError)? .into(); user.compare_password(&request.old_password) .change_context(UserErrors::InvalidOldPassword)?; if request.old_password == request.new_password { return Err(UserErrors::ChangePasswordError.into()); } let new_password = domain::UserPassword::new(request.new_password)?; let new_password_hash = utils::user::password::generate_password_hash(new_password.get_secret())?; let _ = state .global_store .update_user_by_user_id( user.get_user_id(), diesel_models::user::UserUpdate::PasswordUpdate { password: new_password_hash, }, ) .await .change_context(UserErrors::InternalServerError)?; let _ = auth::blacklist::insert_user_in_blacklist(&state, user.get_user_id()) .await .map_err(|error| logger::error!(?error)); #[cfg(not(feature = "email"))] { state .store .delete_user_scoped_dashboard_metadata_by_merchant_id_data_key( &user_from_token.user_id, &user_from_token.merchant_id, diesel_models::enums::DashboardMetadata::IsChangePasswordRequired, ) .await .map_err(|e| logger::error!("Error while deleting dashboard metadata {e:?}")) .ok(); } Ok(ApplicationResponse::StatusOk) } #[cfg(feature = "email")] pub async fn forgot_password( state: SessionState, request: user_api::ForgotPasswordRequest, auth_id: Option<String>, theme_id: Option<String>, ) -> UserResponse<()> { let user_email = domain::UserEmail::from_pii_email(request.email)?; utils::user::validate_email_domain_auth_type_using_db( &state, &user_email, UserAuthType::Password, ) .await?; let user_from_db = state .global_store .find_user_by_email(&user_email) .await .map_err(|e| { if e.current_context().is_db_not_found() { e.change_context(UserErrors::UserNotFound) } else { e.change_context(UserErrors::InternalServerError) } }) .map(domain::UserFromStorage::from)?; let theme = theme_utils::get_theme_using_optional_theme_id(&state, theme_id).await?; let email_contents = email_types::ResetPassword { recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?, settings: state.conf.clone(), user_name: domain::UserName::new(user_from_db.get_name())?, auth_id, theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()), theme_config: theme .map(|theme| theme.email_config()) .unwrap_or(state.conf.theme.email_config.clone()), }; state .email_client .compose_and_send_email( email_types::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) .await .map_err(|e| e.change_context(UserErrors::InternalServerError))?; Ok(ApplicationResponse::StatusOk) } pub async fn rotate_password( state: SessionState, user_token: auth::UserFromSinglePurposeToken, request: user_api::RotatePasswordRequest, _req_state: ReqState, ) -> UserResponse<()> { let user: domain::UserFromStorage = state .global_store .find_user_by_id(&user_token.user_id) .await .change_context(UserErrors::InternalServerError)? .into(); let password = domain::UserPassword::new(request.password.to_owned())?; let hash_password = utils::user::password::generate_password_hash(password.get_secret())?; if user.compare_password(&request.password).is_ok() { return Err(UserErrors::ChangePasswordError.into()); } let user = state .global_store .update_user_by_user_id( &user_token.user_id, storage_user::UserUpdate::PasswordUpdate { password: hash_password, }, ) .await .change_context(UserErrors::InternalServerError)?; let _ = auth::blacklist::insert_user_in_blacklist(&state, &user.user_id) .await .map_err(|error| logger::error!(?error)); auth::cookies::remove_cookie_response() } #[cfg(feature = "email")] pub async fn reset_password_token_only_flow( state: SessionState, user_token: auth::UserFromSinglePurposeToken, request: user_api::ResetPasswordRequest, ) -> UserResponse<()> { let token = request.token.expose(); let email_token = auth::decode_jwt::<email_types::EmailToken>(&token, &state) .await .change_context(UserErrors::LinkInvalid)?; auth::blacklist::check_email_token_in_blacklist(&state, &token).await?; let user_from_db: domain::UserFromStorage = state .global_store .find_user_by_email(&email_token.get_email()?) .await .change_context(UserErrors::InternalServerError)? .into(); if user_from_db.get_user_id() != user_token.user_id { return Err(UserErrors::LinkInvalid.into()); } let password = domain::UserPassword::new(request.password)?; let hash_password = utils::user::password::generate_password_hash(password.get_secret())?; let user = state .global_store .update_user_by_user_id( user_from_db.get_user_id(), storage_user::UserUpdate::PasswordUpdate { password: hash_password, }, ) .await .change_context(UserErrors::InternalServerError)?; if !user_from_db.is_verified() { let _ = state .global_store .update_user_by_user_id( user_from_db.get_user_id(), storage_user::UserUpdate::VerifyUser, ) .await .map_err(|error| logger::error!(?error)); } let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token) .await .map_err(|error| logger::error!(?error)); let _ = auth::blacklist::insert_user_in_blacklist(&state, &user.user_id) .await .map_err(|error| logger::error!(?error)); auth::cookies::remove_cookie_response() } pub async fn invite_multiple_user( state: SessionState, user_from_token: auth::UserFromToken, requests: Vec<user_api::InviteUserRequest>, req_state: ReqState, auth_id: Option<String>, ) -> UserResponse<Vec<InviteMultipleUserResponse>> { if requests.len() > 10 { return Err(report!(UserErrors::MaxInvitationsError)) .attach_printable("Number of invite requests must not exceed 10"); } let responses = futures::future::join_all(requests.into_iter().map(|request| async { match handle_invitation(&state, &user_from_token, &request, &req_state, &auth_id).await { Ok(response) => response, Err(error) => { logger::error!(invite_error=?error); InviteMultipleUserResponse { email: request.email, is_email_sent: false, password: None, error: Some(error.current_context().get_error_message().to_string()), } } } })) .await; Ok(ApplicationResponse::Json(responses)) } async fn handle_invitation( state: &SessionState, user_from_token: &auth::UserFromToken, request: &user_api::InviteUserRequest, req_state: &ReqState, auth_id: &Option<String>, ) -> UserResult<InviteMultipleUserResponse> { let inviter_user = user_from_token.get_user_from_db(state).await?; if inviter_user.get_email() == request.email { return Err(UserErrors::InvalidRoleOperationWithMessage( "User Inviting themselves".to_string(), ) .into()); } let role_info = roles::RoleInfo::from_role_id_in_lineage( state, &request.role_id, &user_from_token.merchant_id, &user_from_token.org_id, &user_from_token.profile_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .to_not_found_response(UserErrors::InvalidRoleId)?; if !role_info.is_invitable() { return Err(report!(UserErrors::InvalidRoleId)) .attach_printable(format!("role_id = {} is not invitable", request.role_id)); } let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?; let invitee_user = state.global_store.find_user_by_email(&invitee_email).await; if let Ok(invitee_user) = invitee_user { handle_existing_user_invitation( state, user_from_token, request, invitee_user.into(), role_info, auth_id, ) .await } else if invitee_user .as_ref() .map_err(|e| e.current_context().is_db_not_found()) .err() .unwrap_or(false) { handle_new_user_invitation( state, user_from_token, request, role_info, req_state.clone(), auth_id, ) .await } else { Err(UserErrors::InternalServerError.into()) } } #[allow(unused_variables)] async fn handle_existing_user_invitation( state: &SessionState, user_from_token: &auth::UserFromToken, request: &user_api::InviteUserRequest, invitee_user_from_db: domain::UserFromStorage, role_info: roles::RoleInfo, auth_id: &Option<String>, ) -> UserResult<InviteMultipleUserResponse> { let now = common_utils::date_time::now(); if state .global_store .find_user_role_by_user_id_and_lineage( invitee_user_from_db.get_user_id(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, UserRoleVersion::V1, ) .await .is_err_and(|err| err.current_context().is_db_not_found()) .not() { return Err(UserErrors::UserExists.into()); } if state .global_store .find_user_role_by_user_id_and_lineage( invitee_user_from_db.get_user_id(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, UserRoleVersion::V2, ) .await .is_err_and(|err| err.current_context().is_db_not_found()) .not() { return Err(UserErrors::UserExists.into()); } let (org_id, merchant_id, profile_id) = match role_info.get_entity_type() { EntityType::Tenant => { return Err(UserErrors::InvalidRoleOperationWithMessage( "Tenant roles are not allowed for this operation".to_string(), ) .into()); } EntityType::Organization => (Some(&user_from_token.org_id), None, None), EntityType::Merchant => ( Some(&user_from_token.org_id), Some(&user_from_token.merchant_id), None, ), EntityType::Profile => ( Some(&user_from_token.org_id), Some(&user_from_token.merchant_id), Some(&user_from_token.profile_id), ), }; if state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: invitee_user_from_db.get_user_id(), tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id, merchant_id, profile_id, entity_id: None, version: None, status: None, limit: Some(1), }) .await .is_ok_and(|data| data.is_empty().not()) { return Err(UserErrors::UserExists.into()); } let user_role = domain::NewUserRole { user_id: invitee_user_from_db.get_user_id().to_owned(), role_id: request.role_id.clone(), status: { if cfg!(feature = "email") { UserStatus::InvitationSent } else { UserStatus::Active } }, created_by: user_from_token.user_id.clone(), last_modified_by: user_from_token.user_id.clone(), created_at: now, last_modified: now, entity: domain::NoLevel, }; let _user_role = match role_info.get_entity_type() { EntityType::Tenant => { return Err(UserErrors::InvalidRoleOperationWithMessage( "Tenant roles are not allowed for this operation".to_string(), ) .into()); } EntityType::Organization => { user_role .add_entity(domain::OrganizationLevel { tenant_id: user_from_token .tenant_id .clone() .unwrap_or(state.tenant.tenant_id.clone()), org_id: user_from_token.org_id.clone(), }) .insert_in_v2(state) .await? } EntityType::Merchant => { user_role .add_entity(domain::MerchantLevel { tenant_id: user_from_token .tenant_id .clone() .unwrap_or(state.tenant.tenant_id.clone()), org_id: user_from_token.org_id.clone(), merchant_id: user_from_token.merchant_id.clone(), }) .insert_in_v2(state) .await? } EntityType::Profile => { user_role .add_entity(domain::ProfileLevel { tenant_id: user_from_token .tenant_id .clone() .unwrap_or(state.tenant.tenant_id.clone()), org_id: user_from_token.org_id.clone(), merchant_id: user_from_token.merchant_id.clone(), profile_id: user_from_token.profile_id.clone(), }) .insert_in_v2(state) .await? } }; let is_email_sent; #[cfg(feature = "email")] { let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?; let entity = match role_info.get_entity_type() { EntityType::Tenant => { return Err(UserErrors::InvalidRoleOperationWithMessage( "Tenant roles are not allowed for this operation".to_string(), ) .into()); } EntityType::Organization => email_types::Entity { entity_id: user_from_token.org_id.get_string_repr().to_owned(), entity_type: EntityType::Organization, }, EntityType::Merchant => email_types::Entity { entity_id: user_from_token.merchant_id.get_string_repr().to_owned(), entity_type: EntityType::Merchant, }, EntityType::Profile => email_types::Entity { entity_id: user_from_token.profile_id.get_string_repr().to_owned(), entity_type: EntityType::Profile, }, }; let theme = theme_utils::get_most_specific_theme_using_token_and_min_entity( state, user_from_token, role_info.get_entity_type(), ) .await?; let email_contents = email_types::InviteUser { recipient_email: invitee_email, user_name: domain::UserName::new(invitee_user_from_db.get_name())?, settings: state.conf.clone(), entity, auth_id: auth_id.clone(), theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()), theme_config: theme .map(|theme| theme.email_config()) .unwrap_or(state.conf.theme.email_config.clone()), }; is_email_sent = state .email_client .compose_and_send_email( email_types::get_base_url(state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) .await .map(|email_result| logger::info!(?email_result)) .map_err(|email_result| logger::error!(?email_result)) .is_ok(); } #[cfg(not(feature = "email"))] { is_email_sent = false; } Ok(InviteMultipleUserResponse { email: request.email.clone(), is_email_sent, password: None, error: None, }) } #[allow(unused_variables)] async fn handle_new_user_invitation( state: &SessionState, user_from_token: &auth::UserFromToken, request: &user_api::InviteUserRequest, role_info: roles::RoleInfo, req_state: ReqState, auth_id: &Option<String>, ) -> UserResult<InviteMultipleUserResponse> { let new_user = domain::NewUser::try_from((request.clone(), user_from_token.clone()))?; new_user .insert_user_in_db(state.global_store.as_ref()) .await .change_context(UserErrors::InternalServerError)?; let invitation_status = if cfg!(feature = "email") { UserStatus::InvitationSent } else { UserStatus::Active }; let now = common_utils::date_time::now(); let user_role = domain::NewUserRole { user_id: new_user.get_user_id().to_owned(), role_id: request.role_id.clone(), status: invitation_status, created_by: user_from_token.user_id.clone(), last_modified_by: user_from_token.user_id.clone(), created_at: now, last_modified: now, entity: domain::NoLevel, }; let _user_role = match role_info.get_entity_type() { EntityType::Tenant => { return Err(UserErrors::InvalidRoleOperationWithMessage( "Tenant roles are not allowed for this operation".to_string(), ) .into()); } EntityType::Organization => { user_role .add_entity(domain::OrganizationLevel { tenant_id: user_from_token .tenant_id .clone() .unwrap_or(state.tenant.tenant_id.clone()), org_id: user_from_token.org_id.clone(), }) .insert_in_v2(state) .await? } EntityType::Merchant => { user_role .add_entity(domain::MerchantLevel { tenant_id: user_from_token .tenant_id .clone() .unwrap_or(state.tenant.tenant_id.clone()), org_id: user_from_token.org_id.clone(), merchant_id: user_from_token.merchant_id.clone(), }) .insert_in_v2(state) .await? } EntityType::Profile => { user_role .add_entity(domain::ProfileLevel { tenant_id: user_from_token .tenant_id .clone() .unwrap_or(state.tenant.tenant_id.clone()), org_id: user_from_token.org_id.clone(), merchant_id: user_from_token.merchant_id.clone(), profile_id: user_from_token.profile_id.clone(), }) .insert_in_v2(state) .await? } }; let is_email_sent; #[cfg(feature = "email")] { // TODO: Adding this to avoid clippy lints // Will be adding actual usage for this variable later let _ = req_state.clone(); let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?; let entity = match role_info.get_entity_type() { EntityType::Tenant => { return Err(UserErrors::InvalidRoleOperationWithMessage( "Tenant roles are not allowed for this operation".to_string(), ) .into()); } EntityType::Organization => email_types::Entity { entity_id: user_from_token.org_id.get_string_repr().to_owned(), entity_type: EntityType::Organization, }, EntityType::Merchant => email_types::Entity { entity_id: user_from_token.merchant_id.get_string_repr().to_owned(), entity_type: EntityType::Merchant, }, EntityType::Profile => email_types::Entity { entity_id: user_from_token.profile_id.get_string_repr().to_owned(), entity_type: EntityType::Profile, }, }; let theme = theme_utils::get_most_specific_theme_using_token_and_min_entity( state, user_from_token, role_info.get_entity_type(), ) .await?; let email_contents = email_types::InviteUser { recipient_email: invitee_email, user_name: domain::UserName::new(new_user.get_name())?, settings: state.conf.clone(), entity, auth_id: auth_id.clone(), theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()), theme_config: theme .map(|theme| theme.email_config()) .unwrap_or(state.conf.theme.email_config.clone()), }; let send_email_result = state .email_client .compose_and_send_email( email_types::get_base_url(state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) .await; logger::info!(?send_email_result); is_email_sent = send_email_result.is_ok(); } #[cfg(not(feature = "email"))] { is_email_sent = false; let invited_user_token = auth::UserFromToken { user_id: new_user.get_user_id(), merchant_id: user_from_token.merchant_id.clone(), org_id: user_from_token.org_id.clone(), role_id: request.role_id.clone(), profile_id: user_from_token.profile_id.clone(), tenant_id: user_from_token.tenant_id.clone(), }; let set_metadata_request = SetMetaDataRequest::IsChangePasswordRequired; dashboard_metadata::set_metadata( state.clone(), invited_user_token, set_metadata_request, req_state, ) .await?; } Ok(InviteMultipleUserResponse { is_email_sent, password: new_user .get_password() .map(|password| password.get_secret()), email: request.email.clone(), error: None, }) } #[cfg(feature = "email")] pub async fn resend_invite( state: SessionState, user_from_token: auth::UserFromToken, request: user_api::ReInviteUserRequest, auth_id: Option<String>, ) -> UserResponse<()> { let invitee_email = domain::UserEmail::from_pii_email(request.email)?; let user: domain::UserFromStorage = state .global_store .find_user_by_email(&invitee_email) .await .map_err(|e| { if e.current_context().is_db_not_found() { e.change_context(UserErrors::InvalidRoleOperation) .attach_printable("User not found in the records") } else { e.change_context(UserErrors::InternalServerError) } })? .into(); let user_role = match state .global_store .find_user_role_by_user_id_and_lineage( user.get_user_id(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, UserRoleVersion::V2, ) .await { Ok(user_role) => Some(user_role), Err(err) => { if err.current_context().is_db_not_found() { None } else { return Err(report!(UserErrors::InternalServerError)); } } }; let user_role = match user_role { Some(user_role) => user_role, None => state .global_store .find_user_role_by_user_id_and_lineage( user.get_user_id(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, UserRoleVersion::V1, ) .await .to_not_found_response(UserErrors::InvalidRoleOperationWithMessage( "User not found in records".to_string(), ))?, }; if !matches!(user_role.status, UserStatus::InvitationSent) { return Err(report!(UserErrors::InvalidRoleOperation)) .attach_printable("User status is not InvitationSent".to_string()); } let (entity_id, entity_type) = user_role .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError)?; let invitee_role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_role.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; let theme = theme_utils::get_most_specific_theme_using_token_and_min_entity( &state, &user_from_token, invitee_role_info.get_entity_type(), ) .await?; let email_contents = email_types::InviteUser { recipient_email: invitee_email, user_name: domain::UserName::new(user.get_name())?, settings: state.conf.clone(), entity: email_types::Entity { entity_id, entity_type, }, auth_id: auth_id.clone(), theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()), theme_config: theme .map(|theme| theme.email_config()) .unwrap_or(state.conf.theme.email_config.clone()), }; state .email_client .compose_and_send_email( email_types::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) .await .change_context(UserErrors::InternalServerError)?; Ok(ApplicationResponse::StatusOk) } #[cfg(feature = "email")] pub async fn accept_invite_from_email_token_only_flow( state: SessionState, user_token: auth::UserFromSinglePurposeToken, request: user_api::AcceptInviteFromEmailRequest, ) -> UserResponse<user_api::TokenResponse> { let token = request.token.expose(); let email_token = auth::decode_jwt::<email_types::EmailToken>(&token, &state) .await .change_context(UserErrors::LinkInvalid)?; auth::blacklist::check_email_token_in_blacklist(&state, &token).await?; let user_from_db: domain::UserFromStorage = state .global_store .find_user_by_email(&email_token.get_email()?) .await .change_context(UserErrors::InternalServerError)? .into(); if user_from_db.get_user_id() != user_token.user_id { return Err(UserErrors::LinkInvalid.into()); } let entity = email_token.get_entity().ok_or(UserErrors::LinkInvalid)?; let (org_id, merchant_id, profile_id) = utils::user_role::get_lineage_for_user_id_and_entity_for_accepting_invite( &state, &user_token.user_id, user_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), entity.entity_id.clone(), entity.entity_type, ) .await .change_context(UserErrors::InternalServerError)? .ok_or(UserErrors::InternalServerError)?; let (update_v1_result, update_v2_result) = utils::user_role::update_v1_and_v2_user_roles_in_db( &state, user_from_db.get_user_id(), user_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), &org_id, merchant_id.as_ref(), profile_id.as_ref(), UserRoleUpdate::UpdateStatus { status: UserStatus::Active, modified_by: user_from_db.get_user_id().to_owned(), }, ) .await; if update_v1_result .as_ref() .is_err_and(|err| !err.current_context().is_db_not_found()) || update_v2_result .as_ref() .is_err_and(|err| !err.current_context().is_db_not_found()) { return Err(report!(UserErrors::InternalServerError)); } if update_v1_result.is_err() && update_v2_result.is_err() { return Err(report!(UserErrors::InvalidRoleOperation)) .attach_printable("User not found in the organization")?; } if !user_from_db.is_verified() { let _ = state .global_store .update_user_by_user_id( user_from_db.get_user_id(), storage_user::UserUpdate::VerifyUser, ) .await .map_err(|error| logger::error!(?error)); } let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token) .await .map_err(|error| logger::error!(?error)); let current_flow = domain::CurrentFlow::new( user_token, domain::SPTFlow::AcceptInvitationFromEmail.into(), )?; let next_flow = current_flow.next(user_from_db.clone(), &state).await?; let token = next_flow.get_token(&state).await?; let response = user_api::TokenResponse { token: token.clone(), token_type: next_flow.get_flow().into(), }; auth::cookies::set_cookie_response(response, token) } pub async fn create_internal_user( state: SessionState, request: user_api::CreateInternalUserRequest, ) -> UserResponse<()> { let key_manager_state = &(&state).into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, &common_utils::id_type::MerchantId::get_internal_user_merchant_id( consts::user_role::INTERNAL_USER_MERCHANT_ID, ), &state.store.get_master_key().to_vec().into(), ) .await .map_err(|e| { if e.current_context().is_db_not_found() { e.change_context(UserErrors::MerchantIdNotFound) } else { e.change_context(UserErrors::InternalServerError) } })?; let default_tenant_id = common_utils::id_type::TenantId::try_from_string( common_utils::consts::DEFAULT_TENANT.to_owned(), ) .change_context(UserErrors::InternalServerError) .attach_printable("Unable to parse default tenant id")?; if state.tenant.tenant_id != default_tenant_id { return Err(UserErrors::ForbiddenTenantId) .attach_printable("Operation allowed only for the default tenant"); } let internal_merchant_id = common_utils::id_type::MerchantId::get_internal_user_merchant_id( consts::user_role::INTERNAL_USER_MERCHANT_ID, ); let internal_merchant = state .store .find_merchant_account_by_merchant_id(key_manager_state, &internal_merchant_id, &key_store) .await .map_err(|e| { if e.current_context().is_db_not_found() { e.change_context(UserErrors::MerchantIdNotFound) } else { e.change_context(UserErrors::InternalServerError) } })?; let new_user = domain::NewUser::try_from((request, internal_merchant.organization_id.clone()))?; let mut store_user: storage_user::UserNew = new_user.clone().try_into()?; store_user.set_is_verified(true); state .global_store .insert_user(store_user) .await .map_err(|e| { if e.current_context().is_db_unique_violation() { e.change_context(UserErrors::UserExists) } else { e.change_context(UserErrors::InternalServerError) } }) .map(domain::user::UserFromStorage::from)?; new_user .get_no_level_user_role( common_utils::consts::ROLE_ID_INTERNAL_VIEW_ONLY_USER.to_string(), UserStatus::Active, ) .add_entity(domain::MerchantLevel { tenant_id: default_tenant_id, org_id: internal_merchant.organization_id, merchant_id: internal_merchant_id, }) .insert_in_v2(&state) .await .change_context(UserErrors::InternalServerError)?; Ok(ApplicationResponse::StatusOk) } pub async fn create_tenant_user( state: SessionState, request: user_api::CreateTenantUserRequest, ) -> UserResponse<()> { let key_manager_state = &(&state).into(); let (merchant_id, org_id) = state .store .list_merchant_and_org_ids(key_manager_state, 1, None) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to get merchants list for org")? .pop() .ok_or(UserErrors::InvalidRoleOperation) .attach_printable("No merchants found in the tenancy")?; let new_user = domain::NewUser::try_from(( request, domain::MerchantAccountIdentifier { merchant_id, org_id, }, ))?; let mut store_user: storage_user::UserNew = new_user.clone().try_into()?; store_user.set_is_verified(true); state .global_store .insert_user(store_user) .await .map_err(|e| { if e.current_context().is_db_unique_violation() { e.change_context(UserErrors::UserExists) } else { e.change_context(UserErrors::InternalServerError) } }) .map(domain::user::UserFromStorage::from)?; new_user .get_no_level_user_role( common_utils::consts::ROLE_ID_TENANT_ADMIN.to_string(), UserStatus::Active, ) .add_entity(domain::TenantLevel { tenant_id: state.tenant.tenant_id.clone(), }) .insert_in_v2(&state) .await .change_context(UserErrors::InternalServerError)?; Ok(ApplicationResponse::StatusOk) } #[cfg(feature = "v1")] pub async fn create_org_merchant_for_user( state: SessionState, req: user_api::UserOrgMerchantCreateRequest, ) -> UserResponse<()> { let db_organization = ForeignFrom::foreign_from(req.clone()); let org: diesel_models::organization::Organization = state .accounts_store .insert_organization(db_organization) .await .change_context(UserErrors::InternalServerError)?; let default_product_type = consts::user::DEFAULT_PRODUCT_TYPE; let merchant_account_create_request = utils::user::create_merchant_account_request_for_org(req, org, default_product_type)?; admin::create_merchant_account(state.clone(), merchant_account_create_request) .await .change_context(UserErrors::InternalServerError) .attach_printable("Error while creating a merchant")?; Ok(ApplicationResponse::StatusOk) } pub async fn create_merchant_account( state: SessionState, user_from_token: auth::UserFromToken, req: user_api::UserMerchantCreate, ) -> UserResponse<user_api::UserMerchantAccountResponse> { let user_from_db = user_from_token.get_user_from_db(&state).await?; let new_merchant = domain::NewUserMerchant::try_from((user_from_db, req, user_from_token))?; let domain_merchant_account = new_merchant .create_new_merchant_and_insert_in_db(state.to_owned()) .await?; Ok(ApplicationResponse::Json( user_api::UserMerchantAccountResponse { merchant_id: domain_merchant_account.get_id().to_owned(), merchant_name: domain_merchant_account.merchant_name, product_type: domain_merchant_account.product_type, version: domain_merchant_account.version, }, )) } pub async fn list_user_roles_details( state: SessionState, user_from_token: auth::UserFromToken, request: user_api::GetUserRoleDetailsRequest, _req_state: ReqState, ) -> UserResponse<Vec<user_api::GetUserRoleDetailsResponseV2>> { let required_user = utils::user::get_user_from_db_by_email(&state, request.email.try_into()?) .await .to_not_found_response(UserErrors::InvalidRoleOperation)?; let requestor_role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .to_not_found_response(UserErrors::InternalServerError) .attach_printable("Failed to fetch role info")?; if requestor_role_info.is_internal() { return Err(UserErrors::InvalidRoleOperationWithMessage( "Internal roles are not allowed for this operation".to_string(), ) .into()); } let user_roles_set = state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: required_user.get_user_id(), tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: Some(&user_from_token.org_id), merchant_id: (requestor_role_info.get_entity_type() <= EntityType::Merchant) .then_some(&user_from_token.merchant_id), profile_id: (requestor_role_info.get_entity_type() <= EntityType::Profile) .then_some(&user_from_token.profile_id), entity_id: None, version: None, status: None, limit: None, }) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to fetch user roles")? .into_iter() .collect::<HashSet<_>>(); let org_name = state .accounts_store .find_organization_by_org_id(&user_from_token.org_id) .await .change_context(UserErrors::InternalServerError) .attach_printable("Org id not found")? .get_organization_name(); let org = NameIdUnit { id: user_from_token.org_id.clone(), name: org_name, }; let (merchant_ids, merchant_profile_ids) = user_roles_set.iter().try_fold( (Vec::new(), Vec::new()), |(mut merchant, mut merchant_profile), user_role| { let (_, entity_type) = user_role .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError) .attach_printable("Failed to compute entity id and type")?; match entity_type { EntityType::Merchant => { let merchant_id = user_role .merchant_id .clone() .ok_or(UserErrors::InternalServerError) .attach_printable( "Merchant id not found in user role for merchant level entity", )?; merchant.push(merchant_id) } EntityType::Profile => { let merchant_id = user_role .merchant_id .clone() .ok_or(UserErrors::InternalServerError) .attach_printable( "Merchant id not found in user role for merchant level entity", )?; let profile_id = user_role .profile_id .clone() .ok_or(UserErrors::InternalServerError) .attach_printable( "Profile id not found in user role for profile level entity", )?; merchant.push(merchant_id.clone()); merchant_profile.push((merchant_id, profile_id)) } EntityType::Tenant | EntityType::Organization => (), }; Ok::<_, error_stack::Report<UserErrors>>((merchant, merchant_profile)) }, )?; let merchant_map = state .store .list_multiple_merchant_accounts(&(&state).into(), merchant_ids) .await .change_context(UserErrors::InternalServerError) .attach_printable("Error while listing merchant accounts")? .into_iter() .map(|merchant_account| { ( merchant_account.get_id().to_owned(), merchant_account.merchant_name.clone(), ) }) .collect::<HashMap<_, _>>(); let key_manager_state = &(&state).into(); let profile_map = futures::future::try_join_all(merchant_profile_ids.iter().map( |merchant_profile_id| async { let merchant_key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_profile_id.0, &state.store.get_master_key().to_vec().into(), ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to retrieve merchant key store by merchant_id")?; state .store .find_business_profile_by_profile_id( key_manager_state, &merchant_key_store, &merchant_profile_id.1, ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to retrieve business profile") }, )) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to construct profile map")? .into_iter() .map(|profile| (profile.get_id().to_owned(), profile.profile_name)) .collect::<HashMap<_, _>>(); let role_name_map = futures::future::try_join_all( user_roles_set .iter() .map(|user_role| user_role.role_id.clone()) .collect::<HashSet<_>>() .into_iter() .map(|role_id| async { let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; Ok::<_, error_stack::Report<_>>((role_id, role_info.get_role_name().to_string())) }), ) .await? .into_iter() .collect::<HashMap<_, _>>(); let role_details_list: Vec<_> = user_roles_set .iter() .map(|user_role| { let (_, entity_type) = user_role .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError)?; let (merchant, profile) = match entity_type { EntityType::Tenant | EntityType::Organization => (None, None), EntityType::Merchant => { let merchant_id = &user_role .merchant_id .clone() .ok_or(UserErrors::InternalServerError)?; ( Some(NameIdUnit { id: merchant_id.clone(), name: merchant_map .get(merchant_id) .ok_or(UserErrors::InternalServerError)? .to_owned(), }), None, ) } EntityType::Profile => { let merchant_id = &user_role .merchant_id .clone() .ok_or(UserErrors::InternalServerError)?; let profile_id = &user_role .profile_id .clone() .ok_or(UserErrors::InternalServerError)?; ( Some(NameIdUnit { id: merchant_id.clone(), name: merchant_map .get(merchant_id) .ok_or(UserErrors::InternalServerError)? .to_owned(), }), Some(NameIdUnit { id: profile_id.clone(), name: profile_map .get(profile_id) .ok_or(UserErrors::InternalServerError)? .to_owned(), }), ) } }; Ok(user_api::GetUserRoleDetailsResponseV2 { role_id: user_role.role_id.clone(), org: org.clone(), merchant, profile, status: user_role.status.foreign_into(), entity_type, role_name: role_name_map .get(&user_role.role_id) .ok_or(UserErrors::InternalServerError) .cloned()?, }) }) .collect::<Result<Vec<_>, UserErrors>>()?; Ok(ApplicationResponse::Json(role_details_list)) } #[cfg(feature = "email")] pub async fn verify_email_token_only_flow( state: SessionState, user_token: auth::UserFromSinglePurposeToken, req: user_api::VerifyEmailRequest, ) -> UserResponse<user_api::TokenResponse> { let token = req.token.clone().expose(); let email_token = auth::decode_jwt::<email_types::EmailToken>(&token, &state) .await .change_context(UserErrors::LinkInvalid)?; auth::blacklist::check_email_token_in_blacklist(&state, &token).await?; let user_from_email = state .global_store .find_user_by_email(&email_token.get_email()?) .await .change_context(UserErrors::InternalServerError)?; if user_from_email.user_id != user_token.user_id { return Err(UserErrors::LinkInvalid.into()); } let user_from_db: domain::UserFromStorage = state .global_store .update_user_by_user_id( user_from_email.user_id.as_str(), storage_user::UserUpdate::VerifyUser, ) .await .change_context(UserErrors::InternalServerError)? .into(); let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token) .await .map_err(|error| logger::error!(?error)); let current_flow = domain::CurrentFlow::new(user_token, domain::SPTFlow::VerifyEmail.into())?; let next_flow = current_flow.next(user_from_db, &state).await?; let token = next_flow.get_token(&state).await?; let response = user_api::TokenResponse { token: token.clone(), token_type: next_flow.get_flow().into(), }; auth::cookies::set_cookie_response(response, token) } #[cfg(feature = "email")] pub async fn send_verification_mail( state: SessionState, req: user_api::SendVerifyEmailRequest, auth_id: Option<String>, theme_id: Option<String>, ) -> UserResponse<()> { let user_email = domain::UserEmail::from_pii_email(req.email)?; utils::user::validate_email_domain_auth_type_using_db( &state, &user_email, UserAuthType::MagicLink, ) .await?; let user = state .global_store .find_user_by_email(&user_email) .await .map_err(|e| { if e.current_context().is_db_not_found() { e.change_context(UserErrors::UserNotFound) } else { e.change_context(UserErrors::InternalServerError) } })?; if user.is_verified { return Err(UserErrors::UserAlreadyVerified.into()); } let theme = theme_utils::get_theme_using_optional_theme_id(&state, theme_id).await?; let email_contents = email_types::VerifyEmail { recipient_email: domain::UserEmail::from_pii_email(user.email)?, settings: state.conf.clone(), auth_id, theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()), theme_config: theme .map(|theme| theme.email_config()) .unwrap_or(state.conf.theme.email_config.clone()), }; state .email_client .compose_and_send_email( email_types::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) .await .change_context(UserErrors::InternalServerError)?; Ok(ApplicationResponse::StatusOk) } pub async fn update_user_details( state: SessionState, user_token: auth::UserFromToken, req: user_api::UpdateUserAccountDetailsRequest, _req_state: ReqState, ) -> UserResponse<()> { let user: domain::UserFromStorage = state .global_store .find_user_by_id(&user_token.user_id) .await .change_context(UserErrors::InternalServerError)? .into(); let name = req.name.map(domain::UserName::new).transpose()?; let user_update = storage_user::UserUpdate::AccountUpdate { name: name.map(|name| name.get_secret().expose()), is_verified: None, }; state .global_store .update_user_by_user_id(user.get_user_id(), user_update) .await .change_context(UserErrors::InternalServerError)?; Ok(ApplicationResponse::StatusOk) } #[cfg(feature = "email")] pub async fn user_from_email( state: SessionState, req: user_api::UserFromEmailRequest, ) -> UserResponse<user_api::TokenResponse> { let token = req.token.expose(); let email_token = auth::decode_jwt::<email_types::EmailToken>(&token, &state) .await .change_context(UserErrors::LinkInvalid)?; auth::blacklist::check_email_token_in_blacklist(&state, &token).await?; let user_from_db: domain::UserFromStorage = state .global_store .find_user_by_email(&email_token.get_email()?) .await .change_context(UserErrors::InternalServerError)? .into(); let next_flow = domain::NextFlow::from_origin(email_token.get_flow(), user_from_db.clone(), &state).await?; let token = next_flow.get_token(&state).await?; let response = user_api::TokenResponse { token: token.clone(), token_type: next_flow.get_flow().into(), }; auth::cookies::set_cookie_response(response, token) } pub async fn begin_totp( state: SessionState, user_token: auth::UserFromSinglePurposeToken, ) -> UserResponse<user_api::BeginTotpResponse> { let user_from_db: domain::UserFromStorage = state .global_store .find_user_by_id(&user_token.user_id) .await .change_context(UserErrors::InternalServerError)? .into(); if user_from_db.get_totp_status() == TotpStatus::Set { return Ok(ApplicationResponse::Json(user_api::BeginTotpResponse { secret: None, })); } let totp = tfa_utils::generate_default_totp( user_from_db.get_email(), None, state.conf.user.totp_issuer_name.clone(), )?; let secret = totp.get_secret_base32().into(); tfa_utils::insert_totp_secret_in_redis(&state, &user_token.user_id, &secret).await?; Ok(ApplicationResponse::Json(user_api::BeginTotpResponse { secret: Some(user_api::TotpSecret { secret, totp_url: totp.get_url().into(), }), })) } pub async fn reset_totp( state: SessionState, user_token: auth::UserFromToken, ) -> UserResponse<user_api::BeginTotpResponse> { let user_from_db: domain::UserFromStorage = state .global_store .find_user_by_id(&user_token.user_id) .await .change_context(UserErrors::InternalServerError)? .into(); if user_from_db.get_totp_status() != TotpStatus::Set { return Err(UserErrors::TotpNotSetup.into()); } if !tfa_utils::check_totp_in_redis(&state, &user_token.user_id).await? && !tfa_utils::check_recovery_code_in_redis(&state, &user_token.user_id).await? { return Err(UserErrors::TwoFactorAuthRequired.into()); } let totp = tfa_utils::generate_default_totp( user_from_db.get_email(), None, state.conf.user.totp_issuer_name.clone(), )?; let secret = totp.get_secret_base32().into(); tfa_utils::insert_totp_secret_in_redis(&state, &user_token.user_id, &secret).await?; Ok(ApplicationResponse::Json(user_api::BeginTotpResponse { secret: Some(user_api::TotpSecret { secret, totp_url: totp.get_url().into(), }), })) } pub async fn verify_totp( state: SessionState, user_token: auth::UserIdFromAuth, req: user_api::VerifyTotpRequest, ) -> UserResponse<user_api::TokenResponse> { let user_from_db: domain::UserFromStorage = state .global_store .find_user_by_id(&user_token.user_id) .await .change_context(UserErrors::InternalServerError)? .into(); if user_from_db.get_totp_status() != TotpStatus::Set { return Err(UserErrors::TotpNotSetup.into()); } let user_totp_attempts = tfa_utils::get_totp_attempts_from_redis(&state, &user_token.user_id).await?; if user_totp_attempts >= consts::user::TOTP_MAX_ATTEMPTS { return Err(UserErrors::MaxTotpAttemptsReached.into()); } let user_totp_secret = user_from_db .decrypt_and_get_totp_secret(&state) .await? .ok_or(UserErrors::InternalServerError)?; let totp = tfa_utils::generate_default_totp( user_from_db.get_email(), Some(user_totp_secret), state.conf.user.totp_issuer_name.clone(), )?; if totp .generate_current() .change_context(UserErrors::InternalServerError)? != req.totp.expose() { let _ = tfa_utils::insert_totp_attempts_in_redis( &state, &user_token.user_id, user_totp_attempts + 1, ) .await .inspect_err(|error| logger::error!(?error)); return Err(UserErrors::InvalidTotp.into()); } tfa_utils::insert_totp_in_redis(&state, &user_token.user_id).await?; Ok(ApplicationResponse::StatusOk) } pub async fn update_totp( state: SessionState, user_token: auth::UserIdFromAuth, req: user_api::VerifyTotpRequest, ) -> UserResponse<()> { let user_from_db: domain::UserFromStorage = state .global_store .find_user_by_id(&user_token.user_id) .await .change_context(UserErrors::InternalServerError)? .into(); let new_totp_secret = tfa_utils::get_totp_secret_from_redis(&state, &user_token.user_id) .await? .ok_or(UserErrors::TotpSecretNotFound)?; let totp = tfa_utils::generate_default_totp( user_from_db.get_email(), Some(new_totp_secret), state.conf.user.totp_issuer_name.clone(), )?; if totp .generate_current() .change_context(UserErrors::InternalServerError)? != req.totp.expose() { return Err(UserErrors::InvalidTotp.into()); } let key_store = user_from_db.get_or_create_key_store(&state).await?; state .global_store .update_user_by_user_id( &user_token.user_id, storage_user::UserUpdate::TotpUpdate { totp_status: None, totp_secret: Some( // TODO: Impl conversion trait for User and move this there domain::types::crypto_operation::<String, masking::WithType>( &(&state).into(), type_name!(storage_user::User), domain::types::CryptoOperation::Encrypt(totp.get_secret_base32().into()), Identifier::User(key_store.user_id.clone()), key_store.key.peek(), ) .await .and_then(|val| val.try_into_operation()) .change_context(UserErrors::InternalServerError)? .into(), ), totp_recovery_codes: None, }, ) .await .change_context(UserErrors::InternalServerError)?; let _ = tfa_utils::delete_totp_secret_from_redis(&state, &user_token.user_id) .await .map_err(|error| logger::error!(?error)); // This is not the main task of this API, so we don't throw error if this fails. // Any following API which requires TOTP will throw error if TOTP is not set in redis // and FE will ask user to enter TOTP again let _ = tfa_utils::insert_totp_in_redis(&state, &user_token.user_id) .await .map_err(|error| logger::error!(?error)); Ok(ApplicationResponse::StatusOk) } pub async fn generate_recovery_codes( state: SessionState, user_token: auth::UserIdFromAuth, ) -> UserResponse<user_api::RecoveryCodes> { if !tfa_utils::check_totp_in_redis(&state, &user_token.user_id).await? { return Err(UserErrors::TotpRequired.into()); } let recovery_codes = domain::RecoveryCodes::generate_new(); state .global_store .update_user_by_user_id( &user_token.user_id, storage_user::UserUpdate::TotpUpdate { totp_status: None, totp_secret: None, totp_recovery_codes: Some( recovery_codes .get_hashed() .change_context(UserErrors::InternalServerError)?, ), }, ) .await .change_context(UserErrors::InternalServerError)?; Ok(ApplicationResponse::Json(user_api::RecoveryCodes { recovery_codes: recovery_codes.into_inner(), })) } pub async fn transfer_user_key_store_keymanager( state: SessionState, req: user_api::UserKeyTransferRequest, ) -> UserResponse<user_api::UserTransferKeyResponse> { let db = &state.global_store; let key_stores = db .get_all_user_key_store( &(&state).into(), &state.store.get_master_key().to_vec().into(), req.from, req.limit, ) .await .change_context(UserErrors::InternalServerError)?; Ok(ApplicationResponse::Json( user_api::UserTransferKeyResponse { total_transferred: send_request_to_key_service_for_user(&state, key_stores) .await .change_context(UserErrors::InternalServerError)?, }, )) } pub async fn verify_recovery_code( state: SessionState, user_token: auth::UserIdFromAuth, req: user_api::VerifyRecoveryCodeRequest, ) -> UserResponse<()> { let user_from_db: domain::UserFromStorage = state .global_store .find_user_by_id(&user_token.user_id) .await .change_context(UserErrors::InternalServerError)? .into(); if user_from_db.get_totp_status() != TotpStatus::Set { return Err(UserErrors::TwoFactorAuthNotSetup.into()); } let user_recovery_code_attempts = tfa_utils::get_recovery_code_attempts_from_redis(&state, &user_token.user_id).await?; if user_recovery_code_attempts >= consts::user::RECOVERY_CODE_MAX_ATTEMPTS { return Err(UserErrors::MaxRecoveryCodeAttemptsReached.into()); } let mut recovery_codes = user_from_db .get_recovery_codes() .ok_or(UserErrors::InternalServerError)?; let Some(matching_index) = utils::user::password::get_index_for_correct_recovery_code( &req.recovery_code, &recovery_codes, )? else { let _ = tfa_utils::insert_recovery_code_attempts_in_redis( &state, &user_token.user_id, user_recovery_code_attempts + 1, ) .await .inspect_err(|error| logger::error!(?error)); return Err(UserErrors::InvalidRecoveryCode.into()); }; tfa_utils::insert_recovery_code_in_redis(&state, user_from_db.get_user_id()).await?; let _ = recovery_codes.remove(matching_index); state .global_store .update_user_by_user_id( user_from_db.get_user_id(), storage_user::UserUpdate::TotpUpdate { totp_status: None, totp_secret: None, totp_recovery_codes: Some(recovery_codes), }, ) .await .change_context(UserErrors::InternalServerError)?; Ok(ApplicationResponse::StatusOk) } pub async fn terminate_two_factor_auth( state: SessionState, user_token: auth::UserFromSinglePurposeToken, skip_two_factor_auth: bool, ) -> UserResponse<user_api::TokenResponse> { let user_from_db: domain::UserFromStorage = state .global_store .find_user_by_id(&user_token.user_id) .await .change_context(UserErrors::InternalServerError)? .into(); if state.conf.user.force_two_factor_auth || !skip_two_factor_auth { if !tfa_utils::check_totp_in_redis(&state, &user_token.user_id).await? && !tfa_utils::check_recovery_code_in_redis(&state, &user_token.user_id).await? { return Err(UserErrors::TwoFactorAuthRequired.into()); } if user_from_db.get_recovery_codes().is_none() { return Err(UserErrors::TwoFactorAuthNotSetup.into()); } if user_from_db.get_totp_status() != TotpStatus::Set { state .global_store .update_user_by_user_id( user_from_db.get_user_id(), storage_user::UserUpdate::TotpUpdate { totp_status: Some(TotpStatus::Set), totp_secret: None, totp_recovery_codes: None, }, ) .await .change_context(UserErrors::InternalServerError)?; } } let current_flow = domain::CurrentFlow::new(user_token.clone(), domain::SPTFlow::TOTP.into())?; let next_flow = current_flow.next(user_from_db, &state).await?; let token = next_flow.get_token(&state).await?; let _ = tfa_utils::delete_totp_attempts_from_redis(&state, &user_token.user_id) .await .inspect_err(|error| logger::error!(?error)); let _ = tfa_utils::delete_recovery_code_attempts_from_redis(&state, &user_token.user_id) .await .inspect_err(|error| logger::error!(?error)); auth::cookies::set_cookie_response( user_api::TokenResponse { token: token.clone(), token_type: next_flow.get_flow().into(), }, token, ) } pub async fn check_two_factor_auth_status( state: SessionState, user_token: auth::UserFromToken, ) -> UserResponse<user_api::TwoFactorAuthStatusResponse> { Ok(ApplicationResponse::Json( user_api::TwoFactorAuthStatusResponse { totp: tfa_utils::check_totp_in_redis(&state, &user_token.user_id).await?, recovery_code: tfa_utils::check_recovery_code_in_redis(&state, &user_token.user_id) .await?, }, )) } pub async fn check_two_factor_auth_status_with_attempts( state: SessionState, user_token: auth::UserIdFromAuth, ) -> UserResponse<user_api::TwoFactorStatus> { let user_from_db: domain::UserFromStorage = state .global_store .find_user_by_id(&user_token.user_id) .await .change_context(UserErrors::InternalServerError)? .into(); let is_skippable = state.conf.user.force_two_factor_auth.not(); if user_from_db.get_totp_status() == TotpStatus::NotSet { return Ok(ApplicationResponse::Json(user_api::TwoFactorStatus { status: None, is_skippable, })); }; let totp = user_api::TwoFactorAuthAttempts { is_completed: tfa_utils::check_totp_in_redis(&state, &user_token.user_id).await?, remaining_attempts: consts::user::TOTP_MAX_ATTEMPTS - tfa_utils::get_totp_attempts_from_redis(&state, &user_token.user_id).await?, }; let recovery_code = user_api::TwoFactorAuthAttempts { is_completed: tfa_utils::check_recovery_code_in_redis(&state, &user_token.user_id).await?, remaining_attempts: consts::user::RECOVERY_CODE_MAX_ATTEMPTS - tfa_utils::get_recovery_code_attempts_from_redis(&state, &user_token.user_id).await?, }; Ok(ApplicationResponse::Json(user_api::TwoFactorStatus { status: Some(user_api::TwoFactorAuthStatusResponseWithAttempts { totp, recovery_code, }), is_skippable, })) } pub async fn create_user_authentication_method( state: SessionState, req: user_api::CreateUserAuthenticationMethodRequest, ) -> UserResponse<()> { let user_auth_encryption_key = hex::decode( state .conf .user_auth_methods .get_inner() .encryption_key .clone() .expose(), ) .change_context(UserErrors::InternalServerError) .attach_printable("Failed to decode DEK")?; let id = uuid::Uuid::new_v4().to_string(); let (private_config, public_config) = utils::user::construct_public_and_private_db_configs( &state, &req.auth_method, &user_auth_encryption_key, id.clone(), ) .await?; let auth_methods = state .store .list_user_authentication_methods_for_owner_id(&req.owner_id) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to get list of auth methods for the owner id")?; let (auth_id, email_domain) = if let Some(auth_method) = auth_methods.first() { let email_domain = match req.email_domain { Some(email_domain) => { if email_domain != auth_method.email_domain { return Err(report!(UserErrors::InvalidAuthMethodOperationWithMessage( "Email domain mismatch".to_string() ))); } email_domain } None => auth_method.email_domain.clone(), }; (auth_method.auth_id.clone(), email_domain) } else { let email_domain = req.email_domain .ok_or(UserErrors::InvalidAuthMethodOperationWithMessage( "Email domain not found".to_string(), ))?; (uuid::Uuid::new_v4().to_string(), email_domain) }; for db_auth_method in auth_methods { let is_type_same = db_auth_method.auth_type == (&req.auth_method).foreign_into(); let is_extra_identifier_same = match &req.auth_method { user_api::AuthConfig::OpenIdConnect { public_config, .. } => { let db_auth_name = db_auth_method .public_config .map(|config| { utils::user::parse_value::<user_api::OpenIdConnectPublicConfig>( config, "OpenIdConnectPublicConfig", ) }) .transpose()? .map(|config| config.name); let req_auth_name = public_config.name; db_auth_name.is_some_and(|name| name == req_auth_name) } user_api::AuthConfig::Password | user_api::AuthConfig::MagicLink => true, }; if is_type_same && is_extra_identifier_same { return Err(report!(UserErrors::UserAuthMethodAlreadyExists)); } } let now = common_utils::date_time::now(); state .store .insert_user_authentication_method(UserAuthenticationMethodNew { id, auth_id, owner_id: req.owner_id, owner_type: req.owner_type, auth_type: (&req.auth_method).foreign_into(), private_config, public_config, allow_signup: req.allow_signup, created_at: now, last_modified_at: now, email_domain, }) .await .to_duplicate_response(UserErrors::UserAuthMethodAlreadyExists)?; Ok(ApplicationResponse::StatusOk) } pub async fn update_user_authentication_method( state: SessionState, req: user_api::UpdateUserAuthenticationMethodRequest, ) -> UserResponse<()> { let user_auth_encryption_key = hex::decode( state .conf .user_auth_methods .get_inner() .encryption_key .clone() .expose(), ) .change_context(UserErrors::InternalServerError) .attach_printable("Failed to decode DEK")?; match req { user_api::UpdateUserAuthenticationMethodRequest::AuthMethod { id, auth_config: auth_method, } => { let (private_config, public_config) = utils::user::construct_public_and_private_db_configs( &state, &auth_method, &user_auth_encryption_key, id.clone(), ) .await?; state .store .update_user_authentication_method( &id, UserAuthenticationMethodUpdate::UpdateConfig { private_config, public_config, }, ) .await .map_err(|error| { let user_error = match error.current_context() { StorageError::ValueNotFound(_) => { UserErrors::InvalidAuthMethodOperationWithMessage( "Auth method not found".to_string(), ) } StorageError::DuplicateValue { .. } => { UserErrors::UserAuthMethodAlreadyExists } _ => UserErrors::InternalServerError, }; error.change_context(user_error) })?; } user_api::UpdateUserAuthenticationMethodRequest::EmailDomain { owner_id, email_domain, } => { let auth_methods = state .store .list_user_authentication_methods_for_owner_id(&owner_id) .await .change_context(UserErrors::InternalServerError)?; futures::future::try_join_all(auth_methods.iter().map(|auth_method| async { state .store .update_user_authentication_method( &auth_method.id, UserAuthenticationMethodUpdate::EmailDomain { email_domain: email_domain.clone(), }, ) .await .to_duplicate_response(UserErrors::UserAuthMethodAlreadyExists) })) .await?; } } Ok(ApplicationResponse::StatusOk) } pub async fn list_user_authentication_methods( state: SessionState, req: user_api::GetUserAuthenticationMethodsRequest, ) -> UserResponse<Vec<user_api::UserAuthenticationMethodResponse>> { let user_authentication_methods = match (req.auth_id, req.email_domain) { (Some(auth_id), None) => state .store .list_user_authentication_methods_for_auth_id(&auth_id) .await .change_context(UserErrors::InternalServerError)?, (None, Some(email_domain)) => state .store .list_user_authentication_methods_for_email_domain(&email_domain) .await .change_context(UserErrors::InternalServerError)?, (Some(_), Some(_)) | (None, None) => { return Err(UserErrors::InvalidUserAuthMethodOperation.into()); } }; Ok(ApplicationResponse::Json( user_authentication_methods .into_iter() .map(|auth_method| { let auth_name = match (auth_method.auth_type, auth_method.public_config) { (UserAuthType::OpenIdConnect, config) => { let open_id_public_config: Option<user_api::OpenIdConnectPublicConfig> = config .map(|config| { utils::user::parse_value(config, "OpenIdConnectPublicConfig") }) .transpose()?; if let Some(public_config) = open_id_public_config { Ok(Some(public_config.name)) } else { Err(report!(UserErrors::InternalServerError)) .attach_printable("Public config not found for OIDC auth type") } } _ => Ok(None), }?; Ok(user_api::UserAuthenticationMethodResponse { id: auth_method.id, auth_id: auth_method.auth_id, auth_method: user_api::AuthMethodDetails { name: auth_name, auth_type: auth_method.auth_type, }, allow_signup: auth_method.allow_signup, }) }) .collect::<UserResult<_>>()?, )) } #[cfg(feature = "v1")] pub async fn get_sso_auth_url( state: SessionState, request: user_api::GetSsoAuthUrlRequest, ) -> UserResponse<()> { let user_authentication_method = state .store .get_user_authentication_method_by_id(request.id.as_str()) .await .to_not_found_response(UserErrors::InvalidUserAuthMethodOperation)?; let open_id_private_config = utils::user::decrypt_oidc_private_config( &state, user_authentication_method.private_config, request.id.clone(), ) .await?; let open_id_public_config = serde_json::from_value::<user_api::OpenIdConnectPublicConfig>( user_authentication_method .public_config .ok_or(UserErrors::InternalServerError) .attach_printable("Public config not present")?, ) .change_context(UserErrors::InternalServerError) .attach_printable("Unable to parse OpenIdConnectPublicConfig")?; let oidc_state = Secret::new(nanoid::nanoid!()); utils::user::set_sso_id_in_redis(&state, oidc_state.clone(), request.id).await?; let redirect_url = utils::user::get_oidc_sso_redirect_url(&state, &open_id_public_config.name.to_string()); openidconnect::get_authorization_url( state, redirect_url, oidc_state, open_id_private_config.base_url.into(), open_id_private_config.client_id, ) .await .map(|url| { ApplicationResponse::JsonForRedirection(RedirectionResponse { headers: Vec::with_capacity(0), return_url: String::new(), http_method: String::new(), params: Vec::with_capacity(0), return_url_with_query_params: url.to_string(), }) }) } pub async fn sso_sign( state: SessionState, request: user_api::SsoSignInRequest, user_from_single_purpose_token: Option<auth::UserFromSinglePurposeToken>, ) -> UserResponse<user_api::TokenResponse> { let authentication_method_id = utils::user::get_sso_id_from_redis(&state, request.state.clone()).await?; let user_authentication_method = state .store .get_user_authentication_method_by_id(&authentication_method_id) .await .change_context(UserErrors::InternalServerError)?; let open_id_private_config = utils::user::decrypt_oidc_private_config( &state, user_authentication_method.private_config, authentication_method_id, ) .await?; let open_id_public_config = serde_json::from_value::<user_api::OpenIdConnectPublicConfig>( user_authentication_method .public_config .ok_or(UserErrors::InternalServerError) .attach_printable("Public config not present")?, ) .change_context(UserErrors::InternalServerError) .attach_printable("Unable to parse OpenIdConnectPublicConfig")?; let redirect_url = utils::user::get_oidc_sso_redirect_url(&state, &open_id_public_config.name.to_string()); let email = openidconnect::get_user_email_from_oidc_provider( &state, redirect_url, request.state, open_id_private_config.base_url.into(), open_id_private_config.client_id, request.code, open_id_private_config.client_secret, ) .await?; utils::user::validate_email_domain_auth_type_using_db( &state, &email, UserAuthType::OpenIdConnect, ) .await?; // TODO: Use config to handle not found error let user_from_db: domain::UserFromStorage = state .global_store .find_user_by_email(&email) .await .map(Into::into) .to_not_found_response(UserErrors::UserNotFound)?; if !user_from_db.is_verified() { state .global_store .update_user_by_user_id( user_from_db.get_user_id(), storage_user::UserUpdate::VerifyUser, ) .await .change_context(UserErrors::InternalServerError)?; } let next_flow = if let Some(user_from_single_purpose_token) = user_from_single_purpose_token { let current_flow = domain::CurrentFlow::new(user_from_single_purpose_token, domain::SPTFlow::SSO.into())?; current_flow.next(user_from_db, &state).await? } else { domain::NextFlow::from_origin(domain::Origin::SignInWithSSO, user_from_db, &state).await? }; let token = next_flow.get_token(&state).await?; let response = user_api::TokenResponse { token: token.clone(), token_type: next_flow.get_flow().into(), }; auth::cookies::set_cookie_response(response, token) } pub async fn terminate_auth_select( state: SessionState, user_token: auth::UserFromSinglePurposeToken, req: user_api::AuthSelectRequest, ) -> UserResponse<user_api::TokenResponse> { let user_from_db: domain::UserFromStorage = state .global_store .find_user_by_id(&user_token.user_id) .await .change_context(UserErrors::InternalServerError)? .into(); let user_email = domain::UserEmail::from_pii_email(user_from_db.get_email())?; let auth_methods = state .store .list_user_authentication_methods_for_email_domain(user_email.extract_domain()?) .await .change_context(UserErrors::InternalServerError)?; let user_authentication_method = match (req.id, auth_methods.is_empty()) { (Some(id), _) => auth_methods .into_iter() .find(|auth_method| auth_method.id == id) .ok_or(UserErrors::InvalidUserAuthMethodOperation)?, (None, true) => DEFAULT_USER_AUTH_METHOD.clone(), (None, false) => return Err(UserErrors::InvalidUserAuthMethodOperation.into()), }; let current_flow = domain::CurrentFlow::new(user_token, domain::SPTFlow::AuthSelect.into())?; let mut next_flow = current_flow.next(user_from_db.clone(), &state).await?; // Skip SSO if continue with password(TOTP) if next_flow.get_flow() == domain::UserFlow::SPTFlow(domain::SPTFlow::SSO) && !utils::user::is_sso_auth_type(user_authentication_method.auth_type) { next_flow = next_flow.skip(user_from_db, &state).await?; } let token = next_flow.get_token(&state).await?; auth::cookies::set_cookie_response( user_api::TokenResponse { token: token.clone(), token_type: next_flow.get_flow().into(), }, token, ) } pub async fn list_orgs_for_user( state: SessionState, user_from_token: auth::UserFromToken, ) -> UserResponse<Vec<user_api::ListOrgsForUserResponse>> { let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; if role_info.is_internal() { return Err(UserErrors::InvalidRoleOperationWithMessage( "Internal roles are not allowed for this operation".to_string(), ) .into()); } let orgs = match role_info.get_entity_type() { EntityType::Tenant => { let key_manager_state = &(&state).into(); state .store .list_merchant_and_org_ids( key_manager_state, consts::user::ORG_LIST_LIMIT_FOR_TENANT, None, ) .await .change_context(UserErrors::InternalServerError)? .into_iter() .map(|(_, org_id)| org_id) .collect::<HashSet<_>>() } EntityType::Organization | EntityType::Merchant | EntityType::Profile => state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: user_from_token.user_id.as_str(), tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: None, merchant_id: None, profile_id: None, entity_id: None, version: None, status: Some(UserStatus::Active), limit: None, }) .await .change_context(UserErrors::InternalServerError)? .into_iter() .filter_map(|user_role| user_role.org_id) .collect::<HashSet<_>>(), }; let resp = futures::future::try_join_all( orgs.iter() .map(|org_id| state.accounts_store.find_organization_by_org_id(org_id)), ) .await .change_context(UserErrors::InternalServerError)? .into_iter() .map(|org| user_api::ListOrgsForUserResponse { org_id: org.get_organization_id(), org_name: org.get_organization_name(), }) .collect::<Vec<_>>(); if resp.is_empty() { Err(UserErrors::InternalServerError).attach_printable("No orgs found for a user")?; } Ok(ApplicationResponse::Json(resp)) } pub async fn list_merchants_for_user_in_org( state: SessionState, user_from_token: auth::UserFromToken, ) -> UserResponse<Vec<user_api::UserMerchantAccountResponse>> { let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; if role_info.is_internal() { return Err(UserErrors::InvalidRoleOperationWithMessage( "Internal roles are not allowed for this operation".to_string(), ) .into()); } let merchant_accounts = match role_info.get_entity_type() { EntityType::Tenant | EntityType::Organization => state .store .list_merchant_accounts_by_organization_id(&(&state).into(), &user_from_token.org_id) .await .change_context(UserErrors::InternalServerError)?, EntityType::Merchant | EntityType::Profile => { let merchant_ids = state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: user_from_token.user_id.as_str(), tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: Some(&user_from_token.org_id), merchant_id: None, profile_id: None, entity_id: None, version: None, status: Some(UserStatus::Active), limit: None, }) .await .change_context(UserErrors::InternalServerError)? .into_iter() .filter_map(|user_role| user_role.merchant_id) .collect::<HashSet<_>>() .into_iter() .collect(); state .store .list_multiple_merchant_accounts(&(&state).into(), merchant_ids) .await .change_context(UserErrors::InternalServerError)? } }; // TODO: Add a check to see if merchant accounts are empty, and handle accordingly, when a single route will be used instead // of having two separate routes. Ok(ApplicationResponse::Json( merchant_accounts .into_iter() .map(|merchant_account| user_api::UserMerchantAccountResponse { merchant_name: merchant_account.merchant_name.clone(), merchant_id: merchant_account.get_id().to_owned(), product_type: merchant_account.product_type, version: merchant_account.version, }) .collect::<Vec<_>>(), )) } pub async fn list_profiles_for_user_in_org_and_merchant_account( state: SessionState, user_from_token: auth::UserFromToken, ) -> UserResponse<Vec<user_api::ListProfilesForUserInOrgAndMerchantAccountResponse>> { let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; let key_manager_state = &(&state).into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, &user_from_token.merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .change_context(UserErrors::InternalServerError)?; let profiles = match role_info.get_entity_type() { EntityType::Tenant | EntityType::Organization | EntityType::Merchant => state .store .list_profile_by_merchant_id( key_manager_state, &key_store, &user_from_token.merchant_id, ) .await .change_context(UserErrors::InternalServerError)?, EntityType::Profile => { let profile_ids = state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: user_from_token.user_id.as_str(), tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: Some(&user_from_token.org_id), merchant_id: Some(&user_from_token.merchant_id), profile_id: None, entity_id: None, version: None, status: Some(UserStatus::Active), limit: None, }) .await .change_context(UserErrors::InternalServerError)? .into_iter() .filter_map(|user_role| user_role.profile_id) .collect::<HashSet<_>>(); futures::future::try_join_all(profile_ids.iter().map(|profile_id| { state.store.find_business_profile_by_profile_id( key_manager_state, &key_store, profile_id, ) })) .await .change_context(UserErrors::InternalServerError)? } }; if profiles.is_empty() { Err(UserErrors::InternalServerError).attach_printable("No profile found for a user")?; } Ok(ApplicationResponse::Json( profiles .into_iter() .map( |profile| user_api::ListProfilesForUserInOrgAndMerchantAccountResponse { profile_id: profile.get_id().to_owned(), profile_name: profile.profile_name, }, ) .collect::<Vec<_>>(), )) } pub async fn switch_org_for_user( state: SessionState, request: user_api::SwitchOrganizationRequest, user_from_token: auth::UserFromToken, ) -> UserResponse<user_api::TokenResponse> { if user_from_token.org_id == request.org_id { return Err(UserErrors::InvalidRoleOperationWithMessage( "User switching to same org".to_string(), ) .into()); } let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to retrieve role information")?; if role_info.is_internal() { return Err(UserErrors::InvalidRoleOperationWithMessage( "Org switching not allowed for Internal role".to_string(), ) .into()); } let (merchant_id, profile_id, role_id) = match role_info.get_entity_type() { EntityType::Tenant => { let merchant_id = state .store .list_merchant_accounts_by_organization_id(&(&state).into(), &request.org_id) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to get merchant list for org")? .pop() .ok_or(UserErrors::InvalidRoleOperation) .attach_printable("No merchants found for the org id")? .get_id() .to_owned(); let key_store = state .store .get_merchant_key_store_by_merchant_id( &(&state).into(), &merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .change_context(UserErrors::InternalServerError)?; let profile_id = state .store .list_profile_by_merchant_id(&(&state).into(), &key_store, &merchant_id) .await .change_context(UserErrors::InternalServerError)? .pop() .ok_or(UserErrors::InternalServerError)? .get_id() .to_owned(); (merchant_id, profile_id, user_from_token.role_id) } EntityType::Organization | EntityType::Merchant | EntityType::Profile => { let user_role = state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: &user_from_token.user_id, tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: Some(&request.org_id), merchant_id: None, profile_id: None, entity_id: None, version: None, status: Some(UserStatus::Active), limit: Some(1), }) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to list user roles by user_id and org_id")? .pop() .ok_or(UserErrors::InvalidRoleOperationWithMessage( "No user role found for the requested org_id".to_string(), ))?; let (merchant_id, profile_id) = utils::user_role::get_single_merchant_id_and_profile_id(&state, &user_role).await?; (merchant_id, profile_id, user_role.role_id) } }; let token = utils::user::generate_jwt_auth_token_with_attributes( &state, user_from_token.user_id, merchant_id.clone(), request.org_id.clone(), role_id.clone(), profile_id.clone(), user_from_token.tenant_id.clone(), ) .await?; utils::user_role::set_role_info_in_cache_by_role_id_org_id( &state, &role_id, &request.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await; let response = user_api::TokenResponse { token: token.clone(), token_type: common_enums::TokenPurpose::UserInfo, }; auth::cookies::set_cookie_response(response, token) } pub async fn switch_merchant_for_user_in_org( state: SessionState, request: user_api::SwitchMerchantRequest, user_from_token: auth::UserFromToken, ) -> UserResponse<user_api::TokenResponse> { if user_from_token.merchant_id == request.merchant_id { return Err(UserErrors::InvalidRoleOperationWithMessage( "User switching to same merchant".to_string(), ) .into()); } let key_manager_state = &(&state).into(); let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to retrieve role information")?; // Check if the role is internal and handle separately let (org_id, merchant_id, profile_id, role_id) = if role_info.is_internal() { let merchant_key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, &request.merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .to_not_found_response(UserErrors::MerchantIdNotFound)?; let merchant_account = state .store .find_merchant_account_by_merchant_id( key_manager_state, &request.merchant_id, &merchant_key_store, ) .await .to_not_found_response(UserErrors::MerchantIdNotFound)?; let profile_id = state .store .list_profile_by_merchant_id( key_manager_state, &merchant_key_store, &request.merchant_id, ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to list business profiles by merchant_id")? .pop() .ok_or(UserErrors::InternalServerError) .attach_printable("No business profile found for the given merchant_id")? .get_id() .to_owned(); ( merchant_account.organization_id, request.merchant_id, profile_id, user_from_token.role_id.clone(), ) } else { // Match based on the other entity types match role_info.get_entity_type() { EntityType::Tenant | EntityType::Organization => { let merchant_key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, &request.merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .to_not_found_response(UserErrors::MerchantIdNotFound)?; let merchant_id = state .store .find_merchant_account_by_merchant_id( key_manager_state, &request.merchant_id, &merchant_key_store, ) .await .change_context(UserErrors::MerchantIdNotFound)? .organization_id .eq(&user_from_token.org_id) .then(|| request.merchant_id.clone()) .ok_or_else(|| { UserErrors::InvalidRoleOperationWithMessage( "No such merchant_id found for the user in the org".to_string(), ) })?; let profile_id = state .store .list_profile_by_merchant_id( key_manager_state, &merchant_key_store, &merchant_id, ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to list business profiles by merchant_id")? .pop() .ok_or(UserErrors::InternalServerError) .attach_printable("No business profile found for the merchant_id")? .get_id() .to_owned(); ( user_from_token.org_id.clone(), merchant_id, profile_id, user_from_token.role_id.clone(), ) } EntityType::Merchant | EntityType::Profile => { let user_role = state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: &user_from_token.user_id, tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: Some(&user_from_token.org_id), merchant_id: Some(&request.merchant_id), profile_id: None, entity_id: None, version: None, status: Some(UserStatus::Active), limit: Some(1), }) .await .change_context(UserErrors::InternalServerError) .attach_printable( "Failed to list user roles for the given user_id, org_id and merchant_id", )? .pop() .ok_or(UserErrors::InvalidRoleOperationWithMessage( "No user role associated with the requested merchant_id".to_string(), ))?; let (merchant_id, profile_id) = utils::user_role::get_single_merchant_id_and_profile_id(&state, &user_role) .await?; ( user_from_token.org_id, merchant_id, profile_id, user_role.role_id, ) } } }; let token = utils::user::generate_jwt_auth_token_with_attributes( &state, user_from_token.user_id, merchant_id.clone(), org_id.clone(), role_id.clone(), profile_id, user_from_token.tenant_id.clone(), ) .await?; utils::user_role::set_role_info_in_cache_by_role_id_org_id( &state, &role_id, &org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await; let response = user_api::TokenResponse { token: token.clone(), token_type: common_enums::TokenPurpose::UserInfo, }; auth::cookies::set_cookie_response(response, token) } pub async fn switch_profile_for_user_in_org_and_merchant( state: SessionState, request: user_api::SwitchProfileRequest, user_from_token: auth::UserFromToken, ) -> UserResponse<user_api::TokenResponse> { if user_from_token.profile_id == request.profile_id { return Err(UserErrors::InvalidRoleOperationWithMessage( "User switching to same profile".to_string(), ) .into()); } let key_manager_state = &(&state).into(); let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to retrieve role information")?; let (profile_id, role_id) = match role_info.get_entity_type() { EntityType::Tenant | EntityType::Organization | EntityType::Merchant => { let merchant_key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, &user_from_token.merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to retrieve merchant key store by merchant_id")?; let profile_id = state .store .find_business_profile_by_merchant_id_profile_id( key_manager_state, &merchant_key_store, &user_from_token.merchant_id, &request.profile_id, ) .await .change_context(UserErrors::InvalidRoleOperationWithMessage( "No such profile found for the merchant".to_string(), ))? .get_id() .to_owned(); (profile_id, user_from_token.role_id) } EntityType::Profile => { let user_role = state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload{ user_id:&user_from_token.user_id, tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: Some(&user_from_token.org_id), merchant_id: Some(&user_from_token.merchant_id), profile_id:Some(&request.profile_id), entity_id: None, version:None, status: Some(UserStatus::Active), limit: Some(1) } ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to list user roles for the given user_id, org_id, merchant_id and profile_id")? .pop() .ok_or(UserErrors::InvalidRoleOperationWithMessage( "No user role associated with the profile".to_string(), ))?; (request.profile_id, user_role.role_id) } }; let token = utils::user::generate_jwt_auth_token_with_attributes( &state, user_from_token.user_id, user_from_token.merchant_id.clone(), user_from_token.org_id.clone(), role_id.clone(), profile_id, user_from_token.tenant_id.clone(), ) .await?; utils::user_role::set_role_info_in_cache_by_role_id_org_id( &state, &role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await; let response = user_api::TokenResponse { token: token.clone(), token_type: common_enums::TokenPurpose::UserInfo, }; auth::cookies::set_cookie_response(response, token) }
25,139
1,557
hyperswitch
crates/router/src/core/health_check.rs
.rs
#[cfg(feature = "olap")] use analytics::health_check::HealthCheck; #[cfg(feature = "dynamic_routing")] use api_models::health_check::HealthCheckMap; use api_models::health_check::HealthState; use error_stack::ResultExt; use router_env::logger; use crate::{ consts, core::errors::{self, CustomResult}, routes::app, services::api as services, }; #[async_trait::async_trait] pub trait HealthCheckInterface { async fn health_check_db(&self) -> CustomResult<HealthState, errors::HealthCheckDBError>; async fn health_check_redis(&self) -> CustomResult<HealthState, errors::HealthCheckRedisError>; async fn health_check_locker( &self, ) -> CustomResult<HealthState, errors::HealthCheckLockerError>; async fn health_check_outgoing(&self) -> CustomResult<HealthState, errors::HealthCheckOutGoing>; #[cfg(feature = "olap")] async fn health_check_analytics(&self) -> CustomResult<HealthState, errors::HealthCheckDBError>; #[cfg(feature = "olap")] async fn health_check_opensearch( &self, ) -> CustomResult<HealthState, errors::HealthCheckDBError>; #[cfg(feature = "dynamic_routing")] async fn health_check_grpc( &self, ) -> CustomResult<HealthCheckMap, errors::HealthCheckGRPCServiceError>; } #[async_trait::async_trait] impl HealthCheckInterface for app::SessionState { async fn health_check_db(&self) -> CustomResult<HealthState, errors::HealthCheckDBError> { let db = &*self.store; db.health_check_db().await?; Ok(HealthState::Running) } async fn health_check_redis(&self) -> CustomResult<HealthState, errors::HealthCheckRedisError> { let db = &*self.store; let redis_conn = db .get_redis_conn() .change_context(errors::HealthCheckRedisError::RedisConnectionError)?; redis_conn .serialize_and_set_key_with_expiry(&"test_key".into(), "test_value", 30) .await .change_context(errors::HealthCheckRedisError::SetFailed)?; logger::debug!("Redis set_key was successful"); redis_conn .get_key::<()>(&"test_key".into()) .await .change_context(errors::HealthCheckRedisError::GetFailed)?; logger::debug!("Redis get_key was successful"); redis_conn .delete_key(&"test_key".into()) .await .change_context(errors::HealthCheckRedisError::DeleteFailed)?; logger::debug!("Redis delete_key was successful"); Ok(HealthState::Running) } async fn health_check_locker( &self, ) -> CustomResult<HealthState, errors::HealthCheckLockerError> { let locker = &self.conf.locker; if !locker.mock_locker { let mut url = locker.host_rs.to_owned(); url.push_str(consts::LOCKER_HEALTH_CALL_PATH); let request = services::Request::new(services::Method::Get, &url); services::call_connector_api(self, request, "health_check_for_locker") .await .change_context(errors::HealthCheckLockerError::FailedToCallLocker)? .map_err(|_| { error_stack::report!(errors::HealthCheckLockerError::FailedToCallLocker) })?; Ok(HealthState::Running) } else { Ok(HealthState::NotApplicable) } } #[cfg(feature = "olap")] async fn health_check_analytics( &self, ) -> CustomResult<HealthState, errors::HealthCheckDBError> { let analytics = &self.pool; match analytics { analytics::AnalyticsProvider::Sqlx(client) => client .deep_health_check() .await .change_context(errors::HealthCheckDBError::SqlxAnalyticsError), analytics::AnalyticsProvider::Clickhouse(client) => client .deep_health_check() .await .change_context(errors::HealthCheckDBError::ClickhouseAnalyticsError), analytics::AnalyticsProvider::CombinedCkh(sqlx_client, ckh_client) => { sqlx_client .deep_health_check() .await .change_context(errors::HealthCheckDBError::SqlxAnalyticsError)?; ckh_client .deep_health_check() .await .change_context(errors::HealthCheckDBError::ClickhouseAnalyticsError) } analytics::AnalyticsProvider::CombinedSqlx(sqlx_client, ckh_client) => { sqlx_client .deep_health_check() .await .change_context(errors::HealthCheckDBError::SqlxAnalyticsError)?; ckh_client .deep_health_check() .await .change_context(errors::HealthCheckDBError::ClickhouseAnalyticsError) } }?; Ok(HealthState::Running) } #[cfg(feature = "olap")] async fn health_check_opensearch( &self, ) -> CustomResult<HealthState, errors::HealthCheckDBError> { if let Some(client) = self.opensearch_client.as_ref() { client .deep_health_check() .await .change_context(errors::HealthCheckDBError::OpensearchError)?; Ok(HealthState::Running) } else { Ok(HealthState::NotApplicable) } } async fn health_check_outgoing( &self, ) -> CustomResult<HealthState, errors::HealthCheckOutGoing> { let request = services::Request::new(services::Method::Get, consts::OUTGOING_CALL_URL); services::call_connector_api(self, request, "outgoing_health_check") .await .map_err(|err| errors::HealthCheckOutGoing::OutGoingFailed { message: err.to_string(), })? .map_err(|err| errors::HealthCheckOutGoing::OutGoingFailed { message: format!( "Got a non 200 status while making outgoing request. Error {:?}", err.response ), })?; logger::debug!("Outgoing request successful"); Ok(HealthState::Running) } #[cfg(feature = "dynamic_routing")] async fn health_check_grpc( &self, ) -> CustomResult<HealthCheckMap, errors::HealthCheckGRPCServiceError> { let health_client = &self.grpc_client.health_client; let grpc_config = &self.conf.grpc_client; let health_check_map = health_client .perform_health_check(grpc_config) .await .change_context(errors::HealthCheckGRPCServiceError::FailedToCallService)?; logger::debug!("Health check successful"); Ok(health_check_map) } }
1,491
1,558
hyperswitch
crates/router/src/core/verify_connector.rs
.rs
use api_models::{enums::Connector, verify_connector::VerifyConnectorRequest}; use error_stack::ResultExt; use crate::{ connector, core::errors, services, types::{ api::{ self, verify_connector::{self as types, VerifyConnector}, }, transformers::ForeignInto, }, utils::verify_connector as utils, SessionState, }; pub async fn verify_connector_credentials( state: SessionState, req: VerifyConnectorRequest, _profile_id: Option<common_utils::id_type::ProfileId>, ) -> errors::RouterResponse<()> { let boxed_connector = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &req.connector_name.to_string(), api::GetToken::Connector, None, ) .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven)?; let card_details = utils::get_test_card_details(req.connector_name)?.ok_or( errors::ApiErrorResponse::FlowNotSupported { flow: "Verify credentials".to_string(), connector: req.connector_name.to_string(), }, )?; match req.connector_name { Connector::Stripe => { connector::Stripe::verify( &state, types::VerifyConnectorData { connector: boxed_connector.connector, connector_auth: req.connector_account_details.foreign_into(), card_details, }, ) .await } Connector::Paypal => connector::Paypal::get_access_token( &state, types::VerifyConnectorData { connector: boxed_connector.connector, connector_auth: req.connector_account_details.foreign_into(), card_details, }, ) .await .map(|_| services::ApplicationResponse::StatusOk), _ => Err(errors::ApiErrorResponse::FlowNotSupported { flow: "Verify credentials".to_string(), connector: req.connector_name.to_string(), } .into()), } }
406
1,559
hyperswitch
crates/router/src/core/payments.rs
.rs
pub mod access_token; pub mod conditional_configs; pub mod customers; pub mod flows; pub mod helpers; pub mod operations; #[cfg(feature = "retry")] pub mod retry; pub mod routing; #[cfg(feature = "v2")] pub mod session_operation; pub mod tokenization; pub mod transformers; pub mod types; #[cfg(feature = "olap")] use std::collections::HashMap; use std::{ collections::HashSet, fmt::Debug, marker::PhantomData, ops::Deref, time::Instant, vec::IntoIter, }; #[cfg(feature = "v2")] pub mod payment_methods; #[cfg(feature = "olap")] use api_models::admin::MerchantConnectorInfo; use api_models::{ self, enums, mandates::RecurringDetails, payments::{self as payments_api}, }; pub use common_enums::enums::CallConnectorAction; use common_utils::{ ext_traits::{AsyncExt, StringExt}, id_type, pii, types::{AmountConvertor, MinorUnit, Surcharge}, }; use diesel_models::{ephemeral_key, fraud_check::FraudCheck}; use error_stack::{report, ResultExt}; use events::EventInfo; use futures::future::join_all; use helpers::{decrypt_paze_token, ApplePayData}; use hyperswitch_domain_models::payments::{payment_intent::CustomerData, ClickToPayMetaData}; #[cfg(feature = "v2")] use hyperswitch_domain_models::payments::{ PaymentCaptureData, PaymentConfirmData, PaymentIntentData, PaymentStatusData, }; #[cfg(feature = "v2")] use hyperswitch_domain_models::router_response_types::RedirectForm; pub use hyperswitch_domain_models::{ mandates::{CustomerAcceptance, MandateData}, payment_address::PaymentAddress, payments::{self as domain_payments, HeaderPayload}, router_data::{PaymentMethodToken, RouterData}, router_request_types::CustomerDetails, }; use masking::{ExposeInterface, PeekInterface, Secret}; #[cfg(feature = "v2")] use operations::ValidateStatusForOperation; use redis_interface::errors::RedisError; use router_env::{instrument, tracing}; #[cfg(feature = "olap")] use router_types::transformers::ForeignFrom; use rustc_hash::FxHashMap; use scheduler::utils as pt_utils; #[cfg(feature = "v2")] pub use session_operation::payments_session_core; #[cfg(feature = "olap")] use strum::IntoEnumIterator; use time; #[cfg(feature = "v1")] pub use self::operations::{ PaymentApprove, PaymentCancel, PaymentCapture, PaymentConfirm, PaymentCreate, PaymentIncrementalAuthorization, PaymentPostSessionTokens, PaymentReject, PaymentSession, PaymentSessionUpdate, PaymentStatus, PaymentUpdate, }; use self::{ conditional_configs::perform_decision_management, flows::{ConstructFlowSpecificData, Feature}, operations::{BoxedOperation, Operation, PaymentResponse}, routing::{self as self_routing, SessionFlowRoutingInput}, }; use super::{ errors::StorageErrorExt, payment_methods::surcharge_decision_configs, routing::TransactionData, }; #[cfg(feature = "frm")] use crate::core::fraud_check as frm_core; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use crate::core::routing::helpers as routing_helpers; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use crate::types::api::convert_connector_data_to_routable_connectors; use crate::{ configs::settings::{ApplePayPreDecryptFlow, PaymentMethodTypeTokenFilter}, connector::utils::missing_field_err, consts, core::{ errors::{self, CustomResult, RouterResponse, RouterResult}, payment_methods::{cards, network_tokenization}, payouts, routing::{self as core_routing}, utils::{self as core_utils}, }, db::StorageInterface, logger, routes::{app::ReqState, metrics, payment_methods::ParentPaymentMethodToken, SessionState}, services::{self, api::Authenticate, ConnectorRedirectResponse}, types::{ self as router_types, api::{self, ConnectorCallType, ConnectorCommon}, domain, storage::{self, enums as storage_enums, payment_attempt::PaymentAttemptExt}, transformers::ForeignTryInto, }, utils::{ self, add_apple_pay_flow_metrics, add_connector_http_status_code_metrics, Encode, OptionExt, ValueExt, }, workflows::payment_sync, }; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use crate::{ core::authentication as authentication_core, types::{api::authentication, BrowserInformation}, }; #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments, clippy::type_complexity)] #[instrument(skip_all, fields(payment_id, merchant_id))] pub async fn payments_operation_core<F, Req, Op, FData, D>( state: &SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, profile: &domain::Profile, operation: Op, req: Req, get_tracker_response: operations::GetTrackerResponse<D>, call_connector_action: CallConnectorAction, header_payload: HeaderPayload, ) -> RouterResult<(D, Req, Option<domain::Customer>, Option<u16>, Option<u128>)> where F: Send + Clone + Sync, Req: Send + Sync, 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>, RouterData<F, FData, router_types::PaymentsResponseData>: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<F, FData, D>, // 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); // Get the trackers related to track the state of the payment let operations::GetTrackerResponse { mut payment_data } = get_tracker_response; let (_operation, customer) = operation .to_domain()? .get_customer_details( state, &mut payment_data, &key_store, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound) .attach_printable("Failed while fetching/creating customer")?; operation .to_domain()? .run_decision_manager(state, &mut payment_data, profile) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to run decision manager")?; let connector = operation .to_domain()? .perform_routing( &merchant_account, profile, state, &mut payment_data, &key_store, ) .await?; let payment_data = match connector { ConnectorCallType::PreDetermined(connector_data) => { let router_data = call_connector_service( state, req_state.clone(), &merchant_account, &key_store, connector_data.clone(), &operation, &mut payment_data, &customer, call_connector_action.clone(), None, header_payload.clone(), #[cfg(feature = "frm")] None, #[cfg(not(feature = "frm"))] None, profile, false, false, //should_retry_with_pan is set to false in case of PreDetermined ConnectorCallType ) .await?; let payments_response_operation = Box::new(PaymentResponse); payments_response_operation .to_post_update_tracker()? .save_pm_and_mandate( state, &router_data, &merchant_account, &key_store, &mut payment_data, profile, ) .await?; payments_response_operation .to_post_update_tracker()? .update_tracker( state, payment_data, router_data, &key_store, merchant_account.storage_scheme, ) .await? } ConnectorCallType::Retryable(vec) => todo!(), ConnectorCallType::SessionMultiple(vec) => todo!(), ConnectorCallType::Skip => payment_data, }; Ok((payment_data, req, customer, None, None)) } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments, clippy::type_complexity)] #[instrument(skip_all, fields(payment_id, merchant_id))] 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, )) } #[cfg(feature = "v1")] // This function is intended for use when the feature being implemented is not aligned with the // core payment operations. #[allow(clippy::too_many_arguments, clippy::type_complexity)] #[instrument(skip_all, fields(payment_id, merchant_id))] 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, )) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments, clippy::type_complexity)] #[instrument(skip_all, fields(payment_id, merchant_id))] pub async fn proxy_for_payments_operation_core<F, Req, Op, FData, D>( state: &SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, profile: domain::Profile, operation: Op, req: Req, get_tracker_response: operations::GetTrackerResponse<D>, call_connector_action: CallConnectorAction, header_payload: HeaderPayload, ) -> RouterResult<(D, Req, Option<u16>, Option<u128>)> where F: Send + Clone + Sync, Req: Send + Sync, 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>, RouterData<F, FData, router_types::PaymentsResponseData>: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<F, FData, D>, // 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); // Get the trackers related to track the state of the payment let operations::GetTrackerResponse { mut payment_data } = get_tracker_response; // consume the req merchant_connector_id and set it in the payment_data let connector = operation .to_domain()? .perform_routing( &merchant_account, &profile, state, &mut payment_data, &key_store, ) .await?; let payment_data = match connector { ConnectorCallType::PreDetermined(connector_data) => { let router_data = proxy_for_call_connector_service( state, req_state.clone(), &merchant_account, &key_store, connector_data.clone(), &operation, &mut payment_data, call_connector_action.clone(), header_payload.clone(), &profile, ) .await?; let payments_response_operation = Box::new(PaymentResponse); payments_response_operation .to_post_update_tracker()? .update_tracker( state, payment_data, router_data, &key_store, merchant_account.storage_scheme, ) .await? } ConnectorCallType::Retryable(vec) => todo!(), ConnectorCallType::SessionMultiple(vec) => todo!(), ConnectorCallType::Skip => payment_data, }; Ok((payment_data, req, None, None)) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments, clippy::type_complexity)] #[instrument(skip_all, fields(payment_id, merchant_id))] pub async fn payments_intent_operation_core<F, Req, Op, D>( state: &SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, profile: domain::Profile, key_store: domain::MerchantKeyStore, operation: Op, req: Req, payment_id: id_type::GlobalPaymentId, header_payload: HeaderPayload, platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResult<(D, Req, Option<domain::Customer>)> where F: Send + Clone + Sync, Req: Clone, Op: Operation<F, Req, Data = D> + Send + Sync, D: OperationSessionGetters<F> + OperationSessionSetters<F> + 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 _validate_result = operation .to_validate_request()? .validate_request(&req, &merchant_account)?; tracing::Span::current().record("global_payment_id", payment_id.get_string_repr()); let operations::GetTrackerResponse { mut payment_data } = operation .to_get_tracker()? .get_trackers( state, &payment_id, &req, &merchant_account, &profile, &key_store, &header_payload, platform_merchant_account.as_ref(), ) .await?; let (_operation, customer) = operation .to_domain()? .get_customer_details( state, &mut payment_data, &key_store, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound) .attach_printable("Failed while fetching/creating customer")?; let (_operation, payment_data) = operation .to_update_tracker()? .update_trackers( state, req_state, payment_data, customer.clone(), merchant_account.storage_scheme, None, &key_store, None, header_payload, ) .await?; Ok((payment_data, req, customer)) } #[instrument(skip_all)] #[cfg(feature = "v1")] pub async fn call_decision_manager<F, D>( state: &SessionState, merchant_account: &domain::MerchantAccount, _business_profile: &domain::Profile, payment_data: &D, ) -> RouterResult<Option<enums::AuthenticationType>> where F: Clone, D: OperationSessionGetters<F>, { let setup_mandate = payment_data.get_setup_mandate(); let payment_method_data = payment_data.get_payment_method_data(); let payment_dsl_data = core_routing::PaymentsDslInput::new( setup_mandate, payment_data.get_payment_attempt(), payment_data.get_payment_intent(), payment_method_data, payment_data.get_address(), payment_data.get_recurring_details(), payment_data.get_currency(), ); let algorithm_ref: api::routing::RoutingAlgorithmRef = merchant_account .routing_algorithm .clone() .map(|val| val.parse_value("routing algorithm")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not decode the routing algorithm")? .unwrap_or_default(); let output = perform_decision_management( state, algorithm_ref, merchant_account.get_id(), &payment_dsl_data, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not decode the conditional config")?; Ok(payment_dsl_data .payment_attempt .authentication_type .or(output.override_3ds) .or(Some(storage_enums::AuthenticationType::NoThreeDs))) } // TODO: Move to business profile surcharge column #[instrument(skip_all)] #[cfg(feature = "v2")] pub fn call_decision_manager<F>( state: &SessionState, record: common_types::payments::DecisionManagerRecord, payment_data: &PaymentConfirmData<F>, ) -> RouterResult<Option<enums::AuthenticationType>> where F: Clone, { let payment_method_data = payment_data.get_payment_method_data(); let payment_dsl_data = core_routing::PaymentsDslInput::new( None, payment_data.get_payment_attempt(), payment_data.get_payment_intent(), payment_method_data, payment_data.get_address(), None, payment_data.get_currency(), ); let output = perform_decision_management(record, &payment_dsl_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not decode the conditional config")?; Ok(output.override_3ds) } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn populate_surcharge_details<F>( state: &SessionState, payment_data: &mut PaymentData<F>, ) -> RouterResult<()> where F: Send + Clone, { todo!() } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn populate_surcharge_details<F>( state: &SessionState, payment_data: &mut PaymentData<F>, ) -> RouterResult<()> where F: Send + Clone, { if payment_data .payment_intent .surcharge_applicable .unwrap_or(false) { logger::debug!("payment_intent.surcharge_applicable = true"); if let Some(surcharge_details) = payment_data.payment_attempt.get_surcharge_details() { // if retry payment, surcharge would have been populated from the previous attempt. Use the same surcharge let surcharge_details = types::SurchargeDetails::from((&surcharge_details, &payment_data.payment_attempt)); payment_data.surcharge_details = Some(surcharge_details); return Ok(()); } let raw_card_key = payment_data .payment_method_data .as_ref() .and_then(helpers::get_key_params_for_surcharge_details) .map(|(payment_method, payment_method_type, card_network)| { types::SurchargeKey::PaymentMethodData( payment_method, payment_method_type, card_network, ) }); let saved_card_key = payment_data.token.clone().map(types::SurchargeKey::Token); let surcharge_key = raw_card_key .or(saved_card_key) .get_required_value("payment_method_data or payment_token")?; logger::debug!(surcharge_key_confirm =? surcharge_key); let calculated_surcharge_details = match types::SurchargeMetadata::get_individual_surcharge_detail_from_redis( state, surcharge_key, &payment_data.payment_attempt.attempt_id, ) .await { Ok(surcharge_details) => Some(surcharge_details), Err(err) if err.current_context() == &RedisError::NotFound => None, Err(err) => { Err(err).change_context(errors::ApiErrorResponse::InternalServerError)? } }; payment_data.surcharge_details = calculated_surcharge_details.clone(); //Update payment_attempt net_amount with surcharge details payment_data .payment_attempt .net_amount .set_surcharge_details(calculated_surcharge_details); } else { let surcharge_details = payment_data .payment_attempt .get_surcharge_details() .map(|surcharge_details| { logger::debug!("surcharge sent in payments create request"); types::SurchargeDetails::from(( &surcharge_details, &payment_data.payment_attempt, )) }); payment_data.surcharge_details = surcharge_details; } Ok(()) } #[inline] pub fn get_connector_data( connectors: &mut IntoIter<api::ConnectorData>, ) -> RouterResult<api::ConnectorData> { connectors .next() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Connector not found in connectors iterator") } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn call_surcharge_decision_management_for_session_flow( _state: &SessionState, _merchant_account: &domain::MerchantAccount, _business_profile: &domain::Profile, _payment_attempt: &storage::PaymentAttempt, _payment_intent: &storage::PaymentIntent, _billing_address: Option<hyperswitch_domain_models::address::Address>, _session_connector_data: &[api::SessionConnectorData], ) -> RouterResult<Option<api::SessionSurchargeDetails>> { todo!() } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn call_surcharge_decision_management_for_session_flow( state: &SessionState, _merchant_account: &domain::MerchantAccount, _business_profile: &domain::Profile, payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, billing_address: Option<hyperswitch_domain_models::address::Address>, session_connector_data: &api::SessionConnectorDatas, ) -> RouterResult<Option<api::SessionSurchargeDetails>> { if let Some(surcharge_amount) = payment_attempt.net_amount.get_surcharge_amount() { Ok(Some(api::SessionSurchargeDetails::PreDetermined( types::SurchargeDetails { original_amount: payment_attempt.net_amount.get_order_amount(), surcharge: Surcharge::Fixed(surcharge_amount), tax_on_surcharge: None, surcharge_amount, tax_on_surcharge_amount: payment_attempt .net_amount .get_tax_on_surcharge() .unwrap_or_default(), }, ))) } else { let payment_method_type_list = session_connector_data .iter() .map(|session_connector_data| session_connector_data.payment_method_sub_type) .collect(); #[cfg(feature = "v1")] let algorithm_ref: api::routing::RoutingAlgorithmRef = _merchant_account .routing_algorithm .clone() .map(|val| val.parse_value("routing algorithm")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not decode the routing algorithm")? .unwrap_or_default(); // TODO: Move to business profile surcharge column #[cfg(feature = "v2")] let algorithm_ref: api::routing::RoutingAlgorithmRef = todo!(); let surcharge_results = surcharge_decision_configs::perform_surcharge_decision_management_for_session_flow( state, algorithm_ref, payment_attempt, payment_intent, billing_address, &payment_method_type_list, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error performing surcharge decision operation")?; Ok(if surcharge_results.is_empty_result() { None } else { Some(api::SessionSurchargeDetails::Calculated(surcharge_results)) }) } } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn payments_core<F, Res, Req, Op, FData, D>( state: SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, profile_id: Option<id_type::ProfileId>, key_store: domain::MerchantKeyStore, operation: Op, req: Req, auth_flow: services::AuthFlow, call_connector_action: CallConnectorAction, eligible_connectors: Option<Vec<enums::Connector>>, header_payload: HeaderPayload, platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResponse<Res> where F: Send + Clone + Sync, FData: Send + Sync + Clone, Op: Operation<F, Req, Data = D> + Send + Sync + Clone, Req: Debug + Authenticate + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, Res: transformers::ToResponse<F, D, Op>, // 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>, { let eligible_routable_connectors = eligible_connectors.map(|connectors| { connectors .into_iter() .flat_map(|c| c.foreign_try_into()) .collect() }); let (payment_data, _req, customer, connector_http_status_code, external_latency) = payments_operation_core::<_, _, _, _, _>( &state, req_state, merchant_account, profile_id, key_store, operation.clone(), req, call_connector_action, auth_flow, eligible_routable_connectors, header_payload.clone(), platform_merchant_account, ) .await?; Res::generate_response( payment_data, customer, auth_flow, &state.base_url, operation, &state.conf.connector_request_reference_id_config, connector_http_status_code, external_latency, header_payload.x_hs_latency, ) } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn proxy_for_payments_core<F, Res, Req, Op, FData, D>( state: SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, profile_id: Option<id_type::ProfileId>, key_store: domain::MerchantKeyStore, operation: Op, req: Req, auth_flow: services::AuthFlow, call_connector_action: CallConnectorAction, header_payload: HeaderPayload, platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResponse<Res> where F: Send + Clone + Sync, FData: Send + Sync + Clone, Op: Operation<F, Req, Data = D> + Send + Sync + Clone, Req: Debug + Authenticate + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, Res: transformers::ToResponse<F, D, Op>, // 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>, { let (payment_data, _req, customer, connector_http_status_code, external_latency) = proxy_for_payments_operation_core::<_, _, _, _, _>( &state, req_state, merchant_account, profile_id, key_store, operation.clone(), req, call_connector_action, auth_flow, header_payload.clone(), platform_merchant_account, ) .await?; Res::generate_response( payment_data, customer, auth_flow, &state.base_url, operation, &state.conf.connector_request_reference_id_config, connector_http_status_code, external_latency, header_payload.x_hs_latency, ) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] pub async fn proxy_for_payments_core<F, Res, Req, Op, FData, D>( state: SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, profile: domain::Profile, key_store: domain::MerchantKeyStore, operation: Op, req: Req, payment_id: id_type::GlobalPaymentId, call_connector_action: CallConnectorAction, header_payload: HeaderPayload, ) -> RouterResponse<Res> where F: Send + Clone + Sync, Req: Send + Sync, FData: Send + Sync + Clone, Op: Operation<F, Req, Data = D> + ValidateStatusForOperation + Send + Sync + Clone, Req: Debug, D: OperationSessionGetters<F> + OperationSessionSetters<F> + transformers::GenerateResponse<Res> + Send + Sync + Clone, D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>, RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>, dyn api::Connector: services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>, PaymentResponse: Operation<F, FData, Data = D>, RouterData<F, FData, router_types::PaymentsResponseData>: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<F, FData, D>, { operation .to_validate_request()? .validate_request(&req, &merchant_account)?; let get_tracker_response = operation .to_get_tracker()? .get_trackers( &state, &payment_id, &req, &merchant_account, &profile, &key_store, &header_payload, None, ) .await?; let (payment_data, _req, connector_http_status_code, external_latency) = proxy_for_payments_operation_core::<_, _, _, _, _>( &state, req_state, merchant_account.clone(), key_store, profile.clone(), operation.clone(), req, get_tracker_response, call_connector_action, header_payload.clone(), ) .await?; payment_data.generate_response( &state, connector_http_status_code, external_latency, header_payload.x_hs_latency, &merchant_account, &profile, ) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] pub async fn record_attempt_core( state: SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, profile: domain::Profile, key_store: domain::MerchantKeyStore, req: api_models::payments::PaymentsAttemptRecordRequest, payment_id: id_type::GlobalPaymentId, header_payload: HeaderPayload, platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResponse<api_models::payments::PaymentAttemptResponse> { tracing::Span::current().record("merchant_id", merchant_account.get_id().get_string_repr()); let operation: &operations::payment_attempt_record::PaymentAttemptRecord = &operations::payment_attempt_record::PaymentAttemptRecord; let boxed_operation: BoxedOperation< '_, api::RecordAttempt, api_models::payments::PaymentsAttemptRecordRequest, domain_payments::PaymentAttemptRecordData<api::RecordAttempt>, > = Box::new(operation); let _validate_result = boxed_operation .to_validate_request()? .validate_request(&req, &merchant_account)?; tracing::Span::current().record("global_payment_id", payment_id.get_string_repr()); let operations::GetTrackerResponse { payment_data } = boxed_operation .to_get_tracker()? .get_trackers( &state, &payment_id, &req, &merchant_account, &profile, &key_store, &header_payload, platform_merchant_account.as_ref(), ) .await?; let (_operation, payment_data) = boxed_operation .to_update_tracker()? .update_trackers( &state, req_state, payment_data, None, merchant_account.storage_scheme, None, &key_store, None, header_payload.clone(), ) .await?; transformers::GenerateResponse::generate_response( payment_data, &state, None, None, header_payload.x_hs_latency, &merchant_account, &profile, ) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] pub async fn payments_intent_core<F, Res, Req, Op, D>( state: SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, profile: domain::Profile, key_store: domain::MerchantKeyStore, operation: Op, req: Req, payment_id: id_type::GlobalPaymentId, header_payload: HeaderPayload, platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResponse<Res> where F: Send + Clone + Sync, Op: Operation<F, Req, Data = D> + Send + Sync + Clone, Req: Debug + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, Res: transformers::ToResponse<F, D, Op>, { let (payment_data, _req, customer) = payments_intent_operation_core::<_, _, _, _>( &state, req_state, merchant_account.clone(), profile, key_store, operation.clone(), req, payment_id, header_payload.clone(), platform_merchant_account, ) .await?; Res::generate_response( payment_data, customer, &state.base_url, operation, &state.conf.connector_request_reference_id_config, None, None, header_payload.x_hs_latency, &merchant_account, ) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] pub async fn payments_get_intent_using_merchant_reference( state: SessionState, merchant_account: domain::MerchantAccount, profile: domain::Profile, key_store: domain::MerchantKeyStore, req_state: ReqState, merchant_reference_id: &id_type::PaymentReferenceId, header_payload: HeaderPayload, platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResponse<api::PaymentsIntentResponse> { let db = state.store.as_ref(); let storage_scheme = merchant_account.storage_scheme; let key_manager_state = &(&state).into(); let payment_intent = db .find_payment_intent_by_merchant_reference_id_profile_id( key_manager_state, merchant_reference_id, profile.get_id(), &key_store, &storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let (payment_data, _req, customer) = Box::pin(payments_intent_operation_core::< api::PaymentGetIntent, _, _, PaymentIntentData<api::PaymentGetIntent>, >( &state, req_state, merchant_account.clone(), profile.clone(), key_store.clone(), operations::PaymentGetIntent, api_models::payments::PaymentsGetIntentRequest { id: payment_intent.get_id().clone(), }, payment_intent.get_id().clone(), header_payload.clone(), platform_merchant_account, )) .await?; transformers::ToResponse::< api::PaymentGetIntent, PaymentIntentData<api::PaymentGetIntent>, operations::PaymentGetIntent, >::generate_response( payment_data, customer, &state.base_url, operations::PaymentGetIntent, &state.conf.connector_request_reference_id_config, None, None, header_payload.x_hs_latency, &merchant_account, ) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] pub async fn payments_core<F, Res, Req, Op, FData, D>( state: SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, profile: domain::Profile, key_store: domain::MerchantKeyStore, operation: Op, req: Req, payment_id: id_type::GlobalPaymentId, call_connector_action: CallConnectorAction, header_payload: HeaderPayload, ) -> RouterResponse<Res> where F: Send + Clone + Sync, Req: Send + Sync, FData: Send + Sync + Clone, Op: Operation<F, Req, Data = D> + ValidateStatusForOperation + Send + Sync + Clone, Req: Debug, D: OperationSessionGetters<F> + OperationSessionSetters<F> + transformers::GenerateResponse<Res> + 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>, // To create updatable objects in post update tracker RouterData<F, FData, router_types::PaymentsResponseData>: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<F, FData, D>, { // Validate the request fields operation .to_validate_request()? .validate_request(&req, &merchant_account)?; // Get the tracker related information. This includes payment intent and payment attempt let get_tracker_response = operation .to_get_tracker()? .get_trackers( &state, &payment_id, &req, &merchant_account, &profile, &key_store, &header_payload, None, ) .await?; let (payment_data, _req, customer, connector_http_status_code, external_latency) = payments_operation_core::<_, _, _, _, _>( &state, req_state, merchant_account.clone(), key_store, &profile, operation.clone(), req, get_tracker_response, call_connector_action, header_payload.clone(), ) .await?; payment_data.generate_response( &state, connector_http_status_code, external_latency, header_payload.x_hs_latency, &merchant_account, &profile, ) } #[allow(clippy::too_many_arguments)] #[cfg(feature = "v2")] pub(crate) async fn payments_create_and_confirm_intent( state: SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, profile: domain::Profile, key_store: domain::MerchantKeyStore, request: payments_api::PaymentsRequest, mut header_payload: HeaderPayload, platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResponse<payments_api::PaymentsResponse> { use hyperswitch_domain_models::{ payments::PaymentIntentData, router_flow_types::PaymentCreateIntent, }; let payment_id = id_type::GlobalPaymentId::generate(&state.conf.cell_information.id); let payload = payments_api::PaymentsCreateIntentRequest::from(&request); let create_intent_response = Box::pin(payments_intent_core::< PaymentCreateIntent, payments_api::PaymentsIntentResponse, _, _, PaymentIntentData<PaymentCreateIntent>, >( state.clone(), req_state.clone(), merchant_account.clone(), profile.clone(), key_store.clone(), operations::PaymentIntentCreate, payload, payment_id.clone(), header_payload.clone(), platform_merchant_account, )) .await?; logger::info!(?create_intent_response); let create_intent_response = create_intent_response .get_json_body() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unexpected response from payments core")?; // Adding client secret to ensure client secret validation passes during confirm intent step header_payload.client_secret = Some(create_intent_response.client_secret.clone()); let payload = payments_api::PaymentsConfirmIntentRequest::from(&request); let confirm_intent_response = decide_authorize_or_setup_intent_flow( state, req_state, merchant_account, profile, key_store, &create_intent_response, payload, payment_id, header_payload, ) .await?; logger::info!(?confirm_intent_response); Ok(confirm_intent_response) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] async fn decide_authorize_or_setup_intent_flow( state: SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, profile: domain::Profile, key_store: domain::MerchantKeyStore, create_intent_response: &payments_api::PaymentsIntentResponse, confirm_intent_request: payments_api::PaymentsConfirmIntentRequest, payment_id: id_type::GlobalPaymentId, header_payload: HeaderPayload, ) -> RouterResponse<payments_api::PaymentsResponse> { use hyperswitch_domain_models::{ payments::PaymentConfirmData, router_flow_types::{Authorize, SetupMandate}, }; if create_intent_response.amount_details.order_amount == MinorUnit::zero() { Box::pin(payments_core::< SetupMandate, api_models::payments::PaymentsResponse, _, _, _, PaymentConfirmData<SetupMandate>, >( state, req_state, merchant_account, profile, key_store, operations::PaymentIntentConfirm, confirm_intent_request, payment_id, CallConnectorAction::Trigger, header_payload, )) .await } else { Box::pin(payments_core::< Authorize, api_models::payments::PaymentsResponse, _, _, _, PaymentConfirmData<Authorize>, >( state, req_state, merchant_account, profile, key_store, operations::PaymentIntentConfirm, confirm_intent_request, payment_id, CallConnectorAction::Trigger, header_payload, )) .await } } fn is_start_pay<Op: Debug>(operation: &Op) -> bool { format!("{operation:?}").eq("PaymentStart") } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentsRedirectResponseData { pub connector: Option<String>, pub param: Option<String>, pub merchant_id: Option<id_type::MerchantId>, pub json_payload: Option<serde_json::Value>, pub resource_id: api::PaymentIdType, pub force_sync: bool, pub creds_identifier: Option<String>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentsRedirectResponseData { pub payment_id: id_type::GlobalPaymentId, pub query_params: String, pub json_payload: Option<serde_json::Value>, } #[async_trait::async_trait] pub trait PaymentRedirectFlow: Sync { // Associated type for call_payment_flow response type PaymentFlowResponse; #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] async fn call_payment_flow( &self, state: &SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, merchant_key_store: domain::MerchantKeyStore, req: PaymentsRedirectResponseData, connector_action: CallConnectorAction, connector: String, payment_id: id_type::PaymentId, platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResult<Self::PaymentFlowResponse>; #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] async fn call_payment_flow( &self, state: &SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, merchant_key_store: domain::MerchantKeyStore, profile: domain::Profile, req: PaymentsRedirectResponseData, platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResult<Self::PaymentFlowResponse>; fn get_payment_action(&self) -> services::PaymentAction; #[cfg(feature = "v1")] fn generate_response( &self, payment_flow_response: &Self::PaymentFlowResponse, payment_id: id_type::PaymentId, connector: String, ) -> RouterResult<services::ApplicationResponse<api::RedirectionResponse>>; #[cfg(feature = "v2")] fn generate_response( &self, payment_flow_response: &Self::PaymentFlowResponse, ) -> RouterResult<services::ApplicationResponse<api::RedirectionResponse>>; #[cfg(feature = "v1")] async fn handle_payments_redirect_response( &self, state: SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: PaymentsRedirectResponseData, platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResponse<api::RedirectionResponse> { metrics::REDIRECTION_TRIGGERED.add( 1, router_env::metric_attributes!( ( "connector", req.connector.to_owned().unwrap_or("null".to_string()), ), ("merchant_id", merchant_account.get_id().clone()), ), ); let connector = req.connector.clone().get_required_value("connector")?; let query_params = req.param.clone().get_required_value("param")?; #[cfg(feature = "v1")] let resource_id = api::PaymentIdTypeExt::get_payment_intent_id(&req.resource_id) .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "payment_id", })?; #[cfg(feature = "v2")] //TODO: Will get the global payment id from the resource id, we need to handle this in the further flow let resource_id: id_type::PaymentId = todo!(); // This connector data is ephemeral, the call payment flow will get new connector data // with merchant account details, so the connector_id can be safely set to None here let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &connector, api::GetToken::Connector, None, )?; let flow_type = connector_data .connector .get_flow_type( &query_params, req.json_payload.clone(), self.get_payment_action(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to decide the response flow")?; let payment_flow_response = self .call_payment_flow( &state, req_state, merchant_account.clone(), key_store, req.clone(), flow_type, connector.clone(), resource_id.clone(), platform_merchant_account, ) .await?; self.generate_response(&payment_flow_response, resource_id, connector) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] async fn handle_payments_redirect_response( &self, state: SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, profile: domain::Profile, request: PaymentsRedirectResponseData, platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResponse<api::RedirectionResponse> { metrics::REDIRECTION_TRIGGERED.add( 1, router_env::metric_attributes!(("merchant_id", merchant_account.get_id().clone())), ); let payment_flow_response = self .call_payment_flow( &state, req_state, merchant_account, key_store, profile, request, platform_merchant_account, ) .await?; self.generate_response(&payment_flow_response) } } #[derive(Clone, Debug)] pub struct PaymentRedirectCompleteAuthorize; #[cfg(feature = "v1")] #[async_trait::async_trait] impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize { type PaymentFlowResponse = router_types::RedirectPaymentFlowResponse; #[allow(clippy::too_many_arguments)] async fn call_payment_flow( &self, state: &SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, merchant_key_store: domain::MerchantKeyStore, req: PaymentsRedirectResponseData, connector_action: CallConnectorAction, _connector: String, _payment_id: id_type::PaymentId, platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResult<Self::PaymentFlowResponse> { let key_manager_state = &state.into(); let payment_confirm_req = api::PaymentsRequest { payment_id: Some(req.resource_id.clone()), merchant_id: req.merchant_id.clone(), merchant_connector_details: req.creds_identifier.map(|creds_id| { api::MerchantConnectorDetailsWrap { creds_identifier: creds_id, encoded_data: None, } }), feature_metadata: Some(api_models::payments::FeatureMetadata { redirect_response: Some(api_models::payments::RedirectResponse { param: req.param.map(Secret::new), json_payload: Some(req.json_payload.unwrap_or(serde_json::json!({})).into()), }), search_tags: None, apple_pay_recurring_details: None, }), ..Default::default() }; let response = Box::pin(payments_core::< api::CompleteAuthorize, api::PaymentsResponse, _, _, _, _, >( state.clone(), req_state, merchant_account, None, merchant_key_store.clone(), operations::payment_complete_authorize::CompleteAuthorize, payment_confirm_req, services::api::AuthFlow::Merchant, connector_action, None, HeaderPayload::default(), platform_merchant_account, )) .await?; let payments_response = match response { services::ApplicationResponse::Json(response) => Ok(response), services::ApplicationResponse::JsonWithHeaders((response, _)) => Ok(response), _ => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the response in json"), }?; let profile_id = payments_response .profile_id .as_ref() .get_required_value("profile_id")?; let business_profile = state .store .find_business_profile_by_profile_id(key_manager_state, &merchant_key_store, profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; Ok(router_types::RedirectPaymentFlowResponse { payments_response, business_profile, }) } fn get_payment_action(&self) -> services::PaymentAction { services::PaymentAction::CompleteAuthorize } fn generate_response( &self, payment_flow_response: &Self::PaymentFlowResponse, payment_id: id_type::PaymentId, connector: String, ) -> RouterResult<services::ApplicationResponse<api::RedirectionResponse>> { let payments_response = &payment_flow_response.payments_response; // There might be multiple redirections needed for some flows // If the status is requires customer action, then send the startpay url again // The redirection data must have been provided and updated by the connector let redirection_response = match payments_response.status { enums::IntentStatus::RequiresCustomerAction => { let startpay_url = payments_response .next_action .clone() .and_then(|next_action_data| match next_action_data { api_models::payments::NextActionData::RedirectToUrl { redirect_to_url } => Some(redirect_to_url), api_models::payments::NextActionData::DisplayBankTransferInformation { .. } => None, api_models::payments::NextActionData::ThirdPartySdkSessionToken { .. } => None, api_models::payments::NextActionData::QrCodeInformation{..} => None, api_models::payments::NextActionData::FetchQrCodeInformation{..} => None, api_models::payments::NextActionData::DisplayVoucherInformation{ .. } => None, api_models::payments::NextActionData::WaitScreenInformation{..} => None, api_models::payments::NextActionData::ThreeDsInvoke{..} => None, api_models::payments::NextActionData::InvokeSdkClient{..} => None, api_models::payments::NextActionData::CollectOtp{ .. } => None, api_models::payments::NextActionData::InvokeHiddenIframe{ .. } => None, }) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable( "did not receive redirect to url when status is requires customer action", )?; Ok(api::RedirectionResponse { return_url: String::new(), params: vec![], return_url_with_query_params: startpay_url, http_method: "GET".to_string(), headers: vec![], }) } // If the status is terminal status, then redirect to merchant return url to provide status enums::IntentStatus::Succeeded | enums::IntentStatus::Failed | enums::IntentStatus::Cancelled | enums::IntentStatus::RequiresCapture| enums::IntentStatus::Processing=> helpers::get_handle_response_url( payment_id, &payment_flow_response.business_profile, payments_response, connector, ), _ => Err(errors::ApiErrorResponse::InternalServerError).attach_printable_lazy(|| format!("Could not proceed with payment as payment status {} cannot be handled during redirection",payments_response.status))? }?; Ok(services::ApplicationResponse::JsonForRedirection( redirection_response, )) } } #[derive(Clone, Debug)] pub struct PaymentRedirectSync; #[cfg(feature = "v1")] #[async_trait::async_trait] impl PaymentRedirectFlow for PaymentRedirectSync { type PaymentFlowResponse = router_types::RedirectPaymentFlowResponse; #[allow(clippy::too_many_arguments)] async fn call_payment_flow( &self, state: &SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, merchant_key_store: domain::MerchantKeyStore, req: PaymentsRedirectResponseData, connector_action: CallConnectorAction, _connector: String, _payment_id: id_type::PaymentId, platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResult<Self::PaymentFlowResponse> { let key_manager_state = &state.into(); let payment_sync_req = api::PaymentsRetrieveRequest { resource_id: req.resource_id, merchant_id: req.merchant_id, param: req.param, force_sync: req.force_sync, connector: req.connector, merchant_connector_details: req.creds_identifier.map(|creds_id| { api::MerchantConnectorDetailsWrap { creds_identifier: creds_id, encoded_data: None, } }), client_secret: None, expand_attempts: None, expand_captures: None, }; let response = Box::pin( payments_core::<api::PSync, api::PaymentsResponse, _, _, _, _>( state.clone(), req_state, merchant_account, None, merchant_key_store.clone(), PaymentStatus, payment_sync_req, services::api::AuthFlow::Merchant, connector_action, None, HeaderPayload::default(), platform_merchant_account, ), ) .await?; let payments_response = match response { services::ApplicationResponse::Json(response) => Ok(response), services::ApplicationResponse::JsonWithHeaders((response, _)) => Ok(response), _ => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the response in json"), }?; let profile_id = payments_response .profile_id .as_ref() .get_required_value("profile_id")?; let business_profile = state .store .find_business_profile_by_profile_id(key_manager_state, &merchant_key_store, profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; Ok(router_types::RedirectPaymentFlowResponse { payments_response, business_profile, }) } fn generate_response( &self, payment_flow_response: &Self::PaymentFlowResponse, payment_id: id_type::PaymentId, connector: String, ) -> RouterResult<services::ApplicationResponse<api::RedirectionResponse>> { Ok(services::ApplicationResponse::JsonForRedirection( helpers::get_handle_response_url( payment_id, &payment_flow_response.business_profile, &payment_flow_response.payments_response, connector, )?, )) } fn get_payment_action(&self) -> services::PaymentAction { services::PaymentAction::PSync } } #[cfg(feature = "v2")] impl ValidateStatusForOperation for &PaymentRedirectSync { fn validate_status_for_operation( &self, intent_status: common_enums::IntentStatus, ) -> Result<(), errors::ApiErrorResponse> { match intent_status { common_enums::IntentStatus::RequiresCustomerAction => Ok(()), common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::Processing | common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::PartiallyCapturedAndCapturable => { Err(errors::ApiErrorResponse::PaymentUnexpectedState { current_flow: format!("{self:?}"), field_name: "status".to_string(), current_value: intent_status.to_string(), states: ["requires_customer_action".to_string()].join(", "), }) } } } } #[cfg(feature = "v2")] #[async_trait::async_trait] impl PaymentRedirectFlow for PaymentRedirectSync { type PaymentFlowResponse = router_types::RedirectPaymentFlowResponse<PaymentStatusData<api::PSync>>; async fn call_payment_flow( &self, state: &SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, merchant_key_store: domain::MerchantKeyStore, profile: domain::Profile, req: PaymentsRedirectResponseData, platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResult<Self::PaymentFlowResponse> { let payment_id = req.payment_id.clone(); let payment_sync_request = api::PaymentsRetrieveRequest { param: Some(req.query_params.clone()), force_sync: true, expand_attempts: false, }; let operation = operations::PaymentGet; let boxed_operation: BoxedOperation< '_, api::PSync, api::PaymentsRetrieveRequest, PaymentStatusData<api::PSync>, > = Box::new(operation); let get_tracker_response = boxed_operation .to_get_tracker()? .get_trackers( state, &payment_id, &payment_sync_request, &merchant_account, &profile, &merchant_key_store, &HeaderPayload::default(), platform_merchant_account.as_ref(), ) .await?; let payment_data = &get_tracker_response.payment_data; self.validate_status_for_operation(payment_data.payment_intent.status)?; let payment_attempt = payment_data .payment_attempt .as_ref() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("payment_attempt not found in get_tracker_response")?; let connector = payment_attempt .connector .as_ref() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable( "connector is not set in payment attempt in finish redirection flow", )?; // This connector data is ephemeral, the call payment flow will get new connector data // with merchant account details, so the connector_id can be safely set to None here let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, connector, api::GetToken::Connector, None, )?; let call_connector_action = connector_data .connector .get_flow_type( &req.query_params, req.json_payload.clone(), self.get_payment_action(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to decide the response flow")?; let (payment_data, _, _, _, _) = Box::pin(payments_operation_core::<api::PSync, _, _, _, _>( state, req_state, merchant_account, merchant_key_store.clone(), &profile, operation, payment_sync_request, get_tracker_response, call_connector_action, HeaderPayload::default(), )) .await?; Ok(router_types::RedirectPaymentFlowResponse { payment_data, profile, }) } fn generate_response( &self, payment_flow_response: &Self::PaymentFlowResponse, ) -> RouterResult<services::ApplicationResponse<api::RedirectionResponse>> { let payment_intent = &payment_flow_response.payment_data.payment_intent; let profile = &payment_flow_response.profile; let return_url = payment_intent .return_url .as_ref() .or(profile.return_url.as_ref()) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("return url not found in payment intent and profile")? .to_owned(); let return_url = return_url .add_query_params(("id", payment_intent.id.get_string_repr())) .add_query_params(("status", &payment_intent.status.to_string())); let return_url_str = return_url.into_inner().to_string(); Ok(services::ApplicationResponse::JsonForRedirection( api::RedirectionResponse { return_url_with_query_params: return_url_str, }, )) } fn get_payment_action(&self) -> services::PaymentAction { services::PaymentAction::PSync } } #[derive(Clone, Debug)] pub struct PaymentAuthenticateCompleteAuthorize; #[cfg(feature = "v1")] #[async_trait::async_trait] impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize { type PaymentFlowResponse = router_types::AuthenticatePaymentFlowResponse; #[allow(clippy::too_many_arguments)] async fn call_payment_flow( &self, state: &SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, merchant_key_store: domain::MerchantKeyStore, req: PaymentsRedirectResponseData, connector_action: CallConnectorAction, connector: String, payment_id: id_type::PaymentId, platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResult<Self::PaymentFlowResponse> { let merchant_id = merchant_account.get_id().clone(); let key_manager_state = &state.into(); let payment_intent = state .store .find_payment_intent_by_payment_id_merchant_id( key_manager_state, &payment_id, &merchant_id, &merchant_key_store, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let payment_attempt = state .store .find_payment_attempt_by_attempt_id_merchant_id( &payment_intent.active_attempt.get_id(), &merchant_id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let authentication_id = payment_attempt .authentication_id .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing authentication_id in payment_attempt")?; let authentication = state .store .find_authentication_by_merchant_id_authentication_id( &merchant_id, authentication_id.clone(), ) .await .to_not_found_response(errors::ApiErrorResponse::AuthenticationNotFound { id: authentication_id, })?; // Fetching merchant_connector_account to check if pull_mechanism is enabled for 3ds connector let authentication_merchant_connector_account = helpers::get_merchant_connector_account( state, &merchant_id, None, &merchant_key_store, &payment_intent .profile_id .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing profile_id in payment_intent")?, &payment_attempt .authentication_connector .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing authentication connector in payment_intent")?, None, ) .await?; let is_pull_mechanism_enabled = utils::check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata( authentication_merchant_connector_account .get_metadata() .map(|metadata| metadata.expose()), ); let response = if is_pull_mechanism_enabled || authentication.authentication_type != Some(common_enums::DecoupledAuthenticationType::Challenge) { let payment_confirm_req = api::PaymentsRequest { payment_id: Some(req.resource_id.clone()), merchant_id: req.merchant_id.clone(), feature_metadata: Some(api_models::payments::FeatureMetadata { redirect_response: Some(api_models::payments::RedirectResponse { param: req.param.map(Secret::new), json_payload: Some( req.json_payload.unwrap_or(serde_json::json!({})).into(), ), }), search_tags: None, apple_pay_recurring_details: None, }), ..Default::default() }; Box::pin(payments_core::< api::Authorize, api::PaymentsResponse, _, _, _, _, >( state.clone(), req_state, merchant_account, None, merchant_key_store.clone(), PaymentConfirm, payment_confirm_req, services::api::AuthFlow::Merchant, connector_action, None, HeaderPayload::with_source(enums::PaymentSource::ExternalAuthenticator), platform_merchant_account, )) .await? } else { let payment_sync_req = api::PaymentsRetrieveRequest { resource_id: req.resource_id, merchant_id: req.merchant_id, param: req.param, force_sync: req.force_sync, connector: req.connector, merchant_connector_details: req.creds_identifier.map(|creds_id| { api::MerchantConnectorDetailsWrap { creds_identifier: creds_id, encoded_data: None, } }), client_secret: None, expand_attempts: None, expand_captures: None, }; Box::pin( payments_core::<api::PSync, api::PaymentsResponse, _, _, _, _>( state.clone(), req_state, merchant_account.clone(), None, merchant_key_store.clone(), PaymentStatus, payment_sync_req, services::api::AuthFlow::Merchant, connector_action, None, HeaderPayload::default(), platform_merchant_account, ), ) .await? }; let payments_response = match response { services::ApplicationResponse::Json(response) => Ok(response), services::ApplicationResponse::JsonWithHeaders((response, _)) => Ok(response), _ => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the response in json"), }?; // When intent status is RequiresCustomerAction, Set poll_id in redis to allow the fetch status of poll through retrieve_poll_status api from client if payments_response.status == common_enums::IntentStatus::RequiresCustomerAction { let req_poll_id = core_utils::get_external_authentication_request_poll_id(&payment_id); let poll_id = core_utils::get_poll_id(&merchant_id, req_poll_id.clone()); let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; redis_conn .set_key_with_expiry( &poll_id.into(), api_models::poll::PollStatus::Pending.to_string(), consts::POLL_ID_TTL, ) .await .change_context(errors::StorageError::KVError) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add poll_id in redis")?; }; let default_poll_config = router_types::PollConfig::default(); let default_config_str = default_poll_config .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while stringifying default poll config")?; let poll_config = state .store .find_config_by_key_unwrap_or( &router_types::PollConfig::get_poll_config_key(connector), Some(default_config_str), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("The poll config was not found in the DB")?; let poll_config: router_types::PollConfig = poll_config .config .parse_struct("PollConfig") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while parsing PollConfig")?; let profile_id = payments_response .profile_id .as_ref() .get_required_value("profile_id")?; let business_profile = state .store .find_business_profile_by_profile_id(key_manager_state, &merchant_key_store, profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; Ok(router_types::AuthenticatePaymentFlowResponse { payments_response, poll_config, business_profile, }) } fn generate_response( &self, payment_flow_response: &Self::PaymentFlowResponse, payment_id: id_type::PaymentId, connector: String, ) -> RouterResult<services::ApplicationResponse<api::RedirectionResponse>> { let payments_response = &payment_flow_response.payments_response; let redirect_response = helpers::get_handle_response_url( payment_id.clone(), &payment_flow_response.business_profile, payments_response, connector.clone(), )?; // html script to check if inside iframe, then send post message to parent for redirection else redirect self to return_url let html = core_utils::get_html_redirect_response_for_external_authentication( redirect_response.return_url_with_query_params, payments_response, payment_id, &payment_flow_response.poll_config, )?; Ok(services::ApplicationResponse::Form(Box::new( services::RedirectionFormData { redirect_form: services::RedirectForm::Html { html_data: html }, payment_method_data: None, amount: payments_response.amount.to_string(), currency: payments_response.currency.clone(), }, ))) } fn get_payment_action(&self) -> services::PaymentAction { services::PaymentAction::PaymentAuthenticateCompleteAuthorize } } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] 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)) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] 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) } #[cfg(feature = "v1")] // This function does not perform the tokenization action, as the payment method is not saved in this flow. #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn proxy_for_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, business_profile: &domain::Profile, ) -> 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?; 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()); } 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 mut should_continue_further = access_token::update_router_data_with_access_token_result( &add_access_token_result, &mut router_data, &call_connector_action, ); (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); }; 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(); } let updated_customer = None; let frm_suggestion = None; (_, *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)) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn proxy_for_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, call_connector_action: CallConnectorAction, header_payload: HeaderPayload, business_profile: &domain::Profile, ) -> 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 mut router_data = payment_data .construct_router_data( state, connector.connector.id(), merchant_account, key_store, &None, &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 mut should_continue_further = access_token::update_router_data_with_access_token_result( &add_access_token_result, &mut router_data, &call_connector_action, ); (router_data, should_continue_further) = complete_preprocessing_steps_if_required( state, &connector, payment_data, router_data, operation, should_continue_further, ) .await?; let (connector_request, should_continue_further) = if should_continue_further { router_data .build_flow_specific_connector_request(state, &connector, call_connector_action.clone()) .await? } else { (None, false) }; (_, *payment_data) = operation .to_update_tracker()? .update_trackers( state, req_state, payment_data.clone(), None, merchant_account.storage_scheme, None, key_store, None, header_payload.clone(), ) .await?; let router_data = if should_continue_further { 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) } pub async fn add_decrypted_payment_method_token<F, D>( tokenization_action: TokenizationAction, payment_data: &D, ) -> CustomResult<Option<PaymentMethodToken>, errors::ApiErrorResponse> where F: Send + Clone + Sync, D: OperationSessionGetters<F> + Send + Sync + Clone, { // Tokenization Action will be DecryptApplePayToken, only when payment method type is Apple Pay // and the connector supports Apple Pay predecrypt match &tokenization_action { TokenizationAction::DecryptApplePayToken(payment_processing_details) | TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt( payment_processing_details, ) => { let apple_pay_data = match payment_data.get_payment_method_data() { Some(domain::PaymentMethodData::Wallet(domain::WalletData::ApplePay( wallet_data, ))) => Some( ApplePayData::token_json(domain::WalletData::ApplePay(wallet_data.clone())) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to parse apple pay token to json")? .decrypt( &payment_processing_details.payment_processing_certificate, &payment_processing_details.payment_processing_certificate_key, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to decrypt apple pay token")?, ), _ => None, }; let apple_pay_predecrypt = apple_pay_data .parse_value::<hyperswitch_domain_models::router_data::ApplePayPredecryptData>( "ApplePayPredecryptData", ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "failed to parse decrypted apple pay response to ApplePayPredecryptData", )?; Ok(Some(PaymentMethodToken::ApplePayDecrypt(Box::new( apple_pay_predecrypt, )))) } TokenizationAction::DecryptPazeToken(payment_processing_details) => { let paze_data = match payment_data.get_payment_method_data() { Some(domain::PaymentMethodData::Wallet(domain::WalletData::Paze(wallet_data))) => { Some( decrypt_paze_token( wallet_data.clone(), payment_processing_details.paze_private_key.clone(), payment_processing_details .paze_private_key_passphrase .clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to decrypt paze token")?, ) } _ => None, }; let paze_decrypted_data = paze_data .parse_value::<hyperswitch_domain_models::router_data::PazeDecryptedData>( "PazeDecryptedData", ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to parse PazeDecryptedData")?; Ok(Some(PaymentMethodToken::PazeDecrypt(Box::new( paze_decrypted_data, )))) } TokenizationAction::DecryptGooglePayToken(payment_processing_details) => { let google_pay_data = match payment_data.get_payment_method_data() { Some(domain::PaymentMethodData::Wallet(domain::WalletData::GooglePay( wallet_data, ))) => { let decryptor = helpers::GooglePayTokenDecryptor::new( payment_processing_details .google_pay_root_signing_keys .clone(), payment_processing_details.google_pay_recipient_id.clone(), payment_processing_details.google_pay_private_key.clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to create google pay token decryptor")?; // should_verify_token is set to false to disable verification of token Some( decryptor .decrypt_token(wallet_data.tokenization_data.token.clone(), false) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to decrypt google pay token")?, ) } Some(payment_method_data) => { logger::info!( "Invalid payment_method_data found for Google Pay Decrypt Flow: {:?}", payment_method_data.get_payment_method() ); None } None => { logger::info!("No payment_method_data found for Google Pay Decrypt Flow"); None } }; let google_pay_predecrypt = google_pay_data .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to get GooglePayDecryptedData in response")?; Ok(Some(PaymentMethodToken::GooglePayDecrypt(Box::new( google_pay_predecrypt, )))) } TokenizationAction::ConnectorToken(_) => { logger::info!("Invalid tokenization action found for decryption flow: ConnectorToken",); Ok(None) } token_action => { logger::info!( "Invalid tokenization action found for decryption flow: {:?}", token_action ); Ok(None) } } } pub async fn get_merchant_bank_data_for_open_banking_connectors( merchant_connector_account: &helpers::MerchantConnectorAccountType, key_store: &domain::MerchantKeyStore, connector: &api::ConnectorData, state: &SessionState, merchant_account: &domain::MerchantAccount, ) -> RouterResult<Option<router_types::MerchantRecipientData>> { let merchant_data = merchant_connector_account .get_additional_merchant_data() .get_required_value("additional_merchant_data")? .into_inner() .peek() .clone(); let merchant_recipient_data = merchant_data .parse_value::<router_types::AdditionalMerchantData>("AdditionalMerchantData") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to decode MerchantRecipientData")?; let connector_name = enums::Connector::to_string(&connector.connector_name); let locker_based_connector_list = state.conf.locker_based_open_banking_connectors.clone(); let contains = locker_based_connector_list .connector_list .contains(connector_name.as_str()); let recipient_id = helpers::get_recipient_id_for_open_banking(&merchant_recipient_data)?; let final_recipient_data = if let Some(id) = recipient_id { if contains { // Customer Id for OpenBanking connectors will be merchant_id as the account data stored at locker belongs to the merchant let merchant_id_str = merchant_account.get_id().get_string_repr().to_owned(); let cust_id = id_type::CustomerId::try_from(std::borrow::Cow::from(merchant_id_str)) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to convert to CustomerId")?; let locker_resp = cards::get_payment_method_from_hs_locker( state, key_store, &cust_id, merchant_account.get_id(), id.as_str(), Some(enums::LockerChoice::HyperswitchCardVault), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Merchant bank account data could not be fetched from locker")?; let parsed: router_types::MerchantAccountData = locker_resp .peek() .to_string() .parse_struct("MerchantAccountData") .change_context(errors::ApiErrorResponse::InternalServerError)?; Some(router_types::MerchantRecipientData::AccountData(parsed)) } else { Some(router_types::MerchantRecipientData::ConnectorRecipientId( Secret::new(id), )) } } else { None }; Ok(final_recipient_data) } async fn blocklist_guard<F, ApiRequest, D>( state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, operation: &BoxedOperation<'_, F, ApiRequest, D>, payment_data: &mut D, ) -> CustomResult<bool, errors::ApiErrorResponse> where F: Send + Clone + Sync, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { let merchant_id = merchant_account.get_id(); let blocklist_enabled_key = merchant_id.get_blocklist_guard_key(); let blocklist_guard_enabled = state .store .find_config_by_key_unwrap_or(&blocklist_enabled_key, Some("false".to_string())) .await; let blocklist_guard_enabled: bool = match blocklist_guard_enabled { Ok(config) => serde_json::from_str(&config.config).unwrap_or(false), // If it is not present in db we are defaulting it to false Err(inner) => { if !inner.current_context().is_db_not_found() { logger::error!("Error fetching guard blocklist enabled config {:?}", inner); } false } }; if blocklist_guard_enabled { Ok(operation .to_domain()? .guard_payment_against_blocklist(state, merchant_account, key_store, payment_data) .await?) } else { Ok(false) } } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] 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) } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] 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) } #[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(); 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(), }, ))) } 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"), } } #[cfg(feature = "v1")] 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), } } #[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 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), } } 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) } #[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, 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), } } pub fn is_preprocessing_required_for_wallets(connector_name: String) -> bool { connector_name == *"trustpay" || connector_name == *"payme" } #[cfg(feature = "v1")] #[instrument(skip_all)] 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) } fn is_payment_method_tokenization_enabled_for_connector( state: &SessionState, connector_name: &str, payment_method: storage::enums::PaymentMethod, payment_method_type: Option<storage::enums::PaymentMethodType>, apple_pay_flow: &Option<domain::ApplePayFlow>, ) -> RouterResult<bool> { let connector_tokenization_filter = state.conf.tokenization.0.get(connector_name); Ok(connector_tokenization_filter .map(|connector_filter| { connector_filter .payment_method .clone() .contains(&payment_method) && is_payment_method_type_allowed_for_connector( payment_method_type, connector_filter.payment_method_type.clone(), ) && is_apple_pay_pre_decrypt_type_connector_tokenization( payment_method_type, apple_pay_flow, connector_filter.apple_pay_pre_decrypt_flow.clone(), ) }) .unwrap_or(false)) } fn is_apple_pay_pre_decrypt_type_connector_tokenization( payment_method_type: Option<storage::enums::PaymentMethodType>, apple_pay_flow: &Option<domain::ApplePayFlow>, apple_pay_pre_decrypt_flow_filter: Option<ApplePayPreDecryptFlow>, ) -> bool { match (payment_method_type, apple_pay_flow) { ( Some(storage::enums::PaymentMethodType::ApplePay), Some(domain::ApplePayFlow::Simplified(_)), ) => !matches!( apple_pay_pre_decrypt_flow_filter, Some(ApplePayPreDecryptFlow::NetworkTokenization) ), _ => true, } } fn decide_apple_pay_flow( state: &SessionState, payment_method_type: Option<enums::PaymentMethodType>, merchant_connector_account: Option<&helpers::MerchantConnectorAccountType>, ) -> Option<domain::ApplePayFlow> { payment_method_type.and_then(|pmt| match pmt { enums::PaymentMethodType::ApplePay => { check_apple_pay_metadata(state, merchant_connector_account) } _ => None, }) } fn check_apple_pay_metadata( state: &SessionState, merchant_connector_account: Option<&helpers::MerchantConnectorAccountType>, ) -> Option<domain::ApplePayFlow> { merchant_connector_account.and_then(|mca| { let metadata = mca.get_metadata(); metadata.and_then(|apple_pay_metadata| { let parsed_metadata = apple_pay_metadata .clone() .parse_value::<api_models::payments::ApplepayCombinedSessionTokenData>( "ApplepayCombinedSessionTokenData", ) .map(|combined_metadata| { api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined( combined_metadata.apple_pay_combined, ) }) .or_else(|_| { apple_pay_metadata .parse_value::<api_models::payments::ApplepaySessionTokenData>( "ApplepaySessionTokenData", ) .map(|old_metadata| { api_models::payments::ApplepaySessionTokenMetadata::ApplePay( old_metadata.apple_pay, ) }) }) .map_err(|error| { logger::warn!(?error, "Failed to Parse Value to ApplepaySessionTokenData") }); parsed_metadata.ok().map(|metadata| match metadata { api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined( apple_pay_combined, ) => match apple_pay_combined { api_models::payments::ApplePayCombinedMetadata::Simplified { .. } => { domain::ApplePayFlow::Simplified(payments_api::PaymentProcessingDetails { payment_processing_certificate: state .conf .applepay_decrypt_keys .get_inner() .apple_pay_ppc .clone(), payment_processing_certificate_key: state .conf .applepay_decrypt_keys .get_inner() .apple_pay_ppc_key .clone(), }) } api_models::payments::ApplePayCombinedMetadata::Manual { payment_request_data: _, session_token_data, } => { if let Some(manual_payment_processing_details_at) = session_token_data.payment_processing_details_at { match manual_payment_processing_details_at { payments_api::PaymentProcessingDetailsAt::Hyperswitch( payment_processing_details, ) => domain::ApplePayFlow::Simplified(payment_processing_details), payments_api::PaymentProcessingDetailsAt::Connector => { domain::ApplePayFlow::Manual } } } else { domain::ApplePayFlow::Manual } } }, api_models::payments::ApplepaySessionTokenMetadata::ApplePay(_) => { domain::ApplePayFlow::Manual } }) }) }) } 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, } } 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 } } #[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 { 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, }), } } } } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)] pub struct PazePaymentProcessingDetails { pub paze_private_key: Secret<String>, pub paze_private_key_passphrase: Secret<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayPaymentProcessingDetails { pub google_pay_private_key: Secret<String>, pub google_pay_root_signing_keys: Secret<String>, pub google_pay_recipient_id: Secret<String>, } #[derive(Clone, Debug)] pub enum TokenizationAction { TokenizeInRouter, TokenizeInConnector, TokenizeInConnectorAndRouter, ConnectorToken(String), SkipConnectorTokenization, DecryptApplePayToken(payments_api::PaymentProcessingDetails), TokenizeInConnectorAndApplepayPreDecrypt(payments_api::PaymentProcessingDetails), DecryptPazeToken(PazePaymentProcessingDetails), DecryptGooglePayToken(GooglePayPaymentProcessingDetails), } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] 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)) } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] 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) } #[cfg(feature = "v2")] pub async fn tokenize_in_router_when_confirm_false_or_external_authentication<F, Req, D>( state: &SessionState, operation: &BoxedOperation<'_, F, Req, D>, payment_data: &mut D, validate_result: &operations::ValidateResult, merchant_key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, business_profile: &domain::Profile, ) -> RouterResult<D> where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { todo!() } #[cfg(feature = "v1")] pub async fn tokenize_in_router_when_confirm_false_or_external_authentication<F, Req, D>( state: &SessionState, operation: &BoxedOperation<'_, F, Req, D>, payment_data: &mut D, validate_result: &operations::ValidateResult, merchant_key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, business_profile: &domain::Profile, ) -> RouterResult<D> where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { // On confirm is false and only router related let is_external_authentication_requested = payment_data .get_payment_intent() .request_external_three_ds_authentication; let payment_data = if !is_operation_confirm(operation) || is_external_authentication_requested == Some(true) { 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, false, ) .await?; payment_data.set_payment_method_data(payment_method_data); if let Some(payment_method_id) = pm_id { payment_data.set_payment_method_id_in_attempt(Some(payment_method_id)); } payment_data } else { payment_data }; Ok(payment_data.to_owned()) } #[derive(Clone)] pub struct MandateConnectorDetails { pub connector: String, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, } #[derive(Clone)] pub struct PaymentData<F> where F: Clone, { pub flow: PhantomData<F>, pub payment_intent: storage::PaymentIntent, pub payment_attempt: storage::PaymentAttempt, pub multiple_capture_data: Option<types::MultipleCaptureData>, pub amount: api::Amount, pub mandate_id: Option<api_models::payments::MandateIds>, pub mandate_connector: Option<MandateConnectorDetails>, pub currency: storage_enums::Currency, pub setup_mandate: Option<MandateData>, pub customer_acceptance: Option<CustomerAcceptance>, pub address: PaymentAddress, pub token: Option<String>, pub token_data: Option<storage::PaymentTokenData>, pub confirm: Option<bool>, pub force_sync: Option<bool>, pub payment_method_data: Option<domain::PaymentMethodData>, pub payment_method_info: Option<domain::PaymentMethod>, pub refunds: Vec<storage::Refund>, pub disputes: Vec<storage::Dispute>, pub attempts: Option<Vec<storage::PaymentAttempt>>, pub sessions_token: Vec<api::SessionToken>, pub card_cvc: Option<Secret<String>>, pub email: Option<pii::Email>, pub creds_identifier: Option<String>, pub pm_token: Option<String>, pub connector_customer_id: Option<String>, pub recurring_mandate_payment_data: Option<hyperswitch_domain_models::router_data::RecurringMandatePaymentData>, pub ephemeral_key: Option<ephemeral_key::EphemeralKey>, pub redirect_response: Option<api_models::payments::RedirectResponse>, pub surcharge_details: Option<types::SurchargeDetails>, pub frm_message: Option<FraudCheck>, pub payment_link_data: Option<api_models::payments::PaymentLinkResponse>, pub incremental_authorization_details: Option<IncrementalAuthorizationDetails>, pub authorizations: Vec<diesel_models::authorization::Authorization>, pub authentication: Option<storage::Authentication>, pub recurring_details: Option<RecurringDetails>, pub poll_config: Option<router_types::PollConfig>, pub tax_data: Option<TaxData>, pub session_id: Option<String>, pub service_details: Option<api_models::payments::CtpServiceDetails>, pub card_testing_guard_data: Option<hyperswitch_domain_models::card_testing_guard_data::CardTestingGuardData>, pub vault_operation: Option<domain_payments::VaultOperation>, pub threeds_method_comp_ind: Option<api_models::payments::ThreeDsCompletionIndicator>, } #[derive(Clone, serde::Serialize, Debug)] pub struct TaxData { pub shipping_details: hyperswitch_domain_models::address::Address, pub payment_method_type: enums::PaymentMethodType, } #[derive(Clone, serde::Serialize, Debug)] pub struct PaymentEvent { payment_intent: storage::PaymentIntent, payment_attempt: storage::PaymentAttempt, } impl<F: Clone> PaymentData<F> { // Get the method by which a card is discovered during a payment #[cfg(feature = "v1")] fn get_card_discovery_for_card_payment_method(&self) -> Option<common_enums::CardDiscovery> { match self.payment_attempt.payment_method { Some(storage_enums::PaymentMethod::Card) => { if self .token_data .as_ref() .map(storage::PaymentTokenData::is_permanent_card) .unwrap_or(false) { Some(common_enums::CardDiscovery::SavedCard) } else if self.service_details.is_some() { Some(common_enums::CardDiscovery::ClickToPay) } else { Some(common_enums::CardDiscovery::Manual) } } _ => None, } } fn to_event(&self) -> PaymentEvent { PaymentEvent { payment_intent: self.payment_intent.clone(), payment_attempt: self.payment_attempt.clone(), } } } impl EventInfo for PaymentEvent { type Data = Self; fn data(&self) -> error_stack::Result<Self::Data, events::EventsError> { Ok(self.clone()) } fn key(&self) -> String { "payment".to_string() } } #[derive(Debug, Default, Clone)] pub struct IncrementalAuthorizationDetails { pub additional_amount: MinorUnit, pub total_amount: MinorUnit, pub reason: Option<String>, pub authorization_id: Option<String>, } pub trait CustomerDetailsExt { type Error; fn get_name(&self) -> Result<Secret<String, masking::WithType>, Self::Error>; fn get_email(&self) -> Result<pii::Email, Self::Error>; } impl CustomerDetailsExt for CustomerDetails { type Error = error_stack::Report<errors::ConnectorError>; fn get_name(&self) -> Result<Secret<String, masking::WithType>, Self::Error> { self.name.clone().ok_or_else(missing_field_err("name")) } fn get_email(&self) -> Result<pii::Email, Self::Error> { self.email.clone().ok_or_else(missing_field_err("email")) } } pub async fn get_payment_link_response_from_id( state: &SessionState, payment_link_id: &str, ) -> CustomResult<api_models::payments::PaymentLinkResponse, errors::ApiErrorResponse> { let db = &*state.store; let payment_link_object = db .find_payment_link_by_payment_link_id(payment_link_id) .await .to_not_found_response(errors::ApiErrorResponse::PaymentLinkNotFound)?; Ok(api_models::payments::PaymentLinkResponse { link: payment_link_object.link_to_pay.clone(), secure_link: payment_link_object.secure_link, payment_link_id: payment_link_object.payment_link_id, }) } #[cfg(feature = "v1")] 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), } } } #[cfg(feature = "v1")] 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) } } #[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 .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, } } pub fn is_operation_confirm<Op: Debug>(operation: &Op) -> bool { matches!(format!("{operation:?}").as_str(), "PaymentConfirm") } pub fn is_operation_complete_authorize<Op: Debug>(operation: &Op) -> bool { matches!(format!("{operation:?}").as_str(), "CompleteAuthorize") } #[cfg(all(feature = "olap", feature = "v1"))] pub async fn list_payments( state: SessionState, merchant: domain::MerchantAccount, profile_id_list: Option<Vec<id_type::ProfileId>>, key_store: domain::MerchantKeyStore, constraints: api::PaymentListConstraints, ) -> RouterResponse<api::PaymentListResponse> { helpers::validate_payment_list_request(&constraints)?; let merchant_id = merchant.get_id(); let db = state.store.as_ref(); let payment_intents = helpers::filter_by_constraints( &state, &(constraints, profile_id_list).try_into()?, merchant_id, &key_store, merchant.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let collected_futures = payment_intents.into_iter().map(|pi| { async { match db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &pi.payment_id, merchant_id, &pi.active_attempt.get_id(), // since OLAP doesn't have KV. Force to get the data from PSQL. storage_enums::MerchantStorageScheme::PostgresOnly, ) .await { Ok(pa) => Some(Ok((pi, pa))), Err(error) => { if matches!( error.current_context(), errors::StorageError::ValueNotFound(_) ) { logger::warn!( ?error, "payment_attempts missing for payment_id : {:?}", pi.payment_id, ); return None; } Some(Err(error)) } } } }); //If any of the response are Err, we will get Result<Err(_)> let pi_pa_tuple_vec: Result<Vec<(storage::PaymentIntent, storage::PaymentAttempt)>, _> = join_all(collected_futures) .await .into_iter() .flatten() //Will ignore `None`, will only flatten 1 level .collect::<Result<Vec<(storage::PaymentIntent, storage::PaymentAttempt)>, _>>(); //Will collect responses in same order async, leading to sorted responses //Converting Intent-Attempt array to Response if no error let data: Vec<api::PaymentsResponse> = pi_pa_tuple_vec .change_context(errors::ApiErrorResponse::InternalServerError)? .into_iter() .map(ForeignFrom::foreign_from) .collect(); Ok(services::ApplicationResponse::Json( api::PaymentListResponse { size: data.len(), data, }, )) } #[cfg(all(feature = "v2", feature = "olap"))] pub async fn list_payments( state: SessionState, merchant: domain::MerchantAccount, key_store: domain::MerchantKeyStore, constraints: api::PaymentListConstraints, ) -> RouterResponse<payments_api::PaymentListResponse> { common_utils::metrics::utils::record_operation_time( async { let limit = &constraints.limit; helpers::validate_payment_list_request_for_joins(*limit)?; let db: &dyn StorageInterface = state.store.as_ref(); let fetch_constraints = constraints.clone().into(); let list: Vec<(storage::PaymentIntent, Option<storage::PaymentAttempt>)> = db .get_filtered_payment_intents_attempt( &(&state).into(), merchant.get_id(), &fetch_constraints, &key_store, merchant.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let data: Vec<api_models::payments::PaymentsListResponseItem> = list.into_iter().map(ForeignFrom::foreign_from).collect(); let active_attempt_ids = db .get_filtered_active_attempt_ids_for_total_count( merchant.get_id(), &fetch_constraints, merchant.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while retrieving active_attempt_ids for merchant")?; let total_count = if constraints.has_no_attempt_filters() { i64::try_from(active_attempt_ids.len()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while converting from usize to i64") } else { let active_attempt_ids = active_attempt_ids .into_iter() .flatten() .collect::<Vec<String>>(); db.get_total_count_of_filtered_payment_attempts( merchant.get_id(), &active_attempt_ids, constraints.connector, constraints.payment_method_type, constraints.payment_method_subtype, constraints.authentication_type, constraints.merchant_connector_id, constraints.card_network, merchant.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while retrieving total count of payment attempts") }?; Ok(services::ApplicationResponse::Json( api_models::payments::PaymentListResponse { count: data.len(), total_count, data, }, )) }, &metrics::PAYMENT_LIST_LATENCY, router_env::metric_attributes!(("merchant_id", merchant.get_id().clone())), ) .await } #[cfg(all(feature = "olap", feature = "v1"))] pub async fn apply_filters_on_payments( state: SessionState, merchant: domain::MerchantAccount, profile_id_list: Option<Vec<id_type::ProfileId>>, merchant_key_store: domain::MerchantKeyStore, constraints: api::PaymentListFilterConstraints, ) -> RouterResponse<api::PaymentListResponseV2> { common_utils::metrics::utils::record_operation_time( async { let limit = &constraints.limit; helpers::validate_payment_list_request_for_joins(*limit)?; let db: &dyn StorageInterface = state.store.as_ref(); let pi_fetch_constraints = (constraints.clone(), profile_id_list.clone()).try_into()?; let list: Vec<(storage::PaymentIntent, storage::PaymentAttempt)> = db .get_filtered_payment_intents_attempt( &(&state).into(), merchant.get_id(), &pi_fetch_constraints, &merchant_key_store, merchant.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let data: Vec<api::PaymentsResponse> = list.into_iter().map(ForeignFrom::foreign_from).collect(); let active_attempt_ids = db .get_filtered_active_attempt_ids_for_total_count( merchant.get_id(), &pi_fetch_constraints, merchant.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; let total_count = if constraints.has_no_attempt_filters() { i64::try_from(active_attempt_ids.len()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while converting from usize to i64") } else { db.get_total_count_of_filtered_payment_attempts( merchant.get_id(), &active_attempt_ids, constraints.connector, constraints.payment_method, constraints.payment_method_type, constraints.authentication_type, constraints.merchant_connector_id, constraints.card_network, constraints.card_discovery, merchant.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) }?; Ok(services::ApplicationResponse::Json( api::PaymentListResponseV2 { count: data.len(), total_count, data, }, )) }, &metrics::PAYMENT_LIST_LATENCY, router_env::metric_attributes!(("merchant_id", merchant.get_id().clone())), ) .await } #[cfg(all(feature = "olap", feature = "v1"))] pub async fn get_filters_for_payments( state: SessionState, merchant: domain::MerchantAccount, merchant_key_store: domain::MerchantKeyStore, time_range: common_utils::types::TimeRange, ) -> RouterResponse<api::PaymentListFilters> { let db = state.store.as_ref(); let pi = db .filter_payment_intents_by_time_range_constraints( &(&state).into(), merchant.get_id(), &time_range, &merchant_key_store, merchant.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let filters = db .get_filters_for_payments( pi.as_slice(), merchant.get_id(), // since OLAP doesn't have KV. Force to get the data from PSQL. storage_enums::MerchantStorageScheme::PostgresOnly, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; Ok(services::ApplicationResponse::Json( api::PaymentListFilters { connector: filters.connector, currency: filters.currency, status: filters.status, payment_method: filters.payment_method, payment_method_type: filters.payment_method_type, authentication_type: filters.authentication_type, }, )) } #[cfg(feature = "olap")] pub async fn get_payment_filters( state: SessionState, merchant: domain::MerchantAccount, profile_id_list: Option<Vec<id_type::ProfileId>>, ) -> RouterResponse<api::PaymentListFiltersV2> { let merchant_connector_accounts = if let services::ApplicationResponse::Json(data) = super::admin::list_payment_connectors(state, merchant.get_id().to_owned(), profile_id_list) .await? { data } else { return Err(errors::ApiErrorResponse::InternalServerError.into()); }; let mut connector_map: HashMap<String, Vec<MerchantConnectorInfo>> = HashMap::new(); let mut payment_method_types_map: HashMap< enums::PaymentMethod, HashSet<enums::PaymentMethodType>, > = HashMap::new(); // populate connector map merchant_connector_accounts .iter() .filter_map(|merchant_connector_account| { merchant_connector_account .connector_label .as_ref() .map(|label| { let info = merchant_connector_account.to_merchant_connector_info(label); (merchant_connector_account.get_connector_name(), info) }) }) .for_each(|(connector_name, info)| { connector_map .entry(connector_name.to_string()) .or_default() .push(info); }); // populate payment method type map merchant_connector_accounts .iter() .flat_map(|merchant_connector_account| { merchant_connector_account.payment_methods_enabled.as_ref() }) .map(|payment_methods_enabled| { payment_methods_enabled .iter() .filter_map(|payment_method_enabled| { payment_method_enabled .get_payment_method_type() .map(|types_vec| { ( payment_method_enabled.get_payment_method(), types_vec.clone(), ) }) }) }) .for_each(|payment_methods_enabled| { payment_methods_enabled.for_each( |(payment_method_option, payment_method_types_vec)| { if let Some(payment_method) = payment_method_option { payment_method_types_map .entry(payment_method) .or_default() .extend(payment_method_types_vec.iter().filter_map( |req_payment_method_types| { req_payment_method_types.get_payment_method_type() }, )); } }, ); }); Ok(services::ApplicationResponse::Json( api::PaymentListFiltersV2 { connector: connector_map, currency: enums::Currency::iter().collect(), status: enums::IntentStatus::iter().collect(), payment_method: payment_method_types_map, authentication_type: enums::AuthenticationType::iter().collect(), card_network: enums::CardNetwork::iter().collect(), card_discovery: enums::CardDiscovery::iter().collect(), }, )) } #[cfg(feature = "olap")] pub async fn get_aggregates_for_payments( state: SessionState, merchant: domain::MerchantAccount, profile_id_list: Option<Vec<id_type::ProfileId>>, time_range: common_utils::types::TimeRange, ) -> RouterResponse<api::PaymentsAggregateResponse> { let db = state.store.as_ref(); let intent_status_with_count = db .get_intent_status_with_count(merchant.get_id(), profile_id_list, &time_range) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let mut status_map: HashMap<enums::IntentStatus, i64> = intent_status_with_count.into_iter().collect(); for status in enums::IntentStatus::iter() { status_map.entry(status).or_default(); } Ok(services::ApplicationResponse::Json( api::PaymentsAggregateResponse { status_with_count: status_map, }, )) } #[cfg(feature = "v1")] pub async fn add_process_sync_task( db: &dyn StorageInterface, payment_attempt: &storage::PaymentAttempt, schedule_time: time::PrimitiveDateTime, ) -> CustomResult<(), errors::StorageError> { let tracking_data = api::PaymentsRetrieveRequest { force_sync: true, merchant_id: Some(payment_attempt.merchant_id.clone()), resource_id: api::PaymentIdType::PaymentAttemptId(payment_attempt.get_id().to_owned()), ..Default::default() }; let runner = storage::ProcessTrackerRunner::PaymentsSyncWorkflow; let task = "PAYMENTS_SYNC"; let tag = ["SYNC", "PAYMENT"]; let process_tracker_id = pt_utils::get_process_tracker_id( runner, task, payment_attempt.get_id(), &payment_attempt.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)?; db.insert_process(process_tracker_entry).await?; Ok(()) } #[cfg(feature = "v2")] pub async fn reset_process_sync_task( db: &dyn StorageInterface, payment_attempt: &storage::PaymentAttempt, schedule_time: time::PrimitiveDateTime, ) -> Result<(), errors::ProcessTrackerError> { todo!() } #[cfg(feature = "v1")] pub async fn reset_process_sync_task( db: &dyn StorageInterface, payment_attempt: &storage::PaymentAttempt, schedule_time: time::PrimitiveDateTime, ) -> Result<(), errors::ProcessTrackerError> { let runner = storage::ProcessTrackerRunner::PaymentsSyncWorkflow; let task = "PAYMENTS_SYNC"; let process_tracker_id = pt_utils::get_process_tracker_id( runner, task, payment_attempt.get_id(), &payment_attempt.merchant_id, ); let psync_process = db .find_process_by_id(&process_tracker_id) .await? .ok_or(errors::ProcessTrackerError::ProcessFetchingFailed)?; db.as_scheduler() .reset_process(psync_process, schedule_time) .await?; Ok(()) } #[cfg(feature = "v1")] pub fn update_straight_through_routing<F, D>( payment_data: &mut D, request_straight_through: serde_json::Value, ) -> CustomResult<(), errors::ParsingError> where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { let _: api_models::routing::RoutingAlgorithm = request_straight_through .clone() .parse_value("RoutingAlgorithm") .attach_printable("Invalid straight through routing rules format")?; payment_data.set_straight_through_algorithm_in_payment_attempt(request_straight_through); Ok(()) } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] 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) } 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(), )) } 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) } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] 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) } #[allow(clippy::too_many_arguments)] #[cfg(feature = "v2")] 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!() } #[allow(clippy::too_many_arguments)] #[cfg(feature = "v1")] 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, { // If the connector was already decided previously, use the same connector // This is in case of flows like payments_sync, payments_cancel where the successive operations // with the connector have to be made using the same connector account. if let Some(ref connector_name) = payment_data.get_payment_attempt().connector { // Connector was already decided previously, use the same connector let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, connector_name, api::GetToken::Connector, payment_data .get_payment_attempt() .merchant_connector_id .clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received in 'routed_through'")?; routing_data.routed_through = Some(connector_name.clone()); return Ok(ConnectorCallType::PreDetermined(connector_data)); } if let Some(mandate_connector_details) = payment_data.get_mandate_connector().as_ref() { let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &mandate_connector_details.connector, api::GetToken::Connector, mandate_connector_details.merchant_connector_id.clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received in 'routed_through'")?; routing_data.routed_through = Some(mandate_connector_details.connector.clone()); routing_data .merchant_connector_id .clone_from(&mandate_connector_details.merchant_connector_id); return Ok(ConnectorCallType::PreDetermined(connector_data)); } if let Some((pre_routing_results, storage_pm_type)) = routing_data.routing_info.pre_routing_results.as_ref().zip( payment_data .get_payment_attempt() .payment_method_type .as_ref(), ) { if let (Some(routable_connector_choice), None) = ( pre_routing_results.get(storage_pm_type), &payment_data.get_token_data(), ) { let routable_connector_list = match routable_connector_choice { storage::PreRoutingConnectorChoice::Single(routable_connector) => { vec![routable_connector.clone()] } storage::PreRoutingConnectorChoice::Multiple(routable_connector_list) => { routable_connector_list.clone() } }; let mut pre_routing_connector_data_list = vec![]; let first_routable_connector = routable_connector_list .first() .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?; routing_data.routed_through = Some(first_routable_connector.connector.to_string()); routing_data .merchant_connector_id .clone_from(&first_routable_connector.merchant_connector_id); for connector_choice in routable_connector_list.clone() { let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &connector_choice.connector.to_string(), api::GetToken::Connector, connector_choice.merchant_connector_id.clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received")?; pre_routing_connector_data_list.push(connector_data); } #[cfg(feature = "retry")] let should_do_retry = retry::config_should_call_gsm( &*state.store, merchant_account.get_id(), business_profile, ) .await; #[cfg(feature = "retry")] if payment_data.get_payment_attempt().payment_method_type == Some(storage_enums::PaymentMethodType::ApplePay) && should_do_retry { let retryable_connector_data = helpers::get_apple_pay_retryable_connectors( &state, merchant_account, payment_data, key_store, &pre_routing_connector_data_list, first_routable_connector .merchant_connector_id .clone() .as_ref(), business_profile.clone(), ) .await?; if let Some(connector_data_list) = retryable_connector_data { if connector_data_list.len() > 1 { logger::info!("Constructed apple pay retryable connector list"); return Ok(ConnectorCallType::Retryable(connector_data_list)); } } } let first_pre_routing_connector_data_list = pre_routing_connector_data_list .first() .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?; helpers::override_setup_future_usage_to_on_session(&*state.store, payment_data).await?; return Ok(ConnectorCallType::PreDetermined( first_pre_routing_connector_data_list.clone(), )); } } if let Some(routing_algorithm) = request_straight_through { let (mut connectors, check_eligibility) = routing::perform_straight_through_routing( &routing_algorithm, payment_data.get_creds_identifier(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed execution of straight through routing")?; if check_eligibility { let transaction_data = core_routing::PaymentsDslInput::new( payment_data.get_setup_mandate(), payment_data.get_payment_attempt(), payment_data.get_payment_intent(), payment_data.get_payment_method_data(), payment_data.get_address(), payment_data.get_recurring_details(), payment_data.get_currency(), ); connectors = routing::perform_eligibility_analysis_with_fallback( &state.clone(), key_store, connectors, &TransactionData::Payment(transaction_data), eligible_connectors, business_profile, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed eligibility analysis and fallback")?; } let connector_data = connectors .into_iter() .map(|conn| { api::ConnectorData::get_connector_by_name( &state.conf.connectors, &conn.connector.to_string(), api::GetToken::Connector, conn.merchant_connector_id.clone(), ) }) .collect::<CustomResult<Vec<_>, _>>() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received")?; return decide_multiplex_connector_for_normal_or_recurring_payment( &state, payment_data, routing_data, connector_data, mandate_type, business_profile.is_connector_agnostic_mit_enabled, business_profile.is_network_tokenization_enabled, ) .await; } if let Some(ref routing_algorithm) = routing_data.routing_info.algorithm { let (mut connectors, check_eligibility) = routing::perform_straight_through_routing( routing_algorithm, payment_data.get_creds_identifier(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed execution of straight through routing")?; if check_eligibility { let transaction_data = core_routing::PaymentsDslInput::new( payment_data.get_setup_mandate(), payment_data.get_payment_attempt(), payment_data.get_payment_intent(), payment_data.get_payment_method_data(), payment_data.get_address(), payment_data.get_recurring_details(), payment_data.get_currency(), ); connectors = routing::perform_eligibility_analysis_with_fallback( &state, key_store, connectors, &TransactionData::Payment(transaction_data), eligible_connectors, business_profile, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed eligibility analysis and fallback")?; } let connector_data = connectors .into_iter() .map(|conn| { api::ConnectorData::get_connector_by_name( &state.conf.connectors, &conn.connector.to_string(), api::GetToken::Connector, conn.merchant_connector_id, ) }) .collect::<CustomResult<Vec<_>, _>>() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received")?; return decide_multiplex_connector_for_normal_or_recurring_payment( &state, payment_data, routing_data, connector_data, mandate_type, business_profile.is_connector_agnostic_mit_enabled, business_profile.is_network_tokenization_enabled, ) .await; } let new_pd = payment_data.clone(); let transaction_data = core_routing::PaymentsDslInput::new( new_pd.get_setup_mandate(), new_pd.get_payment_attempt(), new_pd.get_payment_intent(), new_pd.get_payment_method_data(), new_pd.get_address(), new_pd.get_recurring_details(), new_pd.get_currency(), ); route_connector_v1_for_payments( &state, merchant_account, business_profile, key_store, payment_data, transaction_data, routing_data, eligible_connectors, mandate_type, ) .await } #[cfg(feature = "v2")] pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone, D>( state: &SessionState, payment_data: &mut D, routing_data: &mut storage::RoutingData, connectors: Vec<api::ConnectorData>, mandate_type: Option<api::MandateTransactionType>, is_connector_agnostic_mit_enabled: Option<bool>, ) -> RouterResult<ConnectorCallType> where D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { todo!() } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone, D>( state: &SessionState, payment_data: &mut D, routing_data: &mut storage::RoutingData, connectors: Vec<api::ConnectorData>, mandate_type: Option<api::MandateTransactionType>, is_connector_agnostic_mit_enabled: Option<bool>, is_network_tokenization_enabled: bool, ) -> RouterResult<ConnectorCallType> where D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { match ( payment_data.get_payment_intent().setup_future_usage, payment_data.get_token_data().as_ref(), payment_data.get_recurring_details().as_ref(), payment_data.get_payment_intent().off_session, mandate_type, ) { ( Some(storage_enums::FutureUsage::OffSession), Some(_), None, None, Some(api::MandateTransactionType::RecurringMandateTransaction), ) | ( None, None, Some(RecurringDetails::PaymentMethodId(_)), Some(true), Some(api::MandateTransactionType::RecurringMandateTransaction), ) | (None, Some(_), None, Some(true), _) => { logger::debug!("performing routing for token-based MIT flow"); let payment_method_info = payment_data .get_payment_method_info() .get_required_value("payment_method_info")? .clone(); //fetch connectors that support ntid flow let ntid_supported_connectors = &state .conf .network_transaction_id_supported_connectors .connector_list; //filered connectors list with ntid_supported_connectors let filtered_ntid_supported_connectors = filter_ntid_supported_connectors(connectors.clone(), ntid_supported_connectors); //fetch connectors that support network tokenization flow let network_tokenization_supported_connectors = &state .conf .network_tokenization_supported_connectors .connector_list; //filered connectors list with ntid_supported_connectors and network_tokenization_supported_connectors let filtered_nt_supported_connectors = filter_network_tokenization_supported_connectors( filtered_ntid_supported_connectors, network_tokenization_supported_connectors, ); let action_type = decide_action_type( state, is_connector_agnostic_mit_enabled, is_network_tokenization_enabled, &payment_method_info, filtered_nt_supported_connectors.clone(), ) .await; match action_type { Some(ActionType::NetworkTokenWithNetworkTransactionId(nt_data)) => { logger::info!( "using network_tokenization with network_transaction_id for MIT flow" ); let mandate_reference_id = Some(payments_api::MandateReferenceId::NetworkTokenWithNTI( payments_api::NetworkTokenWithNTIRef { network_transaction_id: nt_data.network_transaction_id.to_string(), token_exp_month: nt_data.token_exp_month, token_exp_year: nt_data.token_exp_year, }, )); let chosen_connector_data = filtered_nt_supported_connectors .first() .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) .attach_printable( "no eligible connector found for token-based MIT payment", )?; routing_data.routed_through = Some(chosen_connector_data.connector_name.to_string()); routing_data .merchant_connector_id .clone_from(&chosen_connector_data.merchant_connector_id); payment_data.set_mandate_id(payments_api::MandateIds { mandate_id: None, mandate_reference_id, }); Ok(ConnectorCallType::PreDetermined( chosen_connector_data.clone(), )) } None => { decide_connector_for_normal_or_recurring_payment( state, payment_data, routing_data, connectors, is_connector_agnostic_mit_enabled, &payment_method_info, ) .await } } } ( None, None, Some(RecurringDetails::ProcessorPaymentToken(_token)), Some(true), Some(api::MandateTransactionType::RecurringMandateTransaction), ) => { if let Some(connector) = connectors.first() { routing_data.routed_through = Some(connector.connector_name.clone().to_string()); routing_data .merchant_connector_id .clone_from(&connector.merchant_connector_id); Ok(ConnectorCallType::PreDetermined(api::ConnectorData { connector: connector.connector.clone(), connector_name: connector.connector_name, get_token: connector.get_token.clone(), merchant_connector_id: connector.merchant_connector_id.clone(), })) } else { logger::error!("no eligible connector found for the ppt_mandate payment"); Err(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration.into()) } } _ => { helpers::override_setup_future_usage_to_on_session(&*state.store, payment_data).await?; let first_choice = connectors .first() .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) .attach_printable("no eligible connector found for payment")? .clone(); routing_data.routed_through = Some(first_choice.connector_name.to_string()); routing_data.merchant_connector_id = first_choice.merchant_connector_id; Ok(ConnectorCallType::Retryable(connectors)) } } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[allow(clippy::too_many_arguments)] pub async fn decide_connector_for_normal_or_recurring_payment<F: Clone, D>( state: &SessionState, payment_data: &mut D, routing_data: &mut storage::RoutingData, connectors: Vec<api::ConnectorData>, is_connector_agnostic_mit_enabled: Option<bool>, payment_method_info: &domain::PaymentMethod, ) -> RouterResult<ConnectorCallType> where D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { todo!() } #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") ))] #[allow(clippy::too_many_arguments)] pub async fn decide_connector_for_normal_or_recurring_payment<F: Clone, D>( state: &SessionState, payment_data: &mut D, routing_data: &mut storage::RoutingData, connectors: Vec<api::ConnectorData>, is_connector_agnostic_mit_enabled: Option<bool>, payment_method_info: &domain::PaymentMethod, ) -> RouterResult<ConnectorCallType> where D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { let connector_common_mandate_details = payment_method_info .get_common_mandate_reference() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the common mandate reference")?; let connector_mandate_details = connector_common_mandate_details.payments; let mut connector_choice = None; for connector_data in connectors { let merchant_connector_id = connector_data .merchant_connector_id .as_ref() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to find the merchant connector id")?; if connector_mandate_details .clone() .map(|connector_mandate_details| { connector_mandate_details.contains_key(merchant_connector_id) }) .unwrap_or(false) { logger::info!("using connector_mandate_id for MIT flow"); if let Some(merchant_connector_id) = connector_data.merchant_connector_id.as_ref() { if let Some(mandate_reference_record) = connector_mandate_details.clone() .get_required_value("connector_mandate_details") .change_context(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) .attach_printable("no eligible connector found for token-based MIT flow since there were no connector mandate details")? .get(merchant_connector_id) { common_utils::fp_utils::when( mandate_reference_record .original_payment_authorized_currency .map(|mandate_currency| mandate_currency != payment_data.get_currency()) .unwrap_or(false), || { Err(report!(errors::ApiErrorResponse::MandateValidationFailed { reason: "cross currency mandates not supported".into() })) }, )?; let mandate_reference_id = Some(payments_api::MandateReferenceId::ConnectorMandateId( api_models::payments::ConnectorMandateReferenceId::new( Some(mandate_reference_record.connector_mandate_id.clone()), // connector_mandate_id Some(payment_method_info.get_id().clone()), // payment_method_id None, // update_history mandate_reference_record.mandate_metadata.clone(), // mandate_metadata mandate_reference_record.connector_mandate_request_reference_id.clone(), // connector_mandate_request_reference_id ) )); payment_data.set_recurring_mandate_payment_data( hyperswitch_domain_models::router_data::RecurringMandatePaymentData { payment_method_type: mandate_reference_record .payment_method_type, original_payment_authorized_amount: mandate_reference_record .original_payment_authorized_amount, original_payment_authorized_currency: mandate_reference_record .original_payment_authorized_currency, mandate_metadata: mandate_reference_record .mandate_metadata.clone() }); connector_choice = Some((connector_data, mandate_reference_id.clone())); break; } } } else if is_network_transaction_id_flow( state, is_connector_agnostic_mit_enabled, connector_data.connector_name, payment_method_info, ) { logger::info!("using network_transaction_id for MIT flow"); let network_transaction_id = payment_method_info .network_transaction_id .as_ref() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to fetch the network transaction id")?; let mandate_reference_id = Some(payments_api::MandateReferenceId::NetworkMandateId( network_transaction_id.to_string(), )); connector_choice = Some((connector_data, mandate_reference_id.clone())); break; } else { continue; } } let (chosen_connector_data, mandate_reference_id) = connector_choice .get_required_value("connector_choice") .change_context(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) .attach_printable("no eligible connector found for token-based MIT payment")?; routing_data.routed_through = Some(chosen_connector_data.connector_name.to_string()); routing_data .merchant_connector_id .clone_from(&chosen_connector_data.merchant_connector_id); payment_data.set_mandate_id(payments_api::MandateIds { mandate_id: None, mandate_reference_id, }); Ok(ConnectorCallType::PreDetermined(chosen_connector_data)) } pub fn filter_ntid_supported_connectors( connectors: Vec<api::ConnectorData>, ntid_supported_connectors: &HashSet<enums::Connector>, ) -> Vec<api::ConnectorData> { connectors .into_iter() .filter(|data| ntid_supported_connectors.contains(&data.connector_name)) .collect() } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct NetworkTokenExpiry { pub token_exp_month: Option<Secret<String>>, pub token_exp_year: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct NTWithNTIRef { pub network_transaction_id: String, pub token_exp_month: Option<Secret<String>>, pub token_exp_year: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub enum ActionType { NetworkTokenWithNetworkTransactionId(NTWithNTIRef), } pub fn filter_network_tokenization_supported_connectors( connectors: Vec<api::ConnectorData>, network_tokenization_supported_connectors: &HashSet<enums::Connector>, ) -> Vec<api::ConnectorData> { connectors .into_iter() .filter(|data| network_tokenization_supported_connectors.contains(&data.connector_name)) .collect() } #[cfg(feature = "v1")] pub async fn decide_action_type( state: &SessionState, is_connector_agnostic_mit_enabled: Option<bool>, is_network_tokenization_enabled: bool, payment_method_info: &domain::PaymentMethod, filtered_nt_supported_connectors: Vec<api::ConnectorData>, //network tokenization supported connectors ) -> Option<ActionType> { match ( is_network_token_with_network_transaction_id_flow( is_connector_agnostic_mit_enabled, is_network_tokenization_enabled, payment_method_info, ), !filtered_nt_supported_connectors.is_empty(), ) { (IsNtWithNtiFlow::NtWithNtiSupported(network_transaction_id), true) => { if let Ok((token_exp_month, token_exp_year)) = network_tokenization::do_status_check_for_network_token(state, payment_method_info) .await { Some(ActionType::NetworkTokenWithNetworkTransactionId( NTWithNTIRef { token_exp_month, token_exp_year, network_transaction_id, }, )) } else { None } } (IsNtWithNtiFlow::NtWithNtiSupported(_), false) | (IsNtWithNtiFlow::NTWithNTINotSupported, _) => None, } } pub fn is_network_transaction_id_flow( state: &SessionState, is_connector_agnostic_mit_enabled: Option<bool>, connector: enums::Connector, payment_method_info: &domain::PaymentMethod, ) -> bool { let ntid_supported_connectors = &state .conf .network_transaction_id_supported_connectors .connector_list; is_connector_agnostic_mit_enabled == Some(true) && payment_method_info.get_payment_method_type() == Some(storage_enums::PaymentMethod::Card) && ntid_supported_connectors.contains(&connector) && payment_method_info.network_transaction_id.is_some() } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub enum IsNtWithNtiFlow { NtWithNtiSupported(String), //Network token with Network transaction id supported flow NTWithNTINotSupported, //Network token with Network transaction id not supported } pub fn is_network_token_with_network_transaction_id_flow( is_connector_agnostic_mit_enabled: Option<bool>, is_network_tokenization_enabled: bool, payment_method_info: &domain::PaymentMethod, ) -> IsNtWithNtiFlow { match ( is_connector_agnostic_mit_enabled, is_network_tokenization_enabled, payment_method_info.get_payment_method_type(), payment_method_info.network_transaction_id.clone(), payment_method_info.network_token_locker_id.is_some(), payment_method_info .network_token_requestor_reference_id .is_some(), ) { ( Some(true), true, Some(storage_enums::PaymentMethod::Card), Some(network_transaction_id), true, true, ) => IsNtWithNtiFlow::NtWithNtiSupported(network_transaction_id), _ => IsNtWithNtiFlow::NTWithNTINotSupported, } } pub fn should_add_task_to_process_tracker<F: Clone, D: OperationSessionGetters<F>>( payment_data: &D, ) -> bool { let connector = payment_data.get_payment_attempt().connector.as_deref(); !matches!( ( payment_data.get_payment_attempt().get_payment_method(), connector ), ( Some(storage_enums::PaymentMethod::BankTransfer), Some("stripe") ) ) } #[cfg(feature = "v1")] pub async fn perform_session_token_routing<F, D>( state: SessionState, merchant_account: &domain::MerchantAccount, business_profile: &domain::Profile, key_store: &domain::MerchantKeyStore, payment_data: &D, connectors: api::SessionConnectorDatas, ) -> RouterResult<api::SessionConnectorDatas> where F: Clone, D: OperationSessionGetters<F>, { // Commenting out this code as `list_payment_method_api` and `perform_session_token_routing` // will happen in parallel the behaviour of the session call differ based on filters in // list_payment_method_api // let routing_info: Option<storage::PaymentRoutingInfo> = payment_data // .get_payment_attempt() // .straight_through_algorithm // .clone() // .map(|val| val.parse_value("PaymentRoutingInfo")) // .transpose() // .change_context(errors::ApiErrorResponse::InternalServerError) // .attach_printable("invalid payment routing info format found in payment attempt")?; // if let Some(storage::PaymentRoutingInfo { // pre_routing_results: Some(pre_routing_results), // .. // }) = routing_info // { // let mut payment_methods: rustc_hash::FxHashMap< // (String, enums::PaymentMethodType), // api::SessionConnectorData, // > = rustc_hash::FxHashMap::from_iter(connectors.iter().map(|c| { // ( // ( // c.connector.connector_name.to_string(), // c.payment_method_type, // ), // c.clone(), // ) // })); // let mut final_list: api::SessionConnectorDatas = Vec::new(); // for (routed_pm_type, pre_routing_choice) in pre_routing_results.into_iter() { // let routable_connector_list = match pre_routing_choice { // storage::PreRoutingConnectorChoice::Single(routable_connector) => { // vec![routable_connector.clone()] // } // storage::PreRoutingConnectorChoice::Multiple(routable_connector_list) => { // routable_connector_list.clone() // } // }; // for routable_connector in routable_connector_list { // if let Some(session_connector_data) = // payment_methods.remove(&(routable_connector.to_string(), routed_pm_type)) // { // final_list.push(session_connector_data); // break; // } // } // } // if !final_list.is_empty() { // return Ok(final_list); // } // } let chosen = connectors.apply_filter_for_session_routing(); let sfr = SessionFlowRoutingInput { state: &state, country: payment_data .get_address() .get_payment_method_billing() .and_then(|address| address.address.as_ref()) .and_then(|details| details.country), key_store, merchant_account, payment_attempt: payment_data.get_payment_attempt(), payment_intent: payment_data.get_payment_intent(), chosen, }; let result = self_routing::perform_session_flow_routing( sfr, business_profile, &enums::TransactionType::Payment, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error performing session flow routing")?; let final_list = connectors.filter_and_validate_for_session_flow(&result)?; Ok(final_list) } pub struct SessionTokenRoutingResult { pub final_result: api::SessionConnectorDatas, pub routing_result: FxHashMap<common_enums::PaymentMethodType, Vec<api::routing::SessionRoutingChoice>>, } #[cfg(feature = "v2")] pub async fn perform_session_token_routing<F, D>( state: SessionState, business_profile: &domain::Profile, key_store: &domain::MerchantKeyStore, payment_data: &D, connectors: api::SessionConnectorDatas, ) -> RouterResult<SessionTokenRoutingResult> where F: Clone, D: OperationSessionGetters<F>, { let chosen = connectors.apply_filter_for_session_routing(); let sfr = SessionFlowRoutingInput { country: payment_data .get_payment_intent() .billing_address .as_ref() .and_then(|address| address.get_inner().address.as_ref()) .and_then(|details| details.country), payment_intent: payment_data.get_payment_intent(), chosen, }; let result = self_routing::perform_session_flow_routing( &state, key_store, sfr, business_profile, &enums::TransactionType::Payment, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error performing session flow routing")?; let final_list = connectors.filter_and_validate_for_session_flow(&result)?; Ok(SessionTokenRoutingResult { final_result: final_list, routing_result: result, }) } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn route_connector_v1_for_payments<F, D>( state: &SessionState, merchant_account: &domain::MerchantAccount, business_profile: &domain::Profile, key_store: &domain::MerchantKeyStore, payment_data: &mut D, transaction_data: core_routing::PaymentsDslInput<'_>, 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, { let routing_algorithm_id = { let routing_algorithm = business_profile.routing_algorithm.clone(); let algorithm_ref = routing_algorithm .map(|ra| ra.parse_value::<api::routing::RoutingAlgorithmRef>("RoutingAlgorithmRef")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not decode merchant routing algorithm ref")? .unwrap_or_default(); algorithm_ref.algorithm_id }; let connectors = routing::perform_static_routing_v1( state, merchant_account.get_id(), routing_algorithm_id.as_ref(), business_profile, &TransactionData::Payment(transaction_data.clone()), ) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; let connectors = routing::perform_eligibility_analysis_with_fallback( &state.clone(), key_store, connectors, &TransactionData::Payment(transaction_data), eligible_connectors, business_profile, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed eligibility analysis and fallback")?; // dynamic success based connector selection #[cfg(all(feature = "v1", feature = "dynamic_routing"))] let connectors = { if let Some(algo) = business_profile.dynamic_routing_algorithm.clone() { let dynamic_routing_config: api_models::routing::DynamicRoutingAlgorithmRef = algo .parse_value("DynamicRoutingAlgorithmRef") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")?; let dynamic_split = api_models::routing::RoutingVolumeSplit { routing_type: api_models::routing::RoutingType::Dynamic, split: dynamic_routing_config .dynamic_routing_volume_split .unwrap_or_default(), }; let static_split: api_models::routing::RoutingVolumeSplit = api_models::routing::RoutingVolumeSplit { routing_type: api_models::routing::RoutingType::Static, split: consts::DYNAMIC_ROUTING_MAX_VOLUME - dynamic_routing_config .dynamic_routing_volume_split .unwrap_or_default(), }; let volume_split_vec = vec![dynamic_split, static_split]; let routing_choice = routing::perform_dynamic_routing_volume_split(volume_split_vec, None) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to perform volume split on routing type")?; if routing_choice.routing_type.is_dynamic_routing() { let dynamic_routing_config_params_interpolator = routing_helpers::DynamicRoutingConfigParamsInterpolator::new( payment_data.get_payment_attempt().payment_method, payment_data.get_payment_attempt().payment_method_type, payment_data.get_payment_attempt().authentication_type, payment_data.get_payment_attempt().currency, payment_data .get_billing_address() .and_then(|address| address.address) .and_then(|address| address.country), payment_data .get_payment_attempt() .payment_method_data .as_ref() .and_then(|data| data.as_object()) .and_then(|card| card.get("card")) .and_then(|data| data.as_object()) .and_then(|card| card.get("card_network")) .and_then(|network| network.as_str()) .map(|network| network.to_string()), payment_data .get_payment_attempt() .payment_method_data .as_ref() .and_then(|data| data.as_object()) .and_then(|card| card.get("card")) .and_then(|data| data.as_object()) .and_then(|card| card.get("card_isin")) .and_then(|card_isin| card_isin.as_str()) .map(|card_isin| card_isin.to_string()), ); routing::perform_dynamic_routing( state, connectors.clone(), business_profile, dynamic_routing_config_params_interpolator, ) .await .map_err(|e| logger::error!(dynamic_routing_error=?e)) .unwrap_or(connectors) } else { connectors } } else { connectors } }; let connector_data = connectors .into_iter() .map(|conn| { api::ConnectorData::get_connector_by_name( &state.conf.connectors, &conn.connector.to_string(), api::GetToken::Connector, conn.merchant_connector_id, ) }) .collect::<CustomResult<Vec<_>, _>>() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received")?; decide_multiplex_connector_for_normal_or_recurring_payment( state, payment_data, routing_data, connector_data, mandate_type, business_profile.is_connector_agnostic_mit_enabled, business_profile.is_network_tokenization_enabled, ) .await } #[cfg(feature = "payouts")] #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] pub async fn route_connector_v1_for_payouts( state: &SessionState, merchant_account: &domain::MerchantAccount, business_profile: &domain::Profile, key_store: &domain::MerchantKeyStore, transaction_data: &payouts::PayoutData, routing_data: &mut storage::RoutingData, eligible_connectors: Option<Vec<enums::RoutableConnectors>>, ) -> RouterResult<ConnectorCallType> { todo!() } #[cfg(feature = "payouts")] #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn route_connector_v1_for_payouts( state: &SessionState, merchant_account: &domain::MerchantAccount, business_profile: &domain::Profile, key_store: &domain::MerchantKeyStore, transaction_data: &payouts::PayoutData, routing_data: &mut storage::RoutingData, eligible_connectors: Option<Vec<enums::RoutableConnectors>>, ) -> RouterResult<ConnectorCallType> { let routing_algorithm_id = { let routing_algorithm = business_profile.payout_routing_algorithm.clone(); let algorithm_ref = routing_algorithm .map(|ra| ra.parse_value::<api::routing::RoutingAlgorithmRef>("RoutingAlgorithmRef")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not decode merchant routing algorithm ref")? .unwrap_or_default(); algorithm_ref.algorithm_id }; let connectors = routing::perform_static_routing_v1( state, merchant_account.get_id(), routing_algorithm_id.as_ref(), business_profile, &TransactionData::Payout(transaction_data), ) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; let connectors = routing::perform_eligibility_analysis_with_fallback( &state.clone(), key_store, connectors, &TransactionData::Payout(transaction_data), eligible_connectors, business_profile, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed eligibility analysis and fallback")?; let first_connector_choice = connectors .first() .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) .attach_printable("Empty connector list returned")? .clone(); let connector_data = connectors .into_iter() .map(|conn| { api::ConnectorData::get_connector_by_name( &state.conf.connectors, &conn.connector.to_string(), api::GetToken::Connector, conn.merchant_connector_id, ) }) .collect::<CustomResult<Vec<_>, _>>() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received")?; routing_data.routed_through = Some(first_connector_choice.connector.to_string()); routing_data.merchant_connector_id = first_connector_choice.merchant_connector_id; Ok(ConnectorCallType::Retryable(connector_data)) } #[cfg(all(feature = "v2", feature = "customer_v2"))] pub async fn payment_external_authentication( _state: SessionState, _merchant_account: domain::MerchantAccount, _key_store: domain::MerchantKeyStore, _req: api_models::payments::PaymentsExternalAuthenticationRequest, ) -> RouterResponse<api_models::payments::PaymentsExternalAuthenticationResponse> { todo!() } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all)] pub async fn payment_external_authentication<F: Clone + Sync>( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: api_models::payments::PaymentsExternalAuthenticationRequest, ) -> RouterResponse<api_models::payments::PaymentsExternalAuthenticationResponse> { use super::unified_authentication_service::types::ExternalAuthentication; use crate::core::unified_authentication_service::{ types::UnifiedAuthenticationService, utils::external_authentication_update_trackers, }; let db = &*state.store; let key_manager_state = &(&state).into(); let merchant_id = merchant_account.get_id(); let storage_scheme = merchant_account.storage_scheme; let payment_id = req.payment_id; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( key_manager_state, &payment_id, merchant_id, &key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let attempt_id = payment_intent.active_attempt.get_id().clone(); let payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, merchant_id, &attempt_id.clone(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; if payment_attempt.external_three_ds_authentication_attempted != Some(true) { Err(errors::ApiErrorResponse::PreconditionFailed { message: "You cannot authenticate this payment because payment_attempt.external_three_ds_authentication_attempted is false".to_owned(), })? } helpers::validate_payment_status_against_allowed_statuses( payment_intent.status, &[storage_enums::IntentStatus::RequiresCustomerAction], "authenticate", )?; let optional_customer = match &payment_intent.customer_id { Some(customer_id) => Some( state .store .find_customer_by_customer_id_merchant_id( key_manager_state, customer_id, merchant_account.get_id(), &key_store, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!("error while finding customer with customer_id {customer_id:?}") })?, ), None => None, }; let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; let currency = payment_attempt.currency.get_required_value("currency")?; let amount = payment_attempt.get_total_amount(); let shipping_address = helpers::create_or_find_address_for_payment_by_request( &state, None, payment_intent.shipping_address_id.as_deref(), merchant_id, payment_intent.customer_id.as_ref(), &key_store, &payment_intent.payment_id, storage_scheme, ) .await?; let billing_address = helpers::create_or_find_address_for_payment_by_request( &state, None, payment_attempt .payment_method_billing_address_id .as_deref() .or(payment_intent.billing_address_id.as_deref()), merchant_id, payment_intent.customer_id.as_ref(), &key_store, &payment_intent.payment_id, storage_scheme, ) .await?; let authentication_connector = payment_attempt .authentication_connector .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("authentication_connector not found in payment_attempt")?; let merchant_connector_account = helpers::get_merchant_connector_account( &state, merchant_id, None, &key_store, profile_id, authentication_connector.as_str(), None, ) .await?; let authentication = db .find_authentication_by_merchant_id_authentication_id( merchant_id, payment_attempt .authentication_id .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing authentication_id in payment_attempt")?, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while fetching authentication record")?; let business_profile = state .store .find_business_profile_by_profile_id(key_manager_state, &key_store, profile_id) .await .change_context(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let payment_method_details = helpers::get_payment_method_details_from_payment_token( &state, &payment_attempt, &payment_intent, &key_store, storage_scheme, ) .await? .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing payment_method_details")?; let browser_info: Option<BrowserInformation> = payment_attempt .browser_info .clone() .map(|browser_information| browser_information.parse_value("BrowserInformation")) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "browser_info", })?; let payment_connector_name = payment_attempt .connector .as_ref() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing connector in payment_attempt")?; let return_url = Some(helpers::create_authorize_url( &state.base_url, &payment_attempt.clone(), payment_connector_name, )); let mca_id_option = merchant_connector_account.get_mca_id(); // Bind temporary value let merchant_connector_account_id_or_connector_name = mca_id_option .as_ref() .map(|mca_id| mca_id.get_string_repr()) .unwrap_or(&authentication_connector); let webhook_url = helpers::create_webhook_url( &state.base_url, merchant_id, merchant_connector_account_id_or_connector_name, ); let authentication_details = business_profile .authentication_connector_details .clone() .get_required_value("authentication_connector_details") .attach_printable("authentication_connector_details not configured by the merchant")?; let authentication_response = if helpers::is_merchant_eligible_authentication_service(merchant_account.get_id(), &state) .await? { let auth_response = <ExternalAuthentication as UnifiedAuthenticationService<F>>::authentication( &state, &business_profile, payment_method_details.1, payment_method_details.0, billing_address .as_ref() .map(|address| address.into()) .ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "billing_address", })?, shipping_address.as_ref().map(|address| address.into()), browser_info, Some(amount), Some(currency), authentication::MessageCategory::Payment, req.device_channel, authentication.clone(), return_url, req.sdk_information, req.threeds_method_comp_ind, optional_customer.and_then(|customer| customer.email.map(pii::Email::from)), webhook_url, authentication_details.three_ds_requestor_url.clone(), &merchant_connector_account, &authentication_connector, payment_intent.payment_id, ) .await?; let authentication = external_authentication_update_trackers( &state, auth_response, authentication.clone(), None, ) .await?; authentication::AuthenticationResponse::try_from(authentication)? } else { Box::pin(authentication_core::perform_authentication( &state, business_profile.merchant_id, authentication_connector, payment_method_details.0, payment_method_details.1, billing_address .as_ref() .map(|address| address.into()) .ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "billing_address", })?, shipping_address.as_ref().map(|address| address.into()), browser_info, merchant_connector_account, Some(amount), Some(currency), authentication::MessageCategory::Payment, req.device_channel, authentication, return_url, req.sdk_information, req.threeds_method_comp_ind, optional_customer.and_then(|customer| customer.email.map(pii::Email::from)), webhook_url, authentication_details.three_ds_requestor_url.clone(), payment_intent.psd2_sca_exemption_type, payment_intent.payment_id, payment_intent.force_3ds_challenge_trigger.unwrap_or(false), )) .await? }; Ok(services::ApplicationResponse::Json( api_models::payments::PaymentsExternalAuthenticationResponse { transaction_status: authentication_response.trans_status, acs_url: authentication_response .acs_url .as_ref() .map(ToString::to_string), challenge_request: authentication_response.challenge_request, acs_reference_number: authentication_response.acs_reference_number, acs_trans_id: authentication_response.acs_trans_id, three_dsserver_trans_id: authentication_response.three_dsserver_trans_id, acs_signed_content: authentication_response.acs_signed_content, three_ds_requestor_url: authentication_details.three_ds_requestor_url, three_ds_requestor_app_url: authentication_details.three_ds_requestor_app_url, }, )) } #[instrument(skip_all)] #[cfg(feature = "v2")] pub async fn payment_start_redirection( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: api_models::payments::PaymentStartRedirectionRequest, ) -> RouterResponse<serde_json::Value> { let db = &*state.store; let key_manager_state = &(&state).into(); let storage_scheme = merchant_account.storage_scheme; let payment_intent = db .find_payment_intent_by_id(key_manager_state, &req.id, &key_store, storage_scheme) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; //TODO: send valid html error pages in this case, or atleast redirect to valid html error pages utils::when( payment_intent.status != storage_enums::IntentStatus::RequiresCustomerAction, || { Err(errors::ApiErrorResponse::PaymentUnexpectedState { current_flow: "PaymentStartRedirection".to_string(), field_name: "status".to_string(), current_value: payment_intent.status.to_string(), states: ["requires_customer_action".to_string()].join(", "), }) }, )?; let payment_attempt = db .find_payment_attempt_by_id( key_manager_state, &key_store, payment_intent .active_attempt_id .as_ref() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing active attempt in payment_intent")?, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while fetching payment_attempt")?; let redirection_data = payment_attempt .redirection_data .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing authentication_data in payment_attempt")?; Ok(services::ApplicationResponse::Form(Box::new( services::RedirectionFormData { redirect_form: redirection_data, payment_method_data: None, amount: payment_attempt.amount_details.get_net_amount().to_string(), currency: payment_intent.amount_details.currency.to_string(), }, ))) } #[instrument(skip_all)] pub async fn get_extended_card_info( state: SessionState, merchant_id: id_type::MerchantId, payment_id: id_type::PaymentId, ) -> RouterResponse<payments_api::ExtendedCardInfoResponse> { let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let key = helpers::get_redis_key_for_extended_card_info(&merchant_id, &payment_id); let payload = redis_conn .get_key::<String>(&key.into()) .await .change_context(errors::ApiErrorResponse::ExtendedCardInfoNotFound)?; Ok(services::ApplicationResponse::Json( payments_api::ExtendedCardInfoResponse { payload }, )) } #[cfg(all(feature = "olap", feature = "v1"))] pub async fn payments_manual_update( state: SessionState, req: api_models::payments::PaymentsManualUpdateRequest, ) -> RouterResponse<api_models::payments::PaymentsManualUpdateResponse> { let api_models::payments::PaymentsManualUpdateRequest { payment_id, attempt_id, merchant_id, attempt_status, error_code, error_message, error_reason, connector_transaction_id, } = req; let key_manager_state = &(&state).into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) .attach_printable("Error while fetching the key store by merchant_id")?; let merchant_account = state .store .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) .attach_printable("Error while fetching the merchant_account by merchant_id")?; let payment_attempt = state .store .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_id, &merchant_id, &attempt_id.clone(), merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) .attach_printable( "Error while fetching the payment_attempt by payment_id, merchant_id and attempt_id", )?; let payment_intent = state .store .find_payment_intent_by_payment_id_merchant_id( key_manager_state, &payment_id, merchant_account.get_id(), &key_store, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) .attach_printable("Error while fetching the payment_intent by payment_id, merchant_id")?; let option_gsm = if let Some(((code, message), connector_name)) = error_code .as_ref() .zip(error_message.as_ref()) .zip(payment_attempt.connector.as_ref()) { helpers::get_gsm_record( &state, Some(code.to_string()), Some(message.to_string()), connector_name.to_string(), // We need to get the unified_code and unified_message of the Authorize flow "Authorize".to_string(), ) .await } else { None }; // Update the payment_attempt let attempt_update = storage::PaymentAttemptUpdate::ManualUpdate { status: attempt_status, error_code, error_message, error_reason, updated_by: merchant_account.storage_scheme.to_string(), unified_code: option_gsm.as_ref().and_then(|gsm| gsm.unified_code.clone()), unified_message: option_gsm.and_then(|gsm| gsm.unified_message), connector_transaction_id, }; let updated_payment_attempt = state .store .update_payment_attempt_with_attempt_id( payment_attempt.clone(), attempt_update, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) .attach_printable("Error while updating the payment_attempt")?; // If the payment_attempt is active attempt for an intent, update the intent status if payment_intent.active_attempt.get_id() == payment_attempt.attempt_id { let intent_status = enums::IntentStatus::foreign_from(updated_payment_attempt.status); let payment_intent_update = storage::PaymentIntentUpdate::ManualUpdate { status: Some(intent_status), updated_by: merchant_account.storage_scheme.to_string(), }; state .store .update_payment_intent( key_manager_state, payment_intent, payment_intent_update, &key_store, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) .attach_printable("Error while updating payment_intent")?; } Ok(services::ApplicationResponse::Json( api_models::payments::PaymentsManualUpdateResponse { payment_id: updated_payment_attempt.payment_id, attempt_id: updated_payment_attempt.attempt_id, merchant_id: updated_payment_attempt.merchant_id, attempt_status: updated_payment_attempt.status, error_code: updated_payment_attempt.error_code, error_message: updated_payment_attempt.error_message, error_reason: updated_payment_attempt.error_reason, connector_transaction_id: updated_payment_attempt.connector_transaction_id, }, )) } pub trait PaymentMethodChecker<F> { fn should_update_in_post_update_tracker(&self) -> bool; fn should_update_in_update_tracker(&self) -> bool; } #[cfg(feature = "v1")] impl<F: Clone> PaymentMethodChecker<F> for PaymentData<F> { fn should_update_in_post_update_tracker(&self) -> bool { let payment_method_type = self .payment_intent .tax_details .as_ref() .and_then(|tax_details| tax_details.payment_method_type.as_ref().map(|pmt| pmt.pmt)); matches!( payment_method_type, Some(storage_enums::PaymentMethodType::Paypal) ) } fn should_update_in_update_tracker(&self) -> bool { let payment_method_type = self .payment_intent .tax_details .as_ref() .and_then(|tax_details| tax_details.payment_method_type.as_ref().map(|pmt| pmt.pmt)); matches!( payment_method_type, Some(storage_enums::PaymentMethodType::ApplePay) | Some(storage_enums::PaymentMethodType::GooglePay) ) } } 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>; } 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); } #[cfg(feature = "v1")] impl<F: Clone> OperationSessionGetters<F> for PaymentData<F> { fn get_payment_attempt(&self) -> &storage::PaymentAttempt { &self.payment_attempt } fn get_payment_intent(&self) -> &storage::PaymentIntent { &self.payment_intent } fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod> { self.payment_method_info.as_ref() } fn get_mandate_id(&self) -> Option<&payments_api::MandateIds> { self.mandate_id.as_ref() } // what is this address find out and not required remove this fn get_address(&self) -> &PaymentAddress { &self.address } fn get_merchant_connector_id_in_attempt(&self) -> Option<id_type::MerchantConnectorAccountId> { self.payment_attempt.merchant_connector_id.clone() } fn get_creds_identifier(&self) -> Option<&str> { self.creds_identifier.as_deref() } fn get_token(&self) -> Option<&str> { self.token.as_deref() } fn get_multiple_capture_data(&self) -> Option<&types::MultipleCaptureData> { self.multiple_capture_data.as_ref() } fn get_payment_link_data(&self) -> Option<api_models::payments::PaymentLinkResponse> { self.payment_link_data.clone() } fn get_ephemeral_key(&self) -> Option<ephemeral_key::EphemeralKey> { self.ephemeral_key.clone() } fn get_setup_mandate(&self) -> Option<&MandateData> { self.setup_mandate.as_ref() } fn get_poll_config(&self) -> Option<router_types::PollConfig> { self.poll_config.clone() } fn get_authentication(&self) -> Option<&storage::Authentication> { self.authentication.as_ref() } fn get_frm_message(&self) -> Option<FraudCheck> { self.frm_message.clone() } fn get_refunds(&self) -> Vec<storage::Refund> { self.refunds.clone() } fn get_disputes(&self) -> Vec<storage::Dispute> { self.disputes.clone() } fn get_authorizations(&self) -> Vec<diesel_models::authorization::Authorization> { self.authorizations.clone() } fn get_attempts(&self) -> Option<Vec<storage::PaymentAttempt>> { self.attempts.clone() } fn get_recurring_details(&self) -> Option<&RecurringDetails> { self.recurring_details.as_ref() } #[cfg(feature = "v1")] fn get_payment_intent_profile_id(&self) -> Option<&id_type::ProfileId> { self.payment_intent.profile_id.as_ref() } #[cfg(feature = "v2")] fn get_payment_intent_profile_id(&self) -> Option<&id_type::ProfileId> { Some(&self.payment_intent.profile_id) } fn get_currency(&self) -> storage_enums::Currency { self.currency } fn get_amount(&self) -> api::Amount { self.amount } fn get_payment_attempt_connector(&self) -> Option<&str> { self.payment_attempt.connector.as_deref() } fn get_billing_address(&self) -> Option<hyperswitch_domain_models::address::Address> { self.address.get_payment_method_billing().cloned() } fn get_payment_method_data(&self) -> Option<&domain::PaymentMethodData> { self.payment_method_data.as_ref() } fn get_sessions_token(&self) -> Vec<api::SessionToken> { self.sessions_token.clone() } fn get_token_data(&self) -> Option<&storage::PaymentTokenData> { self.token_data.as_ref() } fn get_mandate_connector(&self) -> Option<&MandateConnectorDetails> { self.mandate_connector.as_ref() } fn get_force_sync(&self) -> Option<bool> { self.force_sync } #[cfg(feature = "v1")] fn get_capture_method(&self) -> Option<enums::CaptureMethod> { self.payment_attempt.capture_method } #[cfg(feature = "v1")] fn get_vault_operation(&self) -> Option<&domain_payments::VaultOperation> { self.vault_operation.as_ref() } // #[cfg(feature = "v2")] // fn get_capture_method(&self) -> Option<enums::CaptureMethod> { // Some(self.payment_intent.capture_method) // } // #[cfg(feature = "v2")] // fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt> { // todo!(); // } } #[cfg(feature = "v1")] impl<F: Clone> OperationSessionSetters<F> for PaymentData<F> { // Setters Implementation fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { self.payment_intent = payment_intent; } fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) { self.payment_attempt = payment_attempt; } fn set_payment_method_data(&mut self, payment_method_data: Option<domain::PaymentMethodData>) { self.payment_method_data = payment_method_data; } fn set_payment_method_id_in_attempt(&mut self, payment_method_id: Option<String>) { self.payment_attempt.payment_method_id = payment_method_id; } fn set_email_if_not_present(&mut self, email: pii::Email) { self.email = self.email.clone().or(Some(email)); } fn set_pm_token(&mut self, token: String) { self.pm_token = Some(token); } fn set_connector_customer_id(&mut self, customer_id: Option<String>) { self.connector_customer_id = customer_id; } fn push_sessions_token(&mut self, token: api::SessionToken) { self.sessions_token.push(token); } fn set_surcharge_details(&mut self, surcharge_details: Option<types::SurchargeDetails>) { self.surcharge_details = surcharge_details; } fn set_merchant_connector_id_in_attempt( &mut self, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, ) { self.payment_attempt.merchant_connector_id = merchant_connector_id; } #[cfg(feature = "v1")] fn set_capture_method_in_attempt(&mut self, capture_method: enums::CaptureMethod) { self.payment_attempt.capture_method = Some(capture_method); } fn set_frm_message(&mut self, frm_message: FraudCheck) { self.frm_message = Some(frm_message); } fn set_payment_intent_status(&mut self, status: storage_enums::IntentStatus) { self.payment_intent.status = status; } fn set_authentication_type_in_attempt( &mut self, authentication_type: Option<enums::AuthenticationType>, ) { self.payment_attempt.authentication_type = authentication_type; } fn set_recurring_mandate_payment_data( &mut self, recurring_mandate_payment_data: hyperswitch_domain_models::router_data::RecurringMandatePaymentData, ) { self.recurring_mandate_payment_data = Some(recurring_mandate_payment_data); } fn set_mandate_id(&mut self, mandate_id: api_models::payments::MandateIds) { self.mandate_id = Some(mandate_id); } #[cfg(feature = "v1")] fn set_setup_future_usage_in_payment_intent( &mut self, setup_future_usage: storage_enums::FutureUsage, ) { self.payment_intent.setup_future_usage = Some(setup_future_usage); } #[cfg(feature = "v2")] fn set_setup_future_usage_in_payment_intent( &mut self, setup_future_usage: storage_enums::FutureUsage, ) { self.payment_intent.setup_future_usage = setup_future_usage; } #[cfg(feature = "v1")] fn set_straight_through_algorithm_in_payment_attempt( &mut self, straight_through_algorithm: serde_json::Value, ) { self.payment_attempt.straight_through_algorithm = Some(straight_through_algorithm); } fn set_connector_in_payment_attempt(&mut self, connector: Option<String>) { self.payment_attempt.connector = connector; } fn set_vault_operation(&mut self, vault_operation: domain_payments::VaultOperation) { self.vault_operation = Some(vault_operation); } } #[cfg(feature = "v2")] impl<F: Clone> OperationSessionGetters<F> for PaymentIntentData<F> { fn get_payment_attempt(&self) -> &storage::PaymentAttempt { todo!() } fn get_payment_intent(&self) -> &storage::PaymentIntent { &self.payment_intent } fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod> { todo!() } fn get_mandate_id(&self) -> Option<&payments_api::MandateIds> { todo!() } // what is this address find out and not required remove this fn get_address(&self) -> &PaymentAddress { todo!() } fn get_creds_identifier(&self) -> Option<&str> { todo!() } fn get_token(&self) -> Option<&str> { todo!() } fn get_multiple_capture_data(&self) -> Option<&types::MultipleCaptureData> { todo!() } fn get_payment_link_data(&self) -> Option<api_models::payments::PaymentLinkResponse> { todo!() } fn get_ephemeral_key(&self) -> Option<ephemeral_key::EphemeralKey> { todo!() } fn get_setup_mandate(&self) -> Option<&MandateData> { todo!() } fn get_poll_config(&self) -> Option<router_types::PollConfig> { todo!() } fn get_authentication(&self) -> Option<&storage::Authentication> { todo!() } fn get_frm_message(&self) -> Option<FraudCheck> { todo!() } fn get_refunds(&self) -> Vec<storage::Refund> { todo!() } fn get_disputes(&self) -> Vec<storage::Dispute> { todo!() } fn get_authorizations(&self) -> Vec<diesel_models::authorization::Authorization> { todo!() } fn get_attempts(&self) -> Option<Vec<storage::PaymentAttempt>> { todo!() } fn get_recurring_details(&self) -> Option<&RecurringDetails> { todo!() } fn get_payment_intent_profile_id(&self) -> Option<&id_type::ProfileId> { Some(&self.payment_intent.profile_id) } fn get_currency(&self) -> storage_enums::Currency { self.payment_intent.amount_details.currency } fn get_amount(&self) -> api::Amount { todo!() } fn get_payment_attempt_connector(&self) -> Option<&str> { todo!() } fn get_merchant_connector_id_in_attempt(&self) -> Option<id_type::MerchantConnectorAccountId> { todo!() } fn get_billing_address(&self) -> Option<hyperswitch_domain_models::address::Address> { todo!() } fn get_payment_method_data(&self) -> Option<&domain::PaymentMethodData> { todo!() } fn get_sessions_token(&self) -> Vec<api::SessionToken> { self.sessions_token.clone() } fn get_token_data(&self) -> Option<&storage::PaymentTokenData> { todo!() } fn get_mandate_connector(&self) -> Option<&MandateConnectorDetails> { todo!() } fn get_force_sync(&self) -> Option<bool> { todo!() } fn get_capture_method(&self) -> Option<enums::CaptureMethod> { todo!() } fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt> { todo!(); } } #[cfg(feature = "v2")] impl<F: Clone> OperationSessionSetters<F> for PaymentIntentData<F> { // Setters Implementation fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { self.payment_intent = payment_intent; } fn set_payment_attempt(&mut self, _payment_attempt: storage::PaymentAttempt) { todo!() } fn set_payment_method_data(&mut self, _payment_method_data: Option<domain::PaymentMethodData>) { todo!() } fn set_payment_method_id_in_attempt(&mut self, _payment_method_id: Option<String>) { todo!() } fn set_email_if_not_present(&mut self, _email: pii::Email) { todo!() } fn set_pm_token(&mut self, _token: String) { todo!() } fn set_connector_customer_id(&mut self, _customer_id: Option<String>) { todo!() } fn push_sessions_token(&mut self, token: api::SessionToken) { self.sessions_token.push(token); } fn set_surcharge_details(&mut self, _surcharge_details: Option<types::SurchargeDetails>) { todo!() } fn set_merchant_connector_id_in_attempt( &mut self, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, ) { todo!() } fn set_frm_message(&mut self, _frm_message: FraudCheck) { todo!() } fn set_payment_intent_status(&mut self, status: storage_enums::IntentStatus) { self.payment_intent.status = status; } fn set_authentication_type_in_attempt( &mut self, _authentication_type: Option<enums::AuthenticationType>, ) { todo!() } fn set_recurring_mandate_payment_data( &mut self, _recurring_mandate_payment_data: hyperswitch_domain_models::router_data::RecurringMandatePaymentData, ) { todo!() } fn set_mandate_id(&mut self, _mandate_id: api_models::payments::MandateIds) { todo!() } fn set_setup_future_usage_in_payment_intent( &mut self, setup_future_usage: storage_enums::FutureUsage, ) { self.payment_intent.setup_future_usage = setup_future_usage; } fn set_connector_in_payment_attempt(&mut self, _connector: Option<String>) { todo!() } } #[cfg(feature = "v2")] impl<F: Clone> OperationSessionGetters<F> for PaymentConfirmData<F> { fn get_payment_attempt(&self) -> &storage::PaymentAttempt { &self.payment_attempt } fn get_payment_intent(&self) -> &storage::PaymentIntent { &self.payment_intent } fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod> { todo!() } fn get_mandate_id(&self) -> Option<&payments_api::MandateIds> { todo!() } fn get_address(&self) -> &PaymentAddress { &self.payment_address } fn get_creds_identifier(&self) -> Option<&str> { None } fn get_token(&self) -> Option<&str> { todo!() } fn get_multiple_capture_data(&self) -> Option<&types::MultipleCaptureData> { todo!() } fn get_payment_link_data(&self) -> Option<api_models::payments::PaymentLinkResponse> { todo!() } fn get_ephemeral_key(&self) -> Option<ephemeral_key::EphemeralKey> { todo!() } fn get_setup_mandate(&self) -> Option<&MandateData> { todo!() } fn get_poll_config(&self) -> Option<router_types::PollConfig> { todo!() } fn get_authentication(&self) -> Option<&storage::Authentication> { todo!() } fn get_frm_message(&self) -> Option<FraudCheck> { todo!() } fn get_refunds(&self) -> Vec<storage::Refund> { todo!() } fn get_disputes(&self) -> Vec<storage::Dispute> { todo!() } fn get_authorizations(&self) -> Vec<diesel_models::authorization::Authorization> { todo!() } fn get_attempts(&self) -> Option<Vec<storage::PaymentAttempt>> { todo!() } fn get_recurring_details(&self) -> Option<&RecurringDetails> { todo!() } fn get_payment_intent_profile_id(&self) -> Option<&id_type::ProfileId> { Some(&self.payment_intent.profile_id) } fn get_currency(&self) -> storage_enums::Currency { self.payment_intent.amount_details.currency } fn get_amount(&self) -> api::Amount { todo!() } fn get_payment_attempt_connector(&self) -> Option<&str> { self.payment_attempt.connector.as_deref() } fn get_merchant_connector_id_in_attempt(&self) -> Option<id_type::MerchantConnectorAccountId> { self.payment_attempt.merchant_connector_id.clone() } fn get_billing_address(&self) -> Option<hyperswitch_domain_models::address::Address> { todo!() } fn get_payment_method_data(&self) -> Option<&domain::PaymentMethodData> { self.payment_method_data.as_ref() } fn get_sessions_token(&self) -> Vec<api::SessionToken> { todo!() } fn get_token_data(&self) -> Option<&storage::PaymentTokenData> { todo!() } fn get_mandate_connector(&self) -> Option<&MandateConnectorDetails> { todo!() } fn get_force_sync(&self) -> Option<bool> { todo!() } fn get_capture_method(&self) -> Option<enums::CaptureMethod> { todo!() } fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt> { Some(&self.payment_attempt) } } #[cfg(feature = "v2")] impl<F: Clone> OperationSessionSetters<F> for PaymentConfirmData<F> { // Setters Implementation fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { self.payment_intent = payment_intent; } fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) { self.payment_attempt = payment_attempt; } fn set_payment_method_data(&mut self, _payment_method_data: Option<domain::PaymentMethodData>) { todo!() } fn set_payment_method_id_in_attempt(&mut self, _payment_method_id: Option<String>) { todo!() } fn set_email_if_not_present(&mut self, _email: pii::Email) { todo!() } fn set_pm_token(&mut self, _token: String) { todo!() } fn set_connector_customer_id(&mut self, _customer_id: Option<String>) { // TODO: handle this case. Should we add connector_customer_id in paymentConfirmData? } fn push_sessions_token(&mut self, _token: api::SessionToken) { todo!() } fn set_surcharge_details(&mut self, _surcharge_details: Option<types::SurchargeDetails>) { todo!() } #[track_caller] fn set_merchant_connector_id_in_attempt( &mut self, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, ) { self.payment_attempt.merchant_connector_id = merchant_connector_id; } fn set_frm_message(&mut self, _frm_message: FraudCheck) { todo!() } fn set_payment_intent_status(&mut self, status: storage_enums::IntentStatus) { self.payment_intent.status = status; } fn set_authentication_type_in_attempt( &mut self, _authentication_type: Option<enums::AuthenticationType>, ) { todo!() } fn set_recurring_mandate_payment_data( &mut self, _recurring_mandate_payment_data: hyperswitch_domain_models::router_data::RecurringMandatePaymentData, ) { todo!() } fn set_mandate_id(&mut self, _mandate_id: api_models::payments::MandateIds) { todo!() } fn set_setup_future_usage_in_payment_intent( &mut self, setup_future_usage: storage_enums::FutureUsage, ) { self.payment_intent.setup_future_usage = setup_future_usage; } fn set_connector_in_payment_attempt(&mut self, connector: Option<String>) { self.payment_attempt.connector = connector; } } #[cfg(feature = "v2")] impl<F: Clone> OperationSessionGetters<F> for PaymentStatusData<F> { #[track_caller] fn get_payment_attempt(&self) -> &storage::PaymentAttempt { todo!() } fn get_payment_intent(&self) -> &storage::PaymentIntent { &self.payment_intent } fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod> { todo!() } fn get_mandate_id(&self) -> Option<&payments_api::MandateIds> { todo!() } fn get_address(&self) -> &PaymentAddress { &self.payment_address } fn get_creds_identifier(&self) -> Option<&str> { None } fn get_token(&self) -> Option<&str> { todo!() } fn get_multiple_capture_data(&self) -> Option<&types::MultipleCaptureData> { todo!() } fn get_payment_link_data(&self) -> Option<api_models::payments::PaymentLinkResponse> { todo!() } fn get_ephemeral_key(&self) -> Option<ephemeral_key::EphemeralKey> { todo!() } fn get_setup_mandate(&self) -> Option<&MandateData> { todo!() } fn get_poll_config(&self) -> Option<router_types::PollConfig> { todo!() } fn get_authentication(&self) -> Option<&storage::Authentication> { todo!() } fn get_frm_message(&self) -> Option<FraudCheck> { todo!() } fn get_refunds(&self) -> Vec<storage::Refund> { todo!() } fn get_disputes(&self) -> Vec<storage::Dispute> { todo!() } fn get_authorizations(&self) -> Vec<diesel_models::authorization::Authorization> { todo!() } fn get_attempts(&self) -> Option<Vec<storage::PaymentAttempt>> { todo!() } fn get_recurring_details(&self) -> Option<&RecurringDetails> { todo!() } fn get_payment_intent_profile_id(&self) -> Option<&id_type::ProfileId> { Some(&self.payment_intent.profile_id) } fn get_currency(&self) -> storage_enums::Currency { self.payment_intent.amount_details.currency } fn get_amount(&self) -> api::Amount { todo!() } fn get_payment_attempt_connector(&self) -> Option<&str> { todo!() } fn get_merchant_connector_id_in_attempt(&self) -> Option<id_type::MerchantConnectorAccountId> { todo!() } fn get_billing_address(&self) -> Option<hyperswitch_domain_models::address::Address> { todo!() } fn get_payment_method_data(&self) -> Option<&domain::PaymentMethodData> { todo!() } fn get_sessions_token(&self) -> Vec<api::SessionToken> { todo!() } fn get_token_data(&self) -> Option<&storage::PaymentTokenData> { todo!() } fn get_mandate_connector(&self) -> Option<&MandateConnectorDetails> { todo!() } fn get_force_sync(&self) -> Option<bool> { todo!() } fn get_capture_method(&self) -> Option<enums::CaptureMethod> { todo!() } fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt> { self.payment_attempt.as_ref() } } #[cfg(feature = "v2")] impl<F: Clone> OperationSessionSetters<F> for PaymentStatusData<F> { fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { self.payment_intent = payment_intent; } fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) { self.payment_attempt = Some(payment_attempt); } fn set_payment_method_data(&mut self, _payment_method_data: Option<domain::PaymentMethodData>) { todo!() } fn set_payment_method_id_in_attempt(&mut self, _payment_method_id: Option<String>) { todo!() } fn set_email_if_not_present(&mut self, _email: pii::Email) { todo!() } fn set_pm_token(&mut self, _token: String) { todo!() } fn set_connector_customer_id(&mut self, _customer_id: Option<String>) { // TODO: handle this case. Should we add connector_customer_id in paymentConfirmData? } fn push_sessions_token(&mut self, _token: api::SessionToken) { todo!() } fn set_surcharge_details(&mut self, _surcharge_details: Option<types::SurchargeDetails>) { todo!() } #[track_caller] fn set_merchant_connector_id_in_attempt( &mut self, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, ) { todo!() } fn set_frm_message(&mut self, _frm_message: FraudCheck) { todo!() } fn set_payment_intent_status(&mut self, status: storage_enums::IntentStatus) { self.payment_intent.status = status; } fn set_authentication_type_in_attempt( &mut self, _authentication_type: Option<enums::AuthenticationType>, ) { todo!() } fn set_recurring_mandate_payment_data( &mut self, _recurring_mandate_payment_data: hyperswitch_domain_models::router_data::RecurringMandatePaymentData, ) { todo!() } fn set_mandate_id(&mut self, _mandate_id: api_models::payments::MandateIds) { todo!() } fn set_setup_future_usage_in_payment_intent( &mut self, setup_future_usage: storage_enums::FutureUsage, ) { self.payment_intent.setup_future_usage = setup_future_usage; } fn set_connector_in_payment_attempt(&mut self, connector: Option<String>) { todo!() } } #[cfg(feature = "v2")] impl<F: Clone> OperationSessionGetters<F> for PaymentCaptureData<F> { #[track_caller] fn get_payment_attempt(&self) -> &storage::PaymentAttempt { &self.payment_attempt } fn get_payment_intent(&self) -> &storage::PaymentIntent { &self.payment_intent } fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod> { todo!() } fn get_mandate_id(&self) -> Option<&payments_api::MandateIds> { todo!() } // what is this address find out and not required remove this fn get_address(&self) -> &PaymentAddress { todo!() } fn get_creds_identifier(&self) -> Option<&str> { None } fn get_token(&self) -> Option<&str> { todo!() } fn get_multiple_capture_data(&self) -> Option<&types::MultipleCaptureData> { todo!() } fn get_payment_link_data(&self) -> Option<api_models::payments::PaymentLinkResponse> { todo!() } fn get_ephemeral_key(&self) -> Option<ephemeral_key::EphemeralKey> { todo!() } fn get_setup_mandate(&self) -> Option<&MandateData> { todo!() } fn get_poll_config(&self) -> Option<router_types::PollConfig> { todo!() } fn get_authentication(&self) -> Option<&storage::Authentication> { todo!() } fn get_frm_message(&self) -> Option<FraudCheck> { todo!() } fn get_refunds(&self) -> Vec<storage::Refund> { todo!() } fn get_disputes(&self) -> Vec<storage::Dispute> { todo!() } fn get_authorizations(&self) -> Vec<diesel_models::authorization::Authorization> { todo!() } fn get_attempts(&self) -> Option<Vec<storage::PaymentAttempt>> { todo!() } fn get_recurring_details(&self) -> Option<&RecurringDetails> { todo!() } fn get_payment_intent_profile_id(&self) -> Option<&id_type::ProfileId> { Some(&self.payment_intent.profile_id) } fn get_currency(&self) -> storage_enums::Currency { self.payment_intent.amount_details.currency } fn get_amount(&self) -> api::Amount { todo!() } fn get_payment_attempt_connector(&self) -> Option<&str> { todo!() } fn get_merchant_connector_id_in_attempt(&self) -> Option<id_type::MerchantConnectorAccountId> { todo!() } fn get_billing_address(&self) -> Option<hyperswitch_domain_models::address::Address> { todo!() } fn get_payment_method_data(&self) -> Option<&domain::PaymentMethodData> { todo!() } fn get_sessions_token(&self) -> Vec<api::SessionToken> { todo!() } fn get_token_data(&self) -> Option<&storage::PaymentTokenData> { todo!() } fn get_mandate_connector(&self) -> Option<&MandateConnectorDetails> { todo!() } fn get_force_sync(&self) -> Option<bool> { todo!() } fn get_capture_method(&self) -> Option<enums::CaptureMethod> { todo!() } #[cfg(feature = "v2")] fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt> { Some(&self.payment_attempt) } } #[cfg(feature = "v2")] impl<F: Clone> OperationSessionSetters<F> for PaymentCaptureData<F> { fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { self.payment_intent = payment_intent; } fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) { self.payment_attempt = payment_attempt; } fn set_payment_method_data(&mut self, _payment_method_data: Option<domain::PaymentMethodData>) { todo!() } fn set_payment_method_id_in_attempt(&mut self, _payment_method_id: Option<String>) { todo!() } fn set_email_if_not_present(&mut self, _email: pii::Email) { todo!() } fn set_pm_token(&mut self, _token: String) { todo!() } fn set_connector_customer_id(&mut self, _customer_id: Option<String>) { // TODO: handle this case. Should we add connector_customer_id in paymentConfirmData? } fn push_sessions_token(&mut self, _token: api::SessionToken) { todo!() } fn set_surcharge_details(&mut self, _surcharge_details: Option<types::SurchargeDetails>) { todo!() } #[track_caller] fn set_merchant_connector_id_in_attempt( &mut self, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, ) { todo!() } fn set_frm_message(&mut self, _frm_message: FraudCheck) { todo!() } fn set_payment_intent_status(&mut self, status: storage_enums::IntentStatus) { self.payment_intent.status = status; } fn set_authentication_type_in_attempt( &mut self, _authentication_type: Option<enums::AuthenticationType>, ) { todo!() } fn set_recurring_mandate_payment_data( &mut self, _recurring_mandate_payment_data: hyperswitch_domain_models::router_data::RecurringMandatePaymentData, ) { todo!() } fn set_mandate_id(&mut self, _mandate_id: api_models::payments::MandateIds) { todo!() } fn set_setup_future_usage_in_payment_intent( &mut self, setup_future_usage: storage_enums::FutureUsage, ) { self.payment_intent.setup_future_usage = setup_future_usage; } fn set_connector_in_payment_attempt(&mut self, connector: Option<String>) { todo!() } }
66,999
1,560
hyperswitch
crates/router/src/core/api_locking.rs
.rs
use std::fmt::Debug; use actix_web::rt::time as actix_time; use error_stack::{report, ResultExt}; use redis_interface as redis; use router_env::{instrument, logger, tracing}; use super::errors::{self, RouterResult}; use crate::routes::{app::SessionStateInfo, lock_utils}; pub const API_LOCK_PREFIX: &str = "API_LOCK"; #[derive(Clone, Debug, Eq, PartialEq)] pub enum LockStatus { // status when the lock is acquired by the caller Acquired, // [#2129] pick up request_id from AppState and populate here // status when the lock is acquired by some other caller Busy, } #[derive(Clone, Debug)] pub enum LockAction { // Sleep until the lock is acquired Hold { input: LockingInput }, // Queue it but return response as 2xx, could be used for webhooks QueueWithOk, // Return Error Drop, // Locking Not applicable NotApplicable, } #[derive(Clone, Debug)] pub struct LockingInput { pub unique_locking_key: String, pub api_identifier: lock_utils::ApiIdentifier, pub override_lock_retries: Option<u32>, } impl LockingInput { fn get_redis_locking_key(&self, merchant_id: common_utils::id_type::MerchantId) -> String { format!( "{}_{}_{}_{}", API_LOCK_PREFIX, merchant_id.get_string_repr(), self.api_identifier, self.unique_locking_key ) } } impl LockAction { #[instrument(skip_all)] pub async fn perform_locking_action<A>( self, state: &A, merchant_id: common_utils::id_type::MerchantId, ) -> RouterResult<()> where A: SessionStateInfo, { match self { Self::Hold { input } => { let redis_conn = state .store() .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError)?; let redis_locking_key = input.get_redis_locking_key(merchant_id); let delay_between_retries_in_milliseconds = state .conf() .lock_settings .delay_between_retries_in_milliseconds; let redis_lock_expiry_seconds = state.conf().lock_settings.redis_lock_expiry_seconds; let lock_retries = input .override_lock_retries .unwrap_or(state.conf().lock_settings.lock_retries); for _retry in 0..lock_retries { let redis_lock_result = redis_conn .set_key_if_not_exists_with_expiry( &redis_locking_key.as_str().into(), state.get_request_id(), Some(i64::from(redis_lock_expiry_seconds)), ) .await; match redis_lock_result { Ok(redis::SetnxReply::KeySet) => { logger::info!("Lock acquired for locking input {:?}", input); tracing::Span::current() .record("redis_lock_acquired", redis_locking_key); return Ok(()); } Ok(redis::SetnxReply::KeyNotSet) => { logger::info!( "Lock busy by other request when tried for locking input {:?}", input ); actix_time::sleep(tokio::time::Duration::from_millis(u64::from( delay_between_retries_in_milliseconds, ))) .await; } Err(err) => { return Err(err) .change_context(errors::ApiErrorResponse::InternalServerError) } } } Err(report!(errors::ApiErrorResponse::ResourceBusy)) } Self::QueueWithOk | Self::Drop | Self::NotApplicable => Ok(()), } } #[instrument(skip_all)] pub async fn free_lock_action<A>( self, state: &A, merchant_id: common_utils::id_type::MerchantId, ) -> RouterResult<()> where A: SessionStateInfo, { match self { Self::Hold { input } => { let redis_conn = state .store() .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError)?; let redis_locking_key = input.get_redis_locking_key(merchant_id); match redis_conn .get_key::<Option<String>>(&redis_locking_key.as_str().into()) .await { Ok(val) => { if val == state.get_request_id() { match redis_conn .delete_key(&redis_locking_key.as_str().into()) .await { Ok(redis::types::DelReply::KeyDeleted) => { logger::info!("Lock freed for locking input {:?}", input); tracing::Span::current() .record("redis_lock_released", redis_locking_key); Ok(()) } Ok(redis::types::DelReply::KeyNotDeleted) => { Err(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Status release lock called but key is not found in redis", ) } Err(error) => Err(error) .change_context(errors::ApiErrorResponse::InternalServerError), } } else { Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("The request_id which acquired the lock is not equal to the request_id requesting for releasing the lock") } } Err(error) => { Err(error).change_context(errors::ApiErrorResponse::InternalServerError) } } } Self::QueueWithOk | Self::Drop | Self::NotApplicable => Ok(()), } } } pub trait GetLockingInput { fn get_locking_input<F>(&self, flow: F) -> LockAction where F: router_env::types::FlowMetric, lock_utils::ApiIdentifier: From<F>; }
1,251
1,561
hyperswitch
crates/router/src/core/locker_migration.rs
.rs
#[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] use api_models::enums as api_enums; use api_models::locker_migration::MigrateCardResponse; use common_utils::{errors::CustomResult, id_type}; #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] use diesel_models::enums as storage_enums; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use error_stack::FutureExt; use error_stack::ResultExt; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use futures::TryFutureExt; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use super::errors::StorageErrorExt; #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] use super::payment_methods::cards; #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] use crate::services::logger; #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] use crate::types::api; use crate::{errors, routes::SessionState, services, types::domain}; #[cfg(all( feature = "v2", feature = "customer_v2", feature = "payment_methods_v2" ))] pub async fn rust_locker_migration( _state: SessionState, _merchant_id: &id_type::MerchantId, ) -> CustomResult<services::ApplicationResponse<MigrateCardResponse>, errors::ApiErrorResponse> { todo!() } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "customer_v2"), not(feature = "payment_methods_v2") ))] pub async fn rust_locker_migration( state: SessionState, merchant_id: &id_type::MerchantId, ) -> CustomResult<services::ApplicationResponse<MigrateCardResponse>, errors::ApiErrorResponse> { use crate::db::customers::CustomerListConstraints; let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; let merchant_account = db .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) .change_context(errors::ApiErrorResponse::InternalServerError)?; // Handle cases where the number of customers is greater than the limit let constraints = CustomerListConstraints { limit: u16::MAX, offset: None, }; let domain_customers = db .list_customers_by_merchant_id(key_manager_state, merchant_id, &key_store, constraints) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; let mut customers_moved = 0; let mut cards_moved = 0; for customer in domain_customers { let result = db .find_payment_method_by_customer_id_merchant_id_list( key_manager_state, &key_store, &customer.customer_id, merchant_id, None, ) .change_context(errors::ApiErrorResponse::InternalServerError) .and_then(|pm| { call_to_locker( &state, pm, &customer.customer_id, merchant_id, &merchant_account, ) }) .await?; customers_moved += 1; cards_moved += result; } Ok(services::api::ApplicationResponse::Json( MigrateCardResponse { status_code: "200".to_string(), status_message: "Card migration completed".to_string(), customers_moved, cards_moved, }, )) } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] pub async fn call_to_locker( state: &SessionState, payment_methods: Vec<domain::PaymentMethod>, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, merchant_account: &domain::MerchantAccount, ) -> CustomResult<usize, errors::ApiErrorResponse> { let mut cards_moved = 0; for pm in payment_methods.into_iter().filter(|pm| { matches!( pm.get_payment_method_type(), Some(storage_enums::PaymentMethod::Card) ) }) { let card = cards::get_card_from_locker( state, customer_id, merchant_id, pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id), ) .await; let card = match card { Ok(card) => card, Err(err) => { logger::error!("Failed to fetch card from Basilisk HS locker : {:?}", err); continue; } }; let card_details = api::CardDetail { card_number: card.card_number, card_exp_month: card.card_exp_month, card_exp_year: card.card_exp_year, card_holder_name: card.name_on_card, nick_name: card.nick_name.map(masking::Secret::new), card_issuing_country: None, card_network: None, card_issuer: None, card_type: None, }; let pm_create = api::PaymentMethodCreate { payment_method: pm.get_payment_method_type(), payment_method_type: pm.get_payment_method_subtype(), payment_method_issuer: pm.payment_method_issuer, payment_method_issuer_code: pm.payment_method_issuer_code, card: Some(card_details.clone()), #[cfg(feature = "payouts")] wallet: None, #[cfg(feature = "payouts")] bank_transfer: None, metadata: pm.metadata, customer_id: Some(pm.customer_id), card_network: card.card_brand, client_secret: None, payment_method_data: None, billing: None, connector_mandate_details: None, network_transaction_id: None, }; let add_card_result = cards::add_card_hs( state, pm_create, &card_details, customer_id, merchant_account, api_enums::LockerChoice::HyperswitchCardVault, Some(pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id)), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable(format!( "Card migration failed for merchant_id: {merchant_id:?}, customer_id: {customer_id:?}, payment_method_id: {} ", pm.payment_method_id )); let (_add_card_rs_resp, _is_duplicate) = match add_card_result { Ok(output) => output, Err(err) => { logger::error!("Failed to add card to Rust locker : {:?}", err); continue; } }; cards_moved += 1; logger::info!( "Card migrated for merchant_id: {merchant_id:?}, customer_id: {customer_id:?}, payment_method_id: {} ", pm.payment_method_id ); } Ok(cards_moved) } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub async fn call_to_locker( _state: &SessionState, _payment_methods: Vec<domain::PaymentMethod>, _customer_id: &id_type::CustomerId, _merchant_id: &id_type::MerchantId, _merchant_account: &domain::MerchantAccount, ) -> CustomResult<usize, errors::ApiErrorResponse> { todo!() }
1,754
1,562
hyperswitch
crates/router/src/core/webhooks.rs
.rs
#[cfg(feature = "v1")] mod incoming; #[cfg(feature = "v2")] mod incoming_v2; #[cfg(feature = "v1")] mod outgoing; #[cfg(all(feature = "revenue_recovery", feature = "v2"))] mod recovery_incoming; pub mod types; pub mod utils; #[cfg(feature = "olap")] pub mod webhook_events; #[cfg(feature = "v2")] pub(crate) use self::incoming_v2::incoming_webhooks_wrapper; #[cfg(feature = "v1")] pub(crate) use self::{ incoming::incoming_webhooks_wrapper, outgoing::{ create_event_and_trigger_outgoing_webhook, get_outgoing_webhook_request, trigger_webhook_and_raise_event, }, }; const MERCHANT_ID: &str = "merchant_id";
166
1,563
hyperswitch
crates/router/src/core/recon.rs
.rs
use api_models::recon as recon_api; #[cfg(feature = "email")] use common_utils::{ext_traits::AsyncExt, types::theme::ThemeLineage}; use error_stack::ResultExt; #[cfg(feature = "email")] use masking::{ExposeInterface, PeekInterface, Secret}; #[cfg(feature = "email")] use crate::{ consts, services::email::types as email_types, types::domain, utils::user::theme as theme_utils, }; use crate::{ core::errors::{self, RouterResponse, UserErrors, UserResponse}, services::{api as service_api, authentication}, types::{ api::{self as api_types, enums}, storage, transformers::ForeignTryFrom, }, SessionState, }; #[allow(unused_variables)] pub async fn send_recon_request( state: SessionState, auth_data: authentication::AuthenticationDataWithUser, ) -> RouterResponse<recon_api::ReconStatusResponse> { #[cfg(not(feature = "email"))] return Ok(service_api::ApplicationResponse::Json( recon_api::ReconStatusResponse { recon_status: enums::ReconStatus::NotRequested, }, )); #[cfg(feature = "email")] { let user_in_db = &auth_data.user; let merchant_id = auth_data.merchant_account.get_id().clone(); let theme = theme_utils::get_most_specific_theme_using_lineage( &state.clone(), ThemeLineage::Merchant { tenant_id: state.tenant.tenant_id.clone(), org_id: auth_data.merchant_account.get_org_id().clone(), merchant_id: merchant_id.clone(), }, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable(format!( "Failed to fetch theme for merchant_id = {:?}", merchant_id ))?; let user_email = user_in_db.email.clone(); let email_contents = email_types::ProFeatureRequest { feature_name: consts::RECON_FEATURE_TAG.to_string(), merchant_id: merchant_id.clone(), user_name: domain::UserName::new(user_in_db.name.clone()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to form username")?, user_email: domain::UserEmail::from_pii_email(user_email.clone()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to convert recipient's email to UserEmail")?, recipient_email: domain::UserEmail::from_pii_email( state.conf.email.recon_recipient_email.clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to convert recipient's email to UserEmail")?, subject: format!( "{} {}", consts::EMAIL_SUBJECT_DASHBOARD_FEATURE_REQUEST, user_email.expose().peek() ), theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()), theme_config: theme .map(|theme| theme.email_config()) .unwrap_or(state.conf.theme.email_config.clone()), }; state .email_client .compose_and_send_email( email_types::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to compose and send email for ProFeatureRequest [Recon]") .async_and_then(|_| async { let updated_merchant_account = storage::MerchantAccountUpdate::ReconUpdate { recon_status: enums::ReconStatus::Requested, }; let db = &*state.store; let key_manager_state = &(&state).into(); let response = db .update_merchant( key_manager_state, auth_data.merchant_account, updated_merchant_account, &auth_data.key_store, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!("Failed while updating merchant's recon status: {merchant_id:?}") })?; Ok(service_api::ApplicationResponse::Json( recon_api::ReconStatusResponse { recon_status: response.recon_status, }, )) }) .await } } pub async fn generate_recon_token( state: SessionState, user_with_role: authentication::UserFromTokenWithRoleInfo, ) -> RouterResponse<recon_api::ReconTokenResponse> { let user = user_with_role.user; let token = authentication::ReconToken::new_token( user.user_id.clone(), user.merchant_id.clone(), &state.conf, user.org_id.clone(), user.profile_id.clone(), user.tenant_id, user_with_role.role_info, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed to create recon token for params [user_id, org_id, mid, pid] [{}, {:?}, {:?}, {:?}]", user.user_id, user.org_id, user.merchant_id, user.profile_id, ) })?; Ok(service_api::ApplicationResponse::Json( recon_api::ReconTokenResponse { token: token.into(), }, )) } pub async fn recon_merchant_account_update( state: SessionState, auth: authentication::AuthenticationData, req: recon_api::ReconUpdateMerchantRequest, ) -> RouterResponse<api_types::MerchantAccountResponse> { let db = &*state.store; let key_manager_state = &(&state).into(); let updated_merchant_account = storage::MerchantAccountUpdate::ReconUpdate { recon_status: req.recon_status, }; let merchant_id = auth.merchant_account.get_id().clone(); let updated_merchant_account = db .update_merchant( key_manager_state, auth.merchant_account.clone(), updated_merchant_account, &auth.key_store, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!("Failed while updating merchant's recon status: {merchant_id:?}") })?; #[cfg(feature = "email")] { let user_email = &req.user_email.clone(); let theme = theme_utils::get_most_specific_theme_using_lineage( &state.clone(), ThemeLineage::Merchant { tenant_id: state.tenant.tenant_id.clone(), org_id: auth.merchant_account.get_org_id().clone(), merchant_id: merchant_id.clone(), }, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable(format!( "Failed to fetch theme for merchant_id = {:?}", merchant_id ))?; let email_contents = email_types::ReconActivation { recipient_email: domain::UserEmail::from_pii_email(user_email.clone()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to convert recipient's email to UserEmail from pii::Email", )?, user_name: domain::UserName::new(Secret::new("HyperSwitch User".to_string())) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to form username")?, subject: consts::EMAIL_SUBJECT_APPROVAL_RECON_REQUEST, theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()), theme_config: theme .map(|theme| theme.email_config()) .unwrap_or(state.conf.theme.email_config.clone()), }; if req.recon_status == enums::ReconStatus::Active { let _ = state .email_client .compose_and_send_email( email_types::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) .await .inspect_err(|err| { router_env::logger::error!( "Failed to compose and send email notifying them of recon activation: {}", err ) }) .change_context(UserErrors::InternalServerError) .attach_printable("Failed to compose and send email for ReconActivation"); } } Ok(service_api::ApplicationResponse::Json( api_types::MerchantAccountResponse::foreign_try_from(updated_merchant_account) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "merchant_account", })?, )) } pub async fn verify_recon_token( state: SessionState, user_with_role: authentication::UserFromTokenWithRoleInfo, ) -> UserResponse<recon_api::VerifyTokenResponse> { let user = user_with_role.user; let user_in_db = user .get_user_from_db(&state) .await .attach_printable_lazy(|| { format!( "Failed to fetch the user from DB for user_id - {}", user.user_id ) })?; let acl = user_with_role.role_info.get_recon_acl(); let optional_acl_str = serde_json::to_string(&acl) .inspect_err(|err| router_env::logger::error!("Failed to serialize acl to string: {}", err)) .change_context(UserErrors::InternalServerError) .attach_printable("Failed to serialize acl to string. Using empty ACL") .ok(); Ok(service_api::ApplicationResponse::Json( recon_api::VerifyTokenResponse { merchant_id: user.merchant_id.to_owned(), user_email: user_in_db.0.email, acl: optional_acl_str, }, )) }
2,051
1,564
hyperswitch
crates/router/src/core/routing.rs
.rs
pub mod helpers; pub mod transformers; use std::collections::HashSet; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use api_models::routing::DynamicRoutingAlgoAccessor; use api_models::{ enums, mandates as mandates_api, routing, routing::{self as routing_types, RoutingRetrieveQuery}, }; use async_trait::async_trait; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use common_utils::ext_traits::AsyncExt; use diesel_models::routing_algorithm::RoutingAlgorithm; use error_stack::ResultExt; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use external_services::grpc_client::dynamic_routing::{ contract_routing_client::ContractBasedDynamicRouting, success_rate_client::SuccessBasedDynamicRouting, }; use hyperswitch_domain_models::{mandates, payment_address}; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use router_env::logger; use rustc_hash::FxHashSet; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use storage_impl::redis::cache; #[cfg(feature = "payouts")] use super::payouts; use super::{ errors::RouterResult, payments::{ routing::{self as payments_routing}, OperationSessionGetters, }, }; #[cfg(feature = "v1")] use crate::utils::ValueExt; #[cfg(feature = "v2")] use crate::{core::admin, utils::ValueExt}; use crate::{ core::{ errors::{self, CustomResult, RouterResponse, StorageErrorExt}, metrics, utils as core_utils, }, db::StorageInterface, routes::SessionState, services::api as service_api, types::{ api, domain, storage::{self, enums as storage_enums}, transformers::{ForeignInto, ForeignTryFrom}, }, utils::{self, OptionExt}, }; pub enum TransactionData<'a> { Payment(PaymentsDslInput<'a>), #[cfg(feature = "payouts")] Payout(&'a payouts::PayoutData), } #[derive(Clone)] pub struct PaymentsDslInput<'a> { pub setup_mandate: Option<&'a mandates::MandateData>, pub payment_attempt: &'a storage::PaymentAttempt, pub payment_intent: &'a storage::PaymentIntent, pub payment_method_data: Option<&'a domain::PaymentMethodData>, pub address: &'a payment_address::PaymentAddress, pub recurring_details: Option<&'a mandates_api::RecurringDetails>, pub currency: storage_enums::Currency, } impl<'a> PaymentsDslInput<'a> { 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, } } } #[cfg(feature = "v2")] struct RoutingAlgorithmUpdate(RoutingAlgorithm); #[cfg(feature = "v2")] impl RoutingAlgorithmUpdate { pub fn create_new_routing_algorithm( request: &routing_types::RoutingConfigRequest, merchant_id: &common_utils::id_type::MerchantId, profile_id: common_utils::id_type::ProfileId, transaction_type: enums::TransactionType, ) -> Self { let algorithm_id = common_utils::generate_routing_id_of_default_length(); let timestamp = common_utils::date_time::now(); let algo = RoutingAlgorithm { algorithm_id, profile_id, merchant_id: merchant_id.clone(), name: request.name.clone(), description: Some(request.description.clone()), kind: request.algorithm.get_kind().foreign_into(), algorithm_data: serde_json::json!(request.algorithm), created_at: timestamp, modified_at: timestamp, algorithm_for: transaction_type, }; Self(algo) } 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)) } } pub async fn retrieve_merchant_routing_dictionary( state: SessionState, merchant_account: domain::MerchantAccount, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, query_params: RoutingRetrieveQuery, transaction_type: &enums::TransactionType, ) -> RouterResponse<routing_types::RoutingKind> { metrics::ROUTING_MERCHANT_DICTIONARY_RETRIEVE.add(1, &[]); let routing_metadata: Vec<diesel_models::routing_algorithm::RoutingProfileMetadata> = state .store .list_routing_algorithm_metadata_by_merchant_id_transaction_type( merchant_account.get_id(), transaction_type, i64::from(query_params.limit.unwrap_or_default()), i64::from(query_params.offset.unwrap_or_default()), ) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; let routing_metadata = super::utils::filter_objects_based_on_profile_id_list(profile_id_list, routing_metadata); let result = routing_metadata .into_iter() .map(ForeignInto::foreign_into) .collect::<Vec<_>>(); metrics::ROUTING_MERCHANT_DICTIONARY_RETRIEVE_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json( routing_types::RoutingKind::RoutingAlgorithm(result), )) } #[cfg(feature = "v2")] 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)) } #[cfg(feature = "v1")] 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)) } #[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 = 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(), )) } #[cfg(feature = "v1")] 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(), )) } #[cfg(feature = "v2")] 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)) } #[cfg(feature = "v1")] pub async fn retrieve_routing_algorithm_from_algorithm_id( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, authentication_profile_id: Option<common_utils::id_type::ProfileId>, algorithm_id: common_utils::id_type::RoutingId, ) -> RouterResponse<routing_types::MerchantRoutingAlgorithm> { metrics::ROUTING_RETRIEVE_CONFIG.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let routing_algorithm = db .find_routing_algorithm_by_algorithm_id_merchant_id( &algorithm_id, merchant_account.get_id(), ) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; let business_profile = core_utils::validate_and_get_business_profile( db, key_manager_state, &key_store, Some(&routing_algorithm.profile_id), merchant_account.get_id(), ) .await? .get_required_value("Profile") .change_context(errors::ApiErrorResponse::ResourceIdNotFound)?; core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?; let response = routing_types::MerchantRoutingAlgorithm::foreign_try_from(routing_algorithm) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to parse routing algorithm")?; metrics::ROUTING_RETRIEVE_CONFIG_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json(response)) } #[cfg(feature = "v2")] pub async fn unlink_routing_config_under_profile( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, profile_id: common_utils::id_type::ProfileId, transaction_type: &enums::TransactionType, ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { metrics::ROUTING_UNLINK_CONFIG.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let business_profile = core_utils::validate_and_get_business_profile( db, key_manager_state, &key_store, Some(&profile_id), merchant_account.get_id(), ) .await? .get_required_value("Profile")?; let routing_algo_id = match transaction_type { enums::TransactionType::Payment => business_profile.routing_algorithm_id.clone(), #[cfg(feature = "payouts")] enums::TransactionType::Payout => business_profile.payout_routing_algorithm_id.clone(), }; if let Some(algorithm_id) = routing_algo_id { let record = RoutingAlgorithmUpdate::fetch_routing_algo( merchant_account.get_id(), &algorithm_id, db, ) .await?; let response = record.0.foreign_into(); admin::ProfileWrapper::new(business_profile) .update_profile_and_invalidate_routing_config_for_active_algorithm_id_update( db, key_manager_state, &key_store, algorithm_id, transaction_type, ) .await?; metrics::ROUTING_UNLINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json(response)) } else { Err(errors::ApiErrorResponse::PreconditionFailed { message: "Algorithm is already inactive".to_string(), })? } } #[cfg(feature = "v1")] pub async fn unlink_routing_config( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, request: routing_types::RoutingConfigRequest, authentication_profile_id: Option<common_utils::id_type::ProfileId>, transaction_type: &enums::TransactionType, ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { metrics::ROUTING_UNLINK_CONFIG.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let profile_id = request .profile_id .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "profile_id", }) .attach_printable("Profile_id not provided")?; let business_profile = core_utils::validate_and_get_business_profile( db, key_manager_state, &key_store, Some(&profile_id), merchant_account.get_id(), ) .await?; match business_profile { Some(business_profile) => { core_utils::validate_profile_id_from_auth_layer( authentication_profile_id, &business_profile, )?; let routing_algo_ref: routing_types::RoutingAlgorithmRef = match transaction_type { enums::TransactionType::Payment => business_profile.routing_algorithm.clone(), #[cfg(feature = "payouts")] enums::TransactionType::Payout => business_profile.payout_routing_algorithm.clone(), } .map(|val| val.parse_value("RoutingAlgorithmRef")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to deserialize routing algorithm ref from merchant account")? .unwrap_or_default(); let timestamp = common_utils::date_time::now_unix_timestamp(); match routing_algo_ref.algorithm_id { Some(algorithm_id) => { let routing_algorithm: routing_types::RoutingAlgorithmRef = routing_types::RoutingAlgorithmRef { algorithm_id: None, timestamp, config_algo_id: routing_algo_ref.config_algo_id.clone(), surcharge_config_algo_id: routing_algo_ref.surcharge_config_algo_id, }; let record = db .find_routing_algorithm_by_profile_id_algorithm_id( &profile_id, &algorithm_id, ) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; let response = record.foreign_into(); helpers::update_profile_active_algorithm_ref( db, key_manager_state, &key_store, business_profile, routing_algorithm, transaction_type, ) .await?; metrics::ROUTING_UNLINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json(response)) } None => Err(errors::ApiErrorResponse::PreconditionFailed { message: "Algorithm is already inactive".to_string(), })?, } } None => Err(errors::ApiErrorResponse::InvalidRequestData { message: "The business_profile is not present".to_string(), } .into()), } } #[cfg(feature = "v2")] pub async fn update_default_fallback_routing( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, profile_id: common_utils::id_type::ProfileId, updated_list_of_connectors: Vec<routing_types::RoutableConnectorChoice>, ) -> RouterResponse<Vec<routing_types::RoutableConnectorChoice>> { metrics::ROUTING_UPDATE_CONFIG.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let profile = core_utils::validate_and_get_business_profile( db, key_manager_state, &key_store, Some(&profile_id), merchant_account.get_id(), ) .await? .get_required_value("Profile")?; let profile_wrapper = admin::ProfileWrapper::new(profile); let default_list_of_connectors = profile_wrapper.get_default_fallback_list_of_connector_under_profile()?; utils::when( default_list_of_connectors.len() != updated_list_of_connectors.len(), || { Err(errors::ApiErrorResponse::PreconditionFailed { message: "current config and updated config have different lengths".to_string(), }) }, )?; let existing_set_of_default_connectors: FxHashSet<String> = FxHashSet::from_iter( default_list_of_connectors .iter() .map(|conn_choice| conn_choice.to_string()), ); let updated_set_of_default_connectors: FxHashSet<String> = FxHashSet::from_iter( updated_list_of_connectors .iter() .map(|conn_choice| conn_choice.to_string()), ); let symmetric_diff_between_existing_and_updated_connectors: Vec<String> = existing_set_of_default_connectors .symmetric_difference(&updated_set_of_default_connectors) .cloned() .collect(); utils::when( !symmetric_diff_between_existing_and_updated_connectors.is_empty(), || { Err(errors::ApiErrorResponse::InvalidRequestData { message: format!( "connector mismatch between old and new configs ({})", symmetric_diff_between_existing_and_updated_connectors.join(", ") ), }) }, )?; profile_wrapper .update_default_fallback_routing_of_connectors_under_profile( db, &updated_list_of_connectors, key_manager_state, &key_store, ) .await?; metrics::ROUTING_UPDATE_CONFIG_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json( updated_list_of_connectors, )) } #[cfg(feature = "v1")] pub async fn update_default_routing_config( state: SessionState, merchant_account: domain::MerchantAccount, updated_config: Vec<routing_types::RoutableConnectorChoice>, transaction_type: &enums::TransactionType, ) -> RouterResponse<Vec<routing_types::RoutableConnectorChoice>> { metrics::ROUTING_UPDATE_CONFIG.add(1, &[]); let db = state.store.as_ref(); let default_config = helpers::get_merchant_default_config( db, merchant_account.get_id().get_string_repr(), transaction_type, ) .await?; utils::when(default_config.len() != updated_config.len(), || { Err(errors::ApiErrorResponse::PreconditionFailed { message: "current config and updated config have different lengths".to_string(), }) })?; let existing_set: FxHashSet<String> = FxHashSet::from_iter(default_config.iter().map(|c| c.to_string())); let updated_set: FxHashSet<String> = FxHashSet::from_iter(updated_config.iter().map(|c| c.to_string())); let symmetric_diff: Vec<String> = existing_set .symmetric_difference(&updated_set) .cloned() .collect(); utils::when(!symmetric_diff.is_empty(), || { Err(errors::ApiErrorResponse::InvalidRequestData { message: format!( "connector mismatch between old and new configs ({})", symmetric_diff.join(", ") ), }) })?; helpers::update_merchant_default_config( db, merchant_account.get_id().get_string_repr(), updated_config.clone(), transaction_type, ) .await?; metrics::ROUTING_UPDATE_CONFIG_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json(updated_config)) } #[cfg(feature = "v2")] pub async fn retrieve_default_fallback_algorithm_for_profile( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, profile_id: common_utils::id_type::ProfileId, ) -> RouterResponse<Vec<routing_types::RoutableConnectorChoice>> { metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let profile = core_utils::validate_and_get_business_profile( db, key_manager_state, &key_store, Some(&profile_id), merchant_account.get_id(), ) .await? .get_required_value("Profile")?; let connectors_choice = admin::ProfileWrapper::new(profile) .get_default_fallback_list_of_connector_under_profile()?; metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json(connectors_choice)) } #[cfg(feature = "v1")] pub async fn retrieve_default_routing_config( state: SessionState, profile_id: Option<common_utils::id_type::ProfileId>, merchant_account: domain::MerchantAccount, transaction_type: &enums::TransactionType, ) -> RouterResponse<Vec<routing_types::RoutableConnectorChoice>> { metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG.add(1, &[]); let db = state.store.as_ref(); let id = profile_id .map(|profile_id| profile_id.get_string_repr().to_owned()) .unwrap_or_else(|| merchant_account.get_id().get_string_repr().to_string()); helpers::get_merchant_default_config(db, &id, transaction_type) .await .map(|conn_choice| { metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG_SUCCESS_RESPONSE.add(1, &[]); service_api::ApplicationResponse::Json(conn_choice) }) } #[cfg(feature = "v2")] pub async fn retrieve_routing_config_under_profile( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, query_params: RoutingRetrieveQuery, profile_id: common_utils::id_type::ProfileId, transaction_type: &enums::TransactionType, ) -> RouterResponse<routing_types::LinkedRoutingConfigRetrieveResponse> { metrics::ROUTING_RETRIEVE_LINK_CONFIG.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let business_profile = core_utils::validate_and_get_business_profile( db, key_manager_state, &key_store, Some(&profile_id), merchant_account.get_id(), ) .await? .get_required_value("Profile")?; let record = db .list_routing_algorithm_metadata_by_profile_id( business_profile.get_id(), i64::from(query_params.limit.unwrap_or_default()), i64::from(query_params.offset.unwrap_or_default()), ) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; let active_algorithms = record .into_iter() .filter(|routing_rec| &routing_rec.algorithm_for == transaction_type) .map(|routing_algo| routing_algo.foreign_into()) .collect::<Vec<_>>(); metrics::ROUTING_RETRIEVE_LINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json( routing_types::LinkedRoutingConfigRetrieveResponse::ProfileBased(active_algorithms), )) } #[cfg(feature = "v1")] pub async fn retrieve_linked_routing_config( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, authentication_profile_id: Option<common_utils::id_type::ProfileId>, query_params: routing_types::RoutingRetrieveLinkQuery, transaction_type: &enums::TransactionType, ) -> RouterResponse<routing_types::LinkedRoutingConfigRetrieveResponse> { metrics::ROUTING_RETRIEVE_LINK_CONFIG.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let business_profiles = if let Some(profile_id) = query_params.profile_id { core_utils::validate_and_get_business_profile( db, key_manager_state, &key_store, Some(&profile_id), merchant_account.get_id(), ) .await? .map(|profile| vec![profile]) .get_required_value("Profile") .change_context(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })? } else { let business_profile = db .list_profile_by_merchant_id(key_manager_state, &key_store, merchant_account.get_id()) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; core_utils::filter_objects_based_on_profile_id_list( authentication_profile_id.map(|profile_id| vec![profile_id]), business_profile.clone(), ) }; let mut active_algorithms = Vec::new(); for business_profile in business_profiles { let profile_id = business_profile.get_id().to_owned(); let routing_ref: routing_types::RoutingAlgorithmRef = match transaction_type { enums::TransactionType::Payment => business_profile.routing_algorithm, #[cfg(feature = "payouts")] enums::TransactionType::Payout => business_profile.payout_routing_algorithm, } .clone() .map(|val| val.parse_value("RoutingAlgorithmRef")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to deserialize routing algorithm ref from merchant account")? .unwrap_or_default(); if let Some(algorithm_id) = routing_ref.algorithm_id { let record = db .find_routing_algorithm_metadata_by_algorithm_id_profile_id( &algorithm_id, &profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; active_algorithms.push(record.foreign_into()); } } metrics::ROUTING_RETRIEVE_LINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json( routing_types::LinkedRoutingConfigRetrieveResponse::ProfileBased(active_algorithms), )) } // List all the default fallback algorithms under all the profile under a merchant pub async fn retrieve_default_routing_config_for_profiles( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, transaction_type: &enums::TransactionType, ) -> RouterResponse<Vec<routing_types::ProfileDefaultRoutingConfig>> { metrics::ROUTING_RETRIEVE_CONFIG_FOR_PROFILE.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let all_profiles = db .list_profile_by_merchant_id(key_manager_state, &key_store, merchant_account.get_id()) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound) .attach_printable("error retrieving all business profiles for merchant")?; let retrieve_config_futures = all_profiles .iter() .map(|prof| { helpers::get_merchant_default_config( db, prof.get_id().get_string_repr(), transaction_type, ) }) .collect::<Vec<_>>(); let configs = futures::future::join_all(retrieve_config_futures) .await .into_iter() .collect::<Result<Vec<_>, _>>()?; let default_configs = configs .into_iter() .zip(all_profiles.iter().map(|prof| prof.get_id().to_owned())) .map( |(config, profile_id)| routing_types::ProfileDefaultRoutingConfig { profile_id, connectors: config, }, ) .collect::<Vec<_>>(); metrics::ROUTING_RETRIEVE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json(default_configs)) } pub async fn update_default_routing_config_for_profile( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, updated_config: Vec<routing_types::RoutableConnectorChoice>, profile_id: common_utils::id_type::ProfileId, transaction_type: &enums::TransactionType, ) -> RouterResponse<routing_types::ProfileDefaultRoutingConfig> { metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let business_profile = core_utils::validate_and_get_business_profile( db, key_manager_state, &key_store, Some(&profile_id), merchant_account.get_id(), ) .await? .get_required_value("Profile") .change_context(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let default_config = helpers::get_merchant_default_config( db, business_profile.get_id().get_string_repr(), transaction_type, ) .await?; utils::when(default_config.len() != updated_config.len(), || { Err(errors::ApiErrorResponse::PreconditionFailed { message: "current config and updated config have different lengths".to_string(), }) })?; let existing_set = FxHashSet::from_iter( default_config .iter() .map(|c| (c.connector.to_string(), c.merchant_connector_id.as_ref())), ); let updated_set = FxHashSet::from_iter( updated_config .iter() .map(|c| (c.connector.to_string(), c.merchant_connector_id.as_ref())), ); let symmetric_diff = existing_set .symmetric_difference(&updated_set) .cloned() .collect::<Vec<_>>(); utils::when(!symmetric_diff.is_empty(), || { let error_str = symmetric_diff .into_iter() .map(|(connector, ident)| format!("'{connector}:{ident:?}'")) .collect::<Vec<_>>() .join(", "); Err(errors::ApiErrorResponse::InvalidRequestData { message: format!("connector mismatch between old and new configs ({error_str})"), }) })?; helpers::update_merchant_default_config( db, business_profile.get_id().get_string_repr(), updated_config.clone(), transaction_type, ) .await?; metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json( routing_types::ProfileDefaultRoutingConfig { profile_id: business_profile.get_id().to_owned(), connectors: updated_config, }, )) } // Toggle the specific routing type as well as add the default configs in RoutingAlgorithm table // and update the same in business profile table. #[cfg(all(feature = "v1", feature = "dynamic_routing"))] pub async fn toggle_specific_dynamic_routing( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, feature_to_enable: routing::DynamicRoutingFeatures, profile_id: common_utils::id_type::ProfileId, dynamic_routing_type: routing::DynamicRoutingType, ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { metrics::ROUTING_CREATE_REQUEST_RECEIVED.add( 1, router_env::metric_attributes!(("profile_id", profile_id.clone())), ); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let business_profile: domain::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") .change_context(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let dynamic_routing_algo_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(); match feature_to_enable { routing::DynamicRoutingFeatures::Metrics | routing::DynamicRoutingFeatures::DynamicConnectorSelection => { // occurs when algorithm is already present in the db // 1. If present with same feature then return response as already enabled // 2. Else update the feature and persist the same on db // 3. If not present in db then create a new default entry helpers::enable_dynamic_routing_algorithm( &state, key_store, business_profile, feature_to_enable, dynamic_routing_algo_ref, dynamic_routing_type, ) .await } routing::DynamicRoutingFeatures::None => { // disable specific dynamic routing for the requested profile helpers::disable_dynamic_routing_algorithm( &state, key_store, business_profile, dynamic_routing_algo_ref, dynamic_routing_type, ) .await } } } #[cfg(feature = "v1")] pub async fn configure_dynamic_routing_volume_split( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, profile_id: common_utils::id_type::ProfileId, routing_info: routing::RoutingVolumeSplit, ) -> RouterResponse<()> { metrics::ROUTING_CREATE_REQUEST_RECEIVED.add( 1, router_env::metric_attributes!(("profile_id", profile_id.clone())), ); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); utils::when( routing_info.split > crate::consts::DYNAMIC_ROUTING_MAX_VOLUME, || { Err(errors::ApiErrorResponse::InvalidRequestData { message: "Dynamic routing volume split should be less than 100".to_string(), }) }, )?; let business_profile: domain::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") .change_context(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let mut dynamic_routing_algo_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(); dynamic_routing_algo_ref.update_volume_split(Some(routing_info.split)); helpers::update_business_profile_active_dynamic_algorithm_ref( db, &((&state).into()), &key_store, business_profile.clone(), dynamic_routing_algo_ref.clone(), ) .await?; Ok(service_api::ApplicationResponse::StatusOk) } #[cfg(all(feature = "v1", feature = "dynamic_routing"))] pub async fn success_based_routing_update_configs( state: SessionState, request: routing_types::SuccessBasedRoutingConfig, algorithm_id: common_utils::id_type::RoutingId, profile_id: common_utils::id_type::ProfileId, ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE.add( 1, router_env::metric_attributes!(("profile_id", profile_id.clone())), ); let db = state.store.as_ref(); let dynamic_routing_algo_to_update = db .find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algorithm_id) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; let mut config_to_update: routing::SuccessBasedRoutingConfig = dynamic_routing_algo_to_update .algorithm_data .parse_value::<routing::SuccessBasedRoutingConfig>("SuccessBasedRoutingConfig") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to deserialize algorithm data from routing table into SuccessBasedRoutingConfig")?; config_to_update.update(request); let updated_algorithm_id = common_utils::generate_routing_id_of_default_length(); let timestamp = common_utils::date_time::now(); let algo = RoutingAlgorithm { algorithm_id: updated_algorithm_id, profile_id: dynamic_routing_algo_to_update.profile_id, merchant_id: dynamic_routing_algo_to_update.merchant_id, name: dynamic_routing_algo_to_update.name, description: dynamic_routing_algo_to_update.description, kind: dynamic_routing_algo_to_update.kind, algorithm_data: serde_json::json!(config_to_update), created_at: timestamp, modified_at: timestamp, algorithm_for: dynamic_routing_algo_to_update.algorithm_for, }; let record = db .insert_routing_algorithm(algo) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to insert record in routing algorithm table")?; // redact cache for success based routing configs let cache_key = format!( "{}_{}", profile_id.get_string_repr(), algorithm_id.get_string_repr() ); let cache_entries_to_redact = vec![cache::CacheKind::SuccessBasedDynamicRoutingCache( cache_key.into(), )]; let _ = cache::redact_from_redis_and_publish( state.store.get_cache_store().as_ref(), cache_entries_to_redact, ) .await .map_err(|e| logger::error!("unable to publish into the redact channel for evicting the success based routing config cache {e:?}")); let new_record = record.foreign_into(); metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE.add( 1, router_env::metric_attributes!(("profile_id", profile_id.clone())), ); state .grpc_client .dynamic_routing .success_rate_client .as_ref() .async_map(|sr_client| async { sr_client .invalidate_success_rate_routing_keys( profile_id.get_string_repr().into(), state.get_grpc_headers(), ) .await .change_context(errors::ApiErrorResponse::GenericNotFoundError { message: "Failed to invalidate the routing keys".to_string(), }) }) .await .transpose()?; Ok(service_api::ApplicationResponse::Json(new_record)) } #[cfg(all(feature = "v1", feature = "dynamic_routing"))] pub async fn contract_based_dynamic_routing_setup( state: SessionState, key_store: domain::MerchantKeyStore, merchant_account: domain::MerchantAccount, profile_id: common_utils::id_type::ProfileId, feature_to_enable: routing_types::DynamicRoutingFeatures, config: Option<routing_types::ContractBasedRoutingConfig>, ) -> RouterResult<service_api::ApplicationResponse<routing_types::RoutingDictionaryRecord>> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let business_profile: domain::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") .change_context(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let mut dynamic_routing_algo_ref: Option<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", ) .ok() .flatten(); utils::when( dynamic_routing_algo_ref .as_mut() .and_then(|algo| { algo.contract_based_routing.as_mut().map(|contract_algo| { *contract_algo.get_enabled_features() == feature_to_enable && contract_algo .clone() .get_algorithm_id_with_timestamp() .algorithm_id .is_some() }) }) .unwrap_or(false), || { Err(errors::ApiErrorResponse::PreconditionFailed { message: "Contract Routing with specified features is already enabled".to_string(), }) }, )?; if feature_to_enable == routing::DynamicRoutingFeatures::None { let algorithm = dynamic_routing_algo_ref .clone() .get_required_value("dynamic_routing_algo_ref") .attach_printable("Failed to get dynamic_routing_algo_ref")?; return helpers::disable_dynamic_routing_algorithm( &state, key_store, business_profile, algorithm, routing_types::DynamicRoutingType::ContractBasedRouting, ) .await; } let config = config .get_required_value("ContractBasedRoutingConfig") .attach_printable("Failed to get ContractBasedRoutingConfig from request")?; 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 = RoutingAlgorithm { algorithm_id: algorithm_id.clone(), profile_id: profile_id.clone(), merchant_id, name: helpers::CONTRACT_BASED_DYNAMIC_ROUTING_ALGORITHM.to_string(), description: None, kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic, algorithm_data: serde_json::json!(config), created_at: timestamp, modified_at: timestamp, algorithm_for: common_enums::TransactionType::Payment, }; // 1. if dynamic_routing_algo_ref already present, insert contract based algo and disable success based // 2. if dynamic_routing_algo_ref is not present, create a new dynamic_routing_algo_ref with contract algo set up let final_algorithm = if let Some(mut algo) = dynamic_routing_algo_ref { algo.update_algorithm_id( algorithm_id, feature_to_enable, routing_types::DynamicRoutingType::ContractBasedRouting, ); if feature_to_enable == routing::DynamicRoutingFeatures::DynamicConnectorSelection { algo.disable_algorithm_id(routing_types::DynamicRoutingType::SuccessRateBasedRouting); } algo } else { let contract_algo = routing_types::ContractRoutingAlgorithm { algorithm_id_with_timestamp: routing_types::DynamicAlgorithmWithTimestamp::new(Some( algorithm_id.clone(), )), enabled_feature: feature_to_enable, }; routing_types::DynamicRoutingAlgorithmRef { success_based_algorithm: None, elimination_routing_algorithm: None, dynamic_routing_volume_split: None, contract_based_routing: Some(contract_algo), } }; // validate the contained mca_ids let mut contained_mca = Vec::new(); if let Some(info_vec) = &config.label_info { for info in info_vec { utils::when( contained_mca.iter().any(|mca_id| mca_id == &info.mca_id), || { Err(error_stack::Report::new( errors::ApiErrorResponse::InvalidRequestData { message: "Duplicate mca configuration received".to_string(), }, )) }, )?; contained_mca.push(info.mca_id.to_owned()); } let validation_futures: Vec<_> = info_vec .iter() .map(|info| async { let mca_id = info.mca_id.clone(); let label = info.label.clone(); let mca = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_account.get_id(), &mca_id, &key_store, ) .await .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: mca_id.get_string_repr().to_owned(), })?; utils::when(mca.connector_name != label, || { Err(error_stack::Report::new( errors::ApiErrorResponse::InvalidRequestData { message: "Incorrect mca configuration received".to_string(), }, )) })?; Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(()) }) .collect(); futures::future::try_join_all(validation_futures).await?; } let record = db .insert_routing_algorithm(algo) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to insert record in routing algorithm table")?; helpers::update_business_profile_active_dynamic_algorithm_ref( db, key_manager_state, &key_store, business_profile, final_algorithm, ) .await?; let new_record = record.foreign_into(); metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add( 1, router_env::metric_attributes!(("profile_id", profile_id.get_string_repr().to_string())), ); Ok(service_api::ApplicationResponse::Json(new_record)) } #[cfg(all(feature = "v1", feature = "dynamic_routing"))] pub async fn contract_based_routing_update_configs( state: SessionState, request: routing_types::ContractBasedRoutingConfig, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, algorithm_id: common_utils::id_type::RoutingId, profile_id: common_utils::id_type::ProfileId, ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE.add( 1, router_env::metric_attributes!(("profile_id", profile_id.get_string_repr().to_owned())), ); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let dynamic_routing_algo_to_update = db .find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algorithm_id) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; let mut config_to_update: routing::ContractBasedRoutingConfig = dynamic_routing_algo_to_update .algorithm_data .parse_value::<routing::ContractBasedRoutingConfig>("ContractBasedRoutingConfig") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to deserialize algorithm data from routing table into ContractBasedRoutingConfig")?; // validate the contained mca_ids let mut contained_mca = Vec::new(); if let Some(info_vec) = &request.label_info { for info in info_vec { let mca = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_account.get_id(), &info.mca_id, &key_store, ) .await .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: info.mca_id.get_string_repr().to_owned(), })?; utils::when(mca.connector_name != info.label, || { Err(errors::ApiErrorResponse::InvalidRequestData { message: "Incorrect mca configuration received".to_string(), }) })?; utils::when( contained_mca.iter().any(|mca_id| mca_id == &info.mca_id), || { Err(error_stack::Report::new( errors::ApiErrorResponse::InvalidRequestData { message: "Duplicate mca configuration received".to_string(), }, )) }, )?; contained_mca.push(info.mca_id.to_owned()); } } config_to_update.update(request); let updated_algorithm_id = common_utils::generate_routing_id_of_default_length(); let timestamp = common_utils::date_time::now(); let algo = RoutingAlgorithm { algorithm_id: updated_algorithm_id, profile_id: dynamic_routing_algo_to_update.profile_id, merchant_id: dynamic_routing_algo_to_update.merchant_id, name: dynamic_routing_algo_to_update.name, description: dynamic_routing_algo_to_update.description, kind: dynamic_routing_algo_to_update.kind, algorithm_data: serde_json::json!(config_to_update), created_at: timestamp, modified_at: timestamp, algorithm_for: dynamic_routing_algo_to_update.algorithm_for, }; let record = db .insert_routing_algorithm(algo) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to insert record in routing algorithm table")?; // redact cache for contract based routing configs let cache_key = format!( "{}_{}", profile_id.get_string_repr(), algorithm_id.get_string_repr() ); let cache_entries_to_redact = vec![cache::CacheKind::ContractBasedDynamicRoutingCache( cache_key.into(), )]; let _ = cache::redact_from_redis_and_publish( state.store.get_cache_store().as_ref(), cache_entries_to_redact, ) .await .map_err(|e| logger::error!("unable to publish into the redact channel for evicting the contract based routing config cache {e:?}")); let new_record = record.foreign_into(); metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE.add( 1, router_env::metric_attributes!(("profile_id", profile_id.get_string_repr().to_owned())), ); state .grpc_client .clone() .dynamic_routing .contract_based_client .clone() .async_map(|ct_client| async move { ct_client .invalidate_contracts( profile_id.get_string_repr().into(), state.get_grpc_headers(), ) .await .change_context(errors::ApiErrorResponse::GenericNotFoundError { message: "Failed to invalidate the contract based routing keys".to_string(), }) }) .await .transpose()?; Ok(service_api::ApplicationResponse::Json(new_record)) } #[async_trait] pub trait GetRoutableConnectorsForChoice { async fn get_routable_connectors( &self, db: &dyn StorageInterface, business_profile: &domain::Profile, ) -> RouterResult<RoutableConnectors>; } pub struct StraightThroughAlgorithmTypeSingle(pub serde_json::Value); #[async_trait] impl GetRoutableConnectorsForChoice for StraightThroughAlgorithmTypeSingle { async fn get_routable_connectors( &self, _db: &dyn StorageInterface, _business_profile: &domain::Profile, ) -> RouterResult<RoutableConnectors> { let straight_through_routing_algorithm = self .0 .clone() .parse_value::<api::routing::StraightThroughAlgorithm>("RoutingAlgorithm") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse the straight through routing algorithm")?; let routable_connector = match straight_through_routing_algorithm { api::routing::StraightThroughAlgorithm::Single(connector) => { vec![*connector] } api::routing::StraightThroughAlgorithm::Priority(_) | api::routing::StraightThroughAlgorithm::VolumeSplit(_) => { Err(errors::RoutingError::DslIncorrectSelectionAlgorithm) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Unsupported algorithm received as a result of static routing", )? } }; Ok(RoutableConnectors(routable_connector)) } } pub struct DecideConnector; #[async_trait] impl GetRoutableConnectorsForChoice for DecideConnector { async fn get_routable_connectors( &self, db: &dyn StorageInterface, business_profile: &domain::Profile, ) -> RouterResult<RoutableConnectors> { let fallback_config = helpers::get_merchant_default_config( db, business_profile.get_id().get_string_repr(), &common_enums::TransactionType::Payment, ) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; Ok(RoutableConnectors(fallback_config)) } } pub struct RoutableConnectors(Vec<routing_types::RoutableConnectorChoice>); impl RoutableConnectors { pub fn filter_network_transaction_id_flow_supported_connectors( self, nit_connectors: HashSet<String>, ) -> Self { let connectors = self .0 .into_iter() .filter(|routable_connector_choice| { nit_connectors.contains(&routable_connector_choice.connector.to_string()) }) .collect(); Self(connectors) } pub async fn construct_dsl_and_perform_eligibility_analysis<F, D>( self, state: &SessionState, key_store: &domain::MerchantKeyStore, payment_data: &D, profile_id: &common_utils::id_type::ProfileId, ) -> RouterResult<Vec<api::ConnectorData>> where F: Send + Clone, D: OperationSessionGetters<F>, { let payments_dsl_input = PaymentsDslInput::new( payment_data.get_setup_mandate(), payment_data.get_payment_attempt(), payment_data.get_payment_intent(), payment_data.get_payment_method_data(), payment_data.get_address(), payment_data.get_recurring_details(), payment_data.get_currency(), ); let routable_connector_choice = self.0.clone(); let backend_input = payments_routing::make_dsl_input(&payments_dsl_input) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct dsl input")?; let connectors = payments_routing::perform_cgraph_filtering( state, key_store, routable_connector_choice, backend_input, None, profile_id, &common_enums::TransactionType::Payment, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Eligibility analysis failed for routable connectors")?; let connector_data = connectors .into_iter() .map(|conn| { api::ConnectorData::get_connector_by_name( &state.conf.connectors, &conn.connector.to_string(), api::GetToken::Connector, conn.merchant_connector_id.clone(), ) }) .collect::<CustomResult<Vec<_>, _>>() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received")?; Ok(connector_data) } }
14,319
1,565
hyperswitch
crates/router/src/core/pm_auth.rs
.rs
use std::{collections::HashMap, str::FromStr}; use api_models::{ enums, payment_methods::{self, BankAccountAccessCreds}, }; use common_enums::{enums::MerchantStorageScheme, PaymentMethodType}; use hex; pub mod helpers; pub mod transformers; use common_utils::{ consts, crypto::{HmacSha256, SignMessage}, ext_traits::{AsyncExt, ValueExt}, generate_id, types::{self as util_types, AmountConvertor}, }; use error_stack::ResultExt; use helpers::PaymentAuthConnectorDataExt; use hyperswitch_domain_models::payments::PaymentIntent; 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}, }; #[cfg(feature = "v1")] pub async fn create_link_token( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, payload: api_models::pm_auth::LinkTokenCreateRequest, headers: Option<hyperswitch_domain_models::payments::HeaderPayload>, ) -> RouterResponse<api_models::pm_auth::LinkTokenCreateResponse> { let db = &*state.store; 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::InternalServerError) .attach_printable("Failed to get payment method auth choices from redis")?; let selected_config = pm_auth_configs .into_iter() .find(|config| { config.payment_method == payload.payment_method && config.payment_method_type == payload.payment_method_type }) .ok_or(ApiErrorResponse::GenericNotFoundError { message: "payment method auth connector name not found".to_string(), })?; let connector_name = selected_config.connector_name.as_str(); let connector = PaymentAuthConnectorData::get_connector_by_name(connector_name)?; let connector_integration: BoxedConnectorIntegration< '_, LinkToken, pm_auth_types::LinkTokenRequest, pm_auth_types::LinkTokenResponse, > = connector.connector.get_connector_integration(); let payment_intent = oss_helpers::verify_payment_intent_time_and_client_secret( &state, &merchant_account, &key_store, payload.client_secret, ) .await?; let billing_country = payment_intent .as_ref() .async_map(|pi| async { oss_helpers::get_address_by_id( &state, pi.billing_address_id.clone(), &key_store, &pi.payment_id, merchant_account.get_id(), merchant_account.storage_scheme, ) .await }) .await .transpose()? .flatten() .and_then(|address| address.country) .map(|country| country.to_string()); #[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(), &selected_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 = { let _ = billing_country; todo!() }; let auth_type = helpers::get_connector_auth_type(merchant_connector_account)?; let router_data = pm_auth_types::LinkTokenRouterData { flow: std::marker::PhantomData, merchant_id: Some(merchant_account.get_id().clone()), connector: Some(connector_name.to_string()), request: pm_auth_types::LinkTokenRequest { client_name: "HyperSwitch".to_string(), country_codes: Some(vec![billing_country.ok_or( ApiErrorResponse::MissingRequiredField { field_name: "billing_country", }, )?]), language: payload.language, user_info: payment_intent.and_then(|pi| pi.customer_id), client_platform: headers .as_ref() .and_then(|header| header.x_client_platform.clone()), android_package_name: headers.as_ref().and_then(|header| header.x_app_id.clone()), redirect_uri: headers .as_ref() .and_then(|header| header.x_redirect_uri.clone()), }, response: Ok(pm_auth_types::LinkTokenResponse { link_token: "".to_string(), }), connector_http_status_code: None, connector_auth_type: auth_type, }; let connector_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 link token creation connector api")?; let link_token_resp = connector_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 response = api_models::pm_auth::LinkTokenCreateResponse { link_token: link_token_resp.link_token, connector: connector.connector_name.to_string(), }; Ok(ApplicationResponse::Json(response)) } #[cfg(feature = "v2")] pub async fn create_link_token( _state: SessionState, _merchant_account: domain::MerchantAccount, _key_store: domain::MerchantKeyStore, _payload: api_models::pm_auth::LinkTokenCreateRequest, _headers: Option<hyperswitch_domain_models::payments::HeaderPayload>, ) -> RouterResponse<api_models::pm_auth::LinkTokenCreateResponse> { todo!() } impl ForeignTryFrom<&types::ConnectorAuthType> for PlaidAuthType { type Error = errors::ConnectorError; fn foreign_try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { types::ConnectorAuthType::BodyKey { api_key, key1 } => { Ok::<Self, errors::ConnectorError>(Self { client_id: api_key.to_owned(), secret: key1.to_owned(), }) } _ => Err(errors::ConnectorError::FailedToObtainAuthType), } } } 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) } #[cfg(feature = "v1")] 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<()> { let db = &*state.clone().store; let (connector_name, access_token) = connector_details; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &(&state).into(), &payload.payment_id, merchant_account.get_id(), &key_store, merchant_account.storage_scheme, ) .await .to_not_found_response(ApiErrorResponse::PaymentNotFound)?; let customer_id = payment_intent .customer_id .ok_or(ApiErrorResponse::CustomerNotFound)?; #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] let payment_methods = db .find_payment_method_by_customer_id_merchant_id_list( &((&state).into()), &key_store, &customer_id, merchant_account.get_id(), None, ) .await .change_context(ApiErrorResponse::InternalServerError)?; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] let payment_methods = db .find_payment_method_by_customer_id_merchant_id_status( &((&state).into()), &key_store, &customer_id, merchant_account.get_id(), common_enums::enums::PaymentMethodStatus::Active, None, merchant_account.storage_scheme, ) .await .change_context(ApiErrorResponse::InternalServerError)?; let mut hash_to_payment_method: HashMap< String, ( domain::PaymentMethod, payment_methods::PaymentMethodDataBankCreds, ), > = HashMap::new(); let key_manager_state = (&state).into(); for pm in payment_methods { if pm.get_payment_method_type() == Some(enums::PaymentMethod::BankDebit) && pm.payment_method_data.is_some() { let bank_details_pm_data = pm .payment_method_data .clone() .map(|x| x.into_inner().expose()) .map(|v| v.parse_value("PaymentMethodsData")) .transpose() .unwrap_or_else(|error| { logger::error!(?error); None }) .and_then(|pmd| match pmd { payment_methods::PaymentMethodsData::BankDetails(bank_creds) => { Some(bank_creds) } _ => None, }) .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("Unable to parse PaymentMethodsData")?; hash_to_payment_method.insert( bank_details_pm_data.hash.clone(), (pm, bank_details_pm_data), ); } } let pm_auth_key = state .conf .payment_method_auth .get_inner() .pm_auth_key .clone() .expose(); let mut update_entries: Vec<(domain::PaymentMethod, storage::PaymentMethodUpdate)> = Vec::new(); let mut new_entries: Vec<domain::PaymentMethod> = Vec::new(); for creds in bank_account_details_resp.credentials { let (account_number, hash_string) = match creds.account_details { pm_auth_types::PaymentMethodTypeDetails::Ach(ach) => ( ach.account_number.clone(), format!( "{}-{}-{}", ach.account_number.peek(), ach.routing_number.peek(), PaymentMethodType::Ach, ), ), pm_auth_types::PaymentMethodTypeDetails::Bacs(bacs) => ( bacs.account_number.clone(), format!( "{}-{}-{}", bacs.account_number.peek(), bacs.sort_code.peek(), PaymentMethodType::Bacs ), ), pm_auth_types::PaymentMethodTypeDetails::Sepa(sepa) => ( sepa.iban.clone(), format!("{}-{}", sepa.iban.expose(), PaymentMethodType::Sepa), ), }; let generated_hash = hex::encode( HmacSha256::sign_message(&HmacSha256, pm_auth_key.as_bytes(), hash_string.as_bytes()) .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to sign the message")?, ); let contains_account = hash_to_payment_method.get(&generated_hash); let mut pmd = payment_methods::PaymentMethodDataBankCreds { mask: account_number .peek() .chars() .rev() .take(4) .collect::<String>() .chars() .rev() .collect::<String>(), hash: generated_hash, account_type: creds.account_type, account_name: creds.account_name, payment_method_type: creds.payment_method_type, connector_details: vec![payment_methods::BankAccountConnectorDetails { connector: connector_name.to_string(), mca_id: mca_id.clone(), access_token: BankAccountAccessCreds::AccessToken(access_token.clone()), account_id: creds.account_id, }], }; if let Some((pm, details)) = contains_account { pmd.connector_details.extend( details .connector_details .clone() .into_iter() .filter(|conn| conn.mca_id != mca_id), ); let payment_method_data = payment_methods::PaymentMethodsData::BankDetails(pmd); let encrypted_data = cards::create_encrypted_data(&key_manager_state, &key_store, payment_method_data) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt customer details")?; let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate { payment_method_data: Some(encrypted_data.into()), }; update_entries.push((pm.clone(), pm_update)); } else { let payment_method_data = payment_methods::PaymentMethodsData::BankDetails(pmd); let encrypted_data = cards::create_encrypted_data( &key_manager_state, &key_store, Some(payment_method_data), ) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt customer details")?; #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] let pm_id = generate_id(consts::ID_LENGTH, "pm"); #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] let pm_id = common_utils::id_type::GlobalPaymentMethodId::generate("random_cell_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to generate GlobalPaymentMethodId")?; let now = common_utils::date_time::now(); #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] let pm_new = domain::PaymentMethod { customer_id: customer_id.clone(), merchant_id: merchant_account.get_id().clone(), payment_method_id: pm_id, payment_method: Some(enums::PaymentMethod::BankDebit), payment_method_type: Some(creds.payment_method_type), status: enums::PaymentMethodStatus::Active, payment_method_issuer: None, scheme: None, metadata: None, payment_method_data: Some(encrypted_data), 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: now, last_modified: now, locker_id: None, last_used_at: now, connector_mandate_details: None, customer_acceptance: None, network_transaction_id: None, client_secret: None, payment_method_billing_address: None, updated_by: None, version: common_types::consts::API_VERSION, network_token_requestor_reference_id: None, network_token_locker_id: None, network_token_payment_method_data: None, }; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] let pm_new = domain::PaymentMethod { customer_id: customer_id.clone(), merchant_id: merchant_account.get_id().clone(), id: pm_id, payment_method_type: Some(enums::PaymentMethod::BankDebit), payment_method_subtype: Some(creds.payment_method_type), status: enums::PaymentMethodStatus::Active, metadata: None, payment_method_data: Some(encrypted_data.into()), created_at: now, last_modified: now, locker_id: None, last_used_at: now, connector_mandate_details: None, customer_acceptance: None, network_transaction_id: None, client_secret: None, payment_method_billing_address: None, updated_by: None, locker_fingerprint_id: None, version: common_types::consts::API_VERSION, network_token_requestor_reference_id: None, network_token_locker_id: None, network_token_payment_method_data: None, }; new_entries.push(pm_new); }; } store_in_db( &state, &key_store, update_entries, new_entries, db, merchant_account.storage_scheme, ) .await?; Ok(()) } #[cfg(feature = "v2")] 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!() } 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(()) } 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) } 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)) } 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) } #[cfg(feature = "v2")] 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)>> { todo!() } #[cfg(feature = "v1")] 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))) }
6,912
1,566
hyperswitch
crates/router/src/core/utils.rs
.rs
use std::{collections::HashSet, marker::PhantomData, str::FromStr}; use api_models::enums::{DisputeStage, DisputeStatus}; #[cfg(feature = "payouts")] use api_models::payouts::PayoutVendorAccountDetails; use common_enums::{IntentStatus, RequestIncrementalAuthorization}; #[cfg(feature = "payouts")] use common_utils::{crypto::Encryptable, pii::Email}; use common_utils::{ errors::CustomResult, ext_traits::AsyncExt, types::{keymanager::KeyManagerState, ConnectorTransactionIdTrait, MinorUnit}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ merchant_connector_account::MerchantConnectorAccount, payment_address::PaymentAddress, router_data::ErrorResponse, router_request_types, types::OrderDetailsWithAmount, }; #[cfg(feature = "payouts")] use masking::{ExposeInterface, PeekInterface}; use maud::{html, PreEscaped}; use router_env::{instrument, tracing}; use uuid::Uuid; use super::payments::helpers; #[cfg(feature = "payouts")] use super::payouts::{helpers as payout_helpers, PayoutData}; #[cfg(feature = "payouts")] use crate::core::payments; use crate::{ configs::Settings, consts, core::{ errors::{self, RouterResult, StorageErrorExt}, payments::PaymentData, }, db::StorageInterface, routes::SessionState, types::{ self, api, domain, storage::{self, enums}, PollConfig, }, utils::{generate_id, generate_uuid, OptionExt, ValueExt}, }; pub const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_DISPUTE_FLOW: &str = "irrelevant_connector_request_reference_id_in_dispute_flow"; #[cfg(feature = "payouts")] pub const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_PAYOUTS_FLOW: &str = "irrelevant_connector_request_reference_id_in_payouts_flow"; const IRRELEVANT_ATTEMPT_ID_IN_DISPUTE_FLOW: &str = "irrelevant_attempt_id_in_dispute_flow"; #[cfg(all(feature = "payouts", feature = "v2", feature = "customer_v2"))] #[instrument(skip_all)] pub async fn construct_payout_router_data<'a, F>( _state: &SessionState, _connector_data: &api::ConnectorData, _merchant_account: &domain::MerchantAccount, _payout_data: &mut PayoutData, ) -> RouterResult<types::PayoutsRouterData<F>> { todo!() } #[cfg(all( feature = "payouts", any(feature = "v1", feature = "v2"), not(feature = "customer_v2") ))] #[instrument(skip_all)] pub async fn construct_payout_router_data<'a, F>( state: &SessionState, connector_data: &api::ConnectorData, merchant_account: &domain::MerchantAccount, payout_data: &mut PayoutData, ) -> RouterResult<types::PayoutsRouterData<F>> { let merchant_connector_account = payout_data .merchant_connector_account .clone() .get_required_value("merchant_connector_account")?; let connector_name = connector_data.connector_name; let connector_auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InternalServerError)?; let billing = payout_data.billing_address.to_owned(); let billing_address = billing.map(|a| { let phone_details = api_models::payments::PhoneDetails { number: a.phone_number.clone().map(Encryptable::into_inner), country_code: a.country_code.to_owned(), }; let address_details = api_models::payments::AddressDetails { city: a.city.to_owned(), country: a.country.to_owned(), line1: a.line1.clone().map(Encryptable::into_inner), line2: a.line2.clone().map(Encryptable::into_inner), line3: a.line3.clone().map(Encryptable::into_inner), zip: a.zip.clone().map(Encryptable::into_inner), first_name: a.first_name.clone().map(Encryptable::into_inner), last_name: a.last_name.clone().map(Encryptable::into_inner), state: a.state.map(Encryptable::into_inner), }; api_models::payments::Address { phone: Some(phone_details), address: Some(address_details), email: a.email.to_owned().map(Email::from), } }); let address = PaymentAddress::new(None, billing_address.map(From::from), None, None); let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on(); let payouts = &payout_data.payouts; let payout_attempt = &payout_data.payout_attempt; let customer_details = &payout_data.customer_details; let connector_label = format!( "{}_{}", payout_data.profile_id.get_string_repr(), connector_name ); let connector_customer_id = customer_details .as_ref() .and_then(|c| c.connector_customer.as_ref()) .and_then(|connector_customer_value| { connector_customer_value .clone() .expose() .get(connector_label) .cloned() }) .and_then(|id| serde_json::from_value::<String>(id).ok()); let vendor_details: Option<PayoutVendorAccountDetails> = match api_models::enums::PayoutConnectors::try_from(connector_name.to_owned()).map_err( |err| report!(errors::ApiErrorResponse::InternalServerError).attach_printable(err), )? { api_models::enums::PayoutConnectors::Stripe => { payout_data.payouts.metadata.to_owned().and_then(|meta| { let val = meta .peek() .to_owned() .parse_value("PayoutVendorAccountDetails") .ok(); val }) } _ => None, }; let connector_transfer_method_id = payout_helpers::should_create_connector_transfer_method(&*payout_data, connector_data)?; let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_account.get_id().to_owned(), customer_id: customer_details.to_owned().map(|c| c.customer_id), tenant_id: state.tenant.tenant_id.clone(), connector_customer: connector_customer_id, connector: connector_name.to_string(), payment_id: common_utils::id_type::PaymentId::get_irrelevant_id("payout") .get_string_repr() .to_owned(), attempt_id: "".to_string(), status: enums::AttemptStatus::Failure, payment_method: enums::PaymentMethod::default(), connector_auth_type, description: None, address, auth_type: enums::AuthenticationType::default(), connector_meta_data: merchant_connector_account.get_metadata(), connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), amount_captured: None, minor_amount_captured: None, payment_method_status: None, request: types::PayoutsData { payout_id: payouts.payout_id.to_owned(), amount: payouts.amount.get_amount_as_i64(), minor_amount: payouts.amount, connector_payout_id: payout_attempt.connector_payout_id.clone(), destination_currency: payouts.destination_currency, source_currency: payouts.source_currency, entity_type: payouts.entity_type.to_owned(), payout_type: payouts.payout_type, vendor_details, priority: payouts.priority, customer_details: customer_details .to_owned() .map(|c| payments::CustomerDetails { customer_id: Some(c.customer_id), name: c.name.map(Encryptable::into_inner), email: c.email.map(Email::from), phone: c.phone.map(Encryptable::into_inner), phone_country_code: c.phone_country_code, }), connector_transfer_method_id, }, response: Ok(types::PayoutsResponseData::default()), access_token: None, session_token: None, reference_id: None, payment_method_token: None, recurring_mandate_payment_data: None, preprocessing_id: None, connector_request_reference_id: payout_attempt.payout_attempt_id.clone(), payout_method_data: payout_data.payout_method_data.to_owned(), quote_id: None, test_mode, payment_method_balance: None, connector_api_version: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, }; Ok(router_data) } #[cfg(feature = "v2")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn construct_refund_router_data<'a, F>( _state: &'a SessionState, _connector_id: &str, _merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, _money: (MinorUnit, enums::Currency), _payment_intent: &'a storage::PaymentIntent, _payment_attempt: &storage::PaymentAttempt, _refund: &'a storage::Refund, _creds_identifier: Option<String>, _split_refunds: Option<router_request_types::SplitRefundsRequest>, ) -> RouterResult<types::RefundsRouterData<F>> { todo!() } #[cfg(feature = "v1")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn construct_refund_router_data<'a, F>( state: &'a SessionState, connector_id: &str, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, money: (MinorUnit, enums::Currency), payment_intent: &'a storage::PaymentIntent, payment_attempt: &storage::PaymentAttempt, refund: &'a storage::Refund, creds_identifier: Option<String>, split_refunds: Option<router_request_types::SplitRefundsRequest>, ) -> RouterResult<types::RefundsRouterData<F>> { let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("profile_id is not set in payment_intent")?; let merchant_connector_account = helpers::get_merchant_connector_account( state, merchant_account.get_id(), creds_identifier.as_deref(), key_store, profile_id, connector_id, payment_attempt.merchant_connector_id.as_ref(), ) .await?; let auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InternalServerError)?; let status = payment_attempt.status; let (payment_amount, currency) = money; let payment_method_type = payment_attempt .payment_method .get_required_value("payment_method_type") .change_context(errors::ApiErrorResponse::InternalServerError)?; let merchant_connector_account_id_or_connector_name = payment_attempt .merchant_connector_id .as_ref() .map(|mca_id| mca_id.get_string_repr()) .unwrap_or(connector_id); let webhook_url = Some(helpers::create_webhook_url( &state.base_url.clone(), merchant_account.get_id(), merchant_connector_account_id_or_connector_name, )); let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on(); let supported_connector = &state .conf .multiple_api_version_supported_connectors .supported_connectors; let connector_enum = api_models::enums::Connector::from_str(connector_id) .change_context(errors::ConnectorError::InvalidConnectorName) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "connector", }) .attach_printable_lazy(|| format!("unable to parse connector name {connector_id:?}"))?; let connector_api_version = if supported_connector.contains(&connector_enum) { state .store .find_config_by_key(&format!("connector_api_version_{connector_id}")) .await .map(|value| value.config) .ok() } else { None }; let browser_info: Option<types::BrowserInformation> = payment_attempt .browser_info .clone() .map(|b| b.parse_value("BrowserInformation")) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "browser_info", })?; let connector_refund_id = refund.get_optional_connector_refund_id().cloned(); let capture_method = payment_attempt.capture_method; let braintree_metadata = payment_intent .connector_metadata .clone() .map(|cm| { cm.parse_value::<api_models::payments::ConnectorMetadata>("ConnectorMetadata") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed parsing ConnectorMetadata") }) .transpose()? .and_then(|cm| cm.braintree); let merchant_account_id = braintree_metadata .as_ref() .and_then(|braintree| braintree.merchant_account_id.clone()); let merchant_config_currency = braintree_metadata.and_then(|braintree| braintree.merchant_config_currency); let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_account.get_id().clone(), customer_id: payment_intent.customer_id.to_owned(), tenant_id: state.tenant.tenant_id.clone(), connector: connector_id.to_string(), payment_id: payment_attempt.payment_id.get_string_repr().to_owned(), attempt_id: payment_attempt.attempt_id.clone(), status, payment_method: payment_method_type, connector_auth_type: auth_type, description: None, // Does refund need shipping/billing address ? address: PaymentAddress::default(), auth_type: payment_attempt.authentication_type.unwrap_or_default(), connector_meta_data: merchant_connector_account.get_metadata(), connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), amount_captured: payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()), payment_method_status: None, minor_amount_captured: payment_intent.amount_captured, request: types::RefundsData { refund_id: refund.refund_id.clone(), connector_transaction_id: refund.get_connector_transaction_id().clone(), refund_amount: refund.refund_amount.get_amount_as_i64(), minor_refund_amount: refund.refund_amount, currency, payment_amount: payment_amount.get_amount_as_i64(), minor_payment_amount: payment_amount, webhook_url, connector_metadata: payment_attempt.connector_metadata.clone(), refund_connector_metadata: refund.metadata.clone(), reason: refund.refund_reason.clone(), connector_refund_id: connector_refund_id.clone(), browser_info, split_refunds, integrity_object: None, refund_status: refund.refund_status, merchant_account_id, merchant_config_currency, capture_method, }, response: Ok(types::RefundsResponseData { connector_refund_id: connector_refund_id.unwrap_or_default(), refund_status: refund.refund_status, }), access_token: None, session_token: None, reference_id: None, payment_method_token: None, connector_customer: None, recurring_mandate_payment_data: None, preprocessing_id: None, connector_request_reference_id: refund.refund_id.clone(), #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, test_mode, payment_method_balance: None, connector_api_version, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: Some(refund.refund_id.clone()), dispute_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, }; Ok(router_data) } pub fn get_or_generate_id( key: &str, provided_id: &Option<String>, prefix: &str, ) -> Result<String, errors::ApiErrorResponse> { let validate_id = |id| validate_id(id, key); provided_id .clone() .map_or(Ok(generate_id(consts::ID_LENGTH, prefix)), validate_id) } pub fn get_or_generate_uuid( key: &str, provided_id: Option<&String>, ) -> Result<String, errors::ApiErrorResponse> { let validate_id = |id: String| validate_uuid(id, key); provided_id .cloned() .map_or(Ok(generate_uuid()), validate_id) } fn invalid_id_format_error(key: &str) -> errors::ApiErrorResponse { errors::ApiErrorResponse::InvalidDataFormat { field_name: key.to_string(), expected_format: format!( "length should be less than {} characters", consts::MAX_ID_LENGTH ), } } pub fn validate_id(id: String, key: &str) -> Result<String, errors::ApiErrorResponse> { if id.len() > consts::MAX_ID_LENGTH { Err(invalid_id_format_error(key)) } else { Ok(id) } } pub fn validate_uuid(uuid: String, key: &str) -> Result<String, errors::ApiErrorResponse> { match (Uuid::parse_str(&uuid), uuid.len() > consts::MAX_ID_LENGTH) { (Ok(_), false) => Ok(uuid), (_, _) => Err(invalid_id_format_error(key)), } } #[cfg(feature = "v1")] pub fn get_split_refunds( split_refund_input: super::refunds::transformers::SplitRefundInput, ) -> RouterResult<Option<router_request_types::SplitRefundsRequest>> { match split_refund_input.split_payment_request.as_ref() { Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment(stripe_payment)) => { let (charge_id_option, charge_type_option) = match ( &split_refund_input.payment_charges, &split_refund_input.split_payment_request, ) { ( Some(common_types::payments::ConnectorChargeResponseData::StripeSplitPayment( stripe_split_payment_response, )), _, ) => ( stripe_split_payment_response.charge_id.clone(), Some(stripe_split_payment_response.charge_type.clone()), ), ( _, Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment( stripe_split_payment_request, )), ) => ( split_refund_input.charge_id, Some(stripe_split_payment_request.charge_type.clone()), ), (_, _) => (None, None), }; if let Some(charge_id) = charge_id_option { let options = super::refunds::validator::validate_stripe_charge_refund( charge_type_option, &split_refund_input.refund_request, )?; Ok(Some( router_request_types::SplitRefundsRequest::StripeSplitRefund( router_request_types::StripeSplitRefund { charge_id, charge_type: stripe_payment.charge_type.clone(), transfer_account_id: stripe_payment.transfer_account_id.clone(), options, }, ), )) } else { Ok(None) } } Some(common_types::payments::SplitPaymentsRequest::AdyenSplitPayment(_)) => { match &split_refund_input.payment_charges { Some(common_types::payments::ConnectorChargeResponseData::AdyenSplitPayment( adyen_split_payment_response, )) => { if let Some(common_types::refunds::SplitRefund::AdyenSplitRefund( split_refund_request, )) = split_refund_input.refund_request.clone() { super::refunds::validator::validate_adyen_charge_refund( adyen_split_payment_response, &split_refund_request, )?; Ok(Some( router_request_types::SplitRefundsRequest::AdyenSplitRefund( split_refund_request, ), )) } else { Ok(None) } } _ => Ok(None), } } Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment(_)) => { match ( &split_refund_input.payment_charges, &split_refund_input.refund_request, ) { ( Some(common_types::payments::ConnectorChargeResponseData::XenditSplitPayment( xendit_split_payment_response, )), Some(common_types::refunds::SplitRefund::XenditSplitRefund( split_refund_request, )), ) => { let user_id = super::refunds::validator::validate_xendit_charge_refund( xendit_split_payment_response, split_refund_request, )?; Ok(user_id.map(|for_user_id| { router_request_types::SplitRefundsRequest::XenditSplitRefund( common_types::domain::XenditSplitSubMerchantData { for_user_id }, ) })) } ( Some(common_types::payments::ConnectorChargeResponseData::XenditSplitPayment( xendit_split_payment_response, )), None, ) => { let option_for_user_id = match xendit_split_payment_response { common_types::payments::XenditChargeResponseData::MultipleSplits( common_types::payments::XenditMultipleSplitResponse { for_user_id, .. }, ) => for_user_id.clone(), common_types::payments::XenditChargeResponseData::SingleSplit( common_types::domain::XenditSplitSubMerchantData { for_user_id }, ) => Some(for_user_id.clone()), }; if option_for_user_id.is_some() { Err(errors::ApiErrorResponse::MissingRequiredField { field_name: "split_refunds.xendit_split_refund.for_user_id", })? } else { Ok(None) } } _ => Ok(None), } } _ => Ok(None), } } #[cfg(test)] mod tests { #![allow(clippy::expect_used)] use super::*; #[test] fn validate_id_length_constraint() { let payment_id = "abcdefghijlkmnopqrstuvwzyzabcdefghijknlmnopsjkdnfjsknfkjsdnfspoig".to_string(); //length = 65 let result = validate_id(payment_id, "payment_id"); assert!(result.is_err()); } #[test] fn validate_id_proper_response() { let payment_id = "abcdefghijlkmnopqrstjhbjhjhkhbhgcxdfxvmhb".to_string(); let result = validate_id(payment_id.clone(), "payment_id"); assert!(result.is_ok()); let result = result.unwrap_or_default(); assert_eq!(result, payment_id); } #[test] fn test_generate_id() { let generated_id = generate_id(consts::ID_LENGTH, "ref"); assert_eq!(generated_id.len(), consts::ID_LENGTH + 4) } #[test] fn test_filter_objects_based_on_profile_id_list() { #[derive(PartialEq, Debug, Clone)] struct Object { profile_id: Option<common_utils::id_type::ProfileId>, } impl Object { pub fn new(profile_id: &'static str) -> Self { Self { profile_id: Some( common_utils::id_type::ProfileId::try_from(std::borrow::Cow::from( profile_id, )) .expect("invalid profile ID"), ), } } } impl GetProfileId for Object { fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> { self.profile_id.as_ref() } } fn new_profile_id(profile_id: &'static str) -> common_utils::id_type::ProfileId { common_utils::id_type::ProfileId::try_from(std::borrow::Cow::from(profile_id)) .expect("invalid profile ID") } // non empty object_list and profile_id_list let object_list = vec![ Object::new("p1"), Object::new("p2"), Object::new("p2"), Object::new("p4"), Object::new("p5"), ]; let profile_id_list = vec![ new_profile_id("p1"), new_profile_id("p2"), new_profile_id("p3"), ]; let filtered_list = filter_objects_based_on_profile_id_list(Some(profile_id_list), object_list.clone()); let expected_result = vec![Object::new("p1"), Object::new("p2"), Object::new("p2")]; assert_eq!(filtered_list, expected_result); // non empty object_list and empty profile_id_list let empty_profile_id_list = vec![]; let filtered_list = filter_objects_based_on_profile_id_list( Some(empty_profile_id_list), object_list.clone(), ); let expected_result = vec![]; assert_eq!(filtered_list, expected_result); // non empty object_list and None profile_id_list let profile_id_list_as_none = None; let filtered_list = filter_objects_based_on_profile_id_list(profile_id_list_as_none, object_list); let expected_result = vec![ Object::new("p1"), Object::new("p2"), Object::new("p2"), Object::new("p4"), Object::new("p5"), ]; assert_eq!(filtered_list, expected_result); } } // Dispute Stage can move linearly from PreDispute -> Dispute -> PreArbitration pub fn validate_dispute_stage( prev_dispute_stage: DisputeStage, dispute_stage: DisputeStage, ) -> bool { match prev_dispute_stage { DisputeStage::PreDispute => true, DisputeStage::Dispute => !matches!(dispute_stage, DisputeStage::PreDispute), DisputeStage::PreArbitration => matches!(dispute_stage, DisputeStage::PreArbitration), } } //Dispute status can go from Opened -> (Expired | Accepted | Cancelled | Challenged -> (Won | Lost)) pub fn validate_dispute_status( prev_dispute_status: DisputeStatus, dispute_status: DisputeStatus, ) -> bool { match prev_dispute_status { DisputeStatus::DisputeOpened => true, DisputeStatus::DisputeExpired => { matches!(dispute_status, DisputeStatus::DisputeExpired) } DisputeStatus::DisputeAccepted => { matches!(dispute_status, DisputeStatus::DisputeAccepted) } DisputeStatus::DisputeCancelled => { matches!(dispute_status, DisputeStatus::DisputeCancelled) } DisputeStatus::DisputeChallenged => matches!( dispute_status, DisputeStatus::DisputeChallenged | DisputeStatus::DisputeWon | DisputeStatus::DisputeLost ), DisputeStatus::DisputeWon => matches!(dispute_status, DisputeStatus::DisputeWon), DisputeStatus::DisputeLost => matches!(dispute_status, DisputeStatus::DisputeLost), } } pub fn validate_dispute_stage_and_dispute_status( prev_dispute_stage: DisputeStage, prev_dispute_status: DisputeStatus, dispute_stage: DisputeStage, dispute_status: DisputeStatus, ) -> CustomResult<(), errors::WebhooksFlowError> { let dispute_stage_validation = validate_dispute_stage(prev_dispute_stage, dispute_stage); let dispute_status_validation = if dispute_stage == prev_dispute_stage { validate_dispute_status(prev_dispute_status, dispute_status) } else { true }; common_utils::fp_utils::when( !(dispute_stage_validation && dispute_status_validation), || { super::metrics::INCOMING_DISPUTE_WEBHOOK_VALIDATION_FAILURE_METRIC.add(1, &[]); Err(errors::WebhooksFlowError::DisputeWebhookValidationFailed)? }, ) } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn construct_accept_dispute_router_data<'a>( state: &'a SessionState, payment_intent: &'a storage::PaymentIntent, payment_attempt: &storage::PaymentAttempt, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, dispute: &storage::Dispute, ) -> RouterResult<types::AcceptDisputeRouterData> { let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("profile_id is not set in payment_intent")? .clone(); let merchant_connector_account = helpers::get_merchant_connector_account( state, merchant_account.get_id(), None, key_store, &profile_id, &dispute.connector, payment_attempt.merchant_connector_id.as_ref(), ) .await?; let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on(); let auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InternalServerError)?; let payment_method = payment_attempt .payment_method .get_required_value("payment_method_type")?; let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_account.get_id().clone(), connector: dispute.connector.to_string(), tenant_id: state.tenant.tenant_id.clone(), payment_id: payment_attempt.payment_id.get_string_repr().to_owned(), attempt_id: payment_attempt.attempt_id.clone(), status: payment_attempt.status, payment_method, connector_auth_type: auth_type, description: None, address: PaymentAddress::default(), auth_type: payment_attempt.authentication_type.unwrap_or_default(), connector_meta_data: merchant_connector_account.get_metadata(), connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), amount_captured: payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()), minor_amount_captured: payment_intent.amount_captured, payment_method_status: None, request: types::AcceptDisputeRequestData { dispute_id: dispute.dispute_id.clone(), connector_dispute_id: dispute.connector_dispute_id.clone(), }, response: Err(ErrorResponse::default()), access_token: None, session_token: None, reference_id: None, payment_method_token: None, connector_customer: None, customer_id: None, recurring_mandate_payment_data: None, preprocessing_id: None, connector_request_reference_id: get_connector_request_reference_id( &state.conf, merchant_account.get_id(), payment_attempt, ), #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, test_mode, payment_method_balance: None, connector_api_version: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, dispute_id: Some(dispute.dispute_id.clone()), refund_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, }; Ok(router_data) } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn construct_submit_evidence_router_data<'a>( state: &'a SessionState, payment_intent: &'a storage::PaymentIntent, payment_attempt: &storage::PaymentAttempt, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, dispute: &storage::Dispute, submit_evidence_request_data: types::SubmitEvidenceRequestData, ) -> RouterResult<types::SubmitEvidenceRouterData> { let connector_id = &dispute.connector; let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("profile_id is not set in payment_intent")? .clone(); let merchant_connector_account = helpers::get_merchant_connector_account( state, merchant_account.get_id(), None, key_store, &profile_id, connector_id, payment_attempt.merchant_connector_id.as_ref(), ) .await?; let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on(); let auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InternalServerError)?; let payment_method = payment_attempt .payment_method .get_required_value("payment_method_type")?; let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_account.get_id().clone(), connector: connector_id.to_string(), payment_id: payment_attempt.payment_id.get_string_repr().to_owned(), tenant_id: state.tenant.tenant_id.clone(), attempt_id: payment_attempt.attempt_id.clone(), status: payment_attempt.status, payment_method, connector_auth_type: auth_type, description: None, address: PaymentAddress::default(), auth_type: payment_attempt.authentication_type.unwrap_or_default(), connector_meta_data: merchant_connector_account.get_metadata(), connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), amount_captured: payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()), minor_amount_captured: payment_intent.amount_captured, request: submit_evidence_request_data, response: Err(ErrorResponse::default()), access_token: None, session_token: None, reference_id: None, payment_method_token: None, connector_customer: None, customer_id: None, recurring_mandate_payment_data: None, preprocessing_id: None, payment_method_balance: None, payment_method_status: None, connector_request_reference_id: get_connector_request_reference_id( &state.conf, merchant_account.get_id(), payment_attempt, ), #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, test_mode, connector_api_version: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: Some(dispute.dispute_id.clone()), connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, }; Ok(router_data) } #[cfg(feature = "v1")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn construct_upload_file_router_data<'a>( state: &'a SessionState, payment_intent: &'a storage::PaymentIntent, payment_attempt: &storage::PaymentAttempt, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, create_file_request: &api::CreateFileRequest, connector_id: &str, file_key: String, ) -> RouterResult<types::UploadFileRouterData> { let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("profile_id is not set in payment_intent")? .clone(); let merchant_connector_account = helpers::get_merchant_connector_account( state, merchant_account.get_id(), None, key_store, &profile_id, connector_id, payment_attempt.merchant_connector_id.as_ref(), ) .await?; let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on(); let auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InternalServerError)?; let payment_method = payment_attempt .payment_method .get_required_value("payment_method_type")?; let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_account.get_id().clone(), connector: connector_id.to_string(), payment_id: payment_attempt.payment_id.get_string_repr().to_owned(), tenant_id: state.tenant.tenant_id.clone(), attempt_id: payment_attempt.attempt_id.clone(), status: payment_attempt.status, payment_method, connector_auth_type: auth_type, description: None, address: PaymentAddress::default(), auth_type: payment_attempt.authentication_type.unwrap_or_default(), connector_meta_data: merchant_connector_account.get_metadata(), connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), amount_captured: payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()), minor_amount_captured: payment_intent.amount_captured, payment_method_status: None, request: types::UploadFileRequestData { file_key, file: create_file_request.file.clone(), file_type: create_file_request.file_type.clone(), file_size: create_file_request.file_size, }, response: Err(ErrorResponse::default()), access_token: None, session_token: None, reference_id: None, payment_method_token: None, connector_customer: None, customer_id: None, recurring_mandate_payment_data: None, preprocessing_id: None, payment_method_balance: None, connector_request_reference_id: get_connector_request_reference_id( &state.conf, merchant_account.get_id(), payment_attempt, ), #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, test_mode, connector_api_version: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, }; Ok(router_data) } #[cfg(feature = "v2")] pub async fn construct_payments_dynamic_tax_calculation_router_data<F: Clone>( state: &SessionState, merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, payment_data: &mut PaymentData<F>, merchant_connector_account: &MerchantConnectorAccount, ) -> RouterResult<types::PaymentsTaxCalculationRouterData> { todo!() } #[cfg(feature = "v1")] pub async fn construct_payments_dynamic_tax_calculation_router_data<F: Clone>( state: &SessionState, merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, payment_data: &mut PaymentData<F>, merchant_connector_account: &MerchantConnectorAccount, ) -> RouterResult<types::PaymentsTaxCalculationRouterData> { let payment_intent = &payment_data.payment_intent.clone(); let payment_attempt = &payment_data.payment_attempt.clone(); #[cfg(feature = "v1")] let test_mode: Option<bool> = merchant_connector_account.test_mode; #[cfg(feature = "v2")] let test_mode = None; let connector_auth_type: types::ConnectorAuthType = merchant_connector_account .connector_account_details .clone() .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while parsing value for ConnectorAuthType")?; let shipping_address = payment_data .tax_data .clone() .map(|tax_data| tax_data.shipping_details) .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Missing shipping_details")?; let order_details: Option<Vec<OrderDetailsWithAmount>> = payment_intent .order_details .clone() .map(|order_details| { order_details .iter() .map(|data| { data.to_owned() .parse_value("OrderDetailsWithAmount") .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "OrderDetailsWithAmount", }) .attach_printable("Unable to parse OrderDetailsWithAmount") }) .collect::<Result<Vec<_>, _>>() }) .transpose()?; let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_account.get_id().to_owned(), customer_id: None, connector_customer: None, connector: merchant_connector_account.connector_name.clone(), payment_id: payment_attempt.payment_id.get_string_repr().to_owned(), attempt_id: payment_attempt.attempt_id.clone(), tenant_id: state.tenant.tenant_id.clone(), status: payment_attempt.status, payment_method: diesel_models::enums::PaymentMethod::default(), connector_auth_type, description: None, address: payment_data.address.clone(), auth_type: payment_attempt.authentication_type.unwrap_or_default(), connector_meta_data: None, connector_wallets_details: None, amount_captured: None, access_token: None, session_token: None, reference_id: None, payment_method_token: None, recurring_mandate_payment_data: None, preprocessing_id: None, payment_method_balance: None, connector_api_version: None, request: types::PaymentsTaxCalculationData { amount: payment_intent.amount, shipping_cost: payment_intent.shipping_cost, order_details, currency: payment_data.currency, shipping_address, }, response: Err(ErrorResponse::default()), connector_request_reference_id: get_connector_request_reference_id( &state.conf, merchant_account.get_id(), payment_attempt, ), #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, test_mode, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: None, connector_response: None, payment_method_status: None, minor_amount_captured: 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, }; Ok(router_data) } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn construct_defend_dispute_router_data<'a>( state: &'a SessionState, payment_intent: &'a storage::PaymentIntent, payment_attempt: &storage::PaymentAttempt, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, dispute: &storage::Dispute, ) -> RouterResult<types::DefendDisputeRouterData> { let _db = &*state.store; let connector_id = &dispute.connector; let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("profile_id is not set in payment_intent")? .clone(); let merchant_connector_account = helpers::get_merchant_connector_account( state, merchant_account.get_id(), None, key_store, &profile_id, connector_id, payment_attempt.merchant_connector_id.as_ref(), ) .await?; let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on(); let auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InternalServerError)?; let payment_method = payment_attempt .payment_method .get_required_value("payment_method_type")?; let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_account.get_id().clone(), connector: connector_id.to_string(), payment_id: payment_attempt.payment_id.get_string_repr().to_owned(), tenant_id: state.tenant.tenant_id.clone(), attempt_id: payment_attempt.attempt_id.clone(), status: payment_attempt.status, payment_method, connector_auth_type: auth_type, description: None, address: PaymentAddress::default(), auth_type: payment_attempt.authentication_type.unwrap_or_default(), connector_meta_data: merchant_connector_account.get_metadata(), connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), amount_captured: payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()), minor_amount_captured: payment_intent.amount_captured, payment_method_status: None, request: types::DefendDisputeRequestData { dispute_id: dispute.dispute_id.clone(), connector_dispute_id: dispute.connector_dispute_id.clone(), }, response: Err(ErrorResponse::get_not_implemented()), access_token: None, session_token: None, reference_id: None, payment_method_token: None, customer_id: None, connector_customer: None, recurring_mandate_payment_data: None, preprocessing_id: None, payment_method_balance: None, connector_request_reference_id: get_connector_request_reference_id( &state.conf, merchant_account.get_id(), payment_attempt, ), #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, test_mode, connector_api_version: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: Some(dispute.dispute_id.clone()), connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, }; Ok(router_data) } #[instrument(skip_all)] pub async fn construct_retrieve_file_router_data<'a>( state: &'a SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, file_metadata: &diesel_models::file::FileMetadata, connector_id: &str, ) -> RouterResult<types::RetrieveFileRouterData> { let profile_id = file_metadata .profile_id .as_ref() .ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "profile_id", }) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("profile_id is not set in file_metadata")?; let merchant_connector_account = helpers::get_merchant_connector_account( state, merchant_account.get_id(), None, key_store, profile_id, connector_id, file_metadata.merchant_connector_id.as_ref(), ) .await?; let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on(); let auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InternalServerError)?; let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_account.get_id().clone(), connector: connector_id.to_string(), tenant_id: state.tenant.tenant_id.clone(), customer_id: None, connector_customer: None, payment_id: common_utils::id_type::PaymentId::get_irrelevant_id("dispute") .get_string_repr() .to_owned(), attempt_id: IRRELEVANT_ATTEMPT_ID_IN_DISPUTE_FLOW.to_string(), status: diesel_models::enums::AttemptStatus::default(), payment_method: diesel_models::enums::PaymentMethod::default(), connector_auth_type: auth_type, description: None, address: PaymentAddress::default(), auth_type: diesel_models::enums::AuthenticationType::default(), connector_meta_data: merchant_connector_account.get_metadata(), connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), amount_captured: None, minor_amount_captured: None, payment_method_status: None, request: types::RetrieveFileRequestData { provider_file_id: file_metadata .provider_file_id .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Missing provider file id")?, }, response: Err(ErrorResponse::default()), access_token: None, session_token: None, reference_id: None, payment_method_token: None, recurring_mandate_payment_data: None, preprocessing_id: None, payment_method_balance: None, connector_request_reference_id: IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_DISPUTE_FLOW .to_string(), #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, test_mode, connector_api_version: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, }; Ok(router_data) } pub fn is_merchant_enabled_for_payment_id_as_connector_request_id( conf: &Settings, merchant_id: &common_utils::id_type::MerchantId, ) -> bool { let config_map = &conf .connector_request_reference_id_config .merchant_ids_send_payment_id_as_connector_request_id; config_map.contains(merchant_id) } #[cfg(feature = "v1")] pub fn get_connector_request_reference_id( conf: &Settings, merchant_id: &common_utils::id_type::MerchantId, payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, ) -> String { let is_config_enabled_for_merchant = is_merchant_enabled_for_payment_id_as_connector_request_id(conf, merchant_id); // Send payment_id if config is enabled for a merchant, else send attempt_id if is_config_enabled_for_merchant { payment_attempt.payment_id.get_string_repr().to_owned() } else { payment_attempt.attempt_id.to_owned() } } // TODO: Based on the connector configuration, the connector_request_reference_id should be generated #[cfg(feature = "v2")] pub fn get_connector_request_reference_id( conf: &Settings, merchant_id: &common_utils::id_type::MerchantId, payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, ) -> String { todo!() } /// Validate whether the profile_id exists and is associated with the merchant_id pub async fn validate_and_get_business_profile( db: &dyn StorageInterface, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, profile_id: Option<&common_utils::id_type::ProfileId>, merchant_id: &common_utils::id_type::MerchantId, ) -> RouterResult<Option<domain::Profile>> { profile_id .async_map(|profile_id| async { db.find_business_profile_by_profile_id( key_manager_state, merchant_key_store, profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), }) }) .await .transpose()? .map(|business_profile| { // Check if the merchant_id of business profile is same as the current merchant_id if business_profile.merchant_id.ne(merchant_id) { Err(errors::ApiErrorResponse::AccessForbidden { resource: business_profile.get_id().get_string_repr().to_owned(), } .into()) } else { Ok(business_profile) } }) .transpose() } fn connector_needs_business_sub_label(connector_name: &str) -> bool { let connectors_list = [api_models::enums::Connector::Cybersource]; connectors_list .map(|connector| connector.to_string()) .contains(&connector_name.to_string()) } /// Create the connector label /// {connector_name}_{country}_{business_label} pub fn get_connector_label( business_country: Option<api_models::enums::CountryAlpha2>, business_label: Option<&String>, business_sub_label: Option<&String>, connector_name: &str, ) -> Option<String> { business_country .zip(business_label) .map(|(business_country, business_label)| { let mut connector_label = format!("{connector_name}_{business_country}_{business_label}"); // Business sub label is currently being used only for cybersource // To ensure backwards compatibality, cybersource mca's created before this change // will have the business_sub_label value as default. // // Even when creating the connector account, if no sub label is provided, default will be used if connector_needs_business_sub_label(connector_name) { if let Some(sub_label) = business_sub_label { connector_label.push_str(&format!("_{sub_label}")); } else { connector_label.push_str("_default"); // For backwards compatibality } } connector_label }) } #[cfg(feature = "v1")] /// If profile_id is not passed, use default profile if available, or /// If business_details (business_country and business_label) are passed, get the business_profile /// or return a `MissingRequiredField` error #[allow(clippy::too_many_arguments)] pub async fn get_profile_id_from_business_details( key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, business_country: Option<api_models::enums::CountryAlpha2>, business_label: Option<&String>, merchant_account: &domain::MerchantAccount, request_profile_id: Option<&common_utils::id_type::ProfileId>, db: &dyn StorageInterface, should_validate: bool, ) -> RouterResult<common_utils::id_type::ProfileId> { match request_profile_id.or(merchant_account.default_profile.as_ref()) { Some(profile_id) => { // Check whether this business profile belongs to the merchant if should_validate { let _ = validate_and_get_business_profile( db, key_manager_state, merchant_key_store, Some(profile_id), merchant_account.get_id(), ) .await?; } Ok(profile_id.clone()) } None => match business_country.zip(business_label) { Some((business_country, business_label)) => { let profile_name = format!("{business_country}_{business_label}"); let business_profile = db .find_business_profile_by_profile_name_merchant_id( key_manager_state, merchant_key_store, &profile_name, merchant_account.get_id(), ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_name, })?; Ok(business_profile.get_id().to_owned()) } _ => Err(report!(errors::ApiErrorResponse::MissingRequiredField { field_name: "profile_id or business_country, business_label" })), }, } } pub fn get_poll_id(merchant_id: &common_utils::id_type::MerchantId, unique_id: String) -> String { merchant_id.get_poll_id(&unique_id) } pub fn get_external_authentication_request_poll_id( payment_id: &common_utils::id_type::PaymentId, ) -> String { payment_id.get_external_authentication_request_poll_id() } #[cfg(feature = "v1")] pub fn get_html_redirect_response_for_external_authentication( return_url_with_query_params: String, payment_response: &api_models::payments::PaymentsResponse, payment_id: common_utils::id_type::PaymentId, poll_config: &PollConfig, ) -> RouterResult<String> { // if intent_status is requires_customer_action then set poll_id, fetch poll config and do a poll_status post message, else do open_url post message to redirect to return_url let html = match payment_response.status { IntentStatus::RequiresCustomerAction => { // Request poll id sent to client for retrieve_poll_status api let req_poll_id = get_external_authentication_request_poll_id(&payment_id); let poll_frequency = poll_config.frequency; let poll_delay_in_secs = poll_config.delay_in_secs; html! { head { title { "Redirect Form" } (PreEscaped(format!(r#" <script> let return_url = "{return_url_with_query_params}"; let poll_status_data = {{ 'poll_id': '{req_poll_id}', 'frequency': '{poll_frequency}', 'delay_in_secs': '{poll_delay_in_secs}', 'return_url_with_query_params': return_url }}; try {{ // if inside iframe, send post message to parent for redirection if (window.self !== window.parent) {{ window.parent.postMessage({{poll_status: poll_status_data}}, '*') // if parent, redirect self to return_url }} else {{ window.location.href = return_url }} }} catch(err) {{ // if error occurs, send post message to parent and wait for 10 secs to redirect. if doesn't redirect, redirect self to return_url window.parent.postMessage({{poll_status: poll_status_data}}, '*') setTimeout(function() {{ window.location.href = return_url }}, 10000); console.log(err.message) }} </script> "#))) } } .into_string() }, _ => { html! { head { title { "Redirect Form" } (PreEscaped(format!(r#" <script> let return_url = "{return_url_with_query_params}"; try {{ // if inside iframe, send post message to parent for redirection if (window.self !== window.parent) {{ window.parent.postMessage({{openurl_if_required: return_url}}, '*') // if parent, redirect self to return_url }} else {{ window.location.href = return_url }} }} catch(err) {{ // if error occurs, send post message to parent and wait for 10 secs to redirect. if doesn't redirect, redirect self to return_url window.parent.postMessage({{openurl_if_required: return_url}}, '*') setTimeout(function() {{ window.location.href = return_url }}, 10000); console.log(err.message) }} </script> "#))) } } .into_string() }, }; Ok(html) } #[inline] pub 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()) } pub fn get_request_incremental_authorization_value( request_incremental_authorization: Option<bool>, capture_method: Option<common_enums::CaptureMethod>, ) -> RouterResult<Option<RequestIncrementalAuthorization>> { Some(request_incremental_authorization .map(|request_incremental_authorization| { if request_incremental_authorization { if matches!( capture_method, Some(common_enums::CaptureMethod::Automatic) | Some(common_enums::CaptureMethod::SequentialAutomatic) ) { Err(errors::ApiErrorResponse::NotSupported { message: "incremental authorization is not supported when capture_method is automatic".to_owned() })? } Ok(RequestIncrementalAuthorization::True) } else { Ok(RequestIncrementalAuthorization::False) } }) .unwrap_or(Ok(RequestIncrementalAuthorization::default()))).transpose() } pub fn get_incremental_authorization_allowed_value( incremental_authorization_allowed: Option<bool>, request_incremental_authorization: Option<RequestIncrementalAuthorization>, ) -> Option<bool> { if request_incremental_authorization == Some(RequestIncrementalAuthorization::False) { Some(false) } else { incremental_authorization_allowed } } pub(crate) trait GetProfileId { fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId>; } impl GetProfileId for MerchantConnectorAccount { fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> { Some(&self.profile_id) } } impl GetProfileId for storage::PaymentIntent { #[cfg(feature = "v1")] fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> { self.profile_id.as_ref() } // TODO: handle this in a better way for v2 #[cfg(feature = "v2")] fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> { Some(&self.profile_id) } } impl<A> GetProfileId for (storage::PaymentIntent, A) { fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> { self.0.get_profile_id() } } impl GetProfileId for diesel_models::Dispute { fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> { self.profile_id.as_ref() } } impl GetProfileId for diesel_models::Refund { fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> { self.profile_id.as_ref() } } #[cfg(feature = "v1")] impl GetProfileId for api_models::routing::RoutingConfigRequest { fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> { self.profile_id.as_ref() } } #[cfg(feature = "v2")] impl GetProfileId for api_models::routing::RoutingConfigRequest { fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> { Some(&self.profile_id) } } impl GetProfileId for api_models::routing::RoutingRetrieveLinkQuery { fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> { self.profile_id.as_ref() } } impl GetProfileId for diesel_models::routing_algorithm::RoutingProfileMetadata { fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> { Some(&self.profile_id) } } impl GetProfileId for domain::Profile { fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> { Some(self.get_id()) } } #[cfg(feature = "payouts")] impl GetProfileId for storage::Payouts { fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> { Some(&self.profile_id) } } #[cfg(feature = "payouts")] impl<T, F, R> GetProfileId for (storage::Payouts, T, F, R) { fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> { self.0.get_profile_id() } } /// Filter Objects based on profile ids pub(super) fn filter_objects_based_on_profile_id_list< T: GetProfileId, U: IntoIterator<Item = T> + FromIterator<T>, >( profile_id_list_auth_layer: Option<Vec<common_utils::id_type::ProfileId>>, object_list: U, ) -> U { if let Some(profile_id_list) = profile_id_list_auth_layer { let profile_ids_to_filter: HashSet<_> = profile_id_list.iter().collect(); object_list .into_iter() .filter_map(|item| { if item .get_profile_id() .is_some_and(|profile_id| profile_ids_to_filter.contains(profile_id)) { Some(item) } else { None } }) .collect() } else { object_list } } pub(crate) fn validate_profile_id_from_auth_layer<T: GetProfileId + std::fmt::Debug>( profile_id_auth_layer: Option<common_utils::id_type::ProfileId>, object: &T, ) -> RouterResult<()> { match (profile_id_auth_layer, object.get_profile_id()) { (Some(auth_profile_id), Some(object_profile_id)) => { auth_profile_id.eq(object_profile_id).then_some(()).ok_or( errors::ApiErrorResponse::PreconditionFailed { message: "Profile id authentication failed. Please use the correct JWT token" .to_string(), } .into(), ) } (Some(_auth_profile_id), None) => RouterResult::Err( errors::ApiErrorResponse::PreconditionFailed { message: "Couldn't find profile_id in record for authentication".to_string(), } .into(), ) .attach_printable(format!("Couldn't find profile_id in entity {:?}", object)), (None, None) | (None, Some(_)) => Ok(()), } } pub(crate) trait ValidatePlatformMerchant { fn get_platform_merchant_id(&self) -> Option<&common_utils::id_type::MerchantId>; fn validate_platform_merchant( &self, auth_platform_merchant_id: Option<&common_utils::id_type::MerchantId>, ) -> CustomResult<(), errors::ApiErrorResponse> { let data_platform_merchant_id = self.get_platform_merchant_id(); match (data_platform_merchant_id, auth_platform_merchant_id) { (Some(data_platform_merchant_id), Some(auth_platform_merchant_id)) => { common_utils::fp_utils::when( data_platform_merchant_id != auth_platform_merchant_id, || { Err(report!(errors::ApiErrorResponse::PaymentNotFound)).attach_printable(format!( "Data platform merchant id: {data_platform_merchant_id:?} does not match with auth platform merchant id: {auth_platform_merchant_id:?}")) }, ) } (Some(_), None) | (None, Some(_)) => { Err(report!(errors::ApiErrorResponse::InvalidPlatformOperation)) .attach_printable("Platform merchant id is missing in either data or auth") } (None, None) => Ok(()), } } } impl ValidatePlatformMerchant for storage::PaymentIntent { fn get_platform_merchant_id(&self) -> Option<&common_utils::id_type::MerchantId> { self.platform_merchant_id.as_ref() } }
14,760
1,567
hyperswitch
crates/router/src/core/payout_link.rs
.rs
use std::{ cmp::Ordering, collections::{HashMap, HashSet}, }; use actix_web::http::header; use api_models::payouts; use common_utils::{ ext_traits::{AsyncExt, Encode, OptionExt}, link_utils, types::{AmountConvertor, StringMajorUnitForConnector}, }; use diesel_models::PayoutLinkUpdate; use error_stack::ResultExt; use hyperswitch_domain_models::api::{GenericLinks, GenericLinksData}; use super::errors::{RouterResponse, StorageErrorExt}; use crate::{ configs::settings::{PaymentMethodFilterKey, PaymentMethodFilters}, core::payouts::{helpers as payout_helpers, validator}, errors, routes::{app::StorageInterface, SessionState}, services, types::{api, domain, transformers::ForeignFrom}, }; #[cfg(all(feature = "v2", feature = "customer_v2"))] pub async fn initiate_payout_link( _state: SessionState, _merchant_account: domain::MerchantAccount, _key_store: domain::MerchantKeyStore, _req: payouts::PayoutLinkInitiateRequest, _request_headers: &header::HeaderMap, _locale: String, ) -> RouterResponse<services::GenericLinkFormData> { todo!() } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] pub async fn initiate_payout_link( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: payouts::PayoutLinkInitiateRequest, request_headers: &header::HeaderMap, ) -> RouterResponse<services::GenericLinkFormData> { let db: &dyn StorageInterface = &*state.store; let merchant_id = merchant_account.get_id(); // Fetch payout let payout = db .find_payout_by_merchant_id_payout_id( merchant_id, &req.payout_id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?; let payout_attempt = db .find_payout_attempt_by_merchant_id_payout_attempt_id( merchant_id, &format!("{}_{}", payout.payout_id, payout.attempt_count), merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?; let payout_link_id = payout .payout_link_id .clone() .get_required_value("payout link id") .change_context(errors::ApiErrorResponse::GenericNotFoundError { message: "payout link not found".to_string(), })?; // Fetch payout link let payout_link = db .find_payout_link_by_link_id(&payout_link_id) .await .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { message: "payout link not found".to_string(), })?; let allowed_domains = validator::validate_payout_link_render_request_and_get_allowed_domains( request_headers, &payout_link, )?; // Check status and return form data accordingly let has_expired = common_utils::date_time::now() > payout_link.expiry; let status = payout_link.link_status.clone(); let link_data = payout_link.link_data.clone(); let default_config = &state.conf.generic_link.payout_link.clone(); let default_ui_config = default_config.ui_config.clone(); let ui_config_data = link_utils::GenericLinkUiConfigFormData { merchant_name: link_data .ui_config .merchant_name .unwrap_or(default_ui_config.merchant_name), logo: link_data.ui_config.logo.unwrap_or(default_ui_config.logo), theme: link_data .ui_config .theme .clone() .unwrap_or(default_ui_config.theme.clone()), }; match (has_expired, &status) { // Send back generic expired page (true, _) | (_, &link_utils::PayoutLinkStatus::Invalidated) => { let expired_link_data = services::GenericExpiredLinkData { title: "Payout Expired".to_string(), message: "This payout link has expired.".to_string(), theme: link_data.ui_config.theme.unwrap_or(default_ui_config.theme), }; if status != link_utils::PayoutLinkStatus::Invalidated { let payout_link_update = PayoutLinkUpdate::StatusUpdate { link_status: link_utils::PayoutLinkStatus::Invalidated, }; db.update_payout_link(payout_link, payout_link_update) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payout links in db")?; } Ok(services::ApplicationResponse::GenericLinkForm(Box::new( GenericLinks { allowed_domains, data: GenericLinksData::ExpiredLink(expired_link_data), locale: state.locale, }, ))) } // Initiate Payout link flow (_, link_utils::PayoutLinkStatus::Initiated) => { let customer_id = link_data.customer_id; let required_amount_type = StringMajorUnitForConnector; let amount = required_amount_type .convert(payout.amount, payout.destination_currency) .change_context(errors::ApiErrorResponse::CurrencyConversionFailed)?; // Fetch customer let customer = db .find_customer_by_customer_id_merchant_id( &(&state).into(), &customer_id, &req.merchant_id, &key_store, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InvalidRequestData { message: format!( "Customer [{}] not found for link_id - {}", payout_link.primary_reference, payout_link.link_id ), }) .attach_printable_lazy(|| { format!("customer [{}] not found", payout_link.primary_reference) })?; let address = payout .address_id .as_ref() .async_map(|address_id| async { db.find_address_by_address_id(&(&state).into(), address_id, &key_store) .await }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed while fetching address [id - {:?}] for payout [id - {}]", payout.address_id, payout.payout_id ) })?; let enabled_payout_methods = filter_payout_methods( &state, &merchant_account, &key_store, &payout, address.as_ref(), ) .await?; // Fetch default enabled_payout_methods let mut default_enabled_payout_methods: Vec<link_utils::EnabledPaymentMethod> = vec![]; for (payment_method, payment_method_types) in default_config.enabled_payment_methods.clone().into_iter() { let enabled_payment_method = link_utils::EnabledPaymentMethod { payment_method, payment_method_types, }; default_enabled_payout_methods.push(enabled_payment_method); } let fallback_enabled_payout_methods = if enabled_payout_methods.is_empty() { &default_enabled_payout_methods } else { &enabled_payout_methods }; // Fetch enabled payout methods from the request. If not found, fetch the enabled payout methods from MCA, // If none are configured for merchant connector accounts, fetch them from the default enabled payout methods. let mut enabled_payment_methods = link_data .enabled_payment_methods .unwrap_or(fallback_enabled_payout_methods.to_vec()); // Sort payment methods (cards first) enabled_payment_methods.sort_by(|a, b| match (a.payment_method, b.payment_method) { (_, common_enums::PaymentMethod::Card) => Ordering::Greater, (common_enums::PaymentMethod::Card, _) => Ordering::Less, _ => Ordering::Equal, }); let required_field_override = api::RequiredFieldsOverrideRequest { billing: address .as_ref() .map(hyperswitch_domain_models::address::Address::from) .map(From::from), }; let enabled_payment_methods_with_required_fields = ForeignFrom::foreign_from(( &state.conf.payouts.required_fields, enabled_payment_methods.clone(), required_field_override, )); let js_data = payouts::PayoutLinkDetails { publishable_key: masking::Secret::new(merchant_account.publishable_key), client_secret: link_data.client_secret.clone(), payout_link_id: payout_link.link_id, payout_id: payout_link.primary_reference, customer_id: customer.customer_id, session_expiry: payout_link.expiry, return_url: payout_link .return_url .as_ref() .map(|url| url::Url::parse(url)) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse payout status link's return URL")?, ui_config: ui_config_data, enabled_payment_methods, enabled_payment_methods_with_required_fields, amount, currency: payout.destination_currency, locale: state.locale.clone(), form_layout: link_data.form_layout, test_mode: link_data.test_mode.unwrap_or(false), }; let serialized_css_content = String::new(); let serialized_js_content = format!( "window.__PAYOUT_DETAILS = {}", js_data .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize PaymentMethodCollectLinkDetails")? ); let generic_form_data = services::GenericLinkFormData { js_data: serialized_js_content, css_data: serialized_css_content, sdk_url: default_config.sdk_url.to_string(), html_meta_tags: String::new(), }; Ok(services::ApplicationResponse::GenericLinkForm(Box::new( GenericLinks { allowed_domains, data: GenericLinksData::PayoutLink(generic_form_data), locale: state.locale.clone(), }, ))) } // Send back status page (_, link_utils::PayoutLinkStatus::Submitted) => { let translated_unified_message = payout_helpers::get_translated_unified_code_and_message( &state, payout_attempt.unified_code.as_ref(), payout_attempt.unified_message.as_ref(), &state.locale.clone(), ) .await?; let js_data = payouts::PayoutLinkStatusDetails { payout_link_id: payout_link.link_id, payout_id: payout_link.primary_reference, customer_id: link_data.customer_id, session_expiry: payout_link.expiry, return_url: payout_link .return_url .as_ref() .map(|url| url::Url::parse(url)) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse payout status link's return URL")?, status: payout.status, error_code: payout_attempt.unified_code, error_message: translated_unified_message, ui_config: ui_config_data, test_mode: link_data.test_mode.unwrap_or(false), }; let serialized_css_content = String::new(); let serialized_js_content = format!( "window.__PAYOUT_DETAILS = {}", js_data .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize PaymentMethodCollectLinkDetails")? ); let generic_status_data = services::GenericLinkStatusData { js_data: serialized_js_content, css_data: serialized_css_content, }; Ok(services::ApplicationResponse::GenericLinkForm(Box::new( GenericLinks { allowed_domains, data: GenericLinksData::PayoutLinkStatus(generic_status_data), locale: state.locale.clone(), }, ))) } } } #[cfg(all(feature = "payouts", feature = "v1"))] pub async fn filter_payout_methods( state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, payout: &hyperswitch_domain_models::payouts::payouts::Payouts, address: Option<&domain::Address>, ) -> errors::RouterResult<Vec<link_utils::EnabledPaymentMethod>> { use masking::ExposeInterface; let db = &*state.store; let key_manager_state = &state.into(); //Fetch all merchant connector accounts let all_mcas = db .find_merchant_connector_account_by_merchant_id_and_disabled_list( key_manager_state, merchant_account.get_id(), false, key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; // Filter MCAs based on profile_id and connector_type let filtered_mcas = all_mcas.filter_based_on_profile_and_connector_type( &payout.profile_id, common_enums::ConnectorType::PayoutProcessor, ); let mut response: Vec<link_utils::EnabledPaymentMethod> = vec![]; let mut payment_method_list_hm: HashMap< common_enums::PaymentMethod, HashSet<common_enums::PaymentMethodType>, > = HashMap::new(); let mut bank_transfer_hash_set: HashSet<common_enums::PaymentMethodType> = HashSet::new(); let mut card_hash_set: HashSet<common_enums::PaymentMethodType> = HashSet::new(); let mut wallet_hash_set: HashSet<common_enums::PaymentMethodType> = HashSet::new(); let payout_filter_config = &state.conf.payout_method_filters.clone(); for mca in &filtered_mcas { let payout_methods = match &mca.payment_methods_enabled { Some(pm) => pm, None => continue, }; for payout_method in payout_methods.iter() { let parse_result = serde_json::from_value::<api_models::admin::PaymentMethodsEnabled>( payout_method.clone().expose(), ); if let Ok(payment_methods_enabled) = parse_result { let payment_method = payment_methods_enabled.payment_method; let payment_method_types = match payment_methods_enabled.payment_method_types { Some(payment_method_types) => payment_method_types, None => continue, }; let connector = mca.connector_name.clone(); let payout_filter = payout_filter_config.0.get(&connector); for request_payout_method_type in &payment_method_types { let currency_country_filter = check_currency_country_filters( payout_filter, request_payout_method_type, payout.destination_currency, address .as_ref() .and_then(|address| address.country) .as_ref(), )?; if currency_country_filter.unwrap_or(true) { match payment_method { common_enums::PaymentMethod::Card => { card_hash_set .insert(request_payout_method_type.payment_method_type); payment_method_list_hm .insert(payment_method, card_hash_set.clone()); } common_enums::PaymentMethod::Wallet => { wallet_hash_set .insert(request_payout_method_type.payment_method_type); payment_method_list_hm .insert(payment_method, wallet_hash_set.clone()); } common_enums::PaymentMethod::BankTransfer => { bank_transfer_hash_set .insert(request_payout_method_type.payment_method_type); payment_method_list_hm .insert(payment_method, bank_transfer_hash_set.clone()); } common_enums::PaymentMethod::CardRedirect | common_enums::PaymentMethod::PayLater | common_enums::PaymentMethod::BankRedirect | common_enums::PaymentMethod::Crypto | common_enums::PaymentMethod::BankDebit | common_enums::PaymentMethod::Reward | common_enums::PaymentMethod::RealTimePayment | common_enums::PaymentMethod::MobilePayment | common_enums::PaymentMethod::Upi | common_enums::PaymentMethod::Voucher | common_enums::PaymentMethod::OpenBanking | common_enums::PaymentMethod::GiftCard => continue, } } } } } } for (payment_method, payment_method_types) in payment_method_list_hm { if !payment_method_types.is_empty() { let enabled_payment_method = link_utils::EnabledPaymentMethod { payment_method, payment_method_types, }; response.push(enabled_payment_method); } } Ok(response) } pub fn check_currency_country_filters( payout_method_filter: Option<&PaymentMethodFilters>, request_payout_method_type: &api_models::payment_methods::RequestPaymentMethodTypes, currency: common_enums::Currency, country: Option<&common_enums::CountryAlpha2>, ) -> errors::RouterResult<Option<bool>> { if matches!( request_payout_method_type.payment_method_type, common_enums::PaymentMethodType::Credit | common_enums::PaymentMethodType::Debit ) { Ok(Some(true)) } else { let payout_method_type_filter = payout_method_filter.and_then(|payout_method_filter: &PaymentMethodFilters| { payout_method_filter .0 .get(&PaymentMethodFilterKey::PaymentMethodType( request_payout_method_type.payment_method_type, )) }); let country_filter = country.as_ref().and_then(|country| { payout_method_type_filter.and_then(|currency_country_filter| { currency_country_filter .country .as_ref() .map(|country_hash_set| country_hash_set.contains(country)) }) }); let currency_filter = payout_method_type_filter.and_then(|currency_country_filter| { currency_country_filter .currency .as_ref() .map(|currency_hash_set| currency_hash_set.contains(&currency)) }); Ok(currency_filter.or(country_filter)) } }
3,845
1,568
hyperswitch
crates/router/src/core/revenue_recovery.rs
.rs
pub mod transformers; pub mod types; use api_models::{ payments::{PaymentRevenueRecoveryMetadata, PaymentsRetrieveRequest}, process_tracker::revenue_recovery, }; use common_utils::{ self, errors::CustomResult, ext_traits::{OptionExt, ValueExt}, id_type, types::keymanager::KeyManagerState, }; use diesel_models::process_tracker::business_status; use error_stack::{self, ResultExt}; use hyperswitch_domain_models::{ api::ApplicationResponse, behaviour::ReverseConversion, errors::api_error_response, merchant_connector_account, payments::{PaymentIntent, PaymentStatusData}, ApiModelToDieselModelConvertor, }; use scheduler::errors as sch_errors; use crate::{ core::{ errors::{self, RouterResponse, RouterResult, StorageErrorExt}, payments::{self, operations::Operation}, revenue_recovery::types as pcr_types, }, db::StorageInterface, logger, routes::{metrics, SessionState}, types::{ api, storage::{self, revenue_recovery as pcr}, transformers::ForeignInto, }, }; pub const EXECUTE_WORKFLOW: &str = "EXECUTE_WORKFLOW"; pub const PSYNC_WORKFLOW: &str = "PSYNC_WORKFLOW"; pub async fn perform_execute_payment( state: &SessionState, execute_task_process: &storage::ProcessTracker, tracking_data: &pcr::PcrWorkflowTrackingData, pcr_data: &pcr::PcrPaymentData, _key_manager_state: &KeyManagerState, payment_intent: &PaymentIntent, billing_mca: &merchant_connector_account::MerchantConnectorAccount, ) -> Result<(), sch_errors::ProcessTrackerError> { let db = &*state.store; let mut pcr_metadata = payment_intent .feature_metadata .as_ref() .and_then(|feature_metadata| feature_metadata.payment_revenue_recovery_metadata.clone()) .get_required_value("Payment Revenue Recovery Metadata")? .convert_back(); let decision = pcr_types::Decision::get_decision_based_on_params( state, payment_intent.status, pcr_metadata.payment_connector_transmission, payment_intent.active_attempt_id.clone(), pcr_data, &tracking_data.global_payment_id, ) .await?; // TODO decide if its a global failure or is it requeueable error match decision { pcr_types::Decision::Execute => { let action = pcr_types::Action::execute_payment( state, pcr_data.merchant_account.get_id(), payment_intent, execute_task_process, pcr_data, &pcr_metadata, ) .await?; Box::pin(action.execute_payment_task_response_handler( state, payment_intent, execute_task_process, pcr_data, &mut pcr_metadata, billing_mca, )) .await?; } pcr_types::Decision::Psync(attempt_status, attempt_id) => { // find if a psync task is already present let task = PSYNC_WORKFLOW; let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow; let process_tracker_id = attempt_id.get_psync_revenue_recovery_id(task, runner); let psync_process = db.find_process_by_id(&process_tracker_id).await?; match psync_process { Some(_) => { let pcr_status: pcr_types::PcrAttemptStatus = attempt_status.foreign_into(); pcr_status .update_pt_status_based_on_attempt_status_for_execute_payment( db, execute_task_process, ) .await?; } None => { // insert new psync task insert_psync_pcr_task( db, pcr_data.merchant_account.get_id().clone(), payment_intent.get_id().clone(), pcr_data.profile.get_id().clone(), attempt_id.clone(), storage::ProcessTrackerRunner::PassiveRecoveryWorkflow, ) .await?; // finish the current task db.finish_process_with_business_status( execute_task_process.clone(), business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC, ) .await?; } }; } pcr_types::Decision::InvalidDecision => { db.finish_process_with_business_status( execute_task_process.clone(), business_status::EXECUTE_WORKFLOW_COMPLETE, ) .await?; logger::warn!("Abnormal State Identified") } } Ok(()) } async fn insert_psync_pcr_task( db: &dyn StorageInterface, merchant_id: id_type::MerchantId, payment_id: id_type::GlobalPaymentId, profile_id: id_type::ProfileId, payment_attempt_id: id_type::GlobalAttemptId, runner: storage::ProcessTrackerRunner, ) -> RouterResult<storage::ProcessTracker> { let task = PSYNC_WORKFLOW; let process_tracker_id = payment_attempt_id.get_psync_revenue_recovery_id(task, runner); let schedule_time = common_utils::date_time::now(); let psync_workflow_tracking_data = pcr::PcrWorkflowTrackingData { global_payment_id: payment_id, merchant_id, profile_id, payment_attempt_id, }; let tag = ["PCR"]; let process_tracker_entry = storage::ProcessTrackerNew::new( process_tracker_id, task, runner, tag, psync_workflow_tracking_data, None, schedule_time, common_types::consts::API_VERSION, ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct delete tokenized data process tracker task")?; let response = db .insert_process(process_tracker_entry) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct delete tokenized data process tracker task")?; metrics::TASKS_ADDED_COUNT.add(1, router_env::metric_attributes!(("flow", "PsyncPcr"))); Ok(response) } pub async fn call_psync_api( state: &SessionState, global_payment_id: &id_type::GlobalPaymentId, pcr_data: &pcr::PcrPaymentData, ) -> RouterResult<PaymentStatusData<api::PSync>> { let operation = payments::operations::PaymentGet; let req = PaymentsRetrieveRequest { force_sync: false, param: None, expand_attempts: true, }; // TODO : Use api handler instead of calling get_tracker and payments_operation_core // Get the tracker related information. This includes payment intent and payment attempt let get_tracker_response = operation .to_get_tracker()? .get_trackers( state, global_payment_id, &req, &pcr_data.merchant_account, &pcr_data.profile, &pcr_data.key_store, &hyperswitch_domain_models::payments::HeaderPayload::default(), None, ) .await?; let (payment_data, _req, _, _, _) = Box::pin(payments::payments_operation_core::< api::PSync, _, _, _, PaymentStatusData<api::PSync>, >( state, state.get_req_state(), pcr_data.merchant_account.clone(), pcr_data.key_store.clone(), &pcr_data.profile, operation, req, get_tracker_response, payments::CallConnectorAction::Trigger, hyperswitch_domain_models::payments::HeaderPayload::default(), )) .await?; Ok(payment_data) } pub async fn retrieve_revenue_recovery_process_tracker( state: SessionState, id: id_type::GlobalPaymentId, ) -> RouterResponse<revenue_recovery::RevenueRecoveryResponse> { let db = &*state.store; let task = EXECUTE_WORKFLOW; let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow; let process_tracker_id = id.get_execute_revenue_recovery_id(task, runner); let process_tracker = db .find_process_by_id(&process_tracker_id) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound) .attach_printable("error retrieving the process tracker id")? .get_required_value("Process Tracker") .change_context(errors::ApiErrorResponse::GenericNotFoundError { message: "Entry For the following id doesn't exists".to_owned(), })?; let tracking_data = process_tracker .tracking_data .clone() .parse_value::<pcr::PcrWorkflowTrackingData>("PCRWorkflowTrackingData") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to deserialize Pcr Workflow Tracking Data")?; let psync_task = PSYNC_WORKFLOW; let process_tracker_id_for_psync = tracking_data .payment_attempt_id .get_psync_revenue_recovery_id(psync_task, runner); let process_tracker_for_psync = db .find_process_by_id(&process_tracker_id_for_psync) .await .map_err(|e| { logger::error!("Error while retrieving psync task : {:?}", e); }) .ok() .flatten(); let schedule_time_for_psync = process_tracker_for_psync.and_then(|pt| pt.schedule_time); let response = revenue_recovery::RevenueRecoveryResponse { id: process_tracker.id, name: process_tracker.name, schedule_time_for_payment: process_tracker.schedule_time, schedule_time_for_psync, status: process_tracker.status, business_status: process_tracker.business_status, }; Ok(ApplicationResponse::Json(response)) }
2,073
1,569
hyperswitch
crates/router/src/core/customers.rs
.rs
use common_utils::{ crypto::Encryptable, errors::ReportSwitchExt, ext_traits::AsyncExt, id_type, pii, type_name, types::{ keymanager::{Identifier, KeyManagerState, ToEncryptable}, Description, }, }; use error_stack::{report, ResultExt}; use masking::{ExposeInterface, Secret, SwitchStrategy}; use router_env::{instrument, tracing}; #[cfg(all(feature = "v2", feature = "customer_v2"))] use crate::core::payment_methods::cards::create_encrypted_data; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use crate::utils::CustomerAddress; use crate::{ core::{ errors::{self, StorageErrorExt}, payment_methods::{cards, network_tokenization}, }, db::StorageInterface, pii::PeekInterface, routes::{metrics, SessionState}, services, types::{ api::customers, domain::{self, types}, storage::{self, enums}, transformers::ForeignFrom, }, }; pub const REDACTED: &str = "Redacted"; #[instrument(skip(state))] pub async fn create_customer( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, customer_data: customers::CustomerRequest, ) -> errors::CustomerResponse<customers::CustomerResponse> { let db: &dyn StorageInterface = state.store.as_ref(); let key_manager_state = &(&state).into(); let merchant_reference_id = customer_data.get_merchant_reference_id(); let merchant_id = merchant_account.get_id(); let merchant_reference_id_customer = MerchantReferenceIdForCustomer { merchant_reference_id: merchant_reference_id.as_ref(), merchant_id, merchant_account: &merchant_account, key_store: &key_store, key_manager_state, }; // We first need to validate whether the customer with the given customer id already exists // this may seem like a redundant db call, as the insert_customer will anyway return this error // // Consider a scenario where the address is inserted and then when inserting the customer, // it errors out, now the address that was inserted is not deleted merchant_reference_id_customer .verify_if_merchant_reference_not_present_by_optional_merchant_reference_id(db) .await?; let domain_customer = customer_data .create_domain_model_from_request( db, &key_store, &merchant_reference_id, &merchant_account, key_manager_state, &state, ) .await?; let customer = db .insert_customer( domain_customer, key_manager_state, &key_store, merchant_account.storage_scheme, ) .await .to_duplicate_response(errors::CustomersErrorResponse::CustomerAlreadyExists)?; customer_data.generate_response(&customer) } #[async_trait::async_trait] trait CustomerCreateBridge { async fn create_domain_model_from_request<'a>( &'a self, db: &'a dyn StorageInterface, key_store: &'a domain::MerchantKeyStore, merchant_reference_id: &'a Option<id_type::CustomerId>, merchant_account: &'a domain::MerchantAccount, key_manager_state: &'a KeyManagerState, state: &'a SessionState, ) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse>; fn generate_response<'a>( &'a self, customer: &'a domain::Customer, ) -> errors::CustomerResponse<customers::CustomerResponse>; } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[async_trait::async_trait] impl CustomerCreateBridge for customers::CustomerRequest { async fn create_domain_model_from_request<'a>( &'a self, db: &'a dyn StorageInterface, key_store: &'a domain::MerchantKeyStore, merchant_reference_id: &'a Option<id_type::CustomerId>, merchant_account: &'a domain::MerchantAccount, key_manager_state: &'a KeyManagerState, state: &'a SessionState, ) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse> { // Setting default billing address to Db let address = self.get_address(); let merchant_id = merchant_account.get_id(); let key = key_store.key.get_inner().peek(); let customer_billing_address_struct = AddressStructForDbEntry { address: address.as_ref(), customer_data: self, merchant_id, customer_id: merchant_reference_id.as_ref(), storage_scheme: merchant_account.storage_scheme, key_store, key_manager_state, state, }; let address_from_db = customer_billing_address_struct .encrypt_customer_address_and_set_to_db(db) .await?; let encrypted_data = types::crypto_operation( key_manager_state, type_name!(domain::Customer), types::CryptoOperation::BatchEncrypt( domain::FromRequestEncryptableCustomer::to_encryptable( domain::FromRequestEncryptableCustomer { name: self.name.clone(), email: self.email.clone().map(|a| a.expose().switch_strategy()), phone: self.phone.clone(), }, ), ), Identifier::Merchant(key_store.merchant_id.clone()), key, ) .await .and_then(|val| val.try_into_batchoperation()) .switch() .attach_printable("Failed while encrypting Customer")?; let encryptable_customer = domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data) .change_context(errors::CustomersErrorResponse::InternalServerError)?; Ok(domain::Customer { customer_id: merchant_reference_id .to_owned() .ok_or(errors::CustomersErrorResponse::InternalServerError)?, merchant_id: merchant_id.to_owned(), name: encryptable_customer.name, email: encryptable_customer.email.map(|email| { let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), phone: encryptable_customer.phone, description: self.description.clone(), phone_country_code: self.phone_country_code.clone(), metadata: self.metadata.clone(), connector_customer: None, address_id: address_from_db.clone().map(|addr| addr.address_id), created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), default_payment_method_id: None, updated_by: None, version: common_types::consts::API_VERSION, }) } fn generate_response<'a>( &'a self, customer: &'a domain::Customer, ) -> errors::CustomerResponse<customers::CustomerResponse> { let address = self.get_address(); Ok(services::ApplicationResponse::Json( customers::CustomerResponse::foreign_from((customer.clone(), address)), )) } } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[async_trait::async_trait] impl CustomerCreateBridge for customers::CustomerRequest { async fn create_domain_model_from_request<'a>( &'a self, _db: &'a dyn StorageInterface, key_store: &'a domain::MerchantKeyStore, merchant_reference_id: &'a Option<id_type::CustomerId>, merchant_account: &'a domain::MerchantAccount, key_state: &'a KeyManagerState, state: &'a SessionState, ) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse> { let default_customer_billing_address = self.get_default_customer_billing_address(); let encrypted_customer_billing_address = default_customer_billing_address .async_map(|billing_address| { create_encrypted_data(key_state, key_store, billing_address) }) .await .transpose() .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable("Unable to encrypt default customer billing address")?; let default_customer_shipping_address = self.get_default_customer_shipping_address(); let encrypted_customer_shipping_address = default_customer_shipping_address .async_map(|shipping_address| { create_encrypted_data(key_state, key_store, shipping_address) }) .await .transpose() .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable("Unable to encrypt default customer shipping address")?; let merchant_id = merchant_account.get_id().clone(); let key = key_store.key.get_inner().peek(); let encrypted_data = types::crypto_operation( key_state, type_name!(domain::Customer), types::CryptoOperation::BatchEncrypt( domain::FromRequestEncryptableCustomer::to_encryptable( domain::FromRequestEncryptableCustomer { name: Some(self.name.clone()), email: Some(self.email.clone().expose().switch_strategy()), phone: self.phone.clone(), }, ), ), Identifier::Merchant(key_store.merchant_id.clone()), key, ) .await .and_then(|val| val.try_into_batchoperation()) .switch() .attach_printable("Failed while encrypting Customer")?; let encryptable_customer = domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data) .change_context(errors::CustomersErrorResponse::InternalServerError)?; Ok(domain::Customer { id: id_type::GlobalCustomerId::generate(&state.conf.cell_information.id), merchant_reference_id: merchant_reference_id.to_owned(), merchant_id, name: encryptable_customer.name, email: encryptable_customer.email.map(|email| { let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), phone: encryptable_customer.phone, description: self.description.clone(), phone_country_code: self.phone_country_code.clone(), metadata: self.metadata.clone(), connector_customer: None, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), default_payment_method_id: None, updated_by: None, default_billing_address: encrypted_customer_billing_address.map(Into::into), default_shipping_address: encrypted_customer_shipping_address.map(Into::into), version: common_types::consts::API_VERSION, status: common_enums::DeleteStatus::Active, }) } fn generate_response<'a>( &'a self, customer: &'a domain::Customer, ) -> errors::CustomerResponse<customers::CustomerResponse> { Ok(services::ApplicationResponse::Json( customers::CustomerResponse::foreign_from(customer.clone()), )) } } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] struct AddressStructForDbEntry<'a> { address: Option<&'a api_models::payments::AddressDetails>, customer_data: &'a customers::CustomerRequest, merchant_id: &'a id_type::MerchantId, customer_id: Option<&'a id_type::CustomerId>, storage_scheme: common_enums::MerchantStorageScheme, key_store: &'a domain::MerchantKeyStore, key_manager_state: &'a KeyManagerState, state: &'a SessionState, } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] impl AddressStructForDbEntry<'_> { async fn encrypt_customer_address_and_set_to_db( &self, db: &dyn StorageInterface, ) -> errors::CustomResult<Option<domain::Address>, errors::CustomersErrorResponse> { let encrypted_customer_address = self .address .async_map(|addr| async { self.customer_data .get_domain_address( self.state, addr.clone(), self.merchant_id, self.customer_id .ok_or(errors::CustomersErrorResponse::InternalServerError)?, // should we raise error since in v1 appilcation is supposed to have this id or generate it at this point. self.key_store.key.get_inner().peek(), self.storage_scheme, ) .await .switch() .attach_printable("Failed while encrypting address") }) .await .transpose()?; encrypted_customer_address .async_map(|encrypt_add| async { db.insert_address_for_customers(self.key_manager_state, encrypt_add, self.key_store) .await .switch() .attach_printable("Failed while inserting new address") }) .await .transpose() } } struct MerchantReferenceIdForCustomer<'a> { merchant_reference_id: Option<&'a id_type::CustomerId>, merchant_id: &'a id_type::MerchantId, merchant_account: &'a domain::MerchantAccount, key_store: &'a domain::MerchantKeyStore, key_manager_state: &'a KeyManagerState, } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] impl<'a> MerchantReferenceIdForCustomer<'a> { async fn verify_if_merchant_reference_not_present_by_optional_merchant_reference_id( &self, db: &dyn StorageInterface, ) -> Result<Option<()>, error_stack::Report<errors::CustomersErrorResponse>> { self.merchant_reference_id .async_map(|cust| async { self.verify_if_merchant_reference_not_present_by_merchant_reference_id(cust, db) .await }) .await .transpose() } async fn verify_if_merchant_reference_not_present_by_merchant_reference_id( &self, cus: &'a id_type::CustomerId, db: &dyn StorageInterface, ) -> Result<(), error_stack::Report<errors::CustomersErrorResponse>> { match db .find_customer_by_customer_id_merchant_id( self.key_manager_state, cus, self.merchant_id, self.key_store, self.merchant_account.storage_scheme, ) .await { Err(err) => { if !err.current_context().is_db_not_found() { Err(err).switch() } else { Ok(()) } } Ok(_) => Err(report!( errors::CustomersErrorResponse::CustomerAlreadyExists )), } } } #[cfg(all(feature = "v2", feature = "customer_v2"))] impl<'a> MerchantReferenceIdForCustomer<'a> { async fn verify_if_merchant_reference_not_present_by_optional_merchant_reference_id( &self, db: &dyn StorageInterface, ) -> Result<Option<()>, error_stack::Report<errors::CustomersErrorResponse>> { self.merchant_reference_id .async_map(|merchant_ref| async { self.verify_if_merchant_reference_not_present_by_merchant_reference( merchant_ref, db, ) .await }) .await .transpose() } async fn verify_if_merchant_reference_not_present_by_merchant_reference( &self, merchant_ref: &'a id_type::CustomerId, db: &dyn StorageInterface, ) -> Result<(), error_stack::Report<errors::CustomersErrorResponse>> { match db .find_customer_by_merchant_reference_id_merchant_id( self.key_manager_state, merchant_ref, self.merchant_id, self.key_store, self.merchant_account.storage_scheme, ) .await { Err(err) => { if !err.current_context().is_db_not_found() { Err(err).switch() } else { Ok(()) } } Ok(_) => Err(report!( errors::CustomersErrorResponse::CustomerAlreadyExists )), } } } #[cfg(all(any(feature = "v1", feature = "v2",), not(feature = "customer_v2")))] #[instrument(skip(state))] pub async fn retrieve_customer( state: SessionState, merchant_account: domain::MerchantAccount, _profile_id: Option<id_type::ProfileId>, key_store: domain::MerchantKeyStore, customer_id: id_type::CustomerId, ) -> errors::CustomerResponse<customers::CustomerResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let response = db .find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id( key_manager_state, &customer_id, merchant_account.get_id(), &key_store, merchant_account.storage_scheme, ) .await .switch()? .ok_or(errors::CustomersErrorResponse::CustomerNotFound)?; let address = match &response.address_id { Some(address_id) => Some(api_models::payments::AddressDetails::from( db.find_address_by_address_id(key_manager_state, address_id, &key_store) .await .switch()?, )), None => None, }; Ok(services::ApplicationResponse::Json( customers::CustomerResponse::foreign_from((response, address)), )) } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[instrument(skip(state))] pub async fn retrieve_customer( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, id: id_type::GlobalCustomerId, ) -> errors::CustomerResponse<customers::CustomerResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let response = db .find_customer_by_global_id( key_manager_state, &id, merchant_account.get_id(), &key_store, merchant_account.storage_scheme, ) .await .switch()?; Ok(services::ApplicationResponse::Json( customers::CustomerResponse::foreign_from(response), )) } #[instrument(skip(state))] pub async fn list_customers( state: SessionState, merchant_id: id_type::MerchantId, _profile_id_list: Option<Vec<id_type::ProfileId>>, key_store: domain::MerchantKeyStore, request: customers::CustomerListRequest, ) -> errors::CustomerResponse<Vec<customers::CustomerResponse>> { let db = state.store.as_ref(); let customer_list_constraints = crate::db::customers::CustomerListConstraints { limit: request .limit .unwrap_or(crate::consts::DEFAULT_LIST_API_LIMIT), offset: request.offset, }; let domain_customers = db .list_customers_by_merchant_id( &(&state).into(), &merchant_id, &key_store, customer_list_constraints, ) .await .switch()?; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] let customers = domain_customers .into_iter() .map(|domain_customer| customers::CustomerResponse::foreign_from((domain_customer, None))) .collect(); #[cfg(all(feature = "v2", feature = "customer_v2"))] let customers = domain_customers .into_iter() .map(customers::CustomerResponse::foreign_from) .collect(); Ok(services::ApplicationResponse::Json(customers)) } #[cfg(all( feature = "v2", feature = "customer_v2", feature = "payment_methods_v2" ))] #[instrument(skip_all)] pub async fn delete_customer( state: SessionState, merchant_account: domain::MerchantAccount, id: id_type::GlobalCustomerId, key_store: domain::MerchantKeyStore, ) -> errors::CustomerResponse<customers::CustomerDeleteResponse> { let db = &*state.store; let key_manager_state = &(&state).into(); id.redact_customer_details_and_generate_response( db, &key_store, &merchant_account, key_manager_state, &state, ) .await } #[cfg(all( feature = "v2", feature = "customer_v2", feature = "payment_methods_v2" ))] #[async_trait::async_trait] impl CustomerDeleteBridge for id_type::GlobalCustomerId { async fn redact_customer_details_and_generate_response<'a>( &'a self, db: &'a dyn StorageInterface, key_store: &'a domain::MerchantKeyStore, merchant_account: &'a domain::MerchantAccount, key_manager_state: &'a KeyManagerState, state: &'a SessionState, ) -> errors::CustomerResponse<customers::CustomerDeleteResponse> { let customer_orig = db .find_customer_by_global_id( key_manager_state, self, merchant_account.get_id(), key_store, merchant_account.storage_scheme, ) .await .switch()?; let merchant_reference_id = customer_orig.merchant_reference_id.clone(); let customer_mandates = db.find_mandate_by_global_customer_id(self).await.switch()?; for mandate in customer_mandates.into_iter() { if mandate.mandate_status == enums::MandateStatus::Active { Err(errors::CustomersErrorResponse::MandateActive)? } } match db .find_payment_method_list_by_global_customer_id( key_manager_state, key_store, self, None, ) .await { // check this in review Ok(customer_payment_methods) => { for pm in customer_payment_methods.into_iter() { if pm.get_payment_method_type() == Some(enums::PaymentMethod::Card) { cards::delete_card_by_locker_id(state, self, merchant_account.get_id()) .await .switch()?; } // No solution as of now, need to discuss this further with payment_method_v2 // db.delete_payment_method( // key_manager_state, // key_store, // pm, // ) // .await // .switch()?; } } Err(error) => { if error.current_context().is_db_not_found() { Ok(()) } else { Err(error) .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable( "failed find_payment_method_by_customer_id_merchant_id_list", ) }? } }; let key = key_store.key.get_inner().peek(); let identifier = Identifier::Merchant(key_store.merchant_id.clone()); let redacted_encrypted_value: Encryptable<Secret<_>> = types::crypto_operation( key_manager_state, type_name!(storage::Address), types::CryptoOperation::Encrypt(REDACTED.to_string().into()), identifier.clone(), key, ) .await .and_then(|val| val.try_into_operation()) .switch()?; let redacted_encrypted_email = Encryptable::new( redacted_encrypted_value .clone() .into_inner() .switch_strategy(), redacted_encrypted_value.clone().into_encrypted(), ); let updated_customer = storage::CustomerUpdate::Update(Box::new(storage::CustomerGeneralUpdate { name: Some(redacted_encrypted_value.clone()), email: Box::new(Some(redacted_encrypted_email)), phone: Box::new(Some(redacted_encrypted_value.clone())), description: Some(Description::from_str_unchecked(REDACTED)), phone_country_code: Some(REDACTED.to_string()), metadata: None, connector_customer: Box::new(None), default_billing_address: None, default_shipping_address: None, default_payment_method_id: None, status: Some(common_enums::DeleteStatus::Redacted), })); db.update_customer_by_global_id( key_manager_state, self, customer_orig, merchant_account.get_id(), updated_customer, key_store, merchant_account.storage_scheme, ) .await .switch()?; let response = customers::CustomerDeleteResponse { id: self.clone(), merchant_reference_id, customer_deleted: true, address_deleted: true, payment_methods_deleted: true, }; metrics::CUSTOMER_REDACTED.add(1, &[]); Ok(services::ApplicationResponse::Json(response)) } } #[async_trait::async_trait] trait CustomerDeleteBridge { async fn redact_customer_details_and_generate_response<'a>( &'a self, db: &'a dyn StorageInterface, key_store: &'a domain::MerchantKeyStore, merchant_account: &'a domain::MerchantAccount, key_manager_state: &'a KeyManagerState, state: &'a SessionState, ) -> errors::CustomerResponse<customers::CustomerDeleteResponse>; } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "customer_v2"), not(feature = "payment_methods_v2") ))] #[instrument(skip_all)] pub async fn delete_customer( state: SessionState, merchant_account: domain::MerchantAccount, customer_id: id_type::CustomerId, key_store: domain::MerchantKeyStore, ) -> errors::CustomerResponse<customers::CustomerDeleteResponse> { let db = &*state.store; let key_manager_state = &(&state).into(); customer_id .redact_customer_details_and_generate_response( db, &key_store, &merchant_account, key_manager_state, &state, ) .await } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "customer_v2"), not(feature = "payment_methods_v2") ))] #[async_trait::async_trait] impl CustomerDeleteBridge for id_type::CustomerId { async fn redact_customer_details_and_generate_response<'a>( &'a self, db: &'a dyn StorageInterface, key_store: &'a domain::MerchantKeyStore, merchant_account: &'a domain::MerchantAccount, key_manager_state: &'a KeyManagerState, state: &'a SessionState, ) -> errors::CustomerResponse<customers::CustomerDeleteResponse> { let customer_orig = db .find_customer_by_customer_id_merchant_id( key_manager_state, self, merchant_account.get_id(), key_store, merchant_account.storage_scheme, ) .await .switch()?; let customer_mandates = db .find_mandate_by_merchant_id_customer_id(merchant_account.get_id(), self) .await .switch()?; for mandate in customer_mandates.into_iter() { if mandate.mandate_status == enums::MandateStatus::Active { Err(errors::CustomersErrorResponse::MandateActive)? } } match db .find_payment_method_by_customer_id_merchant_id_list( key_manager_state, key_store, self, merchant_account.get_id(), None, ) .await { // check this in review Ok(customer_payment_methods) => { for pm in customer_payment_methods.into_iter() { if pm.get_payment_method_type() == Some(enums::PaymentMethod::Card) { cards::delete_card_from_locker( state, self, merchant_account.get_id(), pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id), ) .await .switch()?; if let Some(network_token_ref_id) = pm.network_token_requestor_reference_id { network_tokenization::delete_network_token_from_locker_and_token_service( state, self, merchant_account.get_id(), pm.payment_method_id.clone(), pm.network_token_locker_id, network_token_ref_id, ) .await .switch()?; } } db.delete_payment_method_by_merchant_id_payment_method_id( key_manager_state, key_store, merchant_account.get_id(), &pm.payment_method_id, ) .await .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable( "failed to delete payment method while redacting customer details", )?; } } Err(error) => { if error.current_context().is_db_not_found() { Ok(()) } else { Err(error) .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable( "failed find_payment_method_by_customer_id_merchant_id_list", ) }? } }; let key = key_store.key.get_inner().peek(); let identifier = Identifier::Merchant(key_store.merchant_id.clone()); let redacted_encrypted_value: Encryptable<Secret<_>> = types::crypto_operation( key_manager_state, type_name!(storage::Address), types::CryptoOperation::Encrypt(REDACTED.to_string().into()), identifier.clone(), key, ) .await .and_then(|val| val.try_into_operation()) .switch()?; let redacted_encrypted_email = Encryptable::new( redacted_encrypted_value .clone() .into_inner() .switch_strategy(), redacted_encrypted_value.clone().into_encrypted(), ); let update_address = storage::AddressUpdate::Update { city: Some(REDACTED.to_string()), country: None, line1: Some(redacted_encrypted_value.clone()), line2: Some(redacted_encrypted_value.clone()), line3: Some(redacted_encrypted_value.clone()), state: Some(redacted_encrypted_value.clone()), zip: Some(redacted_encrypted_value.clone()), first_name: Some(redacted_encrypted_value.clone()), last_name: Some(redacted_encrypted_value.clone()), phone_number: Some(redacted_encrypted_value.clone()), country_code: Some(REDACTED.to_string()), updated_by: merchant_account.storage_scheme.to_string(), email: Some(redacted_encrypted_email), }; match db .update_address_by_merchant_id_customer_id( key_manager_state, self, merchant_account.get_id(), update_address, key_store, ) .await { Ok(_) => Ok(()), Err(error) => { if error.current_context().is_db_not_found() { Ok(()) } else { Err(error) .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable("failed update_address_by_merchant_id_customer_id") } } }?; let updated_customer = storage::CustomerUpdate::Update { name: Some(redacted_encrypted_value.clone()), email: Some( types::crypto_operation( key_manager_state, type_name!(storage::Customer), types::CryptoOperation::Encrypt(REDACTED.to_string().into()), identifier, key, ) .await .and_then(|val| val.try_into_operation()) .switch()?, ), phone: Box::new(Some(redacted_encrypted_value.clone())), description: Some(Description::from_str_unchecked(REDACTED)), phone_country_code: Some(REDACTED.to_string()), metadata: None, connector_customer: Box::new(None), address_id: None, }; db.update_customer_by_customer_id_merchant_id( key_manager_state, self.clone(), merchant_account.get_id().to_owned(), customer_orig, updated_customer, key_store, merchant_account.storage_scheme, ) .await .switch()?; let response = customers::CustomerDeleteResponse { customer_id: self.clone(), customer_deleted: true, address_deleted: true, payment_methods_deleted: true, }; metrics::CUSTOMER_REDACTED.add(1, &[]); Ok(services::ApplicationResponse::Json(response)) } } #[instrument(skip(state))] pub async fn update_customer( state: SessionState, merchant_account: domain::MerchantAccount, update_customer: customers::CustomerUpdateRequestInternal, key_store: domain::MerchantKeyStore, ) -> errors::CustomerResponse<customers::CustomerResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); //Add this in update call if customer can be updated anywhere else #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] let verify_id_for_update_customer = VerifyIdForUpdateCustomer { merchant_reference_id: &update_customer.customer_id, merchant_account: &merchant_account, key_store: &key_store, key_manager_state, }; #[cfg(all(feature = "v2", feature = "customer_v2"))] let verify_id_for_update_customer = VerifyIdForUpdateCustomer { id: &update_customer.id, merchant_account: &merchant_account, key_store: &key_store, key_manager_state, }; let customer = verify_id_for_update_customer .verify_id_and_get_customer_object(db) .await?; let updated_customer = update_customer .request .create_domain_model_from_request( db, &key_store, &merchant_account, key_manager_state, &state, &customer, ) .await?; update_customer.request.generate_response(&updated_customer) } #[async_trait::async_trait] trait CustomerUpdateBridge { async fn create_domain_model_from_request<'a>( &'a self, db: &'a dyn StorageInterface, key_store: &'a domain::MerchantKeyStore, merchant_account: &'a domain::MerchantAccount, key_manager_state: &'a KeyManagerState, state: &'a SessionState, domain_customer: &'a domain::Customer, ) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse>; fn generate_response<'a>( &'a self, customer: &'a domain::Customer, ) -> errors::CustomerResponse<customers::CustomerResponse>; } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] struct AddressStructForDbUpdate<'a> { update_customer: &'a customers::CustomerUpdateRequest, merchant_account: &'a domain::MerchantAccount, key_store: &'a domain::MerchantKeyStore, key_manager_state: &'a KeyManagerState, state: &'a SessionState, domain_customer: &'a domain::Customer, } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] impl AddressStructForDbUpdate<'_> { async fn update_address_if_sent( &self, db: &dyn StorageInterface, ) -> errors::CustomResult<Option<domain::Address>, errors::CustomersErrorResponse> { let address = if let Some(addr) = &self.update_customer.address { match self.domain_customer.address_id.clone() { Some(address_id) => { let customer_address: api_models::payments::AddressDetails = addr.clone(); let update_address = self .update_customer .get_address_update( self.state, customer_address, self.key_store.key.get_inner().peek(), self.merchant_account.storage_scheme, self.merchant_account.get_id().clone(), ) .await .switch() .attach_printable("Failed while encrypting Address while Update")?; Some( db.update_address( self.key_manager_state, address_id, update_address, self.key_store, ) .await .switch() .attach_printable(format!( "Failed while updating address: merchant_id: {:?}, customer_id: {:?}", self.merchant_account.get_id(), self.domain_customer.customer_id ))?, ) } None => { let customer_address: api_models::payments::AddressDetails = addr.clone(); let address = self .update_customer .get_domain_address( self.state, customer_address, self.merchant_account.get_id(), &self.domain_customer.customer_id, self.key_store.key.get_inner().peek(), self.merchant_account.storage_scheme, ) .await .switch() .attach_printable("Failed while encrypting address")?; Some( db.insert_address_for_customers( self.key_manager_state, address, self.key_store, ) .await .switch() .attach_printable("Failed while inserting new address")?, ) } } } else { match &self.domain_customer.address_id { Some(address_id) => Some( db.find_address_by_address_id( self.key_manager_state, address_id, self.key_store, ) .await .switch()?, ), None => None, } }; Ok(address) } } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[derive(Debug)] struct VerifyIdForUpdateCustomer<'a> { merchant_reference_id: &'a id_type::CustomerId, merchant_account: &'a domain::MerchantAccount, key_store: &'a domain::MerchantKeyStore, key_manager_state: &'a KeyManagerState, } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[derive(Debug)] struct VerifyIdForUpdateCustomer<'a> { id: &'a id_type::GlobalCustomerId, merchant_account: &'a domain::MerchantAccount, key_store: &'a domain::MerchantKeyStore, key_manager_state: &'a KeyManagerState, } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] impl VerifyIdForUpdateCustomer<'_> { async fn verify_id_and_get_customer_object( &self, db: &dyn StorageInterface, ) -> Result<domain::Customer, error_stack::Report<errors::CustomersErrorResponse>> { let customer = db .find_customer_by_customer_id_merchant_id( self.key_manager_state, self.merchant_reference_id, self.merchant_account.get_id(), self.key_store, self.merchant_account.storage_scheme, ) .await .switch()?; Ok(customer) } } #[cfg(all(feature = "v2", feature = "customer_v2"))] impl VerifyIdForUpdateCustomer<'_> { async fn verify_id_and_get_customer_object( &self, db: &dyn StorageInterface, ) -> Result<domain::Customer, error_stack::Report<errors::CustomersErrorResponse>> { let customer = db .find_customer_by_global_id( self.key_manager_state, self.id, self.merchant_account.get_id(), self.key_store, self.merchant_account.storage_scheme, ) .await .switch()?; Ok(customer) } } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[async_trait::async_trait] impl CustomerUpdateBridge for customers::CustomerUpdateRequest { async fn create_domain_model_from_request<'a>( &'a self, db: &'a dyn StorageInterface, key_store: &'a domain::MerchantKeyStore, merchant_account: &'a domain::MerchantAccount, key_manager_state: &'a KeyManagerState, state: &'a SessionState, domain_customer: &'a domain::Customer, ) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse> { let update_address_for_update_customer = AddressStructForDbUpdate { update_customer: self, merchant_account, key_store, key_manager_state, state, domain_customer, }; let address = update_address_for_update_customer .update_address_if_sent(db) .await?; let key = key_store.key.get_inner().peek(); let encrypted_data = types::crypto_operation( key_manager_state, type_name!(domain::Customer), types::CryptoOperation::BatchEncrypt( domain::FromRequestEncryptableCustomer::to_encryptable( domain::FromRequestEncryptableCustomer { name: self.name.clone(), email: self .email .as_ref() .map(|a| a.clone().expose().switch_strategy()), phone: self.phone.clone(), }, ), ), Identifier::Merchant(key_store.merchant_id.clone()), key, ) .await .and_then(|val| val.try_into_batchoperation()) .switch()?; let encryptable_customer = domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data) .change_context(errors::CustomersErrorResponse::InternalServerError)?; let response = db .update_customer_by_customer_id_merchant_id( key_manager_state, domain_customer.customer_id.to_owned(), merchant_account.get_id().to_owned(), domain_customer.to_owned(), storage::CustomerUpdate::Update { name: encryptable_customer.name, email: encryptable_customer.email.map(|email| { let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), phone: Box::new(encryptable_customer.phone), phone_country_code: self.phone_country_code.clone(), metadata: self.metadata.clone(), description: self.description.clone(), connector_customer: Box::new(None), address_id: address.clone().map(|addr| addr.address_id), }, key_store, merchant_account.storage_scheme, ) .await .switch()?; Ok(response) } fn generate_response<'a>( &'a self, customer: &'a domain::Customer, ) -> errors::CustomerResponse<customers::CustomerResponse> { let address = self.get_address(); Ok(services::ApplicationResponse::Json( customers::CustomerResponse::foreign_from((customer.clone(), address)), )) } } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[async_trait::async_trait] impl CustomerUpdateBridge for customers::CustomerUpdateRequest { async fn create_domain_model_from_request<'a>( &'a self, db: &'a dyn StorageInterface, key_store: &'a domain::MerchantKeyStore, merchant_account: &'a domain::MerchantAccount, key_manager_state: &'a KeyManagerState, state: &'a SessionState, domain_customer: &'a domain::Customer, ) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse> { let default_billing_address = self.get_default_customer_billing_address(); let encrypted_customer_billing_address = default_billing_address .async_map(|billing_address| { create_encrypted_data(key_manager_state, key_store, billing_address) }) .await .transpose() .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable("Unable to encrypt default customer billing address")?; let default_shipping_address = self.get_default_customer_shipping_address(); let encrypted_customer_shipping_address = default_shipping_address .async_map(|shipping_address| { create_encrypted_data(key_manager_state, key_store, shipping_address) }) .await .transpose() .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable("Unable to encrypt default customer shipping address")?; let key = key_store.key.get_inner().peek(); let encrypted_data = types::crypto_operation( key_manager_state, type_name!(domain::Customer), types::CryptoOperation::BatchEncrypt( domain::FromRequestEncryptableCustomer::to_encryptable( domain::FromRequestEncryptableCustomer { name: self.name.clone(), email: self .email .as_ref() .map(|a| a.clone().expose().switch_strategy()), phone: self.phone.clone(), }, ), ), Identifier::Merchant(key_store.merchant_id.clone()), key, ) .await .and_then(|val| val.try_into_batchoperation()) .switch()?; let encryptable_customer = domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data) .change_context(errors::CustomersErrorResponse::InternalServerError)?; let response = db .update_customer_by_global_id( key_manager_state, &domain_customer.id, domain_customer.to_owned(), merchant_account.get_id(), storage::CustomerUpdate::Update(Box::new(storage::CustomerGeneralUpdate { name: encryptable_customer.name, email: Box::new(encryptable_customer.email.map(|email| { let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable })), phone: Box::new(encryptable_customer.phone), phone_country_code: self.phone_country_code.clone(), metadata: self.metadata.clone(), description: self.description.clone(), connector_customer: Box::new(None), default_billing_address: encrypted_customer_billing_address.map(Into::into), default_shipping_address: encrypted_customer_shipping_address.map(Into::into), default_payment_method_id: Some(self.default_payment_method_id.clone()), status: None, })), key_store, merchant_account.storage_scheme, ) .await .switch()?; Ok(response) } fn generate_response<'a>( &'a self, customer: &'a domain::Customer, ) -> errors::CustomerResponse<customers::CustomerResponse> { Ok(services::ApplicationResponse::Json( customers::CustomerResponse::foreign_from(customer.clone()), )) } } pub async fn migrate_customers( state: SessionState, customers: Vec<customers::CustomerRequest>, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, ) -> errors::CustomerResponse<()> { for customer in customers { match create_customer( state.clone(), merchant_account.clone(), key_store.clone(), customer, ) .await { Ok(_) => (), Err(e) => match e.current_context() { errors::CustomersErrorResponse::CustomerAlreadyExists => (), _ => return Err(e), }, } } Ok(services::ApplicationResponse::Json(())) }
9,916
1,570
hyperswitch
crates/router/src/core/refunds.rs
.rs
pub mod transformers; pub mod validator; #[cfg(feature = "olap")] use std::collections::HashMap; #[cfg(feature = "olap")] use api_models::admin::MerchantConnectorInfo; use common_utils::{ ext_traits::AsyncExt, types::{ConnectorTransactionId, MinorUnit}, }; use diesel_models::process_tracker::business_status; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ router_data::ErrorResponse, router_request_types::SplitRefundsRequest, }; use hyperswitch_interfaces::integrity::{CheckIntegrity, FlowIntegrity, GetIntegrityObject}; use router_env::{instrument, tracing}; use scheduler::{consumer::types::process_data, utils as process_tracker_utils}; #[cfg(feature = "olap")] use strum::IntoEnumIterator; use crate::{ consts, core::{ errors::{self, ConnectorErrorExt, RouterResponse, RouterResult, StorageErrorExt}, payments::{self, access_token, helpers}, refunds::transformers::SplitRefundInput, utils as core_utils, }, db, logger, routes::{metrics, SessionState}, services, types::{ self, api::{self, refunds}, domain, storage::{self, enums}, transformers::{ForeignFrom, ForeignInto}, }, utils::{self, OptionExt}, workflows::payment_sync, }; // ********************************************** REFUND EXECUTE ********************************************** #[instrument(skip_all)] pub async fn refund_create_core( state: SessionState, merchant_account: domain::MerchantAccount, _profile_id: Option<common_utils::id_type::ProfileId>, key_store: domain::MerchantKeyStore, req: refunds::RefundRequest, ) -> RouterResponse<refunds::RefundResponse> { let db = &*state.store; let (merchant_id, payment_intent, payment_attempt, amount); merchant_id = merchant_account.get_id(); payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &(&state).into(), &req.payment_id, merchant_id, &key_store, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; utils::when( !(payment_intent.status == enums::IntentStatus::Succeeded || payment_intent.status == enums::IntentStatus::PartiallyCaptured), || { Err(report!(errors::ApiErrorResponse::PaymentUnexpectedState { current_flow: "refund".into(), field_name: "status".into(), current_value: payment_intent.status.to_string(), states: "succeeded, partially_captured".to_string() }) .attach_printable("unable to refund for a unsuccessful payment intent")) }, )?; // Amount is not passed in request refer from payment intent. amount = req .amount .or(payment_intent.amount_captured) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("amount captured is none in a successful payment")?; //[#299]: Can we change the flow based on some workflow idea utils::when(amount <= MinorUnit::new(0), || { Err(report!(errors::ApiErrorResponse::InvalidDataFormat { field_name: "amount".to_string(), expected_format: "positive integer".to_string() }) .attach_printable("amount less than or equal to zero")) })?; payment_attempt = db .find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( &req.payment_id, merchant_id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::SuccessfulPaymentNotFound)?; let creds_identifier = req .merchant_connector_details .as_ref() .map(|mcd| mcd.creds_identifier.to_owned()); req.merchant_connector_details .to_owned() .async_map(|mcd| async { helpers::insert_merchant_connector_creds_to_config(db, merchant_id, mcd).await }) .await .transpose()?; Box::pin(validate_and_create_refund( &state, &merchant_account, &key_store, &payment_attempt, &payment_intent, amount, req, creds_identifier, )) .await .map(services::ApplicationResponse::Json) } #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn trigger_refund_to_gateway( state: &SessionState, refund: &storage::Refund, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, creds_identifier: Option<String>, split_refunds: Option<SplitRefundsRequest>, ) -> RouterResult<storage::Refund> { let routed_through = payment_attempt .connector .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to retrieve connector from payment attempt")?; let storage_scheme = merchant_account.storage_scheme; metrics::REFUND_COUNT.add( 1, router_env::metric_attributes!(("connector", routed_through.clone())), ); let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &routed_through, api::GetToken::Connector, payment_attempt.merchant_connector_id.clone(), )?; let currency = payment_attempt.currency.ok_or_else(|| { report!(errors::ApiErrorResponse::InternalServerError).attach_printable( "Transaction in invalid. Missing field \"currency\" in payment_attempt.", ) })?; validator::validate_for_valid_refunds(payment_attempt, connector.connector_name)?; let mut router_data = core_utils::construct_refund_router_data( state, &routed_through, merchant_account, key_store, (payment_attempt.get_total_amount(), currency), payment_intent, payment_attempt, refund, creds_identifier.clone(), split_refunds, ) .await?; let add_access_token_result = access_token::add_access_token( state, &connector, merchant_account, &router_data, creds_identifier.as_deref(), ) .await?; logger::debug!(refund_router_data=?router_data); access_token::update_router_data_with_access_token_result( &add_access_token_result, &mut router_data, &payments::CallConnectorAction::Trigger, ); let router_data_res = if !(add_access_token_result.connector_supports_access_token && router_data.access_token.is_none()) { let connector_integration: services::BoxedRefundConnectorIntegrationInterface< api::Execute, types::RefundsData, types::RefundsResponseData, > = connector.connector.get_connector_integration(); let router_data_res = services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, ) .await; let option_refund_error_update = router_data_res .as_ref() .err() .and_then(|error| match error.current_context() { errors::ConnectorError::NotImplemented(message) => { Some(storage::RefundUpdate::ErrorUpdate { refund_status: Some(enums::RefundStatus::Failure), refund_error_message: Some( errors::ConnectorError::NotImplemented(message.to_owned()) .to_string(), ), refund_error_code: Some("NOT_IMPLEMENTED".to_string()), updated_by: storage_scheme.to_string(), connector_refund_id: None, processor_refund_data: None, unified_code: None, unified_message: None, issuer_error_code: None, issuer_error_message: None, }) } errors::ConnectorError::NotSupported { message, connector } => { Some(storage::RefundUpdate::ErrorUpdate { refund_status: Some(enums::RefundStatus::Failure), refund_error_message: Some(format!( "{message} is not supported by {connector}" )), refund_error_code: Some("NOT_SUPPORTED".to_string()), updated_by: storage_scheme.to_string(), connector_refund_id: None, processor_refund_data: None, unified_code: None, unified_message: None, issuer_error_code: None, issuer_error_message: None, }) } _ => None, }); // Update the refund status as failure if connector_error is NotImplemented if let Some(refund_error_update) = option_refund_error_update { state .store .update_refund( refund.to_owned(), refund_error_update, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed while updating refund: refund_id: {}", refund.refund_id ) })?; } let mut refund_router_data_res = router_data_res.to_refund_failed_response()?; // Initiating Integrity check let integrity_result = check_refund_integrity( &refund_router_data_res.request, &refund_router_data_res.response, ); refund_router_data_res.integrity_check = integrity_result; refund_router_data_res } else { router_data }; let refund_update = match router_data_res.response { Err(err) => { let option_gsm = helpers::get_gsm_record( state, Some(err.code.clone()), Some(err.message.clone()), connector.connector_name.to_string(), consts::REFUND_FLOW_STR.to_string(), ) .await; // Note: Some connectors do not have a separate list of refund errors // In such cases, the error codes and messages are stored under "Authorize" flow in GSM table // So we will have to fetch the GSM using Authorize flow in case GSM is not found using "refund_flow" let option_gsm = if option_gsm.is_none() { helpers::get_gsm_record( state, Some(err.code.clone()), Some(err.message.clone()), connector.connector_name.to_string(), consts::AUTHORIZE_FLOW_STR.to_string(), ) .await } else { option_gsm }; let gsm_unified_code = option_gsm.as_ref().and_then(|gsm| gsm.unified_code.clone()); let gsm_unified_message = option_gsm.and_then(|gsm| gsm.unified_message); let (unified_code, unified_message) = if let Some((code, message)) = gsm_unified_code.as_ref().zip(gsm_unified_message.as_ref()) { (code.to_owned(), message.to_owned()) } else { ( consts::DEFAULT_UNIFIED_ERROR_CODE.to_owned(), consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_owned(), ) }; storage::RefundUpdate::ErrorUpdate { refund_status: Some(enums::RefundStatus::Failure), refund_error_message: err.reason.or(Some(err.message)), refund_error_code: Some(err.code), updated_by: storage_scheme.to_string(), connector_refund_id: None, processor_refund_data: None, unified_code: Some(unified_code), unified_message: Some(unified_message), issuer_error_code: err.network_decline_code, issuer_error_message: err.network_error_message, } } Ok(response) => { // match on connector integrity checks match router_data_res.integrity_check.clone() { Err(err) => { let (refund_connector_transaction_id, processor_refund_data) = err.connector_transaction_id.map_or((None, None), |txn_id| { let (refund_id, refund_data) = ConnectorTransactionId::form_id_and_data(txn_id); (Some(refund_id), refund_data) }); metrics::INTEGRITY_CHECK_FAILED.add( 1, router_env::metric_attributes!( ("connector", connector.connector_name.to_string()), ("merchant_id", merchant_account.get_id().clone()), ), ); storage::RefundUpdate::ErrorUpdate { refund_status: Some(enums::RefundStatus::ManualReview), refund_error_message: Some(format!( "Integrity Check Failed! as data mismatched for fields {}", err.field_names )), refund_error_code: Some("IE".to_string()), updated_by: storage_scheme.to_string(), connector_refund_id: refund_connector_transaction_id, processor_refund_data, unified_code: None, unified_message: None, issuer_error_code: None, issuer_error_message: None, } } Ok(()) => { if response.refund_status == diesel_models::enums::RefundStatus::Success { metrics::SUCCESSFUL_REFUND.add( 1, router_env::metric_attributes!(( "connector", connector.connector_name.to_string(), )), ) } let (connector_refund_id, processor_refund_data) = ConnectorTransactionId::form_id_and_data(response.connector_refund_id); storage::RefundUpdate::Update { connector_refund_id, refund_status: response.refund_status, sent_to_gateway: true, refund_error_message: None, refund_arn: "".to_string(), updated_by: storage_scheme.to_string(), processor_refund_data, } } } } }; let response = state .store .update_refund( refund.to_owned(), refund_update, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed while updating refund: refund_id: {}", refund.refund_id ) })?; utils::trigger_refund_outgoing_webhook( state, merchant_account, &response, payment_attempt.profile_id.clone(), key_store, ) .await .map_err(|error| logger::warn!(refunds_outgoing_webhook_error=?error)) .ok(); Ok(response) } pub fn check_refund_integrity<T, Request>( request: &Request, refund_response_data: &Result<types::RefundsResponseData, ErrorResponse>, ) -> Result<(), common_utils::errors::IntegrityCheckError> where T: FlowIntegrity, Request: GetIntegrityObject<T> + CheckIntegrity<Request, T>, { let connector_refund_id = refund_response_data .as_ref() .map(|resp_data| resp_data.connector_refund_id.clone()) .ok(); request.check_integrity(request, connector_refund_id.to_owned()) } // ********************************************** REFUND SYNC ********************************************** pub async fn refund_response_wrapper<F, Fut, T, Req>( state: SessionState, merchant_account: domain::MerchantAccount, profile_id: Option<common_utils::id_type::ProfileId>, key_store: domain::MerchantKeyStore, request: Req, f: F, ) -> RouterResponse<refunds::RefundResponse> where F: Fn( SessionState, domain::MerchantAccount, Option<common_utils::id_type::ProfileId>, domain::MerchantKeyStore, Req, ) -> Fut, Fut: futures::Future<Output = RouterResult<T>>, T: ForeignInto<refunds::RefundResponse>, { Ok(services::ApplicationResponse::Json( f(state, merchant_account, profile_id, key_store, request) .await? .foreign_into(), )) } #[instrument(skip_all)] pub async fn refund_retrieve_core( state: SessionState, merchant_account: domain::MerchantAccount, profile_id: Option<common_utils::id_type::ProfileId>, key_store: domain::MerchantKeyStore, request: refunds::RefundsRetrieveRequest, refund: storage::Refund, ) -> RouterResult<storage::Refund> { let db = &*state.store; let merchant_id = merchant_account.get_id(); core_utils::validate_profile_id_from_auth_layer(profile_id, &refund)?; let payment_id = &refund.payment_id; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &(&state).into(), payment_id, merchant_id, &key_store, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let payment_attempt = db .find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( &refund.connector_transaction_id, payment_id, merchant_id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; let creds_identifier = request .merchant_connector_details .as_ref() .map(|mcd| mcd.creds_identifier.to_owned()); request .merchant_connector_details .to_owned() .async_map(|mcd| async { helpers::insert_merchant_connector_creds_to_config(db, merchant_id, mcd).await }) .await .transpose()?; let split_refunds_req = core_utils::get_split_refunds(SplitRefundInput { split_payment_request: payment_intent.split_payments.clone(), payment_charges: payment_attempt.charges.clone(), charge_id: payment_attempt.charge_id.clone(), refund_request: refund.split_refunds.clone(), })?; let unified_translated_message = if let (Some(unified_code), Some(unified_message)) = (refund.unified_code.clone(), refund.unified_message.clone()) { helpers::get_unified_translation( &state, unified_code, unified_message.clone(), state.locale.to_string(), ) .await .or(Some(unified_message)) } else { refund.unified_message }; let refund = storage::Refund { unified_message: unified_translated_message, ..refund }; let response = if should_call_refund(&refund, request.force_sync.unwrap_or(false)) { Box::pin(sync_refund_with_gateway( &state, &merchant_account, &key_store, &payment_attempt, &payment_intent, &refund, creds_identifier, split_refunds_req, )) .await } else { Ok(refund) }?; Ok(response) } fn should_call_refund(refund: &diesel_models::refund::Refund, force_sync: bool) -> bool { // This implies, we cannot perform a refund sync & `the connector_refund_id` // doesn't exist let predicate1 = refund.connector_refund_id.is_some(); // This allows refund sync at connector level if force_sync is enabled, or // checks if the refund has failed let predicate2 = force_sync || !matches!( refund.refund_status, diesel_models::enums::RefundStatus::Failure | diesel_models::enums::RefundStatus::Success ); predicate1 && predicate2 } #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn sync_refund_with_gateway( state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, refund: &storage::Refund, creds_identifier: Option<String>, split_refunds: Option<SplitRefundsRequest>, ) -> RouterResult<storage::Refund> { let connector_id = refund.connector.to_string(); let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &connector_id, api::GetToken::Connector, payment_attempt.merchant_connector_id.clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the connector")?; let storage_scheme = merchant_account.storage_scheme; let currency = payment_attempt.currency.get_required_value("currency")?; let mut router_data = core_utils::construct_refund_router_data::<api::RSync>( state, &connector_id, merchant_account, key_store, (payment_attempt.get_total_amount(), currency), payment_intent, payment_attempt, refund, creds_identifier.clone(), split_refunds, ) .await?; let add_access_token_result = access_token::add_access_token( state, &connector, merchant_account, &router_data, creds_identifier.as_deref(), ) .await?; logger::debug!(refund_retrieve_router_data=?router_data); access_token::update_router_data_with_access_token_result( &add_access_token_result, &mut router_data, &payments::CallConnectorAction::Trigger, ); let router_data_res = if !(add_access_token_result.connector_supports_access_token && router_data.access_token.is_none()) { let connector_integration: services::BoxedRefundConnectorIntegrationInterface< api::RSync, types::RefundsData, types::RefundsResponseData, > = connector.connector.get_connector_integration(); let mut refund_sync_router_data = services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, ) .await .to_refund_failed_response()?; // Initiating connector integrity checks let integrity_result = check_refund_integrity( &refund_sync_router_data.request, &refund_sync_router_data.response, ); refund_sync_router_data.integrity_check = integrity_result; refund_sync_router_data } else { router_data }; let refund_update = match router_data_res.response { Err(error_message) => { let refund_status = match error_message.status_code { // marking failure for 2xx because this is genuine refund failure 200..=299 => Some(enums::RefundStatus::Failure), _ => None, }; storage::RefundUpdate::ErrorUpdate { refund_status, refund_error_message: error_message.reason.or(Some(error_message.message)), refund_error_code: Some(error_message.code), updated_by: storage_scheme.to_string(), connector_refund_id: None, processor_refund_data: None, unified_code: None, unified_message: None, issuer_error_code: error_message.network_decline_code, issuer_error_message: error_message.network_error_message, } } Ok(response) => match router_data_res.integrity_check.clone() { Err(err) => { metrics::INTEGRITY_CHECK_FAILED.add( 1, router_env::metric_attributes!( ("connector", connector.connector_name.to_string()), ("merchant_id", merchant_account.get_id().clone()), ), ); let (refund_connector_transaction_id, processor_refund_data) = err .connector_transaction_id .map_or((None, None), |refund_id| { let (refund_id, refund_data) = ConnectorTransactionId::form_id_and_data(refund_id); (Some(refund_id), refund_data) }); storage::RefundUpdate::ErrorUpdate { refund_status: Some(enums::RefundStatus::ManualReview), refund_error_message: Some(format!( "Integrity Check Failed! as data mismatched for fields {}", err.field_names )), refund_error_code: Some("IE".to_string()), updated_by: storage_scheme.to_string(), connector_refund_id: refund_connector_transaction_id, processor_refund_data, unified_code: None, unified_message: None, issuer_error_code: None, issuer_error_message: None, } } Ok(()) => { let (connector_refund_id, processor_refund_data) = ConnectorTransactionId::form_id_and_data(response.connector_refund_id); storage::RefundUpdate::Update { connector_refund_id, refund_status: response.refund_status, sent_to_gateway: true, refund_error_message: None, refund_arn: "".to_string(), updated_by: storage_scheme.to_string(), processor_refund_data, } } }, }; let response = state .store .update_refund( refund.to_owned(), refund_update, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound) .attach_printable_lazy(|| { format!( "Unable to update refund with refund_id: {}", refund.refund_id ) })?; utils::trigger_refund_outgoing_webhook( state, merchant_account, &response, payment_attempt.profile_id.clone(), key_store, ) .await .map_err(|error| logger::warn!(refunds_outgoing_webhook_error=?error)) .ok(); Ok(response) } // ********************************************** REFUND UPDATE ********************************************** pub async fn refund_update_core( state: SessionState, merchant_account: domain::MerchantAccount, req: refunds::RefundUpdateRequest, ) -> RouterResponse<refunds::RefundResponse> { let db = state.store.as_ref(); let refund = db .find_refund_by_merchant_id_refund_id( merchant_account.get_id(), &req.refund_id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; let response = db .update_refund( refund, storage::RefundUpdate::MetadataAndReasonUpdate { metadata: req.metadata, reason: req.reason, updated_by: merchant_account.storage_scheme.to_string(), }, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!("Unable to update refund with refund_id: {}", req.refund_id) })?; Ok(services::ApplicationResponse::Json(response.foreign_into())) } // ********************************************** VALIDATIONS ********************************************** #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn validate_and_create_refund( state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, refund_amount: MinorUnit, req: refunds::RefundRequest, creds_identifier: Option<String>, ) -> RouterResult<refunds::RefundResponse> { let db = &*state.store; let split_refunds = core_utils::get_split_refunds(SplitRefundInput { split_payment_request: payment_intent.split_payments.clone(), payment_charges: payment_attempt.charges.clone(), charge_id: payment_attempt.charge_id.clone(), refund_request: req.split_refunds.clone(), })?; // Only for initial dev and testing let refund_type = req.refund_type.unwrap_or_default(); // If Refund Id not passed in request Generate one. let refund_id = core_utils::get_or_generate_id("refund_id", &req.refund_id, "ref")?; let predicate = req .merchant_id .as_ref() .map(|merchant_id| merchant_id != merchant_account.get_id()); utils::when(predicate.unwrap_or(false), || { Err(report!(errors::ApiErrorResponse::InvalidDataFormat { field_name: "merchant_id".to_string(), expected_format: "merchant_id from merchant account".to_string() }) .attach_printable("invalid merchant_id in request")) })?; let connector_transaction_id = payment_attempt.clone().connector_transaction_id.ok_or_else(|| { report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Transaction in invalid. Missing field \"connector_transaction_id\" in payment_attempt.") })?; let all_refunds = db .find_refund_by_merchant_id_connector_transaction_id( merchant_account.get_id(), &connector_transaction_id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; let currency = payment_attempt.currency.get_required_value("currency")?; //[#249]: Add Connector Based Validation here. validator::validate_payment_order_age(&payment_intent.created_at, state.conf.refund.max_age) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "created_at".to_string(), expected_format: format!( "created_at not older than {} days", state.conf.refund.max_age, ), })?; let total_amount_captured = payment_intent .amount_captured .unwrap_or(payment_attempt.get_total_amount()); validator::validate_refund_amount( total_amount_captured.get_amount_as_i64(), &all_refunds, refund_amount.get_amount_as_i64(), ) .change_context(errors::ApiErrorResponse::RefundAmountExceedsPaymentAmount)?; validator::validate_maximum_refund_against_payment_attempt( &all_refunds, state.conf.refund.max_attempts, ) .change_context(errors::ApiErrorResponse::MaximumRefundCount)?; let connector = payment_attempt .connector .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("No connector populated in payment attempt")?; let (connector_transaction_id, processor_transaction_data) = ConnectorTransactionId::form_id_and_data(connector_transaction_id); let refund_create_req = storage::RefundNew { refund_id: refund_id.to_string(), internal_reference_id: utils::generate_id(consts::ID_LENGTH, "refid"), external_reference_id: Some(refund_id.clone()), payment_id: req.payment_id, merchant_id: merchant_account.get_id().clone(), connector_transaction_id, connector, refund_type: req.refund_type.unwrap_or_default().foreign_into(), total_amount: payment_attempt.get_total_amount(), refund_amount, currency, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), refund_status: enums::RefundStatus::Pending, metadata: req.metadata, description: req.reason.clone(), attempt_id: payment_attempt.attempt_id.clone(), refund_reason: req.reason, profile_id: payment_intent.profile_id.clone(), merchant_connector_id: payment_attempt.merchant_connector_id.clone(), charges: None, split_refunds: req.split_refunds, connector_refund_id: None, sent_to_gateway: Default::default(), refund_arn: None, updated_by: Default::default(), organization_id: merchant_account.organization_id.clone(), processor_transaction_data, processor_refund_data: None, }; let refund = match db .insert_refund(refund_create_req, merchant_account.storage_scheme) .await { Ok(refund) => { Box::pin(schedule_refund_execution( state, refund.clone(), refund_type, merchant_account, key_store, payment_attempt, payment_intent, creds_identifier, split_refunds, )) .await? } Err(err) => { if err.current_context().is_db_unique_violation() { Err(errors::ApiErrorResponse::DuplicateRefundRequest)? } else { return Err(err) .change_context(errors::ApiErrorResponse::RefundNotFound) .attach_printable("Inserting Refund failed"); } } }; let unified_translated_message = if let (Some(unified_code), Some(unified_message)) = (refund.unified_code.clone(), refund.unified_message.clone()) { helpers::get_unified_translation( state, unified_code, unified_message.clone(), state.locale.to_string(), ) .await .or(Some(unified_message)) } else { refund.unified_message }; let refund = storage::Refund { unified_message: unified_translated_message, ..refund }; Ok(refund.foreign_into()) } // ********************************************** Refund list ********************************************** /// If payment-id is provided, lists all the refunds associated with that particular payment-id /// If payment-id is not provided, lists the refunds associated with that particular merchant - to the limit specified,if no limits given, it is 10 by default #[instrument(skip_all)] #[cfg(feature = "olap")] pub async fn refund_list( state: SessionState, merchant_account: domain::MerchantAccount, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, req: api_models::refunds::RefundListRequest, ) -> RouterResponse<api_models::refunds::RefundListResponse> { let db = state.store; let limit = validator::validate_refund_list(req.limit)?; let offset = req.offset.unwrap_or_default(); let refund_list = db .filter_refund_by_constraints( merchant_account.get_id(), &(req.clone(), profile_id_list.clone()).try_into()?, merchant_account.storage_scheme, limit, offset, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; let data: Vec<refunds::RefundResponse> = refund_list .into_iter() .map(ForeignInto::foreign_into) .collect(); let total_count = db .get_total_count_of_refunds( merchant_account.get_id(), &(req, profile_id_list).try_into()?, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; Ok(services::ApplicationResponse::Json( api_models::refunds::RefundListResponse { count: data.len(), total_count, data, }, )) } #[instrument(skip_all)] #[cfg(feature = "olap")] pub async fn refund_filter_list( state: SessionState, merchant_account: domain::MerchantAccount, req: common_utils::types::TimeRange, ) -> RouterResponse<api_models::refunds::RefundListMetaData> { let db = state.store; let filter_list = db .filter_refund_by_meta_constraints( merchant_account.get_id(), &req, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; Ok(services::ApplicationResponse::Json(filter_list)) } #[instrument(skip_all)] pub async fn refund_retrieve_core_with_internal_reference_id( state: SessionState, merchant_account: domain::MerchantAccount, profile_id: Option<common_utils::id_type::ProfileId>, key_store: domain::MerchantKeyStore, refund_internal_request_id: String, force_sync: Option<bool>, ) -> RouterResult<storage::Refund> { let db = &*state.store; let merchant_id = merchant_account.get_id(); let refund = db .find_refund_by_internal_reference_id_merchant_id( &refund_internal_request_id, merchant_id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; let request = refunds::RefundsRetrieveRequest { refund_id: refund.refund_id.clone(), force_sync, merchant_connector_details: None, }; Box::pin(refund_retrieve_core( state.clone(), merchant_account, profile_id, key_store, request, refund, )) .await } #[instrument(skip_all)] pub async fn refund_retrieve_core_with_refund_id( state: SessionState, merchant_account: domain::MerchantAccount, profile_id: Option<common_utils::id_type::ProfileId>, key_store: domain::MerchantKeyStore, request: refunds::RefundsRetrieveRequest, ) -> RouterResult<storage::Refund> { let refund_id = request.refund_id.clone(); let db = &*state.store; let merchant_id = merchant_account.get_id(); let refund = db .find_refund_by_merchant_id_refund_id( merchant_id, refund_id.as_str(), merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; Box::pin(refund_retrieve_core( state.clone(), merchant_account, profile_id, key_store, request, refund, )) .await } #[instrument(skip_all)] #[cfg(feature = "olap")] pub async fn refund_manual_update( state: SessionState, req: api_models::refunds::RefundManualUpdateRequest, ) -> RouterResponse<serde_json::Value> { let key_manager_state = &(&state).into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, &req.merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) .attach_printable("Error while fetching the key store by merchant_id")?; let merchant_account = state .store .find_merchant_account_by_merchant_id(key_manager_state, &req.merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) .attach_printable("Error while fetching the merchant_account by merchant_id")?; let refund = state .store .find_refund_by_merchant_id_refund_id( merchant_account.get_id(), &req.refund_id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; let refund_update = storage::RefundUpdate::ManualUpdate { refund_status: req.status.map(common_enums::RefundStatus::from), refund_error_message: req.error_message, refund_error_code: req.error_code, updated_by: merchant_account.storage_scheme.to_string(), }; state .store .update_refund( refund.to_owned(), refund_update, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed while updating refund: refund_id: {}", refund.refund_id ) })?; Ok(services::ApplicationResponse::StatusOk) } #[instrument(skip_all)] #[cfg(feature = "olap")] pub async fn get_filters_for_refunds( state: SessionState, merchant_account: domain::MerchantAccount, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, ) -> RouterResponse<api_models::refunds::RefundListFilters> { let merchant_connector_accounts = if let services::ApplicationResponse::Json(data) = super::admin::list_payment_connectors( state, merchant_account.get_id().to_owned(), profile_id_list, ) .await? { data } else { return Err(errors::ApiErrorResponse::InternalServerError.into()); }; let connector_map = merchant_connector_accounts .into_iter() .filter_map(|merchant_connector_account| { merchant_connector_account .connector_label .clone() .map(|label| { let info = merchant_connector_account.to_merchant_connector_info(&label); (merchant_connector_account.connector_name, info) }) }) .fold( HashMap::new(), |mut map: HashMap<String, Vec<MerchantConnectorInfo>>, (connector_name, info)| { map.entry(connector_name).or_default().push(info); map }, ); Ok(services::ApplicationResponse::Json( api_models::refunds::RefundListFilters { connector: connector_map, currency: enums::Currency::iter().collect(), refund_status: enums::RefundStatus::iter().collect(), }, )) } #[instrument(skip_all)] #[cfg(feature = "olap")] pub async fn get_aggregates_for_refunds( state: SessionState, merchant: domain::MerchantAccount, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: common_utils::types::TimeRange, ) -> RouterResponse<api_models::refunds::RefundAggregateResponse> { let db = state.store.as_ref(); let refund_status_with_count = db .get_refund_status_with_count( merchant.get_id(), profile_id_list, &time_range, merchant.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to find status count")?; let mut status_map: HashMap<enums::RefundStatus, i64> = refund_status_with_count.into_iter().collect(); for status in enums::RefundStatus::iter() { status_map.entry(status).or_default(); } Ok(services::ApplicationResponse::Json( api_models::refunds::RefundAggregateResponse { status_with_count: status_map, }, )) } impl ForeignFrom<storage::Refund> for api::RefundResponse { fn foreign_from(refund: storage::Refund) -> Self { let refund = refund; Self { payment_id: refund.payment_id, refund_id: refund.refund_id, amount: refund.refund_amount, currency: refund.currency.to_string(), reason: refund.refund_reason, status: refund.refund_status.foreign_into(), profile_id: refund.profile_id, metadata: refund.metadata, error_message: refund.refund_error_message, error_code: refund.refund_error_code, created_at: Some(refund.created_at), updated_at: Some(refund.modified_at), connector: refund.connector, merchant_connector_id: refund.merchant_connector_id, split_refunds: refund.split_refunds, unified_code: refund.unified_code, unified_message: refund.unified_message, issuer_error_code: refund.issuer_error_code, issuer_error_message: refund.issuer_error_message, } } } // ********************************************** PROCESS TRACKER ********************************************** #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn schedule_refund_execution( state: &SessionState, refund: storage::Refund, refund_type: api_models::refunds::RefundType, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, creds_identifier: Option<String>, split_refunds: Option<SplitRefundsRequest>, ) -> RouterResult<storage::Refund> { // refunds::RefundResponse> { let db = &*state.store; let runner = storage::ProcessTrackerRunner::RefundWorkflowRouter; let task = "EXECUTE_REFUND"; let task_id = format!("{runner}_{task}_{}", refund.internal_reference_id); let refund_process = db .find_process_by_id(&task_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to find the process id")?; let result = match refund.refund_status { enums::RefundStatus::Pending | enums::RefundStatus::ManualReview => { match (refund.sent_to_gateway, refund_process) { (false, None) => { // Execute the refund task based on refund_type match refund_type { api_models::refunds::RefundType::Scheduled => { add_refund_execute_task(db, &refund, runner) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| format!("Failed while pushing refund execute task to scheduler, refund_id: {}", refund.refund_id))?; Ok(refund) } api_models::refunds::RefundType::Instant => { let update_refund = Box::pin(trigger_refund_to_gateway( state, &refund, merchant_account, key_store, payment_attempt, payment_intent, creds_identifier, split_refunds, )) .await; match update_refund { Ok(updated_refund_data) => { add_refund_sync_task(db, &updated_refund_data, runner) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| format!( "Failed while pushing refund sync task in scheduler: refund_id: {}", refund.refund_id ))?; Ok(updated_refund_data) } Err(err) => Err(err), } } } } _ => { // Sync the refund for status check //[#300]: return refund status response match refund_type { api_models::refunds::RefundType::Scheduled => { add_refund_sync_task(db, &refund, runner) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| format!("Failed while pushing refund sync task in scheduler: refund_id: {}", refund.refund_id))?; Ok(refund) } api_models::refunds::RefundType::Instant => { // [#255]: This is not possible in schedule_refund_execution as it will always be scheduled // sync_refund_with_gateway(data, &refund).await Ok(refund) } } } } } // [#255]: This is not allowed to be otherwise or all _ => Ok(refund), }?; Ok(result) } #[instrument(skip_all)] pub async fn sync_refund_with_gateway_workflow( state: &SessionState, refund_tracker: &storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { let key_manager_state = &state.into(); let refund_core = serde_json::from_value::<storage::RefundCoreWorkflow>(refund_tracker.tracking_data.clone()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "unable to convert into refund_core {:?}", refund_tracker.tracking_data ) })?; let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, &refund_core.merchant_id, &state.store.get_master_key().to_vec().into(), ) .await?; let merchant_account = state .store .find_merchant_account_by_merchant_id( key_manager_state, &refund_core.merchant_id, &key_store, ) .await?; let response = Box::pin(refund_retrieve_core_with_internal_reference_id( state.clone(), merchant_account, None, key_store, refund_core.refund_internal_reference_id, Some(true), )) .await?; let terminal_status = [ enums::RefundStatus::Success, enums::RefundStatus::Failure, enums::RefundStatus::TransactionFailure, ]; match response.refund_status { status if terminal_status.contains(&status) => { state .store .as_scheduler() .finish_process_with_business_status( refund_tracker.clone(), business_status::COMPLETED_BY_PT, ) .await? } _ => { _ = payment_sync::retry_sync_task( &*state.store, response.connector, response.merchant_id, refund_tracker.to_owned(), ) .await?; } } Ok(()) } #[instrument(skip_all)] pub async fn start_refund_workflow( state: &SessionState, refund_tracker: &storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { match refund_tracker.name.as_deref() { Some("EXECUTE_REFUND") => { Box::pin(trigger_refund_execute_workflow(state, refund_tracker)).await } Some("SYNC_REFUND") => { Box::pin(sync_refund_with_gateway_workflow(state, refund_tracker)).await } _ => Err(errors::ProcessTrackerError::JobNotFound), } } #[instrument(skip_all)] pub async fn trigger_refund_execute_workflow( state: &SessionState, refund_tracker: &storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { let db = &*state.store; let refund_core = serde_json::from_value::<storage::RefundCoreWorkflow>(refund_tracker.tracking_data.clone()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "unable to convert into refund_core {:?}", refund_tracker.tracking_data ) })?; let key_manager_state = &state.into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, &refund_core.merchant_id, &state.store.get_master_key().to_vec().into(), ) .await?; let merchant_account = db .find_merchant_account_by_merchant_id( key_manager_state, &refund_core.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let refund = db .find_refund_by_internal_reference_id_merchant_id( &refund_core.refund_internal_reference_id, &refund_core.merchant_id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; match (&refund.sent_to_gateway, &refund.refund_status) { (false, enums::RefundStatus::Pending) => { let merchant_account = db .find_merchant_account_by_merchant_id( key_manager_state, &refund.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let payment_attempt = db .find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( &refund.connector_transaction_id, &refund_core.payment_id, &refund.merchant_id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &(state.into()), &payment_attempt.payment_id, &refund.merchant_id, &key_store, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let split_refunds = core_utils::get_split_refunds(SplitRefundInput { split_payment_request: payment_intent.split_payments.clone(), payment_charges: payment_attempt.charges.clone(), charge_id: payment_attempt.charge_id.clone(), refund_request: refund.split_refunds.clone(), })?; //trigger refund request to gateway let updated_refund = Box::pin(trigger_refund_to_gateway( state, &refund, &merchant_account, &key_store, &payment_attempt, &payment_intent, None, split_refunds, )) .await?; add_refund_sync_task( db, &updated_refund, storage::ProcessTrackerRunner::RefundWorkflowRouter, ) .await?; } (true, enums::RefundStatus::Pending) => { // create sync task add_refund_sync_task( db, &refund, storage::ProcessTrackerRunner::RefundWorkflowRouter, ) .await?; } (_, _) => { //mark task as finished db.as_scheduler() .finish_process_with_business_status( refund_tracker.clone(), business_status::COMPLETED_BY_PT, ) .await?; } }; Ok(()) } #[instrument] pub fn refund_to_refund_core_workflow_model( refund: &storage::Refund, ) -> storage::RefundCoreWorkflow { storage::RefundCoreWorkflow { refund_internal_reference_id: refund.internal_reference_id.clone(), connector_transaction_id: refund.connector_transaction_id.clone(), merchant_id: refund.merchant_id.clone(), payment_id: refund.payment_id.clone(), processor_transaction_data: refund.processor_transaction_data.clone(), } } #[instrument(skip_all)] pub async fn add_refund_sync_task( db: &dyn db::StorageInterface, refund: &storage::Refund, runner: storage::ProcessTrackerRunner, ) -> RouterResult<storage::ProcessTracker> { let task = "SYNC_REFUND"; let process_tracker_id = format!("{runner}_{task}_{}", refund.internal_reference_id); let schedule_time = common_utils::date_time::now(); let refund_workflow_tracking_data = refund_to_refund_core_workflow_model(refund); let tag = ["REFUND"]; let process_tracker_entry = storage::ProcessTrackerNew::new( process_tracker_id, task, runner, tag, refund_workflow_tracking_data, None, schedule_time, common_types::consts::API_VERSION, ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct refund sync process tracker task")?; let response = db .insert_process(process_tracker_entry) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicateRefundRequest) .attach_printable_lazy(|| { format!( "Failed while inserting task in process_tracker: refund_id: {}", refund.refund_id ) })?; metrics::TASKS_ADDED_COUNT.add(1, router_env::metric_attributes!(("flow", "Refund"))); Ok(response) } #[instrument(skip_all)] pub async fn add_refund_execute_task( db: &dyn db::StorageInterface, refund: &storage::Refund, runner: storage::ProcessTrackerRunner, ) -> RouterResult<storage::ProcessTracker> { let task = "EXECUTE_REFUND"; let process_tracker_id = format!("{runner}_{task}_{}", refund.internal_reference_id); let tag = ["REFUND"]; let schedule_time = common_utils::date_time::now(); let refund_workflow_tracking_data = refund_to_refund_core_workflow_model(refund); let process_tracker_entry = storage::ProcessTrackerNew::new( process_tracker_id, task, runner, tag, refund_workflow_tracking_data, None, schedule_time, common_types::consts::API_VERSION, ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct refund execute process tracker task")?; let response = db .insert_process(process_tracker_entry) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicateRefundRequest) .attach_printable_lazy(|| { format!( "Failed while inserting task in process_tracker: refund_id: {}", refund.refund_id ) })?; Ok(response) } pub async fn get_refund_sync_process_schedule_time( db: &dyn db::StorageInterface, connector: &str, merchant_id: &common_utils::id_type::MerchantId, retry_count: i32, ) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> { let redis_mapping: errors::CustomResult<process_data::ConnectorPTMapping, errors::RedisError> = db::get_and_deserialize_key( db, &format!("pt_mapping_refund_sync_{connector}"), "ConnectorPTMapping", ) .await; let mapping = match redis_mapping { Ok(x) => x, Err(err) => { logger::error!("Error: while getting connector mapping: {err:?}"); process_data::ConnectorPTMapping::default() } }; let time_delta = process_tracker_utils::get_schedule_time(mapping, merchant_id, retry_count + 1); Ok(process_tracker_utils::get_time_from_delta(time_delta)) }
12,105
1,571
hyperswitch
crates/router/src/core/fraud_check.rs
.rs
use std::fmt::Debug; use api_models::{self, enums as api_enums}; use common_enums::CaptureMethod; use error_stack::ResultExt; use masking::PeekInterface; 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 super::errors::{ConnectorErrorExt, RouterResponse}; 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, }; pub mod flows; pub mod operation; pub mod types; #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn call_frm_service<D: Clone, F, Req, OperationData>( state: &SessionState, payment_data: &OperationData, frm_data: &mut FrmData, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, ) -> RouterResult<oss_types::RouterData<F, Req, frm_types::FraudCheckResponseData>> where F: Send + Clone, OperationData: payments::OperationSessionGetters<D> + Send + Sync + Clone, // To create connector flow specific interface data FrmData: ConstructFlowSpecificData<F, Req, frm_types::FraudCheckResponseData>, oss_types::RouterData<F, Req, frm_types::FraudCheckResponseData>: FeatureFrm<F, Req> + Send, // To construct connector flow specific api dyn Connector: services::api::ConnectorIntegration<F, Req, frm_types::FraudCheckResponseData>, { todo!() } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn call_frm_service<D: Clone, F, Req, OperationData>( state: &SessionState, payment_data: &OperationData, frm_data: &mut FrmData, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, ) -> RouterResult<oss_types::RouterData<F, Req, frm_types::FraudCheckResponseData>> where F: Send + Clone, OperationData: payments::OperationSessionGetters<D> + Send + Sync + Clone, // To create connector flow specific interface data FrmData: ConstructFlowSpecificData<F, Req, frm_types::FraudCheckResponseData>, oss_types::RouterData<F, Req, frm_types::FraudCheckResponseData>: FeatureFrm<F, Req> + Send, // To construct connector flow specific api dyn Connector: services::api::ConnectorIntegration<F, Req, frm_types::FraudCheckResponseData>, { let merchant_connector_account = payments::construct_profile_id_and_get_mca( state, merchant_account, payment_data, &frm_data.connector_details.connector_name, None, key_store, false, ) .await?; frm_data .payment_attempt .connector_transaction_id .clone_from(&payment_data.get_payment_attempt().connector_transaction_id); let mut router_data = frm_data .construct_router_data( state, &frm_data.connector_details.connector_name, merchant_account, key_store, customer, &merchant_connector_account, None, None, ) .await?; router_data.status = payment_data.get_payment_attempt().status; if matches!( frm_data.fraud_check.frm_transaction_type, FraudCheckType::PreFrm ) && matches!( frm_data.fraud_check.last_step, FraudCheckLastStep::CheckoutOrSale ) { frm_data.fraud_check.last_step = FraudCheckLastStep::TransactionOrRecordRefund } let connector = FraudCheckConnectorData::get_connector_by_name(&frm_data.connector_details.connector_name)?; let router_data_res = router_data .decide_frm_flows( state, &connector, payments::CallConnectorAction::Trigger, merchant_account, ) .await?; Ok(router_data_res) } #[cfg(feature = "v2")] 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, { // Frm routing algorithm is not present in the merchant account // it has to be fetched from the business profile todo!() } #[cfg(feature = "v1")] 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)), } } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] 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!() } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] 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, }) } 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), } } #[allow(clippy::too_many_arguments)] 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) } #[allow(clippy::too_many_arguments)] 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) } } #[allow(clippy::too_many_arguments)] 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) } pub fn is_operation_allowed<Op: Debug>(operation: &Op) -> bool { ![ "PaymentSession", "PaymentApprove", "PaymentReject", "PaymentCapture", "PaymentsCancel", ] .contains(&format!("{operation:?}").as_str()) } #[cfg(feature = "v1")] impl From<PaymentToFrmData> for PaymentDetails { fn from(payment_data: PaymentToFrmData) -> Self { Self { amount: common_utils::types::MinorUnit::from(payment_data.amount).get_amount_as_i64(), currency: payment_data.payment_attempt.currency, payment_method: payment_data.payment_attempt.payment_method, payment_method_type: payment_data.payment_attempt.payment_method_type, refund_transaction_id: None, } } } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn frm_fulfillment_core( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: frm_core_types::FrmFulfillmentRequest, ) -> RouterResponse<frm_types::FraudCheckResponseData> { let db = &*state.clone().store; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &(&state).into(), &req.payment_id.clone(), merchant_account.get_id(), &key_store, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound)?; match payment_intent.status { IntentStatus::Succeeded => { let invalid_request_error = errors::ApiErrorResponse::InvalidRequestData { message: "no fraud check entry found for this payment_id".to_string(), }; let existing_fraud_check = db .find_fraud_check_by_payment_id_if_present( req.payment_id.clone(), merchant_account.get_id().clone(), ) .await .change_context(invalid_request_error.to_owned())?; match existing_fraud_check { Some(fraud_check) => { if (matches!(fraud_check.frm_transaction_type, FraudCheckType::PreFrm) && fraud_check.last_step == FraudCheckLastStep::TransactionOrRecordRefund) || (matches!(fraud_check.frm_transaction_type, FraudCheckType::PostFrm) && fraud_check.last_step == FraudCheckLastStep::CheckoutOrSale) { Box::pin(make_fulfillment_api_call( db, fraud_check, payment_intent, state, merchant_account, key_store, req, )) .await } else { Err(errors::ApiErrorResponse::PreconditionFailed {message:"Frm pre/post flow hasn't terminated yet, so fulfillment cannot be called".to_string(),}.into()) } } None => Err(invalid_request_error.into()), } } _ => Err(errors::ApiErrorResponse::PreconditionFailed { message: "Fulfillment can be performed only for succeeded payment".to_string(), } .into()), } } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn make_fulfillment_api_call( db: &dyn StorageInterface, fraud_check: FraudCheck, payment_intent: PaymentIntent, state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: frm_core_types::FrmFulfillmentRequest, ) -> RouterResponse<frm_types::FraudCheckResponseData> { let payment_attempt = db .find_payment_attempt_by_attempt_id_merchant_id( &payment_intent.active_attempt.get_id(), merchant_account.get_id(), merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let connector_data = FraudCheckConnectorData::get_connector_by_name(&fraud_check.frm_name)?; let connector_integration: services::BoxedFrmConnectorIntegrationInterface< Fulfillment, frm_types::FraudCheckFulfillmentData, frm_types::FraudCheckResponseData, > = connector_data.connector.get_connector_integration(); let router_data = frm_flows::fulfillment_flow::construct_fulfillment_router_data( &state, &payment_intent, &payment_attempt, &merchant_account, &key_store, fraud_check.frm_name.clone(), req, ) .await?; let response = services::execute_connector_processing_step( &state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, ) .await .to_payment_failed_response()?; let fraud_check_copy = fraud_check.clone(); let fraud_check_update = FraudCheckUpdate::ResponseUpdate { frm_status: fraud_check.frm_status, frm_transaction_id: fraud_check.frm_transaction_id, frm_reason: fraud_check.frm_reason, frm_score: fraud_check.frm_score, metadata: fraud_check.metadata, modified_at: common_utils::date_time::now(), last_step: FraudCheckLastStep::Fulfillment, payment_capture_method: fraud_check.payment_capture_method, }; let _updated = db .update_fraud_check_response_with_attempt_id(fraud_check_copy, fraud_check_update) .await .map_err(|error| error.change_context(errors::ApiErrorResponse::PaymentNotFound))?; let fulfillment_response = response .response .map_err(|err| errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: connector_data.connector_name.clone().to_string(), status_code: err.status_code, reason: err.reason, })?; Ok(services::ApplicationResponse::Json(fulfillment_response)) }
6,765
1,572
hyperswitch
crates/router/src/core/mandate.rs
.rs
pub mod helpers; pub mod utils; use api_models::payments; use common_utils::{ext_traits::Encode, id_type}; use diesel_models::enums as storage_enums; use error_stack::{report, ResultExt}; use futures::future; use router_env::{instrument, logger, tracing}; use super::payments::helpers as payment_helper; use crate::{ core::{ errors::{self, RouterResponse, StorageErrorExt}, payments::CallConnectorAction, }, db::StorageInterface, routes::{metrics, SessionState}, services, types::{ self, api::{ mandates::{self, MandateResponseExt}, ConnectorData, GetToken, }, domain, storage::{self, enums::MerchantStorageScheme}, transformers::ForeignFrom, }, utils::OptionExt, }; #[instrument(skip(state))] pub async fn get_mandate( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: mandates::MandateId, ) -> RouterResponse<mandates::MandateResponse> { let mandate = state .store .as_ref() .find_mandate_by_merchant_id_mandate_id( merchant_account.get_id(), &req.mandate_id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; Ok(services::ApplicationResponse::Json( mandates::MandateResponse::from_db_mandate( &state, key_store, mandate, merchant_account.storage_scheme, ) .await?, )) } #[cfg(feature = "v1")] #[instrument(skip(state))] pub async fn revoke_mandate( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: mandates::MandateId, ) -> RouterResponse<mandates::MandateRevokedResponse> { let db = state.store.as_ref(); let mandate = db .find_mandate_by_merchant_id_mandate_id( merchant_account.get_id(), &req.mandate_id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; match mandate.mandate_status { common_enums::MandateStatus::Active | common_enums::MandateStatus::Inactive | common_enums::MandateStatus::Pending => { let profile_id = helpers::get_profile_id_for_mandate( &state, &merchant_account, &key_store, mandate.clone(), ) .await?; let merchant_connector_account = payment_helper::get_merchant_connector_account( &state, merchant_account.get_id(), None, &key_store, &profile_id, &mandate.connector.clone(), mandate.merchant_connector_id.as_ref(), ) .await?; let connector_data = ConnectorData::get_connector_by_name( &state.conf.connectors, &mandate.connector, GetToken::Connector, mandate.merchant_connector_id.clone(), )?; let connector_integration: services::BoxedMandateRevokeConnectorIntegrationInterface< types::api::MandateRevoke, types::MandateRevokeRequestData, types::MandateRevokeResponseData, > = connector_data.connector.get_connector_integration(); let router_data = utils::construct_mandate_revoke_router_data( &state, merchant_connector_account, &merchant_account, mandate.clone(), ) .await?; let response = services::execute_connector_processing_step( &state, connector_integration, &router_data, CallConnectorAction::Trigger, None, ) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; match response.response { Ok(_) => { let update_mandate = db .update_mandate_by_merchant_id_mandate_id( merchant_account.get_id(), &req.mandate_id, storage::MandateUpdate::StatusUpdate { mandate_status: storage::enums::MandateStatus::Revoked, }, mandate, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; Ok(services::ApplicationResponse::Json( mandates::MandateRevokedResponse { mandate_id: update_mandate.mandate_id, status: update_mandate.mandate_status, error_code: None, error_message: None, }, )) } Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: mandate.connector, status_code: err.status_code, reason: err.reason, } .into()), } } common_enums::MandateStatus::Revoked => { Err(errors::ApiErrorResponse::MandateValidationFailed { reason: "Mandate has already been revoked".to_string(), } .into()) } } } #[instrument(skip(db))] pub async fn update_connector_mandate_id( db: &dyn StorageInterface, merchant_id: &id_type::MerchantId, mandate_ids_opt: Option<String>, payment_method_id: Option<String>, resp: Result<types::PaymentsResponseData, types::ErrorResponse>, storage_scheme: MerchantStorageScheme, ) -> RouterResponse<mandates::MandateResponse> { let mandate_details = Option::foreign_from(resp); let connector_mandate_id = mandate_details .clone() .map(|md| { md.encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .map(masking::Secret::new) }) .transpose()?; //Ignore updation if the payment_attempt mandate_id or connector_mandate_id is not present if let Some((mandate_id, connector_id)) = mandate_ids_opt.zip(connector_mandate_id) { let mandate = db .find_mandate_by_merchant_id_mandate_id(merchant_id, &mandate_id, storage_scheme) .await .change_context(errors::ApiErrorResponse::MandateNotFound)?; let update_mandate_details = match payment_method_id { Some(pmd_id) => storage::MandateUpdate::ConnectorMandateIdUpdate { connector_mandate_id: mandate_details .and_then(|mandate_reference| mandate_reference.connector_mandate_id), connector_mandate_ids: Some(connector_id), payment_method_id: pmd_id, original_payment_id: None, }, None => storage::MandateUpdate::ConnectorReferenceUpdate { connector_mandate_ids: Some(connector_id), }, }; // only update the connector_mandate_id if existing is none if mandate.connector_mandate_id.is_none() { db.update_mandate_by_merchant_id_mandate_id( merchant_id, &mandate_id, update_mandate_details, mandate, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::MandateUpdateFailed)?; } } Ok(services::ApplicationResponse::StatusOk) } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip(state))] pub async fn get_customer_mandates( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, customer_id: id_type::CustomerId, ) -> RouterResponse<Vec<mandates::MandateResponse>> { let mandates = state .store .find_mandate_by_merchant_id_customer_id(merchant_account.get_id(), &customer_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed while finding mandate: merchant_id: {:?}, customer_id: {:?}", merchant_account.get_id(), customer_id, ) })?; if mandates.is_empty() { Err(report!(errors::ApiErrorResponse::MandateNotFound).attach_printable("No Mandate found")) } else { let mut response_vec = Vec::with_capacity(mandates.len()); for mandate in mandates { response_vec.push( mandates::MandateResponse::from_db_mandate( &state, key_store.clone(), mandate, merchant_account.storage_scheme, ) .await?, ); } Ok(services::ApplicationResponse::Json(response_vec)) } } fn get_insensitive_payment_method_data_if_exists<F, FData>( router_data: &types::RouterData<F, FData, types::PaymentsResponseData>, ) -> Option<domain::PaymentMethodData> where FData: MandateBehaviour, { match &router_data.request.get_payment_method_data() { domain::PaymentMethodData::Card(_) => None, _ => Some(router_data.request.get_payment_method_data()), } } pub async fn mandate_procedure<F, FData>( state: &SessionState, resp: &types::RouterData<F, FData, types::PaymentsResponseData>, customer_id: &Option<id_type::CustomerId>, pm_id: Option<String>, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, storage_scheme: MerchantStorageScheme, payment_id: &id_type::PaymentId, ) -> errors::RouterResult<Option<String>> where FData: MandateBehaviour, { let Ok(ref response) = resp.response else { return Ok(None); }; match resp.request.get_mandate_id() { Some(mandate_id) => { let Some(ref mandate_id) = mandate_id.mandate_id else { return Ok(None); }; let orig_mandate = state .store .find_mandate_by_merchant_id_mandate_id( &resp.merchant_id, mandate_id, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; let mandate = match orig_mandate.mandate_type { storage_enums::MandateType::SingleUse => state .store .update_mandate_by_merchant_id_mandate_id( &resp.merchant_id, mandate_id, storage::MandateUpdate::StatusUpdate { mandate_status: storage_enums::MandateStatus::Revoked, }, orig_mandate, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::MandateUpdateFailed), storage_enums::MandateType::MultiUse => state .store .update_mandate_by_merchant_id_mandate_id( &resp.merchant_id, mandate_id, storage::MandateUpdate::CaptureAmountUpdate { amount_captured: Some( orig_mandate.amount_captured.unwrap_or(0) + resp.request.get_amount(), ), }, orig_mandate, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::MandateUpdateFailed), }?; metrics::SUBSEQUENT_MANDATE_PAYMENT.add( 1, router_env::metric_attributes!(("connector", mandate.connector)), ); Ok(Some(mandate_id.clone())) } None => { let Some(_mandate_details) = resp.request.get_setup_mandate_details() else { return Ok(None); }; let (mandate_reference, network_txn_id) = match &response { types::PaymentsResponseData::TransactionResponse { mandate_reference, network_txn_id, .. } => (mandate_reference.clone(), network_txn_id.clone()), _ => (Box::new(None), None), }; let mandate_ids = (*mandate_reference) .as_ref() .map(|md| { md.encode_to_value() .change_context(errors::ApiErrorResponse::MandateSerializationFailed) .map(masking::Secret::new) }) .transpose()?; let Some(new_mandate_data) = payment_helper::generate_mandate( resp.merchant_id.clone(), payment_id.to_owned(), resp.connector.clone(), resp.request.get_setup_mandate_details().cloned(), customer_id, pm_id.get_required_value("payment_method_id")?, mandate_ids, network_txn_id, get_insensitive_payment_method_data_if_exists(resp), *mandate_reference, merchant_connector_id, )? else { return Ok(None); }; let connector = new_mandate_data.connector.clone(); logger::debug!("{:?}", new_mandate_data); let res_mandate_id = new_mandate_data.mandate_id.clone(); state .store .insert_mandate(new_mandate_data, storage_scheme) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicateMandate)?; metrics::MANDATE_COUNT.add(1, router_env::metric_attributes!(("connector", connector))); Ok(Some(res_mandate_id)) } } } #[instrument(skip(state))] pub async fn retrieve_mandates_list( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, constraints: api_models::mandates::MandateListConstraints, ) -> RouterResponse<Vec<api_models::mandates::MandateResponse>> { let mandates = state .store .as_ref() .find_mandates_by_merchant_id(merchant_account.get_id(), constraints) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to retrieve mandates")?; let mandates_list = future::try_join_all(mandates.into_iter().map(|mandate| { mandates::MandateResponse::from_db_mandate( &state, key_store.clone(), mandate, merchant_account.storage_scheme, ) })) .await?; Ok(services::ApplicationResponse::Json(mandates_list)) } impl ForeignFrom<Result<types::PaymentsResponseData, types::ErrorResponse>> for Option<types::MandateReference> { fn foreign_from(resp: Result<types::PaymentsResponseData, types::ErrorResponse>) -> Self { match resp { Ok(types::PaymentsResponseData::TransactionResponse { mandate_reference, .. }) => *mandate_reference, _ => None, } } } pub trait MandateBehaviour { fn get_amount(&self) -> i64; fn get_setup_future_usage(&self) -> Option<diesel_models::enums::FutureUsage>; fn get_mandate_id(&self) -> Option<&payments::MandateIds>; fn set_mandate_id(&mut self, new_mandate_id: Option<payments::MandateIds>); fn get_payment_method_data(&self) -> domain::payments::PaymentMethodData; fn get_setup_mandate_details( &self, ) -> Option<&hyperswitch_domain_models::mandates::MandateData>; fn get_customer_acceptance(&self) -> Option<payments::CustomerAcceptance>; }
3,338
1,573
hyperswitch
crates/router/src/core/gsm.rs
.rs
use api_models::gsm as gsm_api_types; use diesel_models::gsm as storage; use error_stack::ResultExt; use router_env::{instrument, tracing}; use crate::{ core::{ errors, errors::{RouterResponse, StorageErrorExt}, }, db::gsm::GsmInterface, services, types::transformers::ForeignInto, SessionState, }; #[instrument(skip_all)] pub async fn create_gsm_rule( state: SessionState, gsm_rule: gsm_api_types::GsmCreateRequest, ) -> RouterResponse<gsm_api_types::GsmResponse> { let db = state.store.as_ref(); GsmInterface::add_gsm_rule(db, gsm_rule.foreign_into()) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: "GSM with given key already exists in our records".to_string(), }) .map(|gsm| services::ApplicationResponse::Json(gsm.foreign_into())) } #[instrument(skip_all)] pub async fn retrieve_gsm_rule( state: SessionState, gsm_request: gsm_api_types::GsmRetrieveRequest, ) -> RouterResponse<gsm_api_types::GsmResponse> { let db = state.store.as_ref(); let gsm_api_types::GsmRetrieveRequest { connector, flow, sub_flow, code, message, } = gsm_request; GsmInterface::find_gsm_rule(db, connector.to_string(), flow, sub_flow, code, message) .await .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { message: "GSM with given key does not exist in our records".to_string(), }) .map(|gsm| services::ApplicationResponse::Json(gsm.foreign_into())) } #[instrument(skip_all)] pub async fn update_gsm_rule( state: SessionState, gsm_request: gsm_api_types::GsmUpdateRequest, ) -> RouterResponse<gsm_api_types::GsmResponse> { let db = state.store.as_ref(); let gsm_api_types::GsmUpdateRequest { connector, flow, sub_flow, code, message, decision, status, router_error, step_up_possible, unified_code, unified_message, error_category, clear_pan_possible, } = gsm_request; GsmInterface::update_gsm_rule( db, connector.to_string(), flow, sub_flow, code, message, storage::GatewayStatusMappingUpdate { decision: decision.map(|d| d.to_string()), status, router_error: Some(router_error), step_up_possible, unified_code, unified_message, error_category, clear_pan_possible, }, ) .await .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { message: "GSM with given key does not exist in our records".to_string(), }) .attach_printable("Failed while updating Gsm rule") .map(|gsm| services::ApplicationResponse::Json(gsm.foreign_into())) } #[instrument(skip_all)] pub async fn delete_gsm_rule( state: SessionState, gsm_request: gsm_api_types::GsmDeleteRequest, ) -> RouterResponse<gsm_api_types::GsmDeleteResponse> { let db = state.store.as_ref(); let gsm_api_types::GsmDeleteRequest { connector, flow, sub_flow, code, message, } = gsm_request; match GsmInterface::delete_gsm_rule( db, connector.to_string(), flow.to_owned(), sub_flow.to_owned(), code.to_owned(), message.to_owned(), ) .await .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { message: "GSM with given key does not exist in our records".to_string(), }) .attach_printable("Failed while Deleting Gsm rule") { Ok(is_deleted) => { if is_deleted { Ok(services::ApplicationResponse::Json( gsm_api_types::GsmDeleteResponse { gsm_rule_delete: true, connector, flow, sub_flow, code, }, )) } else { Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while Deleting Gsm rule, got response as false") } } Err(err) => Err(err), } }
969
1,574
hyperswitch
crates/router/src/core/admin.rs
.rs
use std::str::FromStr; use api_models::{ admin::{self as admin_types}, enums as api_enums, routing as routing_types, }; 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 diesel_models::configs; #[cfg(all(any(feature = "v1", feature = "v2"), feature = "olap"))] use diesel_models::{business_profile::CardTestingGuardConfig, organization::OrganizationBridge}; use error_stack::{report, FutureExt, ResultExt}; use hyperswitch_connectors::connectors::{chargebee, recurly}; use hyperswitch_domain_models::merchant_connector_account::{ FromRequestEncryptableMerchantConnectorAccount, UpdateEncryptableMerchantConnectorAccount, }; use masking::{ExposeInterface, PeekInterface, Secret}; use pm_auth::{connector::plaid::transformers::PlaidAuthType, types as pm_auth_types}; use regex::Regex; use uuid::Uuid; #[cfg(any(feature = "v1", feature = "v2"))] 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, }; const IBAN_MAX_LENGTH: usize = 34; const BACS_SORT_CODE_LENGTH: usize = 6; const BACS_MAX_ACCOUNT_NUMBER_LENGTH: usize = 8; #[inline] pub fn create_merchant_publishable_key() -> String { format!( "pk_{}_{}", router_env::env::prefix_for_env(), Uuid::new_v4().simple() ) } pub async fn insert_merchant_configs( db: &dyn StorageInterface, merchant_id: &id_type::MerchantId, ) -> RouterResult<()> { db.insert_config(configs::ConfigNew { key: merchant_id.get_requires_cvv_key(), config: "true".to_string(), }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while setting requires_cvv config")?; db.insert_config(configs::ConfigNew { key: merchant_id.get_merchant_fingerprint_secret_key(), config: utils::generate_id(consts::FINGERPRINT_SECRET_LENGTH, "fs"), }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while inserting merchant fingerprint secret")?; Ok(()) } #[cfg(feature = "olap")] fn add_publishable_key_to_decision_service( state: &SessionState, merchant_account: &domain::MerchantAccount, ) { let state = state.clone(); let publishable_key = merchant_account.publishable_key.clone(); let merchant_id = merchant_account.get_id().clone(); authentication::decision::spawn_tracked_job( async move { authentication::decision::add_publishable_key( &state, publishable_key.into(), merchant_id, None, ) .await }, authentication::decision::ADD, ); } #[cfg(feature = "olap")] pub async fn create_organization( state: SessionState, req: api::OrganizationCreateRequest, ) -> RouterResponse<api::OrganizationResponse> { let db_organization = ForeignFrom::foreign_from(req); state .accounts_store .insert_organization(db_organization) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: "Organization with the given organization_name already exists".to_string(), }) .attach_printable("Error when creating organization") .map(ForeignFrom::foreign_from) .map(service_api::ApplicationResponse::Json) } #[cfg(feature = "olap")] pub async fn update_organization( state: SessionState, org_id: api::OrganizationId, req: api::OrganizationUpdateRequest, ) -> RouterResponse<api::OrganizationResponse> { let organization_update = diesel_models::organization::OrganizationUpdate::Update { organization_name: req.organization_name, organization_details: req.organization_details, metadata: req.metadata, }; state .accounts_store .update_organization_by_org_id(&org_id.organization_id, organization_update) .await .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { message: "organization with the given id does not exist".to_string(), }) .attach_printable(format!( "Failed to update organization with organization_id: {:?}", org_id.organization_id )) .map(ForeignFrom::foreign_from) .map(service_api::ApplicationResponse::Json) } #[cfg(feature = "olap")] pub async fn get_organization( state: SessionState, org_id: api::OrganizationId, ) -> RouterResponse<api::OrganizationResponse> { #[cfg(all(feature = "v1", feature = "olap"))] { CreateOrValidateOrganization::new(Some(org_id.organization_id)) .create_or_validate(state.accounts_store.as_ref()) .await .map(ForeignFrom::foreign_from) .map(service_api::ApplicationResponse::Json) } #[cfg(all(feature = "v2", feature = "olap"))] { CreateOrValidateOrganization::new(org_id.organization_id) .create_or_validate(state.accounts_store.as_ref()) .await .map(ForeignFrom::foreign_from) .map(service_api::ApplicationResponse::Json) } } #[cfg(feature = "olap")] pub async fn create_merchant_account( state: SessionState, req: api::MerchantAccountCreate, ) -> RouterResponse<api::MerchantAccountResponse> { #[cfg(feature = "keymanager_create")] use common_utils::{keymanager, types::keymanager::EncryptionTransferRequest}; let db = state.store.as_ref(); let key = services::generate_aes256_key() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to generate aes 256 key")?; let master_key = db.get_master_key(); let key_manager_state: &KeyManagerState = &(&state).into(); let merchant_id = req.get_merchant_reference_id(); let identifier = km_types::Identifier::Merchant(merchant_id.clone()); #[cfg(feature = "keymanager_create")] { use base64::Engine; use crate::consts::BASE64_ENGINE; if key_manager_state.enabled { keymanager::transfer_key_to_key_manager( key_manager_state, EncryptionTransferRequest { identifier: identifier.clone(), key: BASE64_ENGINE.encode(key), }, ) .await .change_context(errors::ApiErrorResponse::DuplicateMerchantAccount) .attach_printable("Failed to insert key to KeyManager")?; } } let key_store = domain::MerchantKeyStore { merchant_id: merchant_id.clone(), key: domain_types::crypto_operation( key_manager_state, type_name!(domain::MerchantKeyStore), domain_types::CryptoOperation::Encrypt(key.to_vec().into()), identifier.clone(), master_key, ) .await .and_then(|val| val.try_into_operation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to decrypt data from key store")?, created_at: date_time::now(), }; let domain_merchant_account = req .create_domain_model_from_request(&state, key_store.clone(), &merchant_id) .await?; let key_manager_state = &(&state).into(); db.insert_merchant_key_store( key_manager_state, key_store.clone(), &master_key.to_vec().into(), ) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount)?; let merchant_account = db .insert_merchant(key_manager_state, domain_merchant_account, &key_store) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount)?; add_publishable_key_to_decision_service(&state, &merchant_account); insert_merchant_configs(db, &merchant_id).await?; Ok(service_api::ApplicationResponse::Json( api::MerchantAccountResponse::foreign_try_from(merchant_account) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while generating response")?, )) } #[cfg(feature = "olap")] #[async_trait::async_trait] trait MerchantAccountCreateBridge { async fn create_domain_model_from_request( self, state: &SessionState, key: domain::MerchantKeyStore, identifier: &id_type::MerchantId, ) -> RouterResult<domain::MerchantAccount>; } #[cfg(all(feature = "v1", 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 db = &*state.accounts_store; let publishable_key = create_merchant_publishable_key(); let primary_business_details = self.get_primary_details_as_value().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "primary_business_details", }, )?; let webhook_details = self.webhook_details.clone().map(ForeignInto::foreign_into); let pm_collect_link_config = self.get_pm_link_config_as_value().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "pm_collect_link_config", }, )?; let merchant_details = self.get_merchant_details_as_secret().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "merchant_details", }, )?; self.parse_routing_algorithm() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "routing_algorithm", }) .attach_printable("Invalid routing algorithm given")?; let metadata = self.get_metadata_as_secret().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "metadata", }, )?; // Get the enable payment response hash as a boolean, where the default value is true let enable_payment_response_hash = self.get_enable_payment_response_hash(); let payment_response_hash_key = self.get_payment_response_hash_key(); let parent_merchant_id = get_parent_merchant( state, self.sub_merchants_enabled, self.parent_merchant_id.as_ref(), &key_store, ) .await?; let organization = CreateOrValidateOrganization::new(self.organization_id) .create_or_validate(db) .await?; let key = key_store.key.clone().into_inner(); let key_manager_state = state.into(); let merchant_account = async { Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>( domain::MerchantAccountSetter { merchant_id: identifier.clone(), merchant_name: self .merchant_name .async_lift(|inner| async { domain_types::crypto_operation( &key_manager_state, type_name!(domain::MerchantAccount), domain_types::CryptoOperation::EncryptOptional(inner), km_types::Identifier::Merchant(key_store.merchant_id.clone()), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await?, merchant_details: merchant_details .async_lift(|inner| async { domain_types::crypto_operation( &key_manager_state, type_name!(domain::MerchantAccount), domain_types::CryptoOperation::EncryptOptional(inner), km_types::Identifier::Merchant(key_store.merchant_id.clone()), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await?, return_url: self.return_url.map(|a| a.to_string()), webhook_details, routing_algorithm: Some(serde_json::json!({ "algorithm_id": null, "timestamp": 0 })), sub_merchants_enabled: self.sub_merchants_enabled, parent_merchant_id, enable_payment_response_hash, payment_response_hash_key, redirect_to_merchant_with_http_post: self .redirect_to_merchant_with_http_post .unwrap_or_default(), publishable_key, locker_id: self.locker_id, metadata, storage_scheme: MerchantStorageScheme::PostgresOnly, primary_business_details, created_at: date_time::now(), modified_at: date_time::now(), intent_fulfillment_time: None, frm_routing_algorithm: self.frm_routing_algorithm, #[cfg(feature = "payouts")] payout_routing_algorithm: self.payout_routing_algorithm, #[cfg(not(feature = "payouts"))] payout_routing_algorithm: None, organization_id: organization.get_organization_id(), is_recon_enabled: false, default_profile: None, recon_status: diesel_models::enums::ReconStatus::NotRequested, payment_link_config: None, pm_collect_link_config, version: common_types::consts::API_VERSION, is_platform_account: false, product_type: self.product_type, }, ) } .await .change_context(errors::ApiErrorResponse::InternalServerError)?; let mut domain_merchant_account = domain::MerchantAccount::from(merchant_account); CreateProfile::new(self.primary_business_details.clone()) .create_profiles(state, &mut domain_merchant_account, &key_store) .await?; Ok(domain_merchant_account) } } #[cfg(feature = "olap")] enum CreateOrValidateOrganization { /// Creates a new organization #[cfg(feature = "v1")] Create, /// Validates if this organization exists in the records Validate { organization_id: id_type::OrganizationId, }, } #[cfg(feature = "olap")] impl CreateOrValidateOrganization { #[cfg(all(feature = "v1", feature = "olap"))] /// Create an action to either create or validate the given organization_id /// If organization_id is passed, then validate if this organization exists /// If not passed, create a new organization fn new(organization_id: Option<id_type::OrganizationId>) -> Self { if let Some(organization_id) = organization_id { Self::Validate { organization_id } } else { Self::Create } } #[cfg(all(feature = "v2", feature = "olap"))] /// Create an action to validate the provided organization_id fn new(organization_id: id_type::OrganizationId) -> Self { Self::Validate { organization_id } } #[cfg(feature = "olap")] /// Apply the action, whether to create the organization or validate the given organization_id async fn create_or_validate( &self, db: &dyn AccountsStorageInterface, ) -> RouterResult<diesel_models::organization::Organization> { match self { #[cfg(feature = "v1")] Self::Create => { let new_organization = api_models::organization::OrganizationNew::new(None); let db_organization = ForeignFrom::foreign_from(new_organization); db.insert_organization(db_organization) .await .to_duplicate_response(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error when creating organization") } Self::Validate { organization_id } => db .find_organization_by_org_id(organization_id) .await .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { message: "organization with the given id does not exist".to_string(), }), } } } #[cfg(all(feature = "v1", feature = "olap"))] enum CreateProfile { /// Create profiles from primary business details /// If there is only one profile created, then set this profile as default CreateFromPrimaryBusinessDetails { primary_business_details: Vec<admin_types::PrimaryBusinessDetails>, }, /// Create a default profile, set this as default profile CreateDefaultProfile, } #[cfg(all(feature = "v1", feature = "olap"))] impl CreateProfile { /// Create a new profile action from the given information /// If primary business details exist, then create profiles from them /// If primary business details are empty, then create default profile fn new(primary_business_details: Option<Vec<admin_types::PrimaryBusinessDetails>>) -> Self { match primary_business_details { Some(primary_business_details) if !primary_business_details.is_empty() => { Self::CreateFromPrimaryBusinessDetails { primary_business_details, } } _ => Self::CreateDefaultProfile, } } async fn create_profiles( &self, state: &SessionState, merchant_account: &mut domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> RouterResult<()> { match self { Self::CreateFromPrimaryBusinessDetails { primary_business_details, } => { let business_profiles = Self::create_profiles_for_each_business_details( state, merchant_account.clone(), primary_business_details, key_store, ) .await?; // Update the default business profile in merchant account if business_profiles.len() == 1 { merchant_account.default_profile = business_profiles .first() .map(|business_profile| business_profile.get_id().to_owned()) } } Self::CreateDefaultProfile => { let business_profile = self .create_default_business_profile(state, merchant_account.clone(), key_store) .await?; merchant_account.default_profile = Some(business_profile.get_id().to_owned()); } } Ok(()) } /// Create default profile 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) } /// Create profile for each primary_business_details, /// If there is no default profile in merchant account and only one primary_business_detail /// is available, then create a default profile. 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) } } #[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", }, )?; 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") } } #[cfg(all(feature = "olap", feature = "v2"))] 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)) } #[cfg(all(feature = "olap", feature = "v1"))] 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)) } pub async fn get_merchant_account( state: SessionState, req: api::MerchantId, _profile_id: Option<id_type::ProfileId>, ) -> RouterResponse<api::MerchantAccountResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, &req.merchant_id, &db.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_account = db .find_merchant_account_by_merchant_id(key_manager_state, &req.merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; Ok(service_api::ApplicationResponse::Json( api::MerchantAccountResponse::foreign_try_from(merchant_account) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct response")?, )) } #[cfg(feature = "v1")] /// For backwards compatibility, whenever new business labels are passed in /// primary_business_details, create a profile pub async fn create_profile_from_business_labels( state: &SessionState, db: &dyn StorageInterface, key_store: &domain::MerchantKeyStore, merchant_id: &id_type::MerchantId, new_business_details: Vec<admin_types::PrimaryBusinessDetails>, ) -> RouterResult<()> { let key_manager_state = &state.into(); let merchant_account = db .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let old_business_details = merchant_account .primary_business_details .clone() .parse_value::<Vec<admin_types::PrimaryBusinessDetails>>("PrimaryBusinessDetails") .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "routing_algorithm", }) .attach_printable("Invalid routing algorithm given")?; // find the diff between two vectors let business_profiles_to_create = new_business_details .into_iter() .filter(|business_details| !old_business_details.contains(business_details)) .collect::<Vec<_>>(); for business_profile in business_profiles_to_create { let profile_name = format!("{}_{}", business_profile.country, business_profile.business); let profile_create_request = admin_types::ProfileCreate { profile_name: Some(profile_name), ..Default::default() }; let profile_create_result = create_and_insert_business_profile( state, profile_create_request, merchant_account.clone(), key_store, ) .await .map_err(|profile_insert_error| { // If there is any duplicate error, we need not take any action crate::logger::warn!("Profile already exists {profile_insert_error:?}"); }); // If a profile is created, then unset the default profile if profile_create_result.is_ok() && merchant_account.default_profile.is_some() { let unset_default_profile = domain::MerchantAccountUpdate::UnsetDefaultProfile; db.update_merchant( key_manager_state, merchant_account.clone(), unset_default_profile, key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; } } Ok(()) } #[cfg(any(feature = "v1", feature = "v2", feature = "olap"))] #[async_trait::async_trait] trait MerchantAccountUpdateBridge { async fn get_update_merchant_object( self, state: &SessionState, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, ) -> RouterResult<storage::MerchantAccountUpdate>; } #[cfg(feature = "v1")] #[async_trait::async_trait] impl MerchantAccountUpdateBridge for api::MerchantAccountUpdate { async fn get_update_merchant_object( self, state: &SessionState, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, ) -> RouterResult<storage::MerchantAccountUpdate> { let key_manager_state = &state.into(); let key = key_store.key.get_inner().peek(); let db = state.store.as_ref(); let primary_business_details = self.get_primary_details_as_value().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "primary_business_details", }, )?; let pm_collect_link_config = self.get_pm_link_config_as_value().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "pm_collect_link_config", }, )?; let merchant_details = self.get_merchant_details_as_secret().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "merchant_details", }, )?; self.parse_routing_algorithm().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "routing_algorithm", }, )?; let webhook_details = self.webhook_details.map(ForeignInto::foreign_into); let parent_merchant_id = get_parent_merchant( state, self.sub_merchants_enabled, self.parent_merchant_id.as_ref(), key_store, ) .await?; // This supports changing the business profile by passing in the profile_id let business_profile_id_update = if let Some(ref profile_id) = self.default_profile { // Validate whether profile_id passed in request is valid and is linked to the merchant core_utils::validate_and_get_business_profile( state.store.as_ref(), key_manager_state, key_store, Some(profile_id), merchant_id, ) .await? .map(|business_profile| Some(business_profile.get_id().to_owned())) } else { None }; #[cfg(any(feature = "v1", feature = "v2"))] // In order to support backwards compatibility, if a business_labels are passed in the update // call, then create new profiles with the profile_name as business_label self.primary_business_details .clone() .async_map(|primary_business_details| async { let _ = create_profile_from_business_labels( state, db, key_store, merchant_id, primary_business_details, ) .await; }) .await; let identifier = km_types::Identifier::Merchant(key_store.merchant_id.clone()); Ok(storage::MerchantAccountUpdate::Update { merchant_name: self .merchant_name .map(Secret::new) .async_lift(|inner| async { domain_types::crypto_operation( key_manager_state, type_name!(storage::MerchantAccount), domain_types::CryptoOperation::EncryptOptional(inner), identifier.clone(), key, ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt merchant name")?, merchant_details: merchant_details .async_lift(|inner| async { domain_types::crypto_operation( key_manager_state, type_name!(storage::MerchantAccount), domain_types::CryptoOperation::EncryptOptional(inner), identifier.clone(), key, ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt merchant details")?, return_url: self.return_url.map(|a| a.to_string()), webhook_details, sub_merchants_enabled: self.sub_merchants_enabled, parent_merchant_id, enable_payment_response_hash: self.enable_payment_response_hash, payment_response_hash_key: self.payment_response_hash_key, redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post, locker_id: self.locker_id, metadata: self.metadata, publishable_key: None, primary_business_details, frm_routing_algorithm: self.frm_routing_algorithm, intent_fulfillment_time: None, #[cfg(feature = "payouts")] payout_routing_algorithm: self.payout_routing_algorithm, #[cfg(not(feature = "payouts"))] payout_routing_algorithm: None, default_profile: business_profile_id_update, payment_link_config: None, pm_collect_link_config, routing_algorithm: self.routing_algorithm, }) } } #[cfg(feature = "v2")] #[async_trait::async_trait] impl MerchantAccountUpdateBridge for api::MerchantAccountUpdate { async fn get_update_merchant_object( self, state: &SessionState, _merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, ) -> RouterResult<storage::MerchantAccountUpdate> { let key_manager_state = &state.into(); let key = key_store.key.get_inner().peek(); let merchant_details = self.get_merchant_details_as_secret().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "merchant_details", }, )?; let metadata = self.get_metadata_as_secret().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "metadata", }, )?; let identifier = km_types::Identifier::Merchant(key_store.merchant_id.clone()); Ok(storage::MerchantAccountUpdate::Update { merchant_name: self .merchant_name .map(Secret::new) .async_lift(|inner| async { domain_types::crypto_operation( key_manager_state, type_name!(storage::MerchantAccount), domain_types::CryptoOperation::EncryptOptional(inner), identifier.clone(), key, ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt merchant name")?, merchant_details: merchant_details .async_lift(|inner| async { domain_types::crypto_operation( key_manager_state, type_name!(storage::MerchantAccount), domain_types::CryptoOperation::EncryptOptional(inner), identifier.clone(), key, ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt merchant details")?, metadata: metadata.map(Box::new), publishable_key: None, }) } } pub async fn merchant_account_update( state: SessionState, merchant_id: &id_type::MerchantId, _profile_id: Option<id_type::ProfileId>, req: api::MerchantAccountUpdate, ) -> RouterResponse<api::MerchantAccountResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, merchant_id, &db.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_account_storage_object = req .get_update_merchant_object(&state, merchant_id, &key_store) .await .attach_printable("Failed to create merchant account update object")?; let response = db .update_specific_fields_in_merchant( key_manager_state, merchant_id, merchant_account_storage_object, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; Ok(service_api::ApplicationResponse::Json( api::MerchantAccountResponse::foreign_try_from(response) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while generating response")?, )) } pub async fn merchant_account_delete( state: SessionState, merchant_id: id_type::MerchantId, ) -> RouterResponse<api::MerchantAccountDeleteResponse> { let mut is_deleted = false; let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let merchant_key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_account = db .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &merchant_key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let is_merchant_account_deleted = db .delete_merchant_account_by_merchant_id(&merchant_id) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; if is_merchant_account_deleted { let is_merchant_key_store_deleted = db .delete_merchant_key_store_by_merchant_id(&merchant_id) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; is_deleted = is_merchant_account_deleted && is_merchant_key_store_deleted; } let state = state.clone(); authentication::decision::spawn_tracked_job( async move { authentication::decision::revoke_api_key( &state, merchant_account.publishable_key.into(), ) .await }, authentication::decision::REVOKE, ); match db .delete_config_by_key(merchant_id.get_requires_cvv_key().as_str()) .await { Ok(_) => Ok::<_, errors::ApiErrorResponse>(()), Err(err) => { if err.current_context().is_db_not_found() { crate::logger::error!("requires_cvv config not found in db: {err:?}"); Ok(()) } else { Err(err .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while deleting requires_cvv config"))? } } } .ok(); let response = api::MerchantAccountDeleteResponse { merchant_id, deleted: is_deleted, }; Ok(service_api::ApplicationResponse::Json(response)) } #[cfg(feature = "v1")] async fn get_parent_merchant( state: &SessionState, sub_merchants_enabled: Option<bool>, parent_merchant: Option<&id_type::MerchantId>, key_store: &domain::MerchantKeyStore, ) -> RouterResult<Option<id_type::MerchantId>> { Ok(match sub_merchants_enabled { Some(true) => { Some( parent_merchant.ok_or_else(|| { report!(errors::ValidationError::MissingRequiredField { field_name: "parent_merchant_id".to_string() }) .change_context(errors::ApiErrorResponse::PreconditionFailed { message: "If `sub_merchants_enabled` is `true`, then `parent_merchant_id` is mandatory".to_string(), }) }) .map(|id| validate_merchant_id(state, id,key_store).change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "parent_merchant_id" } ))? .await? .get_id().to_owned() ) } _ => None, }) } #[cfg(feature = "v1")] async fn validate_merchant_id( state: &SessionState, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, ) -> RouterResult<domain::MerchantAccount> { let db = &*state.store; db.find_merchant_account_by_merchant_id(&state.into(), merchant_id, key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) } struct ConnectorAuthTypeAndMetadataValidation<'a> { connector_name: &'a api_models::enums::Connector, auth_type: &'a types::ConnectorAuthType, connector_meta_data: &'a Option<pii::SecretSerdeValue>, } impl ConnectorAuthTypeAndMetadataValidation<'_> { pub fn validate_auth_and_metadata_type( &self, ) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> { let connector_auth_type_validation = ConnectorAuthTypeValidation { auth_type: self.auth_type, }; connector_auth_type_validation.validate_connector_auth_type()?; self.validate_auth_and_metadata_type_with_connector() .map_err(|err| match *err.current_context() { errors::ConnectorError::InvalidConnectorName => { err.change_context(errors::ApiErrorResponse::InvalidRequestData { message: "The connector name is invalid".to_string(), }) } errors::ConnectorError::InvalidConnectorConfig { config: field_name } => err .change_context(errors::ApiErrorResponse::InvalidRequestData { message: format!("The {} is invalid", field_name), }), errors::ConnectorError::FailedToObtainAuthType => { err.change_context(errors::ApiErrorResponse::InvalidRequestData { message: "The auth type is invalid for the connector".to_string(), }) } _ => err.change_context(errors::ApiErrorResponse::InvalidRequestData { message: "The request body is invalid".to_string(), }), }) } fn validate_auth_and_metadata_type_with_connector( &self, ) -> Result<(), error_stack::Report<errors::ConnectorError>> { use crate::connector::*; match self.connector_name { api_enums::Connector::Adyenplatform => { adyenplatform::transformers::AdyenplatformAuthType::try_from(self.auth_type)?; Ok(()) } // api_enums::Connector::Payone => {payone::transformers::PayoneAuthType::try_from(val)?;Ok(())} Added as a template code for future usage #[cfg(feature = "dummy_connector")] api_enums::Connector::DummyConnector1 | api_enums::Connector::DummyConnector2 | api_enums::Connector::DummyConnector3 | api_enums::Connector::DummyConnector4 | api_enums::Connector::DummyConnector5 | api_enums::Connector::DummyConnector6 | api_enums::Connector::DummyConnector7 => { dummyconnector::transformers::DummyConnectorAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Aci => { aci::transformers::AciAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Adyen => { adyen::transformers::AdyenAuthType::try_from(self.auth_type)?; adyen::transformers::AdyenConnectorMetadataObject::try_from( self.connector_meta_data, )?; Ok(()) } api_enums::Connector::Airwallex => { airwallex::transformers::AirwallexAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Authorizedotnet => { authorizedotnet::transformers::AuthorizedotnetAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Bankofamerica => { bankofamerica::transformers::BankOfAmericaAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Billwerk => { billwerk::transformers::BillwerkAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Bitpay => { bitpay::transformers::BitpayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Bambora => { bambora::transformers::BamboraAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Bamboraapac => { bamboraapac::transformers::BamboraapacAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Boku => { boku::transformers::BokuAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Bluesnap => { bluesnap::transformers::BluesnapAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Braintree => { braintree::transformers::BraintreeAuthType::try_from(self.auth_type)?; braintree::transformers::BraintreeMeta::try_from(self.connector_meta_data)?; Ok(()) } api_enums::Connector::Cashtocode => { cashtocode::transformers::CashtocodeAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Chargebee => { chargebee::transformers::ChargebeeAuthType::try_from(self.auth_type)?; chargebee::transformers::ChargebeeMetadata::try_from(self.connector_meta_data)?; Ok(()) } api_enums::Connector::Checkout => { checkout::transformers::CheckoutAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Coinbase => { coinbase::transformers::CoinbaseAuthType::try_from(self.auth_type)?; coinbase::transformers::CoinbaseConnectorMeta::try_from(self.connector_meta_data)?; Ok(()) } api_enums::Connector::Coingate => { coingate::transformers::CoingateAuthType::try_from(self.auth_type)?; coingate::transformers::CoingateConnectorMetadataObject::try_from( self.connector_meta_data, )?; Ok(()) } api_enums::Connector::Cryptopay => { cryptopay::transformers::CryptopayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::CtpMastercard => Ok(()), api_enums::Connector::CtpVisa => Ok(()), api_enums::Connector::Cybersource => { cybersource::transformers::CybersourceAuthType::try_from(self.auth_type)?; cybersource::transformers::CybersourceConnectorMetadataObject::try_from( self.connector_meta_data, )?; Ok(()) } api_enums::Connector::Datatrans => { datatrans::transformers::DatatransAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Deutschebank => { deutschebank::transformers::DeutschebankAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Digitalvirgo => { digitalvirgo::transformers::DigitalvirgoAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Dlocal => { dlocal::transformers::DlocalAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Ebanx => { ebanx::transformers::EbanxAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Elavon => { elavon::transformers::ElavonAuthType::try_from(self.auth_type)?; Ok(()) } // api_enums::Connector::Facilitapay => { // facilitapay::transformers::FacilitapayAuthType::try_from(self.auth_type)?; // Ok(()) // } api_enums::Connector::Fiserv => { fiserv::transformers::FiservAuthType::try_from(self.auth_type)?; fiserv::transformers::FiservSessionObject::try_from(self.connector_meta_data)?; Ok(()) } api_enums::Connector::Fiservemea => { fiservemea::transformers::FiservemeaAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Fiuu => { fiuu::transformers::FiuuAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Forte => { forte::transformers::ForteAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Getnet => { getnet::transformers::GetnetAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Globalpay => { globalpay::transformers::GlobalpayAuthType::try_from(self.auth_type)?; globalpay::transformers::GlobalPayMeta::try_from(self.connector_meta_data)?; Ok(()) } api_enums::Connector::Globepay => { globepay::transformers::GlobepayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Gocardless => { gocardless::transformers::GocardlessAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Gpayments => { gpayments::transformers::GpaymentsAuthType::try_from(self.auth_type)?; gpayments::transformers::GpaymentsMetaData::try_from(self.connector_meta_data)?; Ok(()) } api_enums::Connector::Hipay => { hipay::transformers::HipayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Helcim => { helcim::transformers::HelcimAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Iatapay => { iatapay::transformers::IatapayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Inespay => { inespay::transformers::InespayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Itaubank => { itaubank::transformers::ItaubankAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Jpmorgan => { jpmorgan::transformers::JpmorganAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Juspaythreedsserver => Ok(()), api_enums::Connector::Klarna => { klarna::transformers::KlarnaAuthType::try_from(self.auth_type)?; klarna::transformers::KlarnaConnectorMetadataObject::try_from( self.connector_meta_data, )?; Ok(()) } api_enums::Connector::Mifinity => { mifinity::transformers::MifinityAuthType::try_from(self.auth_type)?; mifinity::transformers::MifinityConnectorMetadataObject::try_from( self.connector_meta_data, )?; Ok(()) } api_enums::Connector::Mollie => { mollie::transformers::MollieAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Moneris => { moneris::transformers::MonerisAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Multisafepay => { multisafepay::transformers::MultisafepayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Netcetera => { netcetera::transformers::NetceteraAuthType::try_from(self.auth_type)?; netcetera::transformers::NetceteraMetaData::try_from(self.connector_meta_data)?; Ok(()) } api_enums::Connector::Nexinets => { nexinets::transformers::NexinetsAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Nexixpay => { nexixpay::transformers::NexixpayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Nmi => { nmi::transformers::NmiAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Nomupay => { nomupay::transformers::NomupayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Noon => { noon::transformers::NoonAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Novalnet => { novalnet::transformers::NovalnetAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Nuvei => { nuvei::transformers::NuveiAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Opennode => { opennode::transformers::OpennodeAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Paybox => { paybox::transformers::PayboxAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Payme => { payme::transformers::PaymeAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Paypal => { paypal::transformers::PaypalAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Payone => { payone::transformers::PayoneAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Paystack => { paystack::transformers::PaystackAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Payu => { payu::transformers::PayuAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Placetopay => { placetopay::transformers::PlacetopayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Powertranz => { powertranz::transformers::PowertranzAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Prophetpay => { prophetpay::transformers::ProphetpayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Rapyd => { rapyd::transformers::RapydAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Razorpay => { razorpay::transformers::RazorpayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Recurly => { recurly::transformers::RecurlyAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Redsys => { redsys::transformers::RedsysAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Shift4 => { shift4::transformers::Shift4AuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Square => { square::transformers::SquareAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Stax => { stax::transformers::StaxAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Taxjar => { taxjar::transformers::TaxjarAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Stripe => { stripe::transformers::StripeAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Stripebilling => { stripebilling::transformers::StripebillingAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Trustpay => { trustpay::transformers::TrustpayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Tsys => { tsys::transformers::TsysAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Volt => { volt::transformers::VoltAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Wellsfargo => { wellsfargo::transformers::WellsfargoAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Wise => { wise::transformers::WiseAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Worldline => { worldline::transformers::WorldlineAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Worldpay => { worldpay::transformers::WorldpayAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Xendit => { xendit::transformers::XenditAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Zen => { zen::transformers::ZenAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Zsl => { zsl::transformers::ZslAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Signifyd => { signifyd::transformers::SignifydAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Riskified => { riskified::transformers::RiskifiedAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Plaid => { PlaidAuthType::foreign_try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Threedsecureio => { threedsecureio::transformers::ThreedsecureioAuthType::try_from(self.auth_type)?; Ok(()) } } } } struct ConnectorAuthTypeValidation<'a> { auth_type: &'a types::ConnectorAuthType, } impl ConnectorAuthTypeValidation<'_> { fn validate_connector_auth_type( &self, ) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> { let validate_non_empty_field = |field_value: &str, field_name: &str| { if field_value.trim().is_empty() { Err(errors::ApiErrorResponse::InvalidDataFormat { field_name: format!("connector_account_details.{}", field_name), expected_format: "a non empty String".to_string(), } .into()) } else { Ok(()) } }; match self.auth_type { hyperswitch_domain_models::router_data::ConnectorAuthType::TemporaryAuth => Ok(()), hyperswitch_domain_models::router_data::ConnectorAuthType::HeaderKey { api_key } => { validate_non_empty_field(api_key.peek(), "api_key") } hyperswitch_domain_models::router_data::ConnectorAuthType::BodyKey { api_key, key1, } => { validate_non_empty_field(api_key.peek(), "api_key")?; validate_non_empty_field(key1.peek(), "key1") } hyperswitch_domain_models::router_data::ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } => { validate_non_empty_field(api_key.peek(), "api_key")?; validate_non_empty_field(key1.peek(), "key1")?; validate_non_empty_field(api_secret.peek(), "api_secret") } hyperswitch_domain_models::router_data::ConnectorAuthType::MultiAuthKey { api_key, key1, api_secret, key2, } => { validate_non_empty_field(api_key.peek(), "api_key")?; validate_non_empty_field(key1.peek(), "key1")?; validate_non_empty_field(api_secret.peek(), "api_secret")?; validate_non_empty_field(key2.peek(), "key2") } hyperswitch_domain_models::router_data::ConnectorAuthType::CurrencyAuthKey { auth_key_map, } => { if auth_key_map.is_empty() { Err(errors::ApiErrorResponse::InvalidDataFormat { field_name: "connector_account_details.auth_key_map".to_string(), expected_format: "a non empty map".to_string(), } .into()) } else { Ok(()) } } hyperswitch_domain_models::router_data::ConnectorAuthType::CertificateAuth { certificate, private_key, } => { client::create_identity_from_certificate_and_key( certificate.to_owned(), private_key.to_owned(), ) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "connector_account_details.certificate or connector_account_details.private_key" .to_string(), expected_format: "a valid base64 encoded string of PEM encoded Certificate and Private Key" .to_string(), })?; Ok(()) } hyperswitch_domain_models::router_data::ConnectorAuthType::NoKey => Ok(()), } } } struct ConnectorStatusAndDisabledValidation<'a> { status: &'a Option<api_enums::ConnectorStatus>, disabled: &'a Option<bool>, auth: &'a types::ConnectorAuthType, current_status: &'a api_enums::ConnectorStatus, } impl ConnectorStatusAndDisabledValidation<'_> { fn validate_status_and_disabled( &self, ) -> RouterResult<(api_enums::ConnectorStatus, Option<bool>)> { let connector_status = match (self.status, self.auth) { ( Some(common_enums::ConnectorStatus::Active), types::ConnectorAuthType::TemporaryAuth, ) => { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Connector status cannot be active when using TemporaryAuth" .to_string(), } .into()); } (Some(status), _) => status, (None, types::ConnectorAuthType::TemporaryAuth) => { &common_enums::ConnectorStatus::Inactive } (None, _) => self.current_status, }; let disabled = match (self.disabled, connector_status) { (Some(false), common_enums::ConnectorStatus::Inactive) => { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Connector cannot be enabled when connector_status is inactive or when using TemporaryAuth" .to_string(), } .into()); } (Some(disabled), _) => Some(*disabled), (None, common_enums::ConnectorStatus::Inactive) => Some(true), // Enable the connector if nothing is passed in the request (None, _) => Some(false), }; Ok((*connector_status, disabled)) } } struct ConnectorMetadata<'a> { connector_metadata: &'a Option<pii::SecretSerdeValue>, } impl ConnectorMetadata<'_> { fn validate_apple_pay_certificates_in_mca_metadata(&self) -> RouterResult<()> { self.connector_metadata .clone() .map(api_models::payments::ConnectorMetadata::from_value) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "metadata".to_string(), expected_format: "connector metadata".to_string(), })? .and_then(|metadata| metadata.get_apple_pay_certificates()) .map(|(certificate, certificate_key)| { client::create_identity_from_certificate_and_key(certificate, certificate_key) }) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "certificate/certificate key", })?; Ok(()) } } struct PMAuthConfigValidation<'a> { connector_type: &'a api_enums::ConnectorType, pm_auth_config: &'a Option<pii::SecretSerdeValue>, db: &'a dyn StorageInterface, merchant_id: &'a id_type::MerchantId, profile_id: &'a id_type::ProfileId, key_store: &'a domain::MerchantKeyStore, key_manager_state: &'a KeyManagerState, } impl PMAuthConfigValidation<'_> { async fn validate_pm_auth(&self, val: &pii::SecretSerdeValue) -> RouterResponse<()> { let config = serde_json::from_value::<api_models::pm_auth::PaymentMethodAuthConfig>( val.clone().expose(), ) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "invalid data received for payment method auth config".to_string(), }) .attach_printable("Failed to deserialize Payment Method Auth config")?; let all_mcas = self .db .find_merchant_connector_account_by_merchant_id_and_disabled_list( self.key_manager_state, self.merchant_id, true, self.key_store, ) .await .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: self.merchant_id.get_string_repr().to_owned(), })?; for conn_choice in config.enabled_payment_methods { let pm_auth_mca = all_mcas .iter() .find(|mca| mca.get_id() == conn_choice.mca_id) .ok_or(errors::ApiErrorResponse::GenericNotFoundError { message: "payment method auth connector account not found".to_string(), })?; if &pm_auth_mca.profile_id != self.profile_id { return Err(errors::ApiErrorResponse::GenericNotFoundError { message: "payment method auth profile_id differs from connector profile_id" .to_string(), } .into()); } } Ok(services::ApplicationResponse::StatusOk) } async fn validate_pm_auth_config(&self) -> RouterResult<()> { if self.connector_type != &api_enums::ConnectorType::PaymentMethodAuth { if let Some(val) = self.pm_auth_config.clone() { self.validate_pm_auth(&val).await?; } } Ok(()) } } struct ConnectorTypeAndConnectorName<'a> { connector_type: &'a api_enums::ConnectorType, connector_name: &'a api_enums::Connector, } impl ConnectorTypeAndConnectorName<'_> { fn get_routable_connector(&self) -> RouterResult<Option<api_enums::RoutableConnectors>> { let mut routable_connector = api_enums::RoutableConnectors::from_str(&self.connector_name.to_string()).ok(); let pm_auth_connector = api_enums::convert_pm_auth_connector(self.connector_name.to_string().as_str()); let authentication_connector = api_enums::convert_authentication_connector(self.connector_name.to_string().as_str()); let tax_connector = api_enums::convert_tax_connector(self.connector_name.to_string().as_str()); let billing_connector = api_enums::convert_billing_connector(self.connector_name.to_string().as_str()); if pm_auth_connector.is_some() { if self.connector_type != &api_enums::ConnectorType::PaymentMethodAuth && self.connector_type != &api_enums::ConnectorType::PaymentProcessor { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid connector type given".to_string(), } .into()); } } else if authentication_connector.is_some() { if self.connector_type != &api_enums::ConnectorType::AuthenticationProcessor { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid connector type given".to_string(), } .into()); } } else if tax_connector.is_some() { if self.connector_type != &api_enums::ConnectorType::TaxProcessor { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid connector type given".to_string(), } .into()); } } else if billing_connector.is_some() { if self.connector_type != &api_enums::ConnectorType::BillingProcessor { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid connector type given".to_string(), } .into()); } } else { let routable_connector_option = self .connector_name .to_string() .parse::<api_enums::RoutableConnectors>() .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid connector name given".to_string(), })?; routable_connector = Some(routable_connector_option); }; Ok(routable_connector) } } #[cfg(feature = "v1")] struct MerchantDefaultConfigUpdate<'a> { routable_connector: &'a Option<api_enums::RoutableConnectors>, merchant_connector_id: &'a id_type::MerchantConnectorAccountId, store: &'a dyn StorageInterface, merchant_id: &'a id_type::MerchantId, profile_id: &'a id_type::ProfileId, transaction_type: &'a api_enums::TransactionType, } #[cfg(feature = "v1")] impl MerchantDefaultConfigUpdate<'_> { async fn retrieve_and_update_default_fallback_routing_algorithm_if_routable_connector_exists( &self, ) -> RouterResult<()> { let mut default_routing_config = routing::helpers::get_merchant_default_config( self.store, self.merchant_id.get_string_repr(), self.transaction_type, ) .await?; let mut default_routing_config_for_profile = routing::helpers::get_merchant_default_config( self.store, self.profile_id.get_string_repr(), self.transaction_type, ) .await?; if let Some(routable_connector_val) = self.routable_connector { let choice = routing_types::RoutableConnectorChoice { choice_kind: routing_types::RoutableChoiceKind::FullStruct, connector: *routable_connector_val, merchant_connector_id: Some(self.merchant_connector_id.clone()), }; if !default_routing_config.contains(&choice) { default_routing_config.push(choice.clone()); routing::helpers::update_merchant_default_config( self.store, self.merchant_id.get_string_repr(), default_routing_config.clone(), self.transaction_type, ) .await?; } if !default_routing_config_for_profile.contains(&choice.clone()) { default_routing_config_for_profile.push(choice); routing::helpers::update_merchant_default_config( self.store, self.profile_id.get_string_repr(), default_routing_config_for_profile.clone(), self.transaction_type, ) .await?; } } Ok(()) } async fn retrieve_and_delete_from_default_fallback_routing_algorithm_if_routable_connector_exists( &self, ) -> RouterResult<()> { let mut default_routing_config = routing::helpers::get_merchant_default_config( self.store, self.merchant_id.get_string_repr(), self.transaction_type, ) .await?; let mut default_routing_config_for_profile = routing::helpers::get_merchant_default_config( self.store, self.profile_id.get_string_repr(), self.transaction_type, ) .await?; if let Some(routable_connector_val) = self.routable_connector { let choice = routing_types::RoutableConnectorChoice { choice_kind: routing_types::RoutableChoiceKind::FullStruct, connector: *routable_connector_val, merchant_connector_id: Some(self.merchant_connector_id.clone()), }; if default_routing_config.contains(&choice) { default_routing_config.retain(|mca| { mca.merchant_connector_id.as_ref() != Some(self.merchant_connector_id) }); routing::helpers::update_merchant_default_config( self.store, self.merchant_id.get_string_repr(), default_routing_config.clone(), self.transaction_type, ) .await?; } if default_routing_config_for_profile.contains(&choice.clone()) { default_routing_config_for_profile.retain(|mca| { mca.merchant_connector_id.as_ref() != Some(self.merchant_connector_id) }); routing::helpers::update_merchant_default_config( self.store, self.profile_id.get_string_repr(), default_routing_config_for_profile.clone(), self.transaction_type, ) .await?; } } Ok(()) } } #[cfg(feature = "v2")] struct DefaultFallbackRoutingConfigUpdate<'a> { routable_connector: &'a Option<api_enums::RoutableConnectors>, merchant_connector_id: &'a id_type::MerchantConnectorAccountId, store: &'a dyn StorageInterface, business_profile: domain::Profile, key_store: hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, key_manager_state: &'a KeyManagerState, } #[cfg(feature = "v2")] impl DefaultFallbackRoutingConfigUpdate<'_> { async fn retrieve_and_update_default_fallback_routing_algorithm_if_routable_connector_exists( &self, ) -> RouterResult<()> { let profile_wrapper = ProfileWrapper::new(self.business_profile.clone()); let default_routing_config_for_profile = &mut profile_wrapper.get_default_fallback_list_of_connector_under_profile()?; if let Some(routable_connector_val) = self.routable_connector { let choice = routing_types::RoutableConnectorChoice { choice_kind: routing_types::RoutableChoiceKind::FullStruct, connector: *routable_connector_val, merchant_connector_id: Some(self.merchant_connector_id.clone()), }; if !default_routing_config_for_profile.contains(&choice.clone()) { default_routing_config_for_profile.push(choice); profile_wrapper .update_default_fallback_routing_of_connectors_under_profile( self.store, default_routing_config_for_profile, self.key_manager_state, &self.key_store, ) .await? } } Ok(()) } async fn retrieve_and_delete_from_default_fallback_routing_algorithm_if_routable_connector_exists( &self, ) -> RouterResult<()> { let profile_wrapper = ProfileWrapper::new(self.business_profile.clone()); let default_routing_config_for_profile = &mut profile_wrapper.get_default_fallback_list_of_connector_under_profile()?; if let Some(routable_connector_val) = self.routable_connector { let choice = routing_types::RoutableConnectorChoice { choice_kind: routing_types::RoutableChoiceKind::FullStruct, connector: *routable_connector_val, merchant_connector_id: Some(self.merchant_connector_id.clone()), }; if default_routing_config_for_profile.contains(&choice.clone()) { default_routing_config_for_profile.retain(|mca| { mca.merchant_connector_id.as_ref() != Some(self.merchant_connector_id) }); profile_wrapper .update_default_fallback_routing_of_connectors_under_profile( self.store, default_routing_config_for_profile, self.key_manager_state, &self.key_store, ) .await? } } Ok(()) } } #[cfg(any(feature = "v1", feature = "v2", feature = "olap"))] #[async_trait::async_trait] trait MerchantConnectorAccountUpdateBridge { async fn get_merchant_connector_account_from_id( self, db: &dyn StorageInterface, merchant_id: &id_type::MerchantId, merchant_connector_id: &id_type::MerchantConnectorAccountId, key_store: &domain::MerchantKeyStore, key_manager_state: &KeyManagerState, ) -> RouterResult<domain::MerchantConnectorAccount>; async fn create_domain_model_from_request( self, state: &SessionState, key_store: domain::MerchantKeyStore, mca: &domain::MerchantConnectorAccount, key_manager_state: &KeyManagerState, merchant_account: &domain::MerchantAccount, ) -> RouterResult<domain::MerchantConnectorAccountUpdate>; } #[cfg(all(feature = "v2", feature = "olap"))] #[async_trait::async_trait] impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnectorUpdate { async fn get_merchant_connector_account_from_id( self, db: &dyn StorageInterface, _merchant_id: &id_type::MerchantId, merchant_connector_id: &id_type::MerchantConnectorAccountId, key_store: &domain::MerchantKeyStore, key_manager_state: &KeyManagerState, ) -> RouterResult<domain::MerchantConnectorAccount> { db.find_merchant_connector_account_by_id( key_manager_state, merchant_connector_id, key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) } async fn create_domain_model_from_request( self, state: &SessionState, key_store: domain::MerchantKeyStore, mca: &domain::MerchantConnectorAccount, key_manager_state: &KeyManagerState, merchant_account: &domain::MerchantAccount, ) -> RouterResult<domain::MerchantConnectorAccountUpdate> { let frm_configs = self.get_frm_config_as_secret(); let payment_methods_enabled = self.payment_methods_enabled; let auth = types::ConnectorAuthType::from_secret_value( self.connector_account_details .clone() .unwrap_or(mca.connector_account_details.clone().into_inner()), ) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "connector_account_details".to_string(), expected_format: "auth_type and api_key".to_string(), })?; let metadata = self.metadata.clone().or(mca.metadata.clone()); let connector_auth_type_and_metadata_validation = ConnectorAuthTypeAndMetadataValidation { connector_name: &mca.connector_name, auth_type: &auth, connector_meta_data: &metadata, }; connector_auth_type_and_metadata_validation.validate_auth_and_metadata_type()?; let connector_status_and_disabled_validation = ConnectorStatusAndDisabledValidation { status: &self.status, disabled: &self.disabled, auth: &auth, current_status: &mca.status, }; let (connector_status, disabled) = connector_status_and_disabled_validation.validate_status_and_disabled()?; let pm_auth_config_validation = PMAuthConfigValidation { connector_type: &self.connector_type, pm_auth_config: &self.pm_auth_config, db: state.store.as_ref(), merchant_id: merchant_account.get_id(), profile_id: &mca.profile_id.clone(), key_store: &key_store, key_manager_state, }; pm_auth_config_validation.validate_pm_auth_config().await?; let merchant_recipient_data = if let Some(data) = &self.additional_merchant_data { Some( process_open_banking_connectors( state, merchant_account.get_id(), &auth, &self.connector_type, &mca.connector_name, types::AdditionalMerchantData::foreign_from(data.clone()), ) .await?, ) } else { None } .map(|data| { serde_json::to_value(types::AdditionalMerchantData::OpenBankingRecipientData( data, )) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize MerchantRecipientData")?; let encrypted_data = domain_types::crypto_operation( key_manager_state, type_name!(domain::MerchantConnectorAccount), domain_types::CryptoOperation::BatchEncrypt( UpdateEncryptableMerchantConnectorAccount::to_encryptable( UpdateEncryptableMerchantConnectorAccount { connector_account_details: self.connector_account_details, connector_wallets_details: helpers::get_connector_wallets_details_with_apple_pay_certificates( &self.metadata, &self.connector_wallets_details, ) .await?, additional_merchant_data: merchant_recipient_data.map(Secret::new), }, ), ), km_types::Identifier::Merchant(key_store.merchant_id.clone()), key_store.key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while decrypting connector account details".to_string())?; let encrypted_data = UpdateEncryptableMerchantConnectorAccount::from_encryptable(encrypted_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while decrypting connector account details")?; let feature_metadata = self .feature_metadata .as_ref() .map(ForeignTryFrom::foreign_try_from) .transpose()?; Ok(storage::MerchantConnectorAccountUpdate::Update { connector_type: Some(self.connector_type), connector_label: self.connector_label.clone(), connector_account_details: Box::new(encrypted_data.connector_account_details), disabled, payment_methods_enabled, metadata: self.metadata, frm_configs, connector_webhook_details: match &self.connector_webhook_details { Some(connector_webhook_details) => Box::new( connector_webhook_details .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .map(Some)? .map(Secret::new), ), None => Box::new(None), }, applepay_verified_domains: None, pm_auth_config: Box::new(self.pm_auth_config), status: Some(connector_status), additional_merchant_data: Box::new(encrypted_data.additional_merchant_data), connector_wallets_details: Box::new(encrypted_data.connector_wallets_details), feature_metadata: Box::new(feature_metadata), }) } } #[cfg(all(feature = "v1", feature = "olap"))] #[async_trait::async_trait] impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnectorUpdate { async fn get_merchant_connector_account_from_id( self, db: &dyn StorageInterface, merchant_id: &id_type::MerchantId, merchant_connector_id: &id_type::MerchantConnectorAccountId, key_store: &domain::MerchantKeyStore, key_manager_state: &KeyManagerState, ) -> RouterResult<domain::MerchantConnectorAccount> { db.find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_id, merchant_connector_id, key_store, ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), }, ) } async fn create_domain_model_from_request( self, state: &SessionState, key_store: domain::MerchantKeyStore, mca: &domain::MerchantConnectorAccount, key_manager_state: &KeyManagerState, merchant_account: &domain::MerchantAccount, ) -> RouterResult<domain::MerchantConnectorAccountUpdate> { let payment_methods_enabled = self.payment_methods_enabled.map(|pm_enabled| { pm_enabled .iter() .flat_map(Encode::encode_to_value) .map(Secret::new) .collect::<Vec<pii::SecretSerdeValue>>() }); let frm_configs = get_frm_config_as_secret(self.frm_configs); let auth: types::ConnectorAuthType = self .connector_account_details .clone() .unwrap_or(mca.connector_account_details.clone().into_inner()) .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "connector_account_details".to_string(), expected_format: "auth_type and api_key".to_string(), })?; let metadata = self.metadata.clone().or(mca.metadata.clone()); let connector_name = mca.connector_name.as_ref(); 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 connector_auth_type_and_metadata_validation = ConnectorAuthTypeAndMetadataValidation { connector_name: &connector_enum, auth_type: &auth, connector_meta_data: &metadata, }; connector_auth_type_and_metadata_validation.validate_auth_and_metadata_type()?; let connector_status_and_disabled_validation = ConnectorStatusAndDisabledValidation { status: &self.status, disabled: &self.disabled, auth: &auth, current_status: &mca.status, }; let (connector_status, disabled) = connector_status_and_disabled_validation.validate_status_and_disabled()?; if self.connector_type != api_enums::ConnectorType::PaymentMethodAuth { if let Some(val) = self.pm_auth_config.clone() { validate_pm_auth( val, state, merchant_account.get_id(), &key_store, merchant_account.clone(), &mca.profile_id, ) .await?; } } let merchant_recipient_data = if let Some(data) = &self.additional_merchant_data { Some( process_open_banking_connectors( state, merchant_account.get_id(), &auth, &self.connector_type, &connector_enum, types::AdditionalMerchantData::foreign_from(data.clone()), ) .await?, ) } else { None } .map(|data| { serde_json::to_value(types::AdditionalMerchantData::OpenBankingRecipientData( data, )) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize MerchantRecipientData")?; let encrypted_data = domain_types::crypto_operation( key_manager_state, type_name!(domain::MerchantConnectorAccount), domain_types::CryptoOperation::BatchEncrypt( UpdateEncryptableMerchantConnectorAccount::to_encryptable( UpdateEncryptableMerchantConnectorAccount { connector_account_details: self.connector_account_details, connector_wallets_details: helpers::get_connector_wallets_details_with_apple_pay_certificates( &self.metadata, &self.connector_wallets_details, ) .await?, additional_merchant_data: merchant_recipient_data.map(Secret::new), }, ), ), km_types::Identifier::Merchant(key_store.merchant_id.clone()), key_store.key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while decrypting connector account details".to_string())?; let encrypted_data = UpdateEncryptableMerchantConnectorAccount::from_encryptable(encrypted_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while decrypting connector account details")?; Ok(storage::MerchantConnectorAccountUpdate::Update { connector_type: Some(self.connector_type), connector_name: None, merchant_connector_id: None, connector_label: self.connector_label.clone(), connector_account_details: Box::new(encrypted_data.connector_account_details), test_mode: self.test_mode, disabled, payment_methods_enabled, metadata: self.metadata, frm_configs, connector_webhook_details: match &self.connector_webhook_details { Some(connector_webhook_details) => Box::new( connector_webhook_details .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .map(Some)? .map(Secret::new), ), None => Box::new(None), }, applepay_verified_domains: None, pm_auth_config: Box::new(self.pm_auth_config), status: Some(connector_status), additional_merchant_data: Box::new(encrypted_data.additional_merchant_data), connector_wallets_details: Box::new(encrypted_data.connector_wallets_details), }) } } #[cfg(any(feature = "v1", feature = "v2", feature = "olap"))] #[async_trait::async_trait] trait MerchantConnectorAccountCreateBridge { async fn create_domain_model_from_request( self, state: &SessionState, key_store: domain::MerchantKeyStore, business_profile: &domain::Profile, key_manager_state: &KeyManagerState, ) -> RouterResult<domain::MerchantConnectorAccount>; async fn validate_and_get_business_profile( self, merchant_account: &domain::MerchantAccount, db: &dyn StorageInterface, key_manager_state: &KeyManagerState, key_store: &domain::MerchantKeyStore, ) -> RouterResult<domain::Profile>; } #[cfg(all(feature = "v2", feature = "olap",))] #[async_trait::async_trait] impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate { async fn create_domain_model_from_request( self, state: &SessionState, key_store: domain::MerchantKeyStore, business_profile: &domain::Profile, key_manager_state: &KeyManagerState, ) -> RouterResult<domain::MerchantConnectorAccount> { // If connector label is not passed in the request, generate one let connector_label = self.get_connector_label(business_profile.profile_name.clone()); let frm_configs = self.get_frm_config_as_secret(); let payment_methods_enabled = self.payment_methods_enabled; // Validate Merchant api details and return error if not in correct format let auth = types::ConnectorAuthType::from_option_secret_value( self.connector_account_details.clone(), ) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "connector_account_details".to_string(), expected_format: "auth_type and api_key".to_string(), })?; let connector_auth_type_and_metadata_validation = ConnectorAuthTypeAndMetadataValidation { connector_name: &self.connector_name, auth_type: &auth, connector_meta_data: &self.metadata, }; connector_auth_type_and_metadata_validation.validate_auth_and_metadata_type()?; let connector_status_and_disabled_validation = ConnectorStatusAndDisabledValidation { status: &self.status, disabled: &self.disabled, auth: &auth, current_status: &api_enums::ConnectorStatus::Active, }; let (connector_status, disabled) = connector_status_and_disabled_validation.validate_status_and_disabled()?; let identifier = km_types::Identifier::Merchant(business_profile.merchant_id.clone()); let merchant_recipient_data = if let Some(data) = &self.additional_merchant_data { Some( process_open_banking_connectors( state, &business_profile.merchant_id, &auth, &self.connector_type, &self.connector_name, types::AdditionalMerchantData::foreign_from(data.clone()), ) .await?, ) } else { None } .map(|data| { serde_json::to_value(types::AdditionalMerchantData::OpenBankingRecipientData( data, )) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize MerchantRecipientData")?; let encrypted_data = domain_types::crypto_operation( key_manager_state, type_name!(domain::MerchantConnectorAccount), domain_types::CryptoOperation::BatchEncrypt( FromRequestEncryptableMerchantConnectorAccount::to_encryptable( FromRequestEncryptableMerchantConnectorAccount { connector_account_details: self.connector_account_details.ok_or( errors::ApiErrorResponse::MissingRequiredField { field_name: "connector_account_details", }, )?, connector_wallets_details: helpers::get_connector_wallets_details_with_apple_pay_certificates( &self.metadata, &self.connector_wallets_details, ) .await?, additional_merchant_data: merchant_recipient_data.map(Secret::new), }, ), ), identifier.clone(), key_store.key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while decrypting connector account details".to_string())?; let encrypted_data = FromRequestEncryptableMerchantConnectorAccount::from_encryptable(encrypted_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while decrypting connector account details")?; let feature_metadata = self .feature_metadata .as_ref() .map(ForeignTryFrom::foreign_try_from) .transpose()?; Ok(domain::MerchantConnectorAccount { merchant_id: business_profile.merchant_id.clone(), connector_type: self.connector_type, connector_name: self.connector_name, connector_account_details: encrypted_data.connector_account_details, payment_methods_enabled, disabled, metadata: self.metadata.clone(), frm_configs, connector_label: Some(connector_label.clone()), created_at: date_time::now(), modified_at: date_time::now(), id: common_utils::generate_merchant_connector_account_id_of_default_length(), connector_webhook_details: match self.connector_webhook_details { Some(connector_webhook_details) => { connector_webhook_details.encode_to_value( ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable(format!("Failed to serialize api_models::admin::MerchantConnectorWebhookDetails for Merchant: {:?}", business_profile.merchant_id)) .map(Some)? .map(Secret::new) } None => None, }, profile_id: business_profile.get_id().to_owned(), applepay_verified_domains: None, pm_auth_config: self.pm_auth_config.clone(), status: connector_status, connector_wallets_details: encrypted_data.connector_wallets_details, additional_merchant_data: encrypted_data.additional_merchant_data, version: common_types::consts::API_VERSION, feature_metadata, }) } async fn validate_and_get_business_profile( self, merchant_account: &domain::MerchantAccount, db: &dyn StorageInterface, key_manager_state: &KeyManagerState, key_store: &domain::MerchantKeyStore, ) -> RouterResult<domain::Profile> { let profile_id = self.profile_id; // Check whether this profile belongs to the merchant 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") .change_context(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; Ok(business_profile) } } #[cfg(feature = "v1")] struct PaymentMethodsEnabled<'a> { payment_methods_enabled: &'a Option<Vec<api_models::admin::PaymentMethodsEnabled>>, } #[cfg(feature = "v1")] impl PaymentMethodsEnabled<'_> { fn get_payment_methods_enabled(&self) -> RouterResult<Option<Vec<pii::SecretSerdeValue>>> { let mut vec = Vec::new(); let payment_methods_enabled = match self.payment_methods_enabled.clone() { Some(val) => { for pm in val.into_iter() { let pm_value = pm .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed while encoding to serde_json::Value, PaymentMethod", )?; vec.push(Secret::new(pm_value)) } Some(vec) } None => None, }; Ok(payment_methods_enabled) } } #[cfg(all(feature = "v1", feature = "olap"))] #[async_trait::async_trait] impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate { async fn create_domain_model_from_request( self, state: &SessionState, key_store: domain::MerchantKeyStore, business_profile: &domain::Profile, key_manager_state: &KeyManagerState, ) -> RouterResult<domain::MerchantConnectorAccount> { // If connector label is not passed in the request, generate one let connector_label = self .connector_label .clone() .or(core_utils::get_connector_label( self.business_country, self.business_label.as_ref(), self.business_sub_label.as_ref(), &self.connector_name.to_string(), )) .unwrap_or(format!( "{}_{}", self.connector_name, business_profile.profile_name )); let payment_methods_enabled = PaymentMethodsEnabled { payment_methods_enabled: &self.payment_methods_enabled, }; let payment_methods_enabled = payment_methods_enabled.get_payment_methods_enabled()?; let frm_configs = self.get_frm_config_as_secret(); // Validate Merchant api details and return error if not in correct format let auth = types::ConnectorAuthType::from_option_secret_value( self.connector_account_details.clone(), ) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "connector_account_details".to_string(), expected_format: "auth_type and api_key".to_string(), })?; let connector_auth_type_and_metadata_validation = ConnectorAuthTypeAndMetadataValidation { connector_name: &self.connector_name, auth_type: &auth, connector_meta_data: &self.metadata, }; connector_auth_type_and_metadata_validation.validate_auth_and_metadata_type()?; let connector_status_and_disabled_validation = ConnectorStatusAndDisabledValidation { status: &self.status, disabled: &self.disabled, auth: &auth, current_status: &api_enums::ConnectorStatus::Active, }; let (connector_status, disabled) = connector_status_and_disabled_validation.validate_status_and_disabled()?; let identifier = km_types::Identifier::Merchant(business_profile.merchant_id.clone()); let merchant_recipient_data = if let Some(data) = &self.additional_merchant_data { Some( process_open_banking_connectors( state, &business_profile.merchant_id, &auth, &self.connector_type, &self.connector_name, types::AdditionalMerchantData::foreign_from(data.clone()), ) .await?, ) } else { None } .map(|data| { serde_json::to_value(types::AdditionalMerchantData::OpenBankingRecipientData( data, )) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize MerchantRecipientData")?; let encrypted_data = domain_types::crypto_operation( key_manager_state, type_name!(domain::MerchantConnectorAccount), domain_types::CryptoOperation::BatchEncrypt( FromRequestEncryptableMerchantConnectorAccount::to_encryptable( FromRequestEncryptableMerchantConnectorAccount { connector_account_details: self.connector_account_details.ok_or( errors::ApiErrorResponse::MissingRequiredField { field_name: "connector_account_details", }, )?, connector_wallets_details: helpers::get_connector_wallets_details_with_apple_pay_certificates( &self.metadata, &self.connector_wallets_details, ) .await?, additional_merchant_data: merchant_recipient_data.map(Secret::new), }, ), ), identifier.clone(), key_store.key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while decrypting connector account details".to_string())?; let encrypted_data = FromRequestEncryptableMerchantConnectorAccount::from_encryptable(encrypted_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while decrypting connector account details")?; Ok(domain::MerchantConnectorAccount { merchant_id: business_profile.merchant_id.clone(), connector_type: self.connector_type, connector_name: self.connector_name.to_string(), merchant_connector_id: common_utils::generate_merchant_connector_account_id_of_default_length(), connector_account_details: encrypted_data.connector_account_details, payment_methods_enabled, disabled, metadata: self.metadata.clone(), frm_configs, connector_label: Some(connector_label.clone()), created_at: date_time::now(), modified_at: date_time::now(), connector_webhook_details: match self.connector_webhook_details { Some(connector_webhook_details) => { connector_webhook_details.encode_to_value( ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable(format!("Failed to serialize api_models::admin::MerchantConnectorWebhookDetails for Merchant: {:?}", business_profile.merchant_id)) .map(Some)? .map(Secret::new) } None => None, }, profile_id: business_profile.get_id().to_owned(), applepay_verified_domains: None, pm_auth_config: self.pm_auth_config.clone(), status: connector_status, connector_wallets_details: encrypted_data.connector_wallets_details, test_mode: self.test_mode, business_country: self.business_country, business_label: self.business_label.clone(), business_sub_label: self.business_sub_label.clone(), additional_merchant_data: encrypted_data.additional_merchant_data, version: common_types::consts::API_VERSION, }) } /// If profile_id is not passed, use default profile if available, or /// If business_details (business_country and business_label) are passed, get the business_profile /// or return a `MissingRequiredField` error async fn validate_and_get_business_profile( self, merchant_account: &domain::MerchantAccount, db: &dyn StorageInterface, key_manager_state: &KeyManagerState, key_store: &domain::MerchantKeyStore, ) -> RouterResult<domain::Profile> { match self.profile_id.or(merchant_account.default_profile.clone()) { Some(profile_id) => { // Check whether this business profile belongs to the merchant 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") .change_context(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; Ok(business_profile) } None => match self.business_country.zip(self.business_label) { Some((business_country, business_label)) => { let profile_name = format!("{business_country}_{business_label}"); let business_profile = db .find_business_profile_by_profile_name_merchant_id( key_manager_state, key_store, &profile_name, merchant_account.get_id(), ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_name, })?; Ok(business_profile) } _ => Err(report!(errors::ApiErrorResponse::MissingRequiredField { field_name: "profile_id or business_country, business_label" })), }, } } } pub async fn create_connector( state: SessionState, req: api::MerchantConnectorCreate, merchant_account: domain::MerchantAccount, auth_profile_id: Option<id_type::ProfileId>, key_store: domain::MerchantKeyStore, ) -> RouterResponse<api_models::admin::MerchantConnectorResponse> { let store = state.store.as_ref(); let key_manager_state = &(&state).into(); #[cfg(feature = "dummy_connector")] fp_utils::when( req.connector_name .validate_dummy_connector_create(state.conf.dummy_connector.enabled), || { Err(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid connector name".to_string(), }) }, )?; let connector_metadata = ConnectorMetadata { connector_metadata: &req.metadata, }; let merchant_id = merchant_account.get_id(); connector_metadata.validate_apple_pay_certificates_in_mca_metadata()?; #[cfg(feature = "v1")] helpers::validate_business_details( req.business_country, req.business_label.as_ref(), &merchant_account, )?; let business_profile = req .clone() .validate_and_get_business_profile(&merchant_account, store, key_manager_state, &key_store) .await?; core_utils::validate_profile_id_from_auth_layer(auth_profile_id, &business_profile)?; let pm_auth_config_validation = PMAuthConfigValidation { connector_type: &req.connector_type, pm_auth_config: &req.pm_auth_config, db: store, merchant_id, profile_id: business_profile.get_id(), key_store: &key_store, key_manager_state, }; pm_auth_config_validation.validate_pm_auth_config().await?; let connector_type_and_connector_enum = ConnectorTypeAndConnectorName { connector_type: &req.connector_type, connector_name: &req.connector_name, }; let routable_connector = connector_type_and_connector_enum.get_routable_connector()?; // The purpose of this merchant account update is just to update the // merchant account `modified_at` field for KGraph cache invalidation state .store .update_specific_fields_in_merchant( key_manager_state, merchant_id, storage::MerchantAccountUpdate::ModifiedAtUpdate, &key_store, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error updating the merchant account when creating payment connector")?; let merchant_connector_account = req .clone() .create_domain_model_from_request( &state, key_store.clone(), &business_profile, key_manager_state, ) .await?; let mca = state .store .insert_merchant_connector_account( key_manager_state, merchant_connector_account.clone(), &key_store, ) .await .to_duplicate_response( errors::ApiErrorResponse::DuplicateMerchantConnectorAccount { profile_id: business_profile.get_id().get_string_repr().to_owned(), connector_label: merchant_connector_account .connector_label .unwrap_or_default(), }, )?; #[cfg(feature = "v1")] //update merchant default config let merchant_default_config_update = MerchantDefaultConfigUpdate { routable_connector: &routable_connector, merchant_connector_id: &mca.get_id(), store, merchant_id, profile_id: business_profile.get_id(), transaction_type: &req.get_transaction_type(), }; #[cfg(feature = "v2")] //update merchant default config let merchant_default_config_update = DefaultFallbackRoutingConfigUpdate { routable_connector: &routable_connector, merchant_connector_id: &mca.get_id(), store, business_profile, key_store, key_manager_state, }; merchant_default_config_update .retrieve_and_update_default_fallback_routing_algorithm_if_routable_connector_exists() .await?; metrics::MCA_CREATE.add( 1, router_env::metric_attributes!( ("connector", req.connector_name.to_string()), ("merchant", merchant_id.clone()), ), ); let mca_response = mca.foreign_try_into()?; Ok(service_api::ApplicationResponse::Json(mca_response)) } #[cfg(feature = "v1")] async fn validate_pm_auth( val: pii::SecretSerdeValue, state: &SessionState, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, merchant_account: domain::MerchantAccount, profile_id: &id_type::ProfileId, ) -> RouterResponse<()> { let config = serde_json::from_value::<api_models::pm_auth::PaymentMethodAuthConfig>(val.expose()) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "invalid data received for payment method auth config".to_string(), }) .attach_printable("Failed to deserialize Payment Method Auth config")?; let all_mcas = state .store .find_merchant_connector_account_by_merchant_id_and_disabled_list( &state.into(), merchant_id, true, key_store, ) .await .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_account.get_id().get_string_repr().to_owned(), })?; for conn_choice in config.enabled_payment_methods { let pm_auth_mca = all_mcas .iter() .find(|mca| mca.get_id() == conn_choice.mca_id) .ok_or(errors::ApiErrorResponse::GenericNotFoundError { message: "payment method auth connector account not found".to_string(), })?; if &pm_auth_mca.profile_id != profile_id { return Err(errors::ApiErrorResponse::GenericNotFoundError { message: "payment method auth profile_id differs from connector profile_id" .to_string(), } .into()); } } Ok(services::ApplicationResponse::StatusOk) } #[cfg(feature = "v1")] pub async fn retrieve_connector( state: SessionState, merchant_id: id_type::MerchantId, profile_id: Option<id_type::ProfileId>, merchant_connector_id: id_type::MerchantConnectorAccountId, ) -> RouterResponse<api_models::admin::MerchantConnectorResponse> { let store = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = store .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &store.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let _merchant_account = store .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let mca = store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, &merchant_id, &merchant_connector_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), })?; core_utils::validate_profile_id_from_auth_layer(profile_id, &mca)?; Ok(service_api::ApplicationResponse::Json( mca.foreign_try_into()?, )) } #[cfg(feature = "v2")] pub async fn retrieve_connector( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, id: id_type::MerchantConnectorAccountId, ) -> RouterResponse<api_models::admin::MerchantConnectorResponse> { let store = state.store.as_ref(); let key_manager_state = &(&state).into(); let merchant_id = merchant_account.get_id(); let mca = store .find_merchant_connector_account_by_id(key_manager_state, &id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: id.clone().get_string_repr().to_string(), })?; // Validate if the merchant_id sent in the request is valid if mca.merchant_id != *merchant_id { return Err(errors::ApiErrorResponse::InvalidRequestData { message: format!( "Invalid merchant_id {} provided for merchant_connector_account {:?}", merchant_id.get_string_repr(), id ), } .into()); } Ok(service_api::ApplicationResponse::Json( mca.foreign_try_into()?, )) } #[cfg(all(feature = "olap", feature = "v2"))] pub async fn list_connectors_for_a_profile( state: SessionState, key_store: domain::MerchantKeyStore, profile_id: id_type::ProfileId, ) -> RouterResponse<Vec<api_models::admin::MerchantConnectorListResponse>> { let store = state.store.as_ref(); let key_manager_state = &(&state).into(); let merchant_connector_accounts = store .list_connector_account_by_profile_id(key_manager_state, &profile_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; let mut response = vec![]; for mca in merchant_connector_accounts.into_iter() { response.push(mca.foreign_try_into()?); } Ok(service_api::ApplicationResponse::Json(response)) } pub async fn list_payment_connectors( state: SessionState, merchant_id: id_type::MerchantId, profile_id_list: Option<Vec<id_type::ProfileId>>, ) -> RouterResponse<Vec<api_models::admin::MerchantConnectorListResponse>> { let store = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = store .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &store.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; // Validate merchant account store .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_connector_accounts = store .find_merchant_connector_account_by_merchant_id_and_disabled_list( key_manager_state, &merchant_id, true, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; let merchant_connector_accounts = core_utils::filter_objects_based_on_profile_id_list( profile_id_list, merchant_connector_accounts, ); let mut response = vec![]; // The can be eliminated once [#79711](https://github.com/rust-lang/rust/issues/79711) is stabilized for mca in merchant_connector_accounts.into_iter() { response.push(mca.foreign_try_into()?); } Ok(service_api::ApplicationResponse::Json(response)) } pub async fn update_connector( state: SessionState, merchant_id: &id_type::MerchantId, profile_id: Option<id_type::ProfileId>, merchant_connector_id: &id_type::MerchantConnectorAccountId, req: api_models::admin::MerchantConnectorUpdate, ) -> RouterResponse<api_models::admin::MerchantConnectorResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, merchant_id, &db.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_account = db .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let mca = req .clone() .get_merchant_connector_account_from_id( db, merchant_id, merchant_connector_id, &key_store, key_manager_state, ) .await?; core_utils::validate_profile_id_from_auth_layer(profile_id, &mca)?; let payment_connector = req .clone() .create_domain_model_from_request( &state, key_store.clone(), &mca, key_manager_state, &merchant_account, ) .await?; // Profile id should always be present let profile_id = mca.profile_id.clone(); let request_connector_label = req.connector_label; let updated_mca = db .update_merchant_connector_account( key_manager_state, mca, payment_connector.into(), &key_store, ) .await .change_context( errors::ApiErrorResponse::DuplicateMerchantConnectorAccount { profile_id: profile_id.get_string_repr().to_owned(), connector_label: request_connector_label.unwrap_or_default(), }, ) .attach_printable_lazy(|| { format!( "Failed while updating MerchantConnectorAccount: id: {:?}", merchant_connector_id ) })?; let response = updated_mca.foreign_try_into()?; Ok(service_api::ApplicationResponse::Json(response)) } #[cfg(feature = "v1")] pub async fn delete_connector( state: SessionState, merchant_id: id_type::MerchantId, merchant_connector_id: id_type::MerchantConnectorAccountId, ) -> RouterResponse<api::MerchantConnectorDeleteResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &db.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let _merchant_account = db .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let mca = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, &merchant_id, &merchant_connector_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), })?; let is_deleted = db .delete_merchant_connector_account_by_merchant_id_merchant_connector_id( &merchant_id, &merchant_connector_id, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), })?; // delete the mca from the config as well let merchant_default_config_delete = MerchantDefaultConfigUpdate { routable_connector: &Some( common_enums::RoutableConnectors::from_str(&mca.connector_name).map_err(|_| { errors::ApiErrorResponse::InvalidDataValue { field_name: "connector_name", } })?, ), merchant_connector_id: &mca.get_id(), store: db, merchant_id: &merchant_id, profile_id: &mca.profile_id, transaction_type: &mca.connector_type.into(), }; merchant_default_config_delete .retrieve_and_delete_from_default_fallback_routing_algorithm_if_routable_connector_exists() .await?; let response = api::MerchantConnectorDeleteResponse { merchant_id, merchant_connector_id, deleted: is_deleted, }; Ok(service_api::ApplicationResponse::Json(response)) } #[cfg(feature = "v2")] pub async fn delete_connector( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, id: id_type::MerchantConnectorAccountId, ) -> RouterResponse<api::MerchantConnectorDeleteResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let merchant_id = merchant_account.get_id(); let mca = db .find_merchant_connector_account_by_id(key_manager_state, &id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: id.clone().get_string_repr().to_string(), })?; // Validate if the merchant_id sent in the request is valid if mca.merchant_id != *merchant_id { return Err(errors::ApiErrorResponse::InvalidRequestData { message: format!( "Invalid merchant_id {} provided for merchant_connector_account {:?}", merchant_id.get_string_repr(), id ), } .into()); } let is_deleted = db .delete_merchant_connector_account_by_id(&id) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: id.clone().get_string_repr().to_string(), })?; let business_profile = db .find_business_profile_by_profile_id(key_manager_state, &key_store, &mca.profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: mca.profile_id.get_string_repr().to_owned(), })?; let merchant_default_config_delete = DefaultFallbackRoutingConfigUpdate { routable_connector: &Some( common_enums::RoutableConnectors::from_str(&mca.connector_name.to_string()).map_err( |_| errors::ApiErrorResponse::InvalidDataValue { field_name: "connector_name", }, )?, ), merchant_connector_id: &mca.get_id(), store: db, business_profile, key_store, key_manager_state, }; merchant_default_config_delete .retrieve_and_delete_from_default_fallback_routing_algorithm_if_routable_connector_exists() .await?; let response = api::MerchantConnectorDeleteResponse { merchant_id: merchant_id.clone(), id, deleted: is_deleted, }; Ok(service_api::ApplicationResponse::Json(response)) } pub async fn kv_for_merchant( state: SessionState, merchant_id: id_type::MerchantId, enable: bool, ) -> RouterResponse<api_models::admin::ToggleKVResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &db.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; // check if the merchant account exists let merchant_account = db .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let updated_merchant_account = match (enable, merchant_account.storage_scheme) { (true, MerchantStorageScheme::RedisKv) | (false, MerchantStorageScheme::PostgresOnly) => { Ok(merchant_account) } (true, MerchantStorageScheme::PostgresOnly) => { if state.conf.as_ref().is_kv_soft_kill_mode() { Err(errors::ApiErrorResponse::InvalidRequestData { message: "Kv cannot be enabled when application is in soft_kill_mode" .to_owned(), })? } db.update_merchant( key_manager_state, merchant_account, storage::MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme: MerchantStorageScheme::RedisKv, }, &key_store, ) .await } (false, MerchantStorageScheme::RedisKv) => { db.update_merchant( key_manager_state, merchant_account, storage::MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme: MerchantStorageScheme::PostgresOnly, }, &key_store, ) .await } } .map_err(|error| { error .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to switch merchant_storage_scheme") })?; let kv_status = matches!( updated_merchant_account.storage_scheme, MerchantStorageScheme::RedisKv ); Ok(service_api::ApplicationResponse::Json( api_models::admin::ToggleKVResponse { merchant_id: updated_merchant_account.get_id().to_owned(), kv_enabled: kv_status, }, )) } pub async fn toggle_kv_for_all_merchants( state: SessionState, enable: bool, ) -> RouterResponse<api_models::admin::ToggleAllKVResponse> { let db = state.store.as_ref(); let storage_scheme = if enable { MerchantStorageScheme::RedisKv } else { MerchantStorageScheme::PostgresOnly }; let total_update = db .update_all_merchant_account(storage::MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme, }) .await .map_err(|error| { error .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to switch merchant_storage_scheme for all merchants") })?; Ok(service_api::ApplicationResponse::Json( api_models::admin::ToggleAllKVResponse { total_updated: total_update, kv_enabled: enable, }, )) } pub async fn check_merchant_account_kv_status( state: SessionState, merchant_id: id_type::MerchantId, ) -> RouterResponse<api_models::admin::ToggleKVResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &db.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; // check if the merchant account exists let merchant_account = db .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let kv_status = matches!( merchant_account.storage_scheme, MerchantStorageScheme::RedisKv ); Ok(service_api::ApplicationResponse::Json( api_models::admin::ToggleKVResponse { merchant_id: merchant_account.get_id().to_owned(), kv_enabled: kv_status, }, )) } pub fn get_frm_config_as_secret( frm_configs: Option<Vec<api_models::admin::FrmConfigs>>, ) -> Option<Vec<Secret<serde_json::Value>>> { match frm_configs.as_ref() { Some(frm_value) => { let configs_for_frm_value: Vec<Secret<serde_json::Value>> = frm_value .iter() .map(|config| { config .encode_to_value() .change_context(errors::ApiErrorResponse::ConfigNotFound) .map(Secret::new) }) .collect::<Result<Vec<_>, _>>() .ok()?; Some(configs_for_frm_value) } None => None, } } #[cfg(feature = "v1")] pub async fn create_and_insert_business_profile( state: &SessionState, request: api::ProfileCreate, merchant_account: domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> RouterResult<domain::Profile> { let business_profile_new = admin::create_profile_from_merchant_account(state, merchant_account, request, key_store) .await?; let profile_name = business_profile_new.profile_name.clone(); state .store .insert_business_profile(&state.into(), key_store, business_profile_new) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: format!( "Business Profile with the profile_name {profile_name} already exists" ), }) .attach_printable("Failed to insert Business profile because of duplication error") } #[cfg(feature = "olap")] #[async_trait::async_trait] trait ProfileCreateBridge { #[cfg(feature = "v1")] async fn create_domain_model_from_request( self, state: &SessionState, merchant_account: &domain::MerchantAccount, key: &domain::MerchantKeyStore, ) -> RouterResult<domain::Profile>; #[cfg(feature = "v2")] async fn create_domain_model_from_request( self, state: &SessionState, key: &domain::MerchantKeyStore, merchant_id: &id_type::MerchantId, ) -> RouterResult<domain::Profile>; } #[cfg(feature = "olap")] #[async_trait::async_trait] impl ProfileCreateBridge for api::ProfileCreate { #[cfg(feature = "v1")] async fn create_domain_model_from_request( self, state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> RouterResult<domain::Profile> { use common_utils::ext_traits::AsyncExt; if let Some(session_expiry) = &self.session_expiry { helpers::validate_session_expiry(session_expiry.to_owned())?; } if let Some(intent_fulfillment_expiry) = self.intent_fulfillment_time { helpers::validate_intent_fulfillment_expiry(intent_fulfillment_expiry)?; } if let Some(ref routing_algorithm) = self.routing_algorithm { let _: api_models::routing::RoutingAlgorithm = routing_algorithm .clone() .parse_value("RoutingAlgorithm") .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "routing_algorithm", }) .attach_printable("Invalid routing algorithm given")?; } // Generate a unique profile id let profile_id = common_utils::generate_profile_id_of_default_length(); let profile_name = self.profile_name.unwrap_or("default".to_string()); let current_time = date_time::now(); let webhook_details = self.webhook_details.map(ForeignInto::foreign_into); let payment_response_hash_key = self .payment_response_hash_key .or(merchant_account.payment_response_hash_key.clone()) .unwrap_or(common_utils::crypto::generate_cryptographically_secure_random_string(64)); let payment_link_config = self.payment_link_config.map(ForeignInto::foreign_into); let key_manager_state = state.into(); let outgoing_webhook_custom_http_headers = self .outgoing_webhook_custom_http_headers .async_map(|headers| { cards::create_encrypted_data(&key_manager_state, key_store, headers) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt outgoing webhook custom HTTP headers")?; let payout_link_config = self .payout_link_config .map(|payout_conf| match payout_conf.config.validate() { Ok(_) => Ok(payout_conf.foreign_into()), Err(e) => Err(error_stack::report!( errors::ApiErrorResponse::InvalidRequestData { message: e.to_string() } )), }) .transpose()?; let key = key_store.key.clone().into_inner(); let key_manager_state = state.into(); let card_testing_secret_key = Some(Secret::new(utils::generate_id( consts::FINGERPRINT_SECRET_LENGTH, "fs", ))); let card_testing_guard_config = match self.card_testing_guard_config { Some(card_testing_guard_config) => Some(CardTestingGuardConfig::foreign_from( card_testing_guard_config, )), None => Some(CardTestingGuardConfig { is_card_ip_blocking_enabled: common_utils::consts::DEFAULT_CARD_IP_BLOCKING_STATUS, card_ip_blocking_threshold: common_utils::consts::DEFAULT_CARD_IP_BLOCKING_THRESHOLD, is_guest_user_card_blocking_enabled: common_utils::consts::DEFAULT_GUEST_USER_CARD_BLOCKING_STATUS, guest_user_card_blocking_threshold: common_utils::consts::DEFAULT_GUEST_USER_CARD_BLOCKING_THRESHOLD, is_customer_id_blocking_enabled: common_utils::consts::DEFAULT_CUSTOMER_ID_BLOCKING_STATUS, customer_id_blocking_threshold: common_utils::consts::DEFAULT_CUSTOMER_ID_BLOCKING_THRESHOLD, card_testing_guard_expiry: common_utils::consts::DEFAULT_CARD_TESTING_GUARD_EXPIRY_IN_SECS, }), }; Ok(domain::Profile::from(domain::ProfileSetter { profile_id, merchant_id: merchant_account.get_id().clone(), profile_name, created_at: current_time, modified_at: current_time, return_url: self .return_url .map(|return_url| return_url.to_string()) .or(merchant_account.return_url.clone()), enable_payment_response_hash: self .enable_payment_response_hash .unwrap_or(merchant_account.enable_payment_response_hash), payment_response_hash_key: Some(payment_response_hash_key), redirect_to_merchant_with_http_post: self .redirect_to_merchant_with_http_post .unwrap_or(merchant_account.redirect_to_merchant_with_http_post), webhook_details: webhook_details.or(merchant_account.webhook_details.clone()), metadata: self.metadata, routing_algorithm: None, intent_fulfillment_time: self .intent_fulfillment_time .map(i64::from) .or(merchant_account.intent_fulfillment_time) .or(Some(common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME)), frm_routing_algorithm: self .frm_routing_algorithm .or(merchant_account.frm_routing_algorithm.clone()), #[cfg(feature = "payouts")] payout_routing_algorithm: self .payout_routing_algorithm .or(merchant_account.payout_routing_algorithm.clone()), #[cfg(not(feature = "payouts"))] payout_routing_algorithm: None, is_recon_enabled: merchant_account.is_recon_enabled, applepay_verified_domains: self.applepay_verified_domains, payment_link_config, session_expiry: self .session_expiry .map(i64::from) .or(Some(common_utils::consts::DEFAULT_SESSION_EXPIRY)), authentication_connector_details: self .authentication_connector_details .map(ForeignInto::foreign_into), payout_link_config, is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled, is_extended_card_info_enabled: None, extended_card_info_config: None, use_billing_as_payment_method_billing: self .use_billing_as_payment_method_billing .or(Some(true)), collect_shipping_details_from_wallet_connector: self .collect_shipping_details_from_wallet_connector .or(Some(false)), collect_billing_details_from_wallet_connector: self .collect_billing_details_from_wallet_connector .or(Some(false)), outgoing_webhook_custom_http_headers, tax_connector_id: self.tax_connector_id, is_tax_connector_enabled: self.is_tax_connector_enabled, always_collect_billing_details_from_wallet_connector: self .always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector: self .always_collect_shipping_details_from_wallet_connector, dynamic_routing_algorithm: None, is_network_tokenization_enabled: self.is_network_tokenization_enabled, is_auto_retries_enabled: self.is_auto_retries_enabled.unwrap_or_default(), max_auto_retries_enabled: self.max_auto_retries_enabled.map(i16::from), always_request_extended_authorization: self.always_request_extended_authorization, is_click_to_pay_enabled: self.is_click_to_pay_enabled, authentication_product_ids: self.authentication_product_ids, card_testing_guard_config, card_testing_secret_key: card_testing_secret_key .async_lift(|inner| async { domain_types::crypto_operation( &key_manager_state, common_utils::type_name!(domain::Profile), domain_types::CryptoOperation::EncryptOptional(inner), km_types::Identifier::Merchant(key_store.merchant_id.clone()), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error while generating card testing secret key")?, is_clear_pan_retries_enabled: self.is_clear_pan_retries_enabled.unwrap_or_default(), force_3ds_challenge: self.force_3ds_challenge.unwrap_or_default(), is_debit_routing_enabled: self.is_debit_routing_enabled.unwrap_or_default(), merchant_business_country: self.merchant_business_country, })) } #[cfg(feature = "v2")] async fn create_domain_model_from_request( self, state: &SessionState, key_store: &domain::MerchantKeyStore, merchant_id: &id_type::MerchantId, ) -> RouterResult<domain::Profile> { if let Some(session_expiry) = &self.session_expiry { helpers::validate_session_expiry(session_expiry.to_owned())?; } // Generate a unique profile id // TODO: the profile_id should be generated from the profile_name let profile_id = common_utils::generate_profile_id_of_default_length(); let profile_name = self.profile_name; let current_time = date_time::now(); let webhook_details = self.webhook_details.map(ForeignInto::foreign_into); let payment_response_hash_key = self .payment_response_hash_key .unwrap_or(common_utils::crypto::generate_cryptographically_secure_random_string(64)); let payment_link_config = self.payment_link_config.map(ForeignInto::foreign_into); let key_manager_state = state.into(); let outgoing_webhook_custom_http_headers = self .outgoing_webhook_custom_http_headers .async_map(|headers| { cards::create_encrypted_data(&key_manager_state, key_store, headers) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt outgoing webhook custom HTTP headers")?; let payout_link_config = self .payout_link_config .map(|payout_conf| match payout_conf.config.validate() { Ok(_) => Ok(payout_conf.foreign_into()), Err(e) => Err(error_stack::report!( errors::ApiErrorResponse::InvalidRequestData { message: e.to_string() } )), }) .transpose()?; let key = key_store.key.clone().into_inner(); let key_manager_state = state.into(); let card_testing_secret_key = Some(Secret::new(utils::generate_id( consts::FINGERPRINT_SECRET_LENGTH, "fs", ))); let card_testing_guard_config = match self.card_testing_guard_config { Some(card_testing_guard_config) => Some(CardTestingGuardConfig::foreign_from( card_testing_guard_config, )), None => Some(CardTestingGuardConfig { is_card_ip_blocking_enabled: common_utils::consts::DEFAULT_CARD_IP_BLOCKING_STATUS, card_ip_blocking_threshold: common_utils::consts::DEFAULT_CARD_IP_BLOCKING_THRESHOLD, is_guest_user_card_blocking_enabled: common_utils::consts::DEFAULT_GUEST_USER_CARD_BLOCKING_STATUS, guest_user_card_blocking_threshold: common_utils::consts::DEFAULT_GUEST_USER_CARD_BLOCKING_THRESHOLD, is_customer_id_blocking_enabled: common_utils::consts::DEFAULT_CUSTOMER_ID_BLOCKING_STATUS, customer_id_blocking_threshold: common_utils::consts::DEFAULT_CUSTOMER_ID_BLOCKING_THRESHOLD, card_testing_guard_expiry: common_utils::consts::DEFAULT_CARD_TESTING_GUARD_EXPIRY_IN_SECS, }), }; Ok(domain::Profile::from(domain::ProfileSetter { id: profile_id, merchant_id: merchant_id.clone(), profile_name, created_at: current_time, modified_at: current_time, return_url: self.return_url, enable_payment_response_hash: self.enable_payment_response_hash.unwrap_or(true), payment_response_hash_key: Some(payment_response_hash_key), redirect_to_merchant_with_http_post: self .redirect_to_merchant_with_http_post .unwrap_or(true), webhook_details, metadata: self.metadata, is_recon_enabled: false, applepay_verified_domains: self.applepay_verified_domains, payment_link_config, session_expiry: self .session_expiry .map(i64::from) .or(Some(common_utils::consts::DEFAULT_SESSION_EXPIRY)), authentication_connector_details: self .authentication_connector_details .map(ForeignInto::foreign_into), payout_link_config, is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled, is_extended_card_info_enabled: None, extended_card_info_config: None, use_billing_as_payment_method_billing: self .use_billing_as_payment_method_billing .or(Some(true)), collect_shipping_details_from_wallet_connector: self .collect_shipping_details_from_wallet_connector_if_required .or(Some(false)), collect_billing_details_from_wallet_connector: self .collect_billing_details_from_wallet_connector_if_required .or(Some(false)), outgoing_webhook_custom_http_headers, always_collect_billing_details_from_wallet_connector: self .always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector: self .always_collect_shipping_details_from_wallet_connector, routing_algorithm_id: None, frm_routing_algorithm_id: None, payout_routing_algorithm_id: None, order_fulfillment_time: self .order_fulfillment_time .map(|order_fulfillment_time| order_fulfillment_time.into_inner()) .or(Some(common_utils::consts::DEFAULT_ORDER_FULFILLMENT_TIME)), order_fulfillment_time_origin: self.order_fulfillment_time_origin, default_fallback_routing: None, should_collect_cvv_during_payment: None, tax_connector_id: self.tax_connector_id, is_tax_connector_enabled: self.is_tax_connector_enabled, is_network_tokenization_enabled: self.is_network_tokenization_enabled, is_click_to_pay_enabled: self.is_click_to_pay_enabled, authentication_product_ids: self.authentication_product_ids, three_ds_decision_manager_config: None, card_testing_guard_config, card_testing_secret_key: card_testing_secret_key .async_lift(|inner| async { domain_types::crypto_operation( &key_manager_state, common_utils::type_name!(domain::Profile), domain_types::CryptoOperation::EncryptOptional(inner), km_types::Identifier::Merchant(key_store.merchant_id.clone()), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error while generating card testing secret key")?, is_clear_pan_retries_enabled: self.is_clear_pan_retries_enabled.unwrap_or_default(), is_debit_routing_enabled: self.is_debit_routing_enabled.unwrap_or_default(), merchant_business_country: self.merchant_business_country, })) } } #[cfg(feature = "olap")] pub async fn create_profile( state: SessionState, request: api::ProfileCreate, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, ) -> RouterResponse<api_models::admin::ProfileResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); #[cfg(feature = "v1")] let business_profile = request .create_domain_model_from_request(&state, &merchant_account, &key_store) .await?; #[cfg(feature = "v2")] let business_profile = request .create_domain_model_from_request(&state, &key_store, merchant_account.get_id()) .await?; let profile_id = business_profile.get_id().to_owned(); let business_profile = db .insert_business_profile(key_manager_state, &key_store, business_profile) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: format!( "Business Profile with the profile_id {} already exists", profile_id.get_string_repr() ), }) .attach_printable("Failed to insert Business profile because of duplication error")?; #[cfg(feature = "v1")] if merchant_account.default_profile.is_some() { let unset_default_profile = domain::MerchantAccountUpdate::UnsetDefaultProfile; db.update_merchant( key_manager_state, merchant_account, unset_default_profile, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; } Ok(service_api::ApplicationResponse::Json( api_models::admin::ProfileResponse::foreign_try_from(business_profile) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse business profile details")?, )) } #[cfg(feature = "olap")] pub async fn list_profile( state: SessionState, merchant_id: id_type::MerchantId, profile_id_list: Option<Vec<id_type::ProfileId>>, ) -> RouterResponse<Vec<api_models::admin::ProfileResponse>> { let db = state.store.as_ref(); let key_store = db .get_merchant_key_store_by_merchant_id( &(&state).into(), &merchant_id, &db.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let profiles = db .list_profile_by_merchant_id(&(&state).into(), &key_store, &merchant_id) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)? .clone(); let profiles = core_utils::filter_objects_based_on_profile_id_list(profile_id_list, profiles); let mut business_profiles = Vec::new(); for profile in profiles { let business_profile = api_models::admin::ProfileResponse::foreign_try_from(profile) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse business profile details")?; business_profiles.push(business_profile); } Ok(service_api::ApplicationResponse::Json(business_profiles)) } pub async fn retrieve_profile( state: SessionState, profile_id: id_type::ProfileId, key_store: domain::MerchantKeyStore, ) -> RouterResponse<api_models::admin::ProfileResponse> { let db = state.store.as_ref(); let business_profile = db .find_business_profile_by_profile_id(&(&state).into(), &key_store, &profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; Ok(service_api::ApplicationResponse::Json( api_models::admin::ProfileResponse::foreign_try_from(business_profile) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse business profile details")?, )) } pub async fn delete_profile( state: SessionState, profile_id: id_type::ProfileId, merchant_id: &id_type::MerchantId, ) -> RouterResponse<bool> { let db = state.store.as_ref(); let delete_result = db .delete_profile_by_profile_id_merchant_id(&profile_id, merchant_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; Ok(service_api::ApplicationResponse::Json(delete_result)) } #[cfg(feature = "olap")] #[async_trait::async_trait] trait ProfileUpdateBridge { async fn get_update_profile_object( self, state: &SessionState, key_store: &domain::MerchantKeyStore, business_profile: &domain::Profile, ) -> RouterResult<domain::ProfileUpdate>; } #[cfg(all(feature = "olap", feature = "v1"))] #[async_trait::async_trait] impl ProfileUpdateBridge for api::ProfileUpdate { async fn get_update_profile_object( self, state: &SessionState, key_store: &domain::MerchantKeyStore, business_profile: &domain::Profile, ) -> RouterResult<domain::ProfileUpdate> { if let Some(session_expiry) = &self.session_expiry { helpers::validate_session_expiry(session_expiry.to_owned())?; } if let Some(intent_fulfillment_expiry) = self.intent_fulfillment_time { helpers::validate_intent_fulfillment_expiry(intent_fulfillment_expiry)?; } let webhook_details = self.webhook_details.map(ForeignInto::foreign_into); if let Some(ref routing_algorithm) = self.routing_algorithm { let _: api_models::routing::RoutingAlgorithm = routing_algorithm .clone() .parse_value("RoutingAlgorithm") .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "routing_algorithm", }) .attach_printable("Invalid routing algorithm given")?; } let payment_link_config = self .payment_link_config .map(|payment_link_conf| match payment_link_conf.validate() { Ok(_) => Ok(payment_link_conf.foreign_into()), Err(e) => Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: e.to_string() })), }) .transpose()?; let extended_card_info_config = self .extended_card_info_config .as_ref() .map(|config| { config.encode_to_value().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "extended_card_info_config", }, ) }) .transpose()? .map(Secret::new); let key_manager_state = state.into(); let outgoing_webhook_custom_http_headers = self .outgoing_webhook_custom_http_headers .async_map(|headers| { cards::create_encrypted_data(&key_manager_state, key_store, headers) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt outgoing webhook custom HTTP headers")?; let payout_link_config = self .payout_link_config .map(|payout_conf| match payout_conf.config.validate() { Ok(_) => Ok(payout_conf.foreign_into()), Err(e) => Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: e.to_string() })), }) .transpose()?; let key = key_store.key.clone().into_inner(); let key_manager_state = state.into(); let card_testing_secret_key = match business_profile.card_testing_secret_key { Some(_) => None, None => { let card_testing_secret_key = Some(Secret::new(utils::generate_id( consts::FINGERPRINT_SECRET_LENGTH, "fs", ))); card_testing_secret_key .async_lift(|inner| async { domain_types::crypto_operation( &key_manager_state, common_utils::type_name!(domain::Profile), domain_types::CryptoOperation::EncryptOptional(inner), km_types::Identifier::Merchant(key_store.merchant_id.clone()), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error while generating card testing secret key")? } }; Ok(domain::ProfileUpdate::Update(Box::new( domain::ProfileGeneralUpdate { profile_name: self.profile_name, return_url: self.return_url.map(|return_url| return_url.to_string()), enable_payment_response_hash: self.enable_payment_response_hash, payment_response_hash_key: self.payment_response_hash_key, redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post, webhook_details, metadata: self.metadata, routing_algorithm: self.routing_algorithm, intent_fulfillment_time: self.intent_fulfillment_time.map(i64::from), frm_routing_algorithm: self.frm_routing_algorithm, #[cfg(feature = "payouts")] payout_routing_algorithm: self.payout_routing_algorithm, #[cfg(not(feature = "payouts"))] payout_routing_algorithm: None, applepay_verified_domains: self.applepay_verified_domains, payment_link_config, session_expiry: self.session_expiry.map(i64::from), authentication_connector_details: self .authentication_connector_details .map(ForeignInto::foreign_into), payout_link_config, extended_card_info_config, use_billing_as_payment_method_billing: self.use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector: self .collect_shipping_details_from_wallet_connector, collect_billing_details_from_wallet_connector: self .collect_billing_details_from_wallet_connector, is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled, outgoing_webhook_custom_http_headers, always_collect_billing_details_from_wallet_connector: self .always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector: self .always_collect_shipping_details_from_wallet_connector, tax_connector_id: self.tax_connector_id, is_tax_connector_enabled: self.is_tax_connector_enabled, dynamic_routing_algorithm: self.dynamic_routing_algorithm, is_network_tokenization_enabled: self.is_network_tokenization_enabled, is_auto_retries_enabled: self.is_auto_retries_enabled, max_auto_retries_enabled: self.max_auto_retries_enabled.map(i16::from), is_click_to_pay_enabled: self.is_click_to_pay_enabled, authentication_product_ids: self.authentication_product_ids, card_testing_guard_config: self .card_testing_guard_config .map(ForeignInto::foreign_into), card_testing_secret_key, is_clear_pan_retries_enabled: self.is_clear_pan_retries_enabled, force_3ds_challenge: self.force_3ds_challenge, // is_debit_routing_enabled: self.is_debit_routing_enabled.unwrap_or_default(), merchant_business_country: self.merchant_business_country, }, ))) } } #[cfg(all(feature = "olap", feature = "v2"))] #[async_trait::async_trait] impl ProfileUpdateBridge for api::ProfileUpdate { async fn get_update_profile_object( self, state: &SessionState, key_store: &domain::MerchantKeyStore, business_profile: &domain::Profile, ) -> RouterResult<domain::ProfileUpdate> { if let Some(session_expiry) = &self.session_expiry { helpers::validate_session_expiry(session_expiry.to_owned())?; } let webhook_details = self.webhook_details.map(ForeignInto::foreign_into); let payment_link_config = self .payment_link_config .map(|payment_link_conf| match payment_link_conf.validate() { Ok(_) => Ok(payment_link_conf.foreign_into()), Err(e) => Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: e.to_string() })), }) .transpose()?; let extended_card_info_config = self .extended_card_info_config .as_ref() .map(|config| { config.encode_to_value().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "extended_card_info_config", }, ) }) .transpose()? .map(Secret::new); let key_manager_state = state.into(); let outgoing_webhook_custom_http_headers = self .outgoing_webhook_custom_http_headers .async_map(|headers| { cards::create_encrypted_data(&key_manager_state, key_store, headers) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt outgoing webhook custom HTTP headers")?; let payout_link_config = self .payout_link_config .map(|payout_conf| match payout_conf.config.validate() { Ok(_) => Ok(payout_conf.foreign_into()), Err(e) => Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: e.to_string() })), }) .transpose()?; let key = key_store.key.clone().into_inner(); let key_manager_state = state.into(); let card_testing_secret_key = match business_profile.card_testing_secret_key { Some(_) => None, None => { let card_testing_secret_key = Some(Secret::new(utils::generate_id( consts::FINGERPRINT_SECRET_LENGTH, "fs", ))); card_testing_secret_key .async_lift(|inner| async { domain_types::crypto_operation( &key_manager_state, common_utils::type_name!(domain::Profile), domain_types::CryptoOperation::EncryptOptional(inner), km_types::Identifier::Merchant(key_store.merchant_id.clone()), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error while generating card testing secret key")? } }; Ok(domain::ProfileUpdate::Update(Box::new( domain::ProfileGeneralUpdate { profile_name: self.profile_name, return_url: self.return_url, enable_payment_response_hash: self.enable_payment_response_hash, payment_response_hash_key: self.payment_response_hash_key, redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post, webhook_details, metadata: self.metadata, applepay_verified_domains: self.applepay_verified_domains, payment_link_config, session_expiry: self.session_expiry.map(i64::from), authentication_connector_details: self .authentication_connector_details .map(ForeignInto::foreign_into), payout_link_config, extended_card_info_config, use_billing_as_payment_method_billing: self.use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector: self .collect_shipping_details_from_wallet_connector_if_required, collect_billing_details_from_wallet_connector: self .collect_billing_details_from_wallet_connector_if_required, is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled, outgoing_webhook_custom_http_headers, order_fulfillment_time: self .order_fulfillment_time .map(|order_fulfillment_time| order_fulfillment_time.into_inner()), order_fulfillment_time_origin: self.order_fulfillment_time_origin, always_collect_billing_details_from_wallet_connector: self .always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector: self .always_collect_shipping_details_from_wallet_connector, is_network_tokenization_enabled: self.is_network_tokenization_enabled, is_click_to_pay_enabled: self.is_click_to_pay_enabled, authentication_product_ids: self.authentication_product_ids, three_ds_decision_manager_config: None, card_testing_guard_config: self .card_testing_guard_config .map(ForeignInto::foreign_into), card_testing_secret_key, is_debit_routing_enabled: self.is_debit_routing_enabled.unwrap_or_default(), merchant_business_country: self.merchant_business_country, }, ))) } } #[cfg(feature = "olap")] pub async fn update_profile( state: SessionState, profile_id: &id_type::ProfileId, key_store: domain::MerchantKeyStore, request: api::ProfileUpdate, ) -> RouterResponse<api::ProfileResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let business_profile = db .find_business_profile_by_profile_id(key_manager_state, &key_store, profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let profile_update = request .get_update_profile_object(&state, &key_store, &business_profile) .await?; let updated_business_profile = db .update_profile_by_profile_id( key_manager_state, &key_store, business_profile, profile_update, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; Ok(service_api::ApplicationResponse::Json( api_models::admin::ProfileResponse::foreign_try_from(updated_business_profile) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse business profile details")?, )) } #[cfg(feature = "v2")] #[derive(Clone, Debug)] pub struct ProfileWrapper { pub profile: domain::Profile, } #[cfg(feature = "v2")] impl ProfileWrapper { pub fn new(profile: domain::Profile) -> Self { Self { profile } } fn get_routing_config_cache_key(self) -> storage_impl::redis::cache::CacheKind<'static> { let merchant_id = self.profile.merchant_id.clone(); let profile_id = self.profile.get_id().to_owned(); storage_impl::redis::cache::CacheKind::Routing( format!( "routing_config_{}_{}", merchant_id.get_string_repr(), profile_id.get_string_repr() ) .into(), ) } pub async fn update_profile_and_invalidate_routing_config_for_active_algorithm_id_update( self, db: &dyn StorageInterface, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, algorithm_id: id_type::RoutingId, transaction_type: &storage::enums::TransactionType, ) -> RouterResult<()> { let routing_cache_key = self.clone().get_routing_config_cache_key(); let (routing_algorithm_id, payout_routing_algorithm_id) = match transaction_type { storage::enums::TransactionType::Payment => (Some(algorithm_id), None), #[cfg(feature = "payouts")] storage::enums::TransactionType::Payout => (None, Some(algorithm_id)), }; let profile_update = domain::ProfileUpdate::RoutingAlgorithmUpdate { routing_algorithm_id, payout_routing_algorithm_id, }; let profile = self.profile; db.update_profile_by_profile_id( key_manager_state, merchant_key_store, profile, profile_update, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update routing algorithm ref in business profile")?; storage_impl::redis::cache::redact_from_redis_and_publish( db.get_cache_store().as_ref(), [routing_cache_key], ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to invalidate routing cache")?; Ok(()) } pub fn get_routing_algorithm_id<'a>( &'a self, transaction_data: &'a routing::TransactionData<'_>, ) -> Option<id_type::RoutingId> { match transaction_data { routing::TransactionData::Payment(_) => self.profile.routing_algorithm_id.clone(), #[cfg(feature = "payouts")] routing::TransactionData::Payout(_) => self.profile.payout_routing_algorithm_id.clone(), } } pub fn get_default_fallback_list_of_connector_under_profile( &self, ) -> RouterResult<Vec<routing_types::RoutableConnectorChoice>> { let fallback_connectors = if let Some(default_fallback_routing) = self.profile.default_fallback_routing.clone() { default_fallback_routing .expose() .parse_value::<Vec<routing_types::RoutableConnectorChoice>>( "Vec<RoutableConnectorChoice>", ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Business Profile default config has invalid structure")? } else { Vec::new() }; Ok(fallback_connectors) } pub fn get_default_routing_configs_from_profile( &self, ) -> RouterResult<routing_types::ProfileDefaultRoutingConfig> { let profile_id = self.profile.get_id().to_owned(); let connectors = self.get_default_fallback_list_of_connector_under_profile()?; Ok(routing_types::ProfileDefaultRoutingConfig { profile_id, connectors, }) } pub async fn update_default_fallback_routing_of_connectors_under_profile( self, db: &dyn StorageInterface, updated_config: &Vec<routing_types::RoutableConnectorChoice>, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, ) -> RouterResult<()> { let default_fallback_routing = Secret::from( updated_config .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to convert routing ref to value")?, ); let profile_update = domain::ProfileUpdate::DefaultRoutingFallbackUpdate { default_fallback_routing: Some(default_fallback_routing), }; db.update_profile_by_profile_id( key_manager_state, merchant_key_store, self.profile, profile_update, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update routing algorithm ref in business profile")?; Ok(()) } } pub async fn extended_card_info_toggle( state: SessionState, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, ext_card_info_choice: admin_types::ExtendedCardInfoChoice, ) -> RouterResponse<admin_types::ExtendedCardInfoChoice> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) .attach_printable("Error while fetching the key store by merchant_id")?; let business_profile = db .find_business_profile_by_profile_id(key_manager_state, &key_store, profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; if business_profile.is_extended_card_info_enabled.is_none() || business_profile .is_extended_card_info_enabled .is_some_and(|existing_config| existing_config != ext_card_info_choice.enabled) { let profile_update = domain::ProfileUpdate::ExtendedCardInfoUpdate { is_extended_card_info_enabled: ext_card_info_choice.enabled, }; db.update_profile_by_profile_id( key_manager_state, &key_store, business_profile, profile_update, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; } Ok(service_api::ApplicationResponse::Json(ext_card_info_choice)) } pub async fn connector_agnostic_mit_toggle( state: SessionState, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, connector_agnostic_mit_choice: admin_types::ConnectorAgnosticMitChoice, ) -> RouterResponse<admin_types::ConnectorAgnosticMitChoice> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) .attach_printable("Error while fetching the key store by merchant_id")?; let business_profile = db .find_business_profile_by_profile_id(key_manager_state, &key_store, profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; if business_profile.merchant_id != *merchant_id { Err(errors::ApiErrorResponse::AccessForbidden { resource: profile_id.get_string_repr().to_owned(), })? } if business_profile.is_connector_agnostic_mit_enabled != Some(connector_agnostic_mit_choice.enabled) { let profile_update = domain::ProfileUpdate::ConnectorAgnosticMitUpdate { is_connector_agnostic_mit_enabled: connector_agnostic_mit_choice.enabled, }; db.update_profile_by_profile_id( key_manager_state, &key_store, business_profile, profile_update, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; } Ok(service_api::ApplicationResponse::Json( connector_agnostic_mit_choice, )) } 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, }, )) } 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) } 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(()) } } } 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) } 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) } pub async fn enable_platform_account( state: SessionState, merchant_id: id_type::MerchantId, ) -> RouterResponse<()> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &db.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_account = db .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; db.update_merchant( key_manager_state, merchant_account, storage::MerchantAccountUpdate::ToPlatformAccount, &key_store, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while enabling platform merchant account") .map(|_| services::ApplicationResponse::StatusOk) }
38,683
1,575
hyperswitch
crates/router/src/core/payouts.rs
.rs
pub mod access_token; pub mod helpers; #[cfg(feature = "payout_retry")] pub mod retry; pub mod transformers; pub mod validator; use std::{ collections::{HashMap, HashSet}, vec::IntoIter, }; #[cfg(feature = "olap")] use api_models::payments as payment_enums; use api_models::{self, enums as api_enums, payouts::PayoutLinkResponse}; #[cfg(feature = "payout_retry")] use common_enums::PayoutRetryType; use common_utils::{ consts, ext_traits::{AsyncExt, ValueExt}, id_type::CustomerId, link_utils::{GenericLinkStatus, GenericLinkUiConfig, PayoutLinkData, PayoutLinkStatus}, types::{MinorUnit, UnifiedCode, UnifiedMessage}, }; use diesel_models::{ enums as storage_enums, generic_link::{GenericLinkNew, PayoutLink}, CommonMandateReference, PayoutsMandateReference, PayoutsMandateReferenceRecord, }; use error_stack::{report, ResultExt}; #[cfg(feature = "olap")] use futures::future::join_all; use hyperswitch_domain_models::payment_methods::PaymentMethod; use masking::{PeekInterface, Secret}; #[cfg(feature = "payout_retry")] use retry::GsmValidation; use router_env::{instrument, logger, tracing, Env}; use scheduler::utils as pt_utils; use serde_json; use time::Duration; #[cfg(feature = "olap")] use crate::types::domain::behaviour::Conversion; #[cfg(feature = "olap")] use crate::types::PayoutActionData; 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}, }; // ********************************************** TYPES ********************************************** #[derive(Clone)] 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>, } // ********************************************** CORE FLOWS ********************************************** 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") } #[cfg(all(feature = "payouts", feature = "v1"))] 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 } } } #[instrument(skip_all)] 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() })?, } } #[cfg(feature = "v1")] #[instrument(skip_all)] 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 } #[cfg(feature = "v2")] #[instrument(skip_all)] 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<()> { todo!() } #[instrument(skip_all)] pub async fn payouts_create_core( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: payouts::PayoutCreateRequest, ) -> RouterResponse<payouts::PayoutCreateResponse> { // Validate create request let (payout_id, payout_method_data, profile_id, customer, payment_method) = validator::validate_create_request(&state, &merchant_account, &req, &key_store).await?; // Create DB entries let mut payout_data = payout_create_db_entries( &state, &merchant_account, &key_store, &req, &payout_id, &profile_id, payout_method_data.as_ref(), &state.locale, customer.as_ref(), payment_method.clone(), ) .await?; let payout_attempt = payout_data.payout_attempt.to_owned(); let payout_type = payout_data.payouts.payout_type.to_owned(); // Persist payout method data in temp locker if req.payout_method_data.is_some() { let customer_id = payout_data .payouts .customer_id .clone() .get_required_value("customer_id when payout_method_data is provided")?; payout_data.payout_method_data = helpers::make_payout_method_data( &state, req.payout_method_data.as_ref(), payout_attempt.payout_token.as_deref(), &customer_id, &payout_attempt.merchant_id, payout_type, &key_store, Some(&mut payout_data), merchant_account.storage_scheme, ) .await?; } if let Some(true) = payout_data.payouts.confirm { payouts_core( &state, &merchant_account, &key_store, &mut payout_data, req.routing.clone(), req.connector.clone(), ) .await? }; response_handler(&state, &merchant_account, &payout_data).await } #[instrument(skip_all)] pub async fn payouts_confirm_core( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: payouts::PayoutCreateRequest, ) -> RouterResponse<payouts::PayoutCreateResponse> { let mut payout_data = make_payout_data( &state, &merchant_account, None, &key_store, &payouts::PayoutRequest::PayoutCreateRequest(Box::new(req.to_owned())), &state.locale, ) .await?; let payout_attempt = payout_data.payout_attempt.to_owned(); let status = payout_attempt.status; helpers::validate_payout_status_against_not_allowed_statuses( status, &[ storage_enums::PayoutStatus::Cancelled, storage_enums::PayoutStatus::Success, storage_enums::PayoutStatus::Failed, storage_enums::PayoutStatus::Pending, storage_enums::PayoutStatus::Ineligible, storage_enums::PayoutStatus::RequiresFulfillment, storage_enums::PayoutStatus::RequiresVendorAccountCreation, ], "confirm", )?; helpers::update_payouts_and_payout_attempt( &mut payout_data, &merchant_account, &req, &state, &key_store, ) .await?; let db = &*state.store; payout_data.payout_link = payout_data .payout_link .clone() .async_map(|pl| async move { let payout_link_update = storage::PayoutLinkUpdate::StatusUpdate { link_status: PayoutLinkStatus::Submitted, }; db.update_payout_link(pl, payout_link_update) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payout links in db") }) .await .transpose()?; payouts_core( &state, &merchant_account, &key_store, &mut payout_data, req.routing.clone(), req.connector.clone(), ) .await?; response_handler(&state, &merchant_account, &payout_data).await } pub async fn payouts_update_core( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: payouts::PayoutCreateRequest, ) -> RouterResponse<payouts::PayoutCreateResponse> { let payout_id = req.payout_id.clone().get_required_value("payout_id")?; let mut payout_data = make_payout_data( &state, &merchant_account, None, &key_store, &payouts::PayoutRequest::PayoutCreateRequest(Box::new(req.to_owned())), &state.locale, ) .await?; let payout_attempt = payout_data.payout_attempt.to_owned(); let status = payout_attempt.status; // Verify update feasibility if helpers::is_payout_terminal_state(status) || helpers::is_payout_initiated(status) { return Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: format!( "Payout {} cannot be updated for status {}", payout_id, status ), })); } helpers::update_payouts_and_payout_attempt( &mut payout_data, &merchant_account, &req, &state, &key_store, ) .await?; let payout_attempt = payout_data.payout_attempt.to_owned(); if (req.connector.is_none(), payout_attempt.connector.is_some()) != (true, true) { // if the connector is not updated but was provided during payout create payout_data.payout_attempt.connector = None; payout_data.payout_attempt.routing_info = None; }; // Update payout method data in temp locker if req.payout_method_data.is_some() { let customer_id = payout_data .payouts .customer_id .clone() .get_required_value("customer_id when payout_method_data is provided")?; payout_data.payout_method_data = helpers::make_payout_method_data( &state, req.payout_method_data.as_ref(), payout_attempt.payout_token.as_deref(), &customer_id, &payout_attempt.merchant_id, payout_data.payouts.payout_type, &key_store, Some(&mut payout_data), merchant_account.storage_scheme, ) .await?; } if let Some(true) = payout_data.payouts.confirm { payouts_core( &state, &merchant_account, &key_store, &mut payout_data, req.routing.clone(), req.connector.clone(), ) .await?; } response_handler(&state, &merchant_account, &payout_data).await } #[cfg(all(feature = "payouts", feature = "v1"))] #[instrument(skip_all)] 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 } #[instrument(skip_all)] pub async fn payouts_cancel_core( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: payouts::PayoutActionRequest, ) -> RouterResponse<payouts::PayoutCreateResponse> { let mut payout_data = make_payout_data( &state, &merchant_account, None, &key_store, &payouts::PayoutRequest::PayoutActionRequest(req.to_owned()), &state.locale, ) .await?; let payout_attempt = payout_data.payout_attempt.to_owned(); let status = payout_attempt.status; // Verify if cancellation can be triggered if helpers::is_payout_terminal_state(status) { return Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: format!( "Payout {} cannot be cancelled for status {}", payout_attempt.payout_id, status ), })); // Make local cancellation } else if helpers::is_eligible_for_local_payout_cancellation(status) { let status = storage_enums::PayoutStatus::Cancelled; let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_attempt.connector_payout_id.to_owned(), status, error_message: Some("Cancelled by user".to_string()), error_code: None, is_eligible: None, unified_code: None, unified_message: None, }; payout_data.payout_attempt = state .store .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 = state .store .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")?; // Trigger connector's cancellation } else { // Form connector data let connector_data = match &payout_attempt.connector { Some(connector) => api::ConnectorData::get_payout_connector_by_name( &state.conf.connectors, connector, api::GetToken::Connector, payout_attempt.merchant_connector_id.clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the connector data")?, _ => Err(errors::ApplicationError::InvalidConfigurationValueError( "Connector not found in payout_attempt - should not reach here".to_string(), )) .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "connector", }) .attach_printable("Connector not found for payout cancellation")?, }; cancel_payout(&state, &merchant_account, &connector_data, &mut payout_data) .await .attach_printable("Payout cancellation failed for given Payout request")?; } response_handler(&state, &merchant_account, &payout_data).await } #[instrument(skip_all)] pub async fn payouts_fulfill_core( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: payouts::PayoutActionRequest, ) -> RouterResponse<payouts::PayoutCreateResponse> { let mut payout_data = make_payout_data( &state, &merchant_account, None, &key_store, &payouts::PayoutRequest::PayoutActionRequest(req.to_owned()), &state.locale, ) .await?; let payout_attempt = payout_data.payout_attempt.to_owned(); let status = payout_attempt.status; // Verify if fulfillment can be triggered if helpers::is_payout_terminal_state(status) || status != api_enums::PayoutStatus::RequiresFulfillment { return Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: format!( "Payout {} cannot be fulfilled for status {}", payout_attempt.payout_id, status ), })); } // Form connector data let connector_data = match &payout_attempt.connector { Some(connector) => api::ConnectorData::get_payout_connector_by_name( &state.conf.connectors, connector, api::GetToken::Connector, payout_attempt.merchant_connector_id.clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the connector data")?, _ => Err(errors::ApplicationError::InvalidConfigurationValueError( "Connector not found in payout_attempt - should not reach here.".to_string(), )) .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "connector", }) .attach_printable("Connector not found for payout fulfillment")?, }; // Trigger fulfillment let customer_id = payout_data .payouts .customer_id .clone() .get_required_value("customer_id")?; payout_data.payout_method_data = Some( helpers::make_payout_method_data( &state, None, payout_attempt.payout_token.as_deref(), &customer_id, &payout_attempt.merchant_id, payout_data.payouts.payout_type, &key_store, Some(&mut payout_data), merchant_account.storage_scheme, ) .await? .get_required_value("payout_method_data")?, ); Box::pin(fulfill_payout( &state, &merchant_account, &key_store, &connector_data, &mut payout_data, )) .await .attach_printable("Payout fulfillment failed for given Payout request")?; 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_attempt.error_message, "error_code": payout_attempt.error_code}) ), })); } response_handler(&state, &merchant_account, &payout_data).await } #[cfg(all(feature = "olap", feature = "v2", feature = "customer_v2"))] pub async fn payouts_list_core( _state: SessionState, _merchant_account: domain::MerchantAccount, _profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, _key_store: domain::MerchantKeyStore, _constraints: payouts::PayoutListConstraints, ) -> RouterResponse<payouts::PayoutListResponse> { todo!() } #[cfg(all( feature = "olap", any(feature = "v1", feature = "v2"), not(feature = "customer_v2") ))] pub async fn payouts_list_core( state: SessionState, merchant_account: domain::MerchantAccount, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, key_store: domain::MerchantKeyStore, constraints: payouts::PayoutListConstraints, ) -> RouterResponse<payouts::PayoutListResponse> { validator::validate_payout_list_request(&constraints)?; let merchant_id = merchant_account.get_id(); let db = state.store.as_ref(); let payouts = helpers::filter_by_constraints( db, &constraints, merchant_id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?; let payouts = core_utils::filter_objects_based_on_profile_id_list(profile_id_list, payouts); let mut pi_pa_tuple_vec = PayoutActionData::new(); for payout in payouts { match db .find_payout_attempt_by_merchant_id_payout_attempt_id( merchant_id, &utils::get_payout_attempt_id(payout.payout_id.clone(), payout.attempt_count), storage_enums::MerchantStorageScheme::PostgresOnly, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) { Ok(payout_attempt) => { let domain_customer = match payout.customer_id.clone() { #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] Some(customer_id) => db .find_customer_by_customer_id_merchant_id( &(&state).into(), &customer_id, merchant_id, &key_store, merchant_account.storage_scheme, ) .await .map_err(|err| { let err_msg = format!( "failed while fetching customer for customer_id - {:?}", customer_id ); logger::warn!(?err, err_msg); }) .ok(), _ => None, }; let payout_id_as_payment_id_type = common_utils::id_type::PaymentId::wrap(payout.payout_id.clone()) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "payout_id contains invalid data".to_string(), }) .attach_printable("Error converting payout_id to PaymentId type")?; let payment_addr = payment_helpers::create_or_find_address_for_payment_by_request( &state, None, payout.address_id.as_deref(), merchant_id, payout.customer_id.as_ref(), &key_store, &payout_id_as_payment_id_type, merchant_account.storage_scheme, ) .await .transpose() .and_then(|addr| { addr.map_err(|err| { let err_msg = format!( "billing_address missing for address_id : {:?}", payout.address_id ); logger::warn!(?err, err_msg); }) .ok() .as_ref() .map(hyperswitch_domain_models::address::Address::from) .map(payment_enums::Address::from) }); pi_pa_tuple_vec.push(( payout.to_owned(), payout_attempt.to_owned(), domain_customer, payment_addr, )); } Err(err) => { let err_msg = format!( "failed while fetching payout_attempt for payout_id - {:?}", payout.payout_id ); logger::warn!(?err, err_msg); } } } let data: Vec<api::PayoutCreateResponse> = pi_pa_tuple_vec .into_iter() .map(ForeignFrom::foreign_from) .collect(); Ok(services::ApplicationResponse::Json( api::PayoutListResponse { size: data.len(), data, total_count: None, }, )) } #[cfg(feature = "olap")] pub async fn payouts_filtered_list_core( state: SessionState, merchant_account: domain::MerchantAccount, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, key_store: domain::MerchantKeyStore, filters: payouts::PayoutListFilterConstraints, ) -> RouterResponse<payouts::PayoutListResponse> { let limit = &filters.limit; validator::validate_payout_list_request_for_joins(*limit)?; let db = state.store.as_ref(); let constraints = filters.clone().into(); let list: Vec<( storage::Payouts, storage::PayoutAttempt, Option<diesel_models::Customer>, Option<diesel_models::Address>, )> = db .filter_payouts_and_attempts( merchant_account.get_id(), &constraints, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?; let list = core_utils::filter_objects_based_on_profile_id_list(profile_id_list, list); let data: Vec<api::PayoutCreateResponse> = join_all(list.into_iter().map(|(p, pa, customer, address)| async { let customer: Option<domain::Customer> = customer .async_and_then(|cust| async { domain::Customer::convert_back( &(&state).into(), cust, &key_store.key, key_store.merchant_id.clone().into(), ) .await .map_err(|err| { let msg = format!("failed to convert customer for id: {:?}", p.customer_id); logger::warn!(?err, msg); }) .ok() }) .await; let payout_addr: Option<payment_enums::Address> = address .async_and_then(|addr| async { domain::Address::convert_back( &(&state).into(), addr, &key_store.key, key_store.merchant_id.clone().into(), ) .await .map(ForeignFrom::foreign_from) .map_err(|err| { let msg = format!("failed to convert address for id: {:?}", p.address_id); logger::warn!(?err, msg); }) .ok() }) .await; Some((p, pa, customer, payout_addr)) })) .await .into_iter() .flatten() .map(ForeignFrom::foreign_from) .collect(); let active_payout_ids = db .filter_active_payout_ids_by_constraints(merchant_account.get_id(), &constraints) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to filter active payout ids based on the constraints")?; let total_count = db .get_total_count_of_filtered_payouts( merchant_account.get_id(), &active_payout_ids, filters.connector.clone(), filters.currency.clone(), filters.status.clone(), filters.payout_method.clone(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed to fetch total count of filtered payouts for the given constraints - {:?}", filters ) })?; Ok(services::ApplicationResponse::Json( api::PayoutListResponse { size: data.len(), data, total_count: Some(total_count), }, )) } #[cfg(feature = "olap")] pub async fn payouts_list_available_filters_core( state: SessionState, merchant_account: domain::MerchantAccount, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: common_utils::types::TimeRange, ) -> RouterResponse<api::PayoutListFilters> { let db = state.store.as_ref(); let payouts = db .filter_payouts_by_time_range_constraints( merchant_account.get_id(), &time_range, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let payouts = core_utils::filter_objects_based_on_profile_id_list(profile_id_list, payouts); let filters = db .get_filters_for_payouts( payouts.as_slice(), merchant_account.get_id(), storage_enums::MerchantStorageScheme::PostgresOnly, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; Ok(services::ApplicationResponse::Json( api::PayoutListFilters { connector: filters.connector, currency: filters.currency, status: filters.status, payout_method: filters.payout_method, }, )) } // ********************************************** HELPERS ********************************************** 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(()) } pub async fn complete_create_recipient( state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, ) -> RouterResult<()> { if !payout_data.should_terminate && matches!( payout_data.payout_attempt.status, common_enums::PayoutStatus::RequiresCreation | common_enums::PayoutStatus::RequiresConfirmation | common_enums::PayoutStatus::RequiresPayoutMethodData ) && connector_data .connector_name .supports_create_recipient(payout_data.payouts.payout_type) { Box::pin(create_recipient( state, merchant_account, key_store, connector_data, payout_data, )) .await .attach_printable("Creation of customer failed")?; } Ok(()) } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] pub async fn create_recipient( state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, ) -> RouterResult<()> { let customer_details = payout_data.customer_details.to_owned(); let connector_name = connector_data.connector_name.to_string(); // Create the connector label using {profile_id}_{connector_name} let connector_label = format!( "{}_{}", payout_data.profile_id.get_string_repr(), connector_name ); let (should_call_connector, _connector_customer_id) = helpers::should_call_payout_connector_create_customer( state, connector_data, &customer_details, &connector_label, ); if should_call_connector { // 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::PoRecipient, types::PayoutsData, types::PayoutsResponseData, > = connector_data.connector.get_connector_integration(); // 3. Call connector service let router_resp = services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, ) .await .to_payout_failed_response()?; match router_resp.response { Ok(recipient_create_data) => { let db = &*state.store; if let Some(customer) = customer_details { if let Some(updated_customer) = customers::update_connector_customer_in_customers( &connector_label, Some(&customer), recipient_create_data.connector_payout_id.clone(), ) .await { #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "customer_v2") ))] { let customer_id = customer.customer_id.to_owned(); payout_data.customer_details = Some( db.update_customer_by_customer_id_merchant_id( &state.into(), customer_id, merchant_account.get_id().to_owned(), customer, updated_customer, key_store, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating customers in db")?, ); } #[cfg(all(feature = "v2", feature = "customer_v2"))] { let customer_id = customer.get_id().clone(); payout_data.customer_details = Some( db.update_customer_by_global_id( &state.into(), &customer_id, customer, merchant_account.get_id(), updated_customer, key_store, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating customers in db")?, ); } } } // Add next step to ProcessTracker if recipient_create_data.should_add_next_step_to_process_tracker { add_external_account_addition_task( &*state.store, payout_data, common_utils::date_time::now().saturating_add(Duration::seconds(consts::STRIPE_ACCOUNT_ONBOARDING_DELAY_IN_SECONDS)), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while adding attach_payout_account_workflow workflow to process tracker")?; // Update payout status in DB let status = recipient_create_data .status .unwrap_or(api_enums::PayoutStatus::RequiresVendorAccountCreation); let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_data .payout_attempt .connector_payout_id .to_owned(), status, error_code: None, error_message: None, is_eligible: recipient_create_data.payout_eligible, unified_code: None, unified_message: None, }; 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")?; // Helps callee functions skip the execution payout_data.should_terminate = true; } else if let Some(status) = recipient_create_data.status { let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_data .payout_attempt .connector_payout_id .to_owned(), status, error_code: None, error_message: None, is_eligible: recipient_create_data.payout_eligible, unified_code: None, unified_message: None, }; 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")?; } } Err(err) => Err(errors::ApiErrorResponse::PayoutFailed { data: serde_json::to_value(err).ok(), })?, } } Ok(()) } #[cfg(all(feature = "v2", feature = "customer_v2"))] pub async fn create_recipient( state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, ) -> RouterResult<()> { todo!() } 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(()) } 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(()) } 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(()) } 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(()) } 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(()) } #[cfg(feature = "v1")] pub async fn complete_payout_retrieve( state: &SessionState, merchant_account: &domain::MerchantAccount, connector_call_type: api::ConnectorCallType, payout_data: &mut PayoutData, ) -> RouterResult<()> { match connector_call_type { api::ConnectorCallType::PreDetermined(connector_data) => { create_payout_retrieve(state, merchant_account, &connector_data, payout_data) .await .attach_printable("Payout retrieval failed for given Payout request")?; } api::ConnectorCallType::Retryable(_) | api::ConnectorCallType::SessionMultiple(_) => { Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Payout retrieval not supported for given ConnectorCallType")? } } Ok(()) } #[cfg(feature = "v2")] pub async fn complete_payout_retrieve( state: &SessionState, merchant_account: &domain::MerchantAccount, connector_call_type: api::ConnectorCallType, payout_data: &mut PayoutData, ) -> RouterResult<()> { todo!() } pub async fn create_payout_retrieve( 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::PoSync, types::PayoutsData, types::PayoutsResponseData, > = connector_data.connector.get_connector_integration(); // 4. 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()?; // 5. Process data returned by the connector update_retrieve_payout_tracker(state, merchant_account, payout_data, &router_data_resp).await?; Ok(()) } pub async fn update_retrieve_payout_tracker<F, T>( state: &SessionState, merchant_account: &domain::MerchantAccount, payout_data: &mut PayoutData, payout_router_data: &types::RouterData<F, T, types::PayoutsResponseData>, ) -> RouterResult<()> { let db = &*state.store; match payout_router_data.response.as_ref() { 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 = if helpers::is_payout_err_state(status) { let (error_code, error_message) = ( payout_response_data.error_code.clone(), payout_response_data.error_message.clone(), ); 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)); storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_response_data.connector_payout_id.clone(), status, error_code, error_message, is_eligible: payout_response_data.payout_eligible, 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", })?, } } else { storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_response_data.connector_payout_id.clone(), 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")?; } Err(err) => { // log in case of error in retrieval logger::error!("Error in payout retrieval"); // show error in the response of sync payout_data.payout_attempt.error_code = Some(err.code.to_owned()); payout_data.payout_attempt.error_message = Some(err.message.to_owned()); } }; Ok(()) } pub async fn complete_create_recipient_disburse_account( state: &SessionState, merchant_account: &domain::MerchantAccount, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, key_store: &domain::MerchantKeyStore, ) -> RouterResult<()> { if !payout_data.should_terminate && matches!( payout_data.payout_attempt.status, storage_enums::PayoutStatus::RequiresVendorAccountCreation | storage_enums::PayoutStatus::RequiresCreation ) && connector_data .connector_name .supports_vendor_disburse_account_create_for_payout() && helpers::should_create_connector_transfer_method(&*payout_data, connector_data)? .is_none() { Box::pin(create_recipient_disburse_account( state, merchant_account, connector_data, payout_data, key_store, )) .await .attach_printable("Creation of customer failed")?; } Ok(()) } pub async fn create_recipient_disburse_account( state: &SessionState, merchant_account: &domain::MerchantAccount, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, key_store: &domain::MerchantKeyStore, ) -> 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::PoRecipientAccount, 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.clone(), 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")?; if let ( true, Some(ref payout_method_data), Some(connector_payout_id), Some(customer_details), Some(merchant_connector_id), ) = ( payout_data.payouts.recurring, payout_data.payout_method_data.clone(), payout_response_data.connector_payout_id.clone(), payout_data.customer_details.clone(), connector_data.merchant_connector_id.clone(), ) { let connector_mandate_details = HashMap::from([( merchant_connector_id.clone(), PayoutsMandateReferenceRecord { transfer_method_id: Some(connector_payout_id), }, )]); let common_connector_mandate = CommonMandateReference { payments: None, payouts: Some(PayoutsMandateReference(connector_mandate_details)), }; let connector_mandate_details_value = common_connector_mandate .get_mandate_details_value() .map_err(|err| { router_env::logger::error!( "Failed to get get_mandate_details_value : {:?}", err ); errors::ApiErrorResponse::MandateUpdateFailed })?; if let Some(pm_method) = payout_data.payment_method.clone() { let pm_update = diesel_models::PaymentMethodUpdate::ConnectorMandateDetailsUpdate { #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] connector_mandate_details: Some(connector_mandate_details_value), #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] connector_mandate_details: Some(common_connector_mandate), }; payout_data.payment_method = Some( db.update_payment_method( &(state.into()), key_store, pm_method, pm_update, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentMethodNotFound) .attach_printable("Unable to find payment method")?, ); } else { #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] let customer_id = Some(customer_details.customer_id); #[cfg(all(feature = "v2", feature = "customer_v2"))] let customer_id = customer_details.merchant_reference_id; if let Some(customer_id) = customer_id { helpers::save_payout_data_to_locker( state, payout_data, &customer_id, payout_method_data, Some(connector_mandate_details_value), merchant_account, key_store, ) .await .attach_printable("Failed to save payout data to locker")?; } }; } } Err(err) => { 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: storage_enums::PayoutStatus::Failed, 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")?; } }; Ok(()) } pub async fn cancel_payout( 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::PoCancel, 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 status = payout_response_data .status .unwrap_or(payout_data.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_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")?; } 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(()) } pub async fn fulfill_payout( state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, 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::PoFulfill, types::PayoutsData, types::PayoutsResponseData, > = connector_data.connector.get_connector_integration(); // 4. 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()?; // 5. Process data returned by the connector let db = &*state.store; match router_data_resp.response { Ok(payout_response_data) => { let status = payout_response_data .status .unwrap_or(payout_data.payout_attempt.status.to_owned()); payout_data.payouts.status = status; 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_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")?; 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()}) ), })); } else if payout_data.payouts.recurring && payout_data.payouts.payout_method_id.clone().is_none() { let payout_method_data = payout_data .payout_method_data .clone() .get_required_value("payout_method_data")?; payout_data .payouts .customer_id .clone() .async_map(|customer_id| async move { helpers::save_payout_data_to_locker( state, payout_data, &customer_id, &payout_method_data, None, merchant_account, key_store, ) .await }) .await .transpose() .attach_printable("Failed to save payout data to locker")?; } } 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(()) } pub async fn response_handler( state: &SessionState, merchant_account: &domain::MerchantAccount, payout_data: &PayoutData, ) -> RouterResponse<payouts::PayoutCreateResponse> { let payout_attempt = payout_data.payout_attempt.to_owned(); let payouts = payout_data.payouts.to_owned(); let payout_method_id: Option<String> = payout_data.payment_method.as_ref().map(|pm| { #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] { pm.payment_method_id.clone() } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] { pm.id.clone().get_string_repr().to_string() } }); let payout_link = payout_data.payout_link.to_owned(); let billing_address = payout_data.billing_address.to_owned(); let customer_details = payout_data.customer_details.to_owned(); let customer_id = payouts.customer_id; let billing = billing_address .as_ref() .map(hyperswitch_domain_models::address::Address::from) .map(From::from); let translated_unified_message = helpers::get_translated_unified_code_and_message( state, payout_attempt.unified_code.as_ref(), payout_attempt.unified_message.as_ref(), &payout_data.current_locale, ) .await?; let additional_payout_method_data = payout_attempt.additional_payout_method_data.clone(); let payout_method_data = additional_payout_method_data.map(payouts::PayoutMethodDataResponse::from); let response = api::PayoutCreateResponse { payout_id: payouts.payout_id.to_owned(), merchant_id: merchant_account.get_id().to_owned(), amount: payouts.amount, currency: payouts.destination_currency.to_owned(), connector: payout_attempt.connector, payout_type: payouts.payout_type.to_owned(), payout_method_data, billing, auto_fulfill: payouts.auto_fulfill, customer_id, email: customer_details.as_ref().and_then(|c| c.email.clone()), name: customer_details.as_ref().and_then(|c| c.name.clone()), phone: customer_details.as_ref().and_then(|c| c.phone.clone()), phone_country_code: customer_details .as_ref() .and_then(|c| c.phone_country_code.clone()), customer: customer_details .as_ref() .map(payment_api_types::CustomerDetailsResponse::foreign_from), client_secret: payouts.client_secret.to_owned(), return_url: payouts.return_url.to_owned(), business_country: payout_attempt.business_country, business_label: payout_attempt.business_label, description: payouts.description.to_owned(), entity_type: payouts.entity_type.to_owned(), recurring: payouts.recurring, metadata: payouts.metadata, merchant_connector_id: payout_attempt.merchant_connector_id.to_owned(), status: payout_attempt.status.to_owned(), error_message: payout_attempt.error_message.to_owned(), error_code: payout_attempt.error_code, profile_id: payout_attempt.profile_id, created: Some(payouts.created_at), connector_transaction_id: payout_attempt.connector_payout_id, priority: payouts.priority, attempts: None, unified_code: payout_attempt.unified_code, unified_message: translated_unified_message, payout_link: payout_link .map(|payout_link| { url::Url::parse(payout_link.url.peek()).map(|link| PayoutLinkResponse { payout_link_id: payout_link.link_id, link: link.into(), }) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse payout link's URL")?, payout_method_id, }; Ok(services::ApplicationResponse::Json(response)) } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[allow(clippy::too_many_arguments)] pub async fn payout_create_db_entries( _state: &SessionState, _merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, _req: &payouts::PayoutCreateRequest, _payout_id: &str, _profile_id: &str, _stored_payout_method_data: Option<&payouts::PayoutMethodData>, _locale: &str, _customer: Option<&domain::Customer>, _payment_method: Option<PaymentMethod>, ) -> RouterResult<PayoutData> { todo!() } // DB entries #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[allow(clippy::too_many_arguments)] pub async fn payout_create_db_entries( state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, req: &payouts::PayoutCreateRequest, payout_id: &String, profile_id: &common_utils::id_type::ProfileId, stored_payout_method_data: Option<&payouts::PayoutMethodData>, locale: &str, customer: Option<&domain::Customer>, payment_method: Option<PaymentMethod>, ) -> RouterResult<PayoutData> { let db = &*state.store; let merchant_id = merchant_account.get_id(); let customer_id = customer.map(|cust| cust.customer_id.clone()); // Validate whether profile_id passed in request is valid and is linked to the merchant let business_profile = validate_and_get_business_profile(state, key_store, profile_id, merchant_id).await?; let payout_link = match req.payout_link { Some(true) => Some( create_payout_link( state, &business_profile, &customer_id .clone() .get_required_value("customer.id when payout_link is true")?, merchant_id, req, payout_id, locale, ) .await?, ), _ => None, }; // We have to do this because the function that is being used to create / get address is from payments // which expects a payment_id let payout_id_as_payment_id_type = common_utils::id_type::PaymentId::try_from(std::borrow::Cow::Owned(payout_id.to_string())) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "payout_id contains invalid data".to_string(), }) .attach_printable("Error converting payout_id to PaymentId type")?; // Get or create address let billing_address = payment_helpers::create_or_find_address_for_payment_by_request( state, req.billing.as_ref(), None, merchant_id, customer_id.as_ref(), key_store, &payout_id_as_payment_id_type, merchant_account.storage_scheme, ) .await?; let address_id = billing_address.to_owned().map(|address| address.address_id); // Make payouts entry let currency = req.currency.to_owned().get_required_value("currency")?; let (payout_method_id, payout_type) = match stored_payout_method_data { Some(payout_method_data) => ( payment_method .as_ref() .map(|pm| pm.payment_method_id.clone()), Some(api_enums::PayoutType::foreign_from(payout_method_data)), ), None => ( payment_method .as_ref() .map(|pm| pm.payment_method_id.clone()), req.payout_type.to_owned(), ), }; let client_secret = utils::generate_id( consts::ID_LENGTH, format!("payout_{payout_id}_secret").as_str(), ); let amount = MinorUnit::from(req.amount.unwrap_or(api::Amount::Zero)); let status = if req.payout_method_data.is_some() || req.payout_token.is_some() || stored_payout_method_data.is_some() { match req.confirm { Some(true) => storage_enums::PayoutStatus::RequiresCreation, _ => storage_enums::PayoutStatus::RequiresConfirmation, } } else { storage_enums::PayoutStatus::RequiresPayoutMethodData }; let payouts_req = storage::PayoutsNew { payout_id: payout_id.to_string(), merchant_id: merchant_id.to_owned(), customer_id: customer_id.to_owned(), address_id: address_id.to_owned(), payout_type, amount, destination_currency: currency, source_currency: currency, description: req.description.to_owned(), recurring: req.recurring.unwrap_or(false), auto_fulfill: req.auto_fulfill.unwrap_or(false), return_url: req.return_url.to_owned(), entity_type: req.entity_type.unwrap_or_default(), payout_method_id, profile_id: profile_id.to_owned(), attempt_count: 1, metadata: req.metadata.clone(), confirm: req.confirm, payout_link_id: payout_link .clone() .map(|link_data| link_data.link_id.clone()), client_secret: Some(client_secret), priority: req.priority, status, created_at: common_utils::date_time::now(), last_modified_at: common_utils::date_time::now(), }; let payouts = db .insert_payout(payouts_req, merchant_account.storage_scheme) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicatePayout { payout_id: payout_id.to_owned(), }) .attach_printable("Error inserting payouts in db")?; // Make payout_attempt entry let payout_attempt_id = utils::get_payout_attempt_id(payout_id, 1); let additional_pm_data_value = req .payout_method_data .clone() .or(stored_payout_method_data.cloned()) .async_and_then(|payout_method_data| async move { helpers::get_additional_payout_data(&payout_method_data, &*state.store, profile_id) .await }) .await; let payout_attempt_req = storage::PayoutAttemptNew { payout_attempt_id: payout_attempt_id.to_string(), payout_id: payout_id.to_owned(), additional_payout_method_data: additional_pm_data_value, merchant_id: merchant_id.to_owned(), status, business_country: req.business_country.to_owned(), business_label: req.business_label.to_owned(), payout_token: req.payout_token.to_owned(), profile_id: profile_id.to_owned(), customer_id, address_id, connector: None, connector_payout_id: None, is_eligible: None, error_message: None, error_code: None, created_at: common_utils::date_time::now(), last_modified_at: common_utils::date_time::now(), merchant_connector_id: None, routing_info: None, unified_code: None, unified_message: None, }; let payout_attempt = db .insert_payout_attempt( payout_attempt_req, &payouts, merchant_account.storage_scheme, ) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicatePayout { payout_id: payout_id.to_owned(), }) .attach_printable("Error inserting payout_attempt in db")?; // Make PayoutData Ok(PayoutData { billing_address, business_profile, customer_details: customer.map(ToOwned::to_owned), merchant_connector_account: None, payouts, payout_attempt, payout_method_data: req .payout_method_data .as_ref() .cloned() .or(stored_payout_method_data.cloned()), should_terminate: false, profile_id: profile_id.to_owned(), payout_link, current_locale: locale.to_string(), payment_method, }) } #[cfg(all(feature = "v2", feature = "customer_v2"))] pub async fn make_payout_data( _state: &SessionState, _merchant_account: &domain::MerchantAccount, _auth_profile_id: Option<common_utils::id_type::ProfileId>, _key_store: &domain::MerchantKeyStore, _req: &payouts::PayoutRequest, locale: &str, ) -> RouterResult<PayoutData> { todo!() } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] pub async fn make_payout_data( state: &SessionState, merchant_account: &domain::MerchantAccount, auth_profile_id: Option<common_utils::id_type::ProfileId>, key_store: &domain::MerchantKeyStore, req: &payouts::PayoutRequest, locale: &str, ) -> RouterResult<PayoutData> { let db = &*state.store; let merchant_id = merchant_account.get_id(); let payout_id = match req { payouts::PayoutRequest::PayoutActionRequest(r) => r.payout_id.clone(), payouts::PayoutRequest::PayoutCreateRequest(r) => r.payout_id.clone().unwrap_or_default(), payouts::PayoutRequest::PayoutRetrieveRequest(r) => r.payout_id.clone(), }; let payouts = db .find_payout_by_merchant_id_payout_id( merchant_id, &payout_id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?; core_utils::validate_profile_id_from_auth_layer(auth_profile_id, &payouts)?; let payout_attempt_id = utils::get_payout_attempt_id(payout_id, payouts.attempt_count); let mut payout_attempt = db .find_payout_attempt_by_merchant_id_payout_attempt_id( merchant_id, &payout_attempt_id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?; let customer_id = payouts.customer_id.as_ref(); // We have to do this because the function that is being used to create / get address is from payments // which expects a payment_id let payout_id_as_payment_id_type = common_utils::id_type::PaymentId::try_from( std::borrow::Cow::Owned(payouts.payout_id.clone()), ) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "payout_id contains invalid data".to_string(), }) .attach_printable("Error converting payout_id to PaymentId type")?; let billing_address = payment_helpers::create_or_find_address_for_payment_by_request( state, None, payouts.address_id.as_deref(), merchant_id, customer_id, key_store, &payout_id_as_payment_id_type, merchant_account.storage_scheme, ) .await?; let payout_id = &payouts.payout_id; let customer_details = customer_id .async_map(|customer_id| async move { db.find_customer_optional_by_customer_id_merchant_id( &state.into(), customer_id, merchant_id, key_store, merchant_account.storage_scheme, ) .await .map_err(|err| err.change_context(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| { format!( "Failed while fetching optional customer [id - {:?}] for payout [id - {}]", customer_id, payout_id ) }) }) .await .transpose()? .and_then(|c| c); let profile_id = payout_attempt.profile_id.clone(); // Validate whether profile_id passed in request is valid and is linked to the merchant let business_profile = validate_and_get_business_profile(state, key_store, &profile_id, merchant_id).await?; let payout_method_data_req = match req { payouts::PayoutRequest::PayoutCreateRequest(r) => r.payout_method_data.to_owned(), payouts::PayoutRequest::PayoutActionRequest(_) => { match payout_attempt.payout_token.to_owned() { Some(payout_token) => { let customer_id = customer_details .as_ref() .map(|cd| cd.customer_id.to_owned()) .get_required_value("customer_id when payout_token is sent")?; helpers::make_payout_method_data( state, None, Some(&payout_token), &customer_id, merchant_account.get_id(), payouts.payout_type, key_store, None, merchant_account.storage_scheme, ) .await? } None => None, } } payouts::PayoutRequest::PayoutRetrieveRequest(_) => None, }; if let Some(payout_method_data) = payout_method_data_req.clone() { let additional_payout_method_data = helpers::get_additional_payout_data(&payout_method_data, &*state.store, &profile_id) .await; let update_additional_payout_method_data = storage::PayoutAttemptUpdate::AdditionalPayoutMethodDataUpdate { additional_payout_method_data, }; payout_attempt = db .update_payout_attempt( &payout_attempt, update_additional_payout_method_data, &payouts, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating additional payout method data in payout_attempt")?; }; let merchant_connector_account = if payout_attempt.connector.is_some() && payout_attempt.merchant_connector_id.is_some() { let connector_name = payout_attempt .connector .clone() .get_required_value("connector_name")?; Some( payment_helpers::get_merchant_connector_account( state, merchant_account.get_id(), None, key_store, &profile_id, connector_name.as_str(), payout_attempt.merchant_connector_id.as_ref(), ) .await?, ) } else { None }; let payout_link = payouts .payout_link_id .clone() .async_map(|link_id| async move { db.find_payout_link_by_link_id(&link_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error fetching payout links from db") }) .await .transpose()?; let payout_method_id = payouts.payout_method_id.clone(); let mut payment_method: Option<PaymentMethod> = None; if let Some(pm_id) = payout_method_id { payment_method = Some( db.find_payment_method( &(state.into()), key_store, &pm_id, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentMethodNotFound) .attach_printable("Unable to find payment method")?, ); } Ok(PayoutData { billing_address, business_profile, customer_details, payouts, payout_attempt, payout_method_data: payout_method_data_req.to_owned(), merchant_connector_account, should_terminate: false, profile_id, payout_link, current_locale: locale.to_string(), payment_method, }) } pub async fn add_external_account_addition_task( db: &dyn StorageInterface, payout_data: &PayoutData, schedule_time: time::PrimitiveDateTime, ) -> CustomResult<(), errors::StorageError> { let runner = storage::ProcessTrackerRunner::AttachPayoutAccountWorkflow; let task = "STRPE_ATTACH_EXTERNAL_ACCOUNT"; let tag = ["PAYOUTS", "STRIPE", "ACCOUNT", "CREATE"]; let process_tracker_id = pt_utils::get_process_tracker_id( runner, task, &payout_data.payout_attempt.payout_attempt_id, &payout_data.payout_attempt.merchant_id, ); let tracking_data = api::PayoutRetrieveRequest { payout_id: payout_data.payouts.payout_id.to_owned(), force_sync: None, merchant_id: Some(payout_data.payouts.merchant_id.to_owned()), }; 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)?; db.insert_process(process_tracker_entry).await?; Ok(()) } async fn validate_and_get_business_profile( state: &SessionState, merchant_key_store: &domain::MerchantKeyStore, profile_id: &common_utils::id_type::ProfileId, merchant_id: &common_utils::id_type::MerchantId, ) -> RouterResult<domain::Profile> { let db = &*state.store; let key_manager_state = &state.into(); if let Some(business_profile) = core_utils::validate_and_get_business_profile( db, key_manager_state, merchant_key_store, Some(profile_id), merchant_id, ) .await? { Ok(business_profile) } else { db.find_business_profile_by_profile_id(key_manager_state, merchant_key_store, profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), }) } } #[allow(clippy::too_many_arguments)] pub async fn create_payout_link( state: &SessionState, business_profile: &domain::Profile, customer_id: &CustomerId, merchant_id: &common_utils::id_type::MerchantId, req: &payouts::PayoutCreateRequest, payout_id: &str, locale: &str, ) -> RouterResult<PayoutLink> { let payout_link_config_req = req.payout_link_config.to_owned(); // Fetch all configs let default_config = &state.conf.generic_link.payout_link; let profile_config = &business_profile.payout_link_config; let profile_ui_config = profile_config.as_ref().map(|c| c.config.ui_config.clone()); let ui_config = payout_link_config_req .as_ref() .and_then(|config| config.ui_config.clone()) .or(profile_ui_config); let test_mode_in_config = payout_link_config_req .as_ref() .and_then(|config| config.test_mode) .or_else(|| profile_config.as_ref().and_then(|c| c.payout_test_mode)); let is_test_mode_enabled = test_mode_in_config.unwrap_or(false); let allowed_domains = match (router_env::which(), is_test_mode_enabled) { // Throw error in case test_mode was enabled in production (Env::Production, true) => Err(report!(errors::ApiErrorResponse::LinkConfigurationError { message: "test_mode cannot be true for creating payout_links in production".to_string() })), // Send empty set of whitelisted domains (_, true) => { Ok(HashSet::new()) }, // Otherwise, fetch and use allowed domains from profile config (_, false) => { profile_config .as_ref() .map(|config| config.config.allowed_domains.to_owned()) .get_required_value("allowed_domains") .change_context(errors::ApiErrorResponse::LinkConfigurationError { message: "Payout links cannot be used without setting allowed_domains in profile. If you're using a non-production environment, you can set test_mode to true while in payout_link_config" .to_string(), }) } }?; // Form data to be injected in the link let (logo, merchant_name, theme) = match ui_config { Some(config) => (config.logo, config.merchant_name, config.theme), _ => (None, None, None), }; let payout_link_config = GenericLinkUiConfig { logo, merchant_name, theme, }; let client_secret = utils::generate_id(consts::ID_LENGTH, "payout_link_secret"); let base_url = profile_config .as_ref() .and_then(|c| c.config.domain_name.as_ref()) .map(|domain| format!("https://{}", domain)) .unwrap_or(state.base_url.clone()); let session_expiry = req .session_expiry .as_ref() .map_or(default_config.expiry, |expiry| *expiry); let url = format!( "{base_url}/payout_link/{}/{payout_id}?locale={}", merchant_id.get_string_repr(), locale ); let link = url::Url::parse(&url) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| format!("Failed to form payout link URL - {}", url))?; let req_enabled_payment_methods = payout_link_config_req .as_ref() .and_then(|req| req.enabled_payment_methods.to_owned()); let amount = req .amount .as_ref() .get_required_value("amount") .attach_printable("amount is a required value when creating payout links")?; let currency = req .currency .as_ref() .get_required_value("currency") .attach_printable("currency is a required value when creating payout links")?; let payout_link_id = core_utils::get_or_generate_id( "payout_link_id", &payout_link_config_req .as_ref() .and_then(|config| config.payout_link_id.clone()), "payout_link", )?; let form_layout = payout_link_config_req .as_ref() .and_then(|config| config.form_layout.to_owned()) .or_else(|| { profile_config .as_ref() .and_then(|config| config.form_layout.to_owned()) }); let data = PayoutLinkData { payout_link_id: payout_link_id.clone(), customer_id: customer_id.clone(), payout_id: payout_id.to_string(), link, client_secret: Secret::new(client_secret), session_expiry, ui_config: payout_link_config, enabled_payment_methods: req_enabled_payment_methods, amount: MinorUnit::from(*amount), currency: *currency, allowed_domains, form_layout, test_mode: test_mode_in_config, }; create_payout_link_db_entry(state, merchant_id, &data, req.return_url.clone()).await } pub async fn create_payout_link_db_entry( state: &SessionState, merchant_id: &common_utils::id_type::MerchantId, payout_link_data: &PayoutLinkData, return_url: Option<String>, ) -> RouterResult<PayoutLink> { let db: &dyn StorageInterface = &*state.store; let link_data = serde_json::to_value(payout_link_data) .map_err(|_| report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable("Failed to convert PayoutLinkData to Value")?; let payout_link = GenericLinkNew { link_id: payout_link_data.payout_link_id.to_string(), primary_reference: payout_link_data.payout_id.to_string(), merchant_id: merchant_id.to_owned(), link_type: common_enums::GenericLinkType::PayoutLink, link_status: GenericLinkStatus::PayoutLink(PayoutLinkStatus::Initiated), link_data, url: payout_link_data.link.to_string().into(), return_url, expiry: common_utils::date_time::now() + Duration::seconds(payout_link_data.session_expiry.into()), ..Default::default() }; db.insert_payout_link(payout_link) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: "payout link already exists".to_string(), }) } #[instrument(skip_all)] pub async fn get_mca_from_profile_id( state: &SessionState, merchant_account: &domain::MerchantAccount, profile_id: &common_utils::id_type::ProfileId, connector_name: &str, merchant_connector_id: Option<&common_utils::id_type::MerchantConnectorAccountId>, key_store: &domain::MerchantKeyStore, ) -> RouterResult<payment_helpers::MerchantConnectorAccountType> { let merchant_connector_account = payment_helpers::get_merchant_connector_account( state, merchant_account.get_id(), None, key_store, profile_id, connector_name, merchant_connector_id, ) .await?; Ok(merchant_connector_account) }
24,122
1,576
hyperswitch
crates/router/src/core/errors.rs
.rs
pub mod customers_error_response; pub mod error_handlers; pub mod transformers; #[cfg(feature = "olap")] pub mod user; pub mod utils; use std::fmt::Display; use actix_web::{body::BoxBody, ResponseError}; pub use common_utils::errors::{CustomResult, ParsingError, ValidationError}; use diesel_models::errors as storage_errors; pub use hyperswitch_domain_models::errors::api_error_response::{ ApiErrorResponse, ErrorType, NotImplementedMessage, }; pub use hyperswitch_interfaces::errors::ConnectorError; pub use redis_interface::errors::RedisError; use scheduler::errors as sch_errors; use storage_impl::errors as storage_impl_errors; #[cfg(feature = "olap")] pub use user::*; pub use self::{ customers_error_response::CustomersErrorResponse, sch_errors::*, storage_errors::*, storage_impl_errors::*, utils::{ConnectorErrorExt, StorageErrorExt}, }; use crate::services; pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>; pub type RouterResponse<T> = CustomResult<services::ApplicationResponse<T>, ApiErrorResponse>; pub type ApplicationResult<T> = error_stack::Result<T, ApplicationError>; pub type ApplicationResponse<T> = ApplicationResult<services::ApplicationResponse<T>>; pub type CustomerResponse<T> = CustomResult<services::ApplicationResponse<T>, CustomersErrorResponse>; macro_rules! impl_error_display { ($st: ident, $arg: tt) => { impl Display for $st { fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( fmt, "{{ error_type: {:?}, error_description: {} }}", self, $arg ) } } }; } #[macro_export] macro_rules! capture_method_not_supported { ($connector:expr, $capture_method:expr) => { Err(errors::ConnectorError::NotSupported { message: format!("{} for selected payment method", $capture_method), connector: $connector, } .into()) }; ($connector:expr, $capture_method:expr, $payment_method_type:expr) => { Err(errors::ConnectorError::NotSupported { message: format!("{} for {}", $capture_method, $payment_method_type), connector: $connector, } .into()) }; } #[macro_export] macro_rules! unimplemented_payment_method { ($payment_method:expr, $connector:expr) => { errors::ConnectorError::NotImplemented(format!( "{} through {}", $payment_method, $connector )) }; ($payment_method:expr, $flow:expr, $connector:expr) => { errors::ConnectorError::NotImplemented(format!( "{} {} through {}", $payment_method, $flow, $connector )) }; } macro_rules! impl_error_type { ($name: ident, $arg: tt) => { #[derive(Debug)] pub struct $name; impl_error_display!($name, $arg); impl std::error::Error for $name {} }; } impl_error_type!(EncryptionError, "Encryption error"); impl From<ring::error::Unspecified> for EncryptionError { fn from(_: ring::error::Unspecified) -> Self { Self } } pub fn http_not_implemented() -> actix_web::HttpResponse<BoxBody> { ApiErrorResponse::NotImplemented { message: NotImplementedMessage::Default, } .error_response() } #[derive(Debug, thiserror::Error)] pub enum HealthCheckOutGoing { #[error("Outgoing call failed with error: {message}")] OutGoingFailed { message: String }, } #[derive(Debug, thiserror::Error)] pub enum VaultError { #[error("Failed to save card in card vault")] SaveCardFailed, #[error("Failed to fetch card details from card vault")] FetchCardFailed, #[error("Failed to delete card in card vault")] DeleteCardFailed, #[error("Failed to encode card vault request")] RequestEncodingFailed, #[error("Failed to deserialize card vault response")] ResponseDeserializationFailed, #[error("Failed to create payment method")] PaymentMethodCreationFailed, #[error("The given payment method is currently not supported in vault")] PaymentMethodNotSupported, #[error("The given payout method is currently not supported in vault")] PayoutMethodNotSupported, #[error("Missing required field: {field_name}")] MissingRequiredField { field_name: &'static str }, #[error("The card vault returned an unexpected response: {0:?}")] UnexpectedResponseError(bytes::Bytes), #[error("Failed to update in PMD table")] UpdateInPaymentMethodDataTableFailed, #[error("Failed to fetch payment method in vault")] FetchPaymentMethodFailed, #[error("Failed to save payment method in vault")] SavePaymentMethodFailed, #[error("Failed to generate fingerprint")] GenerateFingerprintFailed, #[error("Failed to encrypt vault request")] RequestEncryptionFailed, #[error("Failed to decrypt vault response")] ResponseDecryptionFailed, #[error("Failed to call vault")] VaultAPIError, #[error("Failed while calling locker API")] ApiError, } #[derive(Debug, thiserror::Error)] pub enum AwsKmsError { #[error("Failed to base64 decode input data")] Base64DecodingFailed, #[error("Failed to AWS KMS decrypt input data")] DecryptionFailed, #[error("Missing plaintext AWS KMS decryption output")] MissingPlaintextDecryptionOutput, #[error("Failed to UTF-8 decode decryption output")] Utf8DecodingFailed, } #[derive(Debug, thiserror::Error, serde::Serialize)] pub enum WebhooksFlowError { #[error("Merchant webhook config not found")] MerchantConfigNotFound, #[error("Webhook details for merchant not configured")] MerchantWebhookDetailsNotFound, #[error("Merchant does not have a webhook URL configured")] MerchantWebhookUrlNotConfigured, #[error("Webhook event updation failed")] WebhookEventUpdationFailed, #[error("Outgoing webhook body signing failed")] OutgoingWebhookSigningFailed, #[error("Webhook api call to merchant failed")] CallToMerchantFailed, #[error("Webhook not received by merchant")] NotReceivedByMerchant, #[error("Dispute webhook status validation failed")] DisputeWebhookValidationFailed, #[error("Outgoing webhook body encoding failed")] OutgoingWebhookEncodingFailed, #[error("Failed to update outgoing webhook process tracker task")] OutgoingWebhookProcessTrackerTaskUpdateFailed, #[error("Failed to schedule retry attempt for outgoing webhook")] OutgoingWebhookRetrySchedulingFailed, #[error("Outgoing webhook response encoding failed")] OutgoingWebhookResponseEncodingFailed, } impl WebhooksFlowError { pub(crate) fn is_webhook_delivery_retryable_error(&self) -> bool { match self { Self::MerchantConfigNotFound | Self::MerchantWebhookDetailsNotFound | Self::MerchantWebhookUrlNotConfigured | Self::OutgoingWebhookResponseEncodingFailed => false, Self::WebhookEventUpdationFailed | Self::OutgoingWebhookSigningFailed | Self::CallToMerchantFailed | Self::NotReceivedByMerchant | Self::DisputeWebhookValidationFailed | Self::OutgoingWebhookEncodingFailed | Self::OutgoingWebhookProcessTrackerTaskUpdateFailed | Self::OutgoingWebhookRetrySchedulingFailed => true, } } } #[derive(Debug, thiserror::Error)] pub enum ApplePayDecryptionError { #[error("Failed to base64 decode input data")] Base64DecodingFailed, #[error("Failed to decrypt input data")] DecryptionFailed, #[error("Certificate parsing failed")] CertificateParsingFailed, #[error("Certificate parsing failed")] MissingMerchantId, #[error("Key Deserialization failure")] KeyDeserializationFailed, #[error("Failed to Derive a shared secret key")] DerivingSharedSecretKeyFailed, } #[derive(Debug, thiserror::Error)] pub enum PazeDecryptionError { #[error("Failed to base64 decode input data")] Base64DecodingFailed, #[error("Failed to decrypt input data")] DecryptionFailed, #[error("Certificate parsing failed")] CertificateParsingFailed, } #[derive(Debug, thiserror::Error)] pub enum GooglePayDecryptionError { #[error("Invalid expiration time")] InvalidExpirationTime, #[error("Failed to base64 decode input data")] Base64DecodingFailed, #[error("Failed to decrypt input data")] DecryptionFailed, #[error("Failed to deserialize input data")] DeserializationFailed, #[error("Certificate parsing failed")] CertificateParsingFailed, #[error("Key deserialization failure")] KeyDeserializationFailed, #[error("Failed to derive a shared ephemeral key")] DerivingSharedEphemeralKeyFailed, #[error("Failed to derive a shared secret key")] DerivingSharedSecretKeyFailed, #[error("Failed to parse the tag")] ParsingTagError, #[error("HMAC verification failed")] HmacVerificationFailed, #[error("Failed to derive Elliptic Curve key")] DerivingEcKeyFailed, #[error("Failed to Derive Public key")] DerivingPublicKeyFailed, #[error("Failed to Derive Elliptic Curve group")] DerivingEcGroupFailed, #[error("Failed to allocate memory for big number")] BigNumAllocationFailed, #[error("Failed to get the ECDSA signature")] EcdsaSignatureFailed, #[error("Failed to verify the signature")] SignatureVerificationFailed, #[error("Invalid signature is provided")] InvalidSignature, #[error("Failed to parse the Signed Key")] SignedKeyParsingFailure, #[error("The Signed Key is expired")] SignedKeyExpired, #[error("Failed to parse the ECDSA signature")] EcdsaSignatureParsingFailed, #[error("Invalid intermediate signature is provided")] InvalidIntermediateSignature, #[error("Invalid protocol version")] InvalidProtocolVersion, #[error("Decrypted Token has expired")] DecryptedTokenExpired, #[error("Failed to parse the given value")] ParsingFailed, } #[cfg(feature = "detailed_errors")] pub mod error_stack_parsing { #[derive(serde::Deserialize)] pub struct NestedErrorStack<'a> { context: std::borrow::Cow<'a, str>, attachments: Vec<std::borrow::Cow<'a, str>>, sources: Vec<NestedErrorStack<'a>>, } #[derive(serde::Serialize, Debug)] struct LinearErrorStack<'a> { context: std::borrow::Cow<'a, str>, #[serde(skip_serializing_if = "Vec::is_empty")] attachments: Vec<std::borrow::Cow<'a, str>>, } #[derive(serde::Serialize, Debug)] pub struct VecLinearErrorStack<'a>(Vec<LinearErrorStack<'a>>); impl<'a> From<Vec<NestedErrorStack<'a>>> for VecLinearErrorStack<'a> { fn from(value: Vec<NestedErrorStack<'a>>) -> Self { let multi_layered_errors: Vec<_> = value .into_iter() .flat_map(|current_error| { [LinearErrorStack { context: current_error.context, attachments: current_error.attachments, }] .into_iter() .chain(Into::<VecLinearErrorStack<'a>>::into(current_error.sources).0) }) .collect(); Self(multi_layered_errors) } } } #[cfg(feature = "detailed_errors")] pub use error_stack_parsing::*; #[derive(Debug, Clone, thiserror::Error)] pub enum RoutingError { #[error("Merchant routing algorithm not found in cache")] CacheMiss, #[error("Final connector selection failed")] ConnectorSelectionFailed, #[error("[DSL] Missing required field in payment data: '{field_name}'")] DslMissingRequiredField { field_name: String }, #[error("The lock on the DSL cache is most probably poisoned")] DslCachePoisoned, #[error("Expected DSL to be saved in DB but did not find")] DslMissingInDb, #[error("Unable to parse DSL from JSON")] DslParsingError, #[error("Failed to initialize DSL backend")] DslBackendInitError, #[error("Error updating merchant with latest dsl cache contents")] DslMerchantUpdateError, #[error("Error executing the DSL")] DslExecutionError, #[error("Final connector selection failed")] DslFinalConnectorSelectionFailed, #[error("[DSL] Received incorrect selection algorithm as DSL output")] DslIncorrectSelectionAlgorithm, #[error("there was an error saving/retrieving values from the kgraph cache")] KgraphCacheFailure, #[error("failed to refresh the kgraph cache")] KgraphCacheRefreshFailed, #[error("there was an error during the kgraph analysis phase")] KgraphAnalysisError, #[error("'profile_id' was not provided")] ProfileIdMissing, #[error("the profile was not found in the database")] ProfileNotFound, #[error("failed to fetch the fallback config for the merchant")] FallbackConfigFetchFailed, #[error("Invalid connector name received: '{0}'")] InvalidConnectorName(String), #[error("The routing algorithm in merchant account had invalid structure")] InvalidRoutingAlgorithmStructure, #[error("Volume split failed")] VolumeSplitFailed, #[error("Unable to parse metadata")] MetadataParsingError, #[error("Unable to retrieve success based routing config")] SuccessBasedRoutingConfigError, #[error("Params not found in success based routing config")] SuccessBasedRoutingParamsNotFoundError, #[error("Unable to calculate success based routing config from dynamic routing service")] SuccessRateCalculationError, #[error("Success rate client from dynamic routing gRPC service not initialized")] SuccessRateClientInitializationError, #[error("Unable to convert from '{from}' to '{to}'")] GenericConversionError { from: String, to: String }, #[error("Invalid success based connector label received from dynamic routing service: '{0}'")] InvalidSuccessBasedConnectorLabel(String), #[error("unable to find '{field}'")] GenericNotFoundError { field: String }, #[error("Unable to deserialize from '{from}' to '{to}'")] DeserializationError { from: String, to: String }, #[error("Unable to retrieve contract based routing config")] ContractBasedRoutingConfigError, #[error("Params not found in contract based routing config")] ContractBasedRoutingParamsNotFoundError, #[error("Unable to calculate contract score from dynamic routing service: '{err}'")] ContractScoreCalculationError { err: String }, #[error("Unable to update contract score on dynamic routing service")] ContractScoreUpdationError, #[error("contract routing client from dynamic routing gRPC service not initialized")] ContractRoutingClientInitializationError, #[error("Invalid contract based connector label received from dynamic routing service: '{0}'")] InvalidContractBasedConnectorLabel(String), } #[derive(Debug, Clone, thiserror::Error)] pub enum ConditionalConfigError { #[error("failed to fetch the fallback config for the merchant")] FallbackConfigFetchFailed, #[error("The lock on the DSL cache is most probably poisoned")] DslCachePoisoned, #[error("Merchant routing algorithm not found in cache")] CacheMiss, #[error("Expected DSL to be saved in DB but did not find")] DslMissingInDb, #[error("Unable to parse DSL from JSON")] DslParsingError, #[error("Failed to initialize DSL backend")] DslBackendInitError, #[error("Error executing the DSL")] DslExecutionError, #[error("Error constructing the Input")] InputConstructionError, } #[derive(Debug, thiserror::Error)] pub enum NetworkTokenizationError { #[error("Failed to save network token in vault")] SaveNetworkTokenFailed, #[error("Failed to fetch network token details from vault")] FetchNetworkTokenFailed, #[error("Failed to encode network token vault request")] RequestEncodingFailed, #[error("Failed to deserialize network token service response")] ResponseDeserializationFailed, #[error("Failed to delete network token")] DeleteNetworkTokenFailed, #[error("Network token service not configured")] NetworkTokenizationServiceNotConfigured, #[error("Failed while calling Network Token Service API")] ApiError, #[error("Network Tokenization is not enabled for profile")] NetworkTokenizationNotEnabledForProfile, #[error("Network Tokenization is not supported for {message}")] NotSupported { message: String }, #[error("Failed to encrypt the NetworkToken payment method details")] NetworkTokenDetailsEncryptionFailed, } #[derive(Debug, thiserror::Error)] pub enum BulkNetworkTokenizationError { #[error("Failed to validate card details")] CardValidationFailed, #[error("Failed to validate payment method details")] PaymentMethodValidationFailed, #[error("Failed to assign a customer to the card")] CustomerAssignmentFailed, #[error("Failed to perform BIN lookup for the card")] BinLookupFailed, #[error("Failed to tokenize the card details with the network")] NetworkTokenizationFailed, #[error("Failed to store the card details in locker")] VaultSaveFailed, #[error("Failed to create a payment method entry")] PaymentMethodCreationFailed, #[error("Failed to update the payment method")] PaymentMethodUpdationFailed, } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] #[derive(Debug, thiserror::Error)] pub enum RevenueRecoveryError { #[error("Failed to fetch payment intent")] PaymentIntentFetchFailed, #[error("Failed to fetch payment attempt")] PaymentAttemptFetchFailed, #[error("Failed to fetch payment attempt")] PaymentAttemptIdNotFound, #[error("Failed to get revenue recovery invoice webhook")] InvoiceWebhookProcessingFailed, #[error("Failed to get revenue recovery invoice transaction")] TransactionWebhookProcessingFailed, #[error("Failed to create payment intent")] PaymentIntentCreateFailed, #[error("Source verification failed for billing connector")] WebhookAuthenticationFailed, #[error("Payment merchant connector account not found using account reference id")] PaymentMerchantConnectorAccountNotFound, #[error("Failed to fetch primitive date_time")] ScheduleTimeFetchFailed, #[error("Failed to create process tracker")] ProcessTrackerCreationError, #[error("Failed to get the response from process tracker")] ProcessTrackerResponseError, #[error("Billing connector psync call failed")] BillingConnectorPaymentsSyncFailed, }
4,062
1,577
hyperswitch
crates/router/src/core/card_testing_guard.rs
.rs
pub mod utils; use crate::core::errors;
11
1,578
hyperswitch
crates/router/src/core/user_role.rs
.rs
use std::collections::{HashMap, HashSet}; use api_models::{ user as user_api, user_role::{self as user_role_api, role as role_api}, }; use diesel_models::{ enums::{UserRoleVersion, UserStatus}, organization::OrganizationBridge, user_role::UserRoleUpdate, }; use error_stack::{report, ResultExt}; use masking::Secret; use once_cell::sync::Lazy; use crate::{ core::errors::{StorageErrorExt, UserErrors, UserResponse}, db::user_role::{ListUserRolesByOrgIdPayload, ListUserRolesByUserIdPayload}, routes::{app::ReqState, SessionState}, services::{ authentication as auth, authorization::{ info, permission_groups::{ParentGroupExt, PermissionGroupExt}, roles, }, ApplicationResponse, }, types::domain, utils, }; pub mod role; use common_enums::{EntityType, ParentGroup, PermissionGroup}; use strum::IntoEnumIterator; // TODO: To be deprecated pub async fn get_authorization_info_with_groups( _state: SessionState, ) -> UserResponse<user_role_api::AuthorizationInfoResponse> { Ok(ApplicationResponse::Json( user_role_api::AuthorizationInfoResponse( info::get_group_authorization_info() .into_iter() .map(user_role_api::AuthorizationInfo::Group) .collect(), ), )) } pub async fn get_authorization_info_with_group_tag( ) -> UserResponse<user_role_api::AuthorizationInfoResponse> { static GROUPS_WITH_PARENT_TAGS: Lazy<Vec<user_role_api::ParentInfo>> = Lazy::new(|| { PermissionGroup::iter() .map(|group| (group.parent(), group)) .fold( HashMap::new(), |mut acc: HashMap<ParentGroup, Vec<PermissionGroup>>, (key, value)| { acc.entry(key).or_default().push(value); acc }, ) .into_iter() .map(|(name, value)| user_role_api::ParentInfo { name: name.clone(), description: info::get_parent_group_description(name), groups: value, }) .collect() }); Ok(ApplicationResponse::Json( user_role_api::AuthorizationInfoResponse( GROUPS_WITH_PARENT_TAGS .iter() .cloned() .map(user_role_api::AuthorizationInfo::GroupWithTag) .collect(), ), )) } pub async fn get_parent_group_info( state: SessionState, user_from_token: auth::UserFromToken, ) -> UserResponse<Vec<role_api::ParentGroupInfo>> { let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .to_not_found_response(UserErrors::InvalidRoleId)?; let parent_groups = ParentGroup::get_descriptions_for_groups( role_info.get_entity_type(), PermissionGroup::iter().collect(), ) .into_iter() .map(|(parent_group, description)| role_api::ParentGroupInfo { name: parent_group.clone(), description, scopes: PermissionGroup::iter() .filter_map(|group| (group.parent() == parent_group).then_some(group.scope())) // TODO: Remove this hashset conversion when merhant access // and organization access groups are removed .collect::<HashSet<_>>() .into_iter() .collect(), }) .collect::<Vec<_>>(); Ok(ApplicationResponse::Json(parent_groups)) } pub async fn update_user_role( state: SessionState, user_from_token: auth::UserFromToken, req: user_role_api::UpdateUserRoleRequest, _req_state: ReqState, ) -> UserResponse<()> { let role_info = roles::RoleInfo::from_role_id_in_lineage( &state, &req.role_id, &user_from_token.merchant_id, &user_from_token.org_id, &user_from_token.profile_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .to_not_found_response(UserErrors::InvalidRoleId)?; if !role_info.is_updatable() { return Err(report!(UserErrors::InvalidRoleOperation)) .attach_printable(format!("User role cannot be updated to {}", req.role_id)); } let user_to_be_updated = utils::user::get_user_from_db_by_email(&state, domain::UserEmail::try_from(req.email)?) .await .to_not_found_response(UserErrors::InvalidRoleOperation) .attach_printable("User not found in our records".to_string())?; if user_from_token.user_id == user_to_be_updated.get_user_id() { return Err(report!(UserErrors::InvalidRoleOperation)) .attach_printable("User Changing their own role"); } let updator_role = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; let mut is_updated = false; let v2_user_role_to_be_updated = match state .global_store .find_user_role_by_user_id_and_lineage( user_to_be_updated.get_user_id(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, UserRoleVersion::V2, ) .await { Ok(user_role) => Some(user_role), Err(e) => { if e.current_context().is_db_not_found() { None } else { return Err(UserErrors::InternalServerError.into()); } } }; if let Some(user_role) = v2_user_role_to_be_updated { let role_to_be_updated = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_role.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; if !role_to_be_updated.is_updatable() { return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( "User role cannot be updated from {}", role_to_be_updated.get_role_id() )); } if role_info.get_entity_type() != role_to_be_updated.get_entity_type() { return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( "Upgrade and downgrade of roles is not allowed, user_entity_type = {} req_entity_type = {}", role_to_be_updated.get_entity_type(), role_info.get_entity_type(), )); } if updator_role.get_entity_type() < role_to_be_updated.get_entity_type() { return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( "Invalid operation, update requestor = {} cannot update target = {}", updator_role.get_entity_type(), role_to_be_updated.get_entity_type() )); } state .global_store .update_user_role_by_user_id_and_lineage( user_to_be_updated.get_user_id(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, Some(&user_from_token.merchant_id), Some(&user_from_token.profile_id), UserRoleUpdate::UpdateRole { role_id: req.role_id.clone(), modified_by: user_from_token.user_id.clone(), }, UserRoleVersion::V2, ) .await .change_context(UserErrors::InternalServerError)?; is_updated = true; } let v1_user_role_to_be_updated = match state .global_store .find_user_role_by_user_id_and_lineage( user_to_be_updated.get_user_id(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, UserRoleVersion::V1, ) .await { Ok(user_role) => Some(user_role), Err(e) => { if e.current_context().is_db_not_found() { None } else { return Err(UserErrors::InternalServerError.into()); } } }; if let Some(user_role) = v1_user_role_to_be_updated { let role_to_be_updated = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_role.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; if !role_to_be_updated.is_updatable() { return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( "User role cannot be updated from {}", role_to_be_updated.get_role_id() )); } if role_info.get_entity_type() != role_to_be_updated.get_entity_type() { return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( "Upgrade and downgrade of roles is not allowed, user_entity_type = {} req_entity_type = {}", role_to_be_updated.get_entity_type(), role_info.get_entity_type(), )); } if updator_role.get_entity_type() < role_to_be_updated.get_entity_type() { return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( "Invalid operation, update requestor = {} cannot update target = {}", updator_role.get_entity_type(), role_to_be_updated.get_entity_type() )); } state .global_store .update_user_role_by_user_id_and_lineage( user_to_be_updated.get_user_id(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, Some(&user_from_token.merchant_id), Some(&user_from_token.profile_id), UserRoleUpdate::UpdateRole { role_id: req.role_id.clone(), modified_by: user_from_token.user_id, }, UserRoleVersion::V1, ) .await .change_context(UserErrors::InternalServerError)?; is_updated = true; } if !is_updated { return Err(report!(UserErrors::InvalidRoleOperation)) .attach_printable("User with given email is not found in the organization")?; } auth::blacklist::insert_user_in_blacklist(&state, user_to_be_updated.get_user_id()).await?; Ok(ApplicationResponse::StatusOk) } pub async fn accept_invitations_v2( state: SessionState, user_from_token: auth::UserFromToken, req: user_role_api::AcceptInvitationsV2Request, ) -> UserResponse<()> { let lineages = futures::future::try_join_all(req.into_iter().map(|entity| { utils::user_role::get_lineage_for_user_id_and_entity_for_accepting_invite( &state, &user_from_token.user_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), entity.entity_id, entity.entity_type, ) })) .await? .into_iter() .flatten() .collect::<Vec<_>>(); let update_results = futures::future::join_all(lineages.iter().map( |(org_id, merchant_id, profile_id)| async { let (update_v1_result, update_v2_result) = utils::user_role::update_v1_and_v2_user_roles_in_db( &state, user_from_token.user_id.as_str(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id, merchant_id.as_ref(), profile_id.as_ref(), UserRoleUpdate::UpdateStatus { status: UserStatus::Active, modified_by: user_from_token.user_id.clone(), }, ) .await; if update_v1_result.is_err_and(|err| !err.current_context().is_db_not_found()) || update_v2_result.is_err_and(|err| !err.current_context().is_db_not_found()) { Err(report!(UserErrors::InternalServerError)) } else { Ok(()) } }, )) .await; if update_results.is_empty() || update_results.iter().all(Result::is_err) { return Err(UserErrors::MerchantIdNotFound.into()); } Ok(ApplicationResponse::StatusOk) } pub async fn accept_invitations_pre_auth( state: SessionState, user_token: auth::UserFromSinglePurposeToken, req: user_role_api::AcceptInvitationsPreAuthRequest, ) -> UserResponse<user_api::TokenResponse> { let lineages = futures::future::try_join_all(req.into_iter().map(|entity| { utils::user_role::get_lineage_for_user_id_and_entity_for_accepting_invite( &state, &user_token.user_id, user_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), entity.entity_id, entity.entity_type, ) })) .await? .into_iter() .flatten() .collect::<Vec<_>>(); let update_results = futures::future::join_all(lineages.iter().map( |(org_id, merchant_id, profile_id)| async { let (update_v1_result, update_v2_result) = utils::user_role::update_v1_and_v2_user_roles_in_db( &state, user_token.user_id.as_str(), user_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id, merchant_id.as_ref(), profile_id.as_ref(), UserRoleUpdate::UpdateStatus { status: UserStatus::Active, modified_by: user_token.user_id.clone(), }, ) .await; if update_v1_result.is_err_and(|err| !err.current_context().is_db_not_found()) || update_v2_result.is_err_and(|err| !err.current_context().is_db_not_found()) { Err(report!(UserErrors::InternalServerError)) } else { Ok(()) } }, )) .await; if update_results.is_empty() || update_results.iter().all(Result::is_err) { return Err(UserErrors::MerchantIdNotFound.into()); } let user_from_db: domain::UserFromStorage = state .global_store .find_user_by_id(user_token.user_id.as_str()) .await .change_context(UserErrors::InternalServerError)? .into(); let current_flow = domain::CurrentFlow::new(user_token, domain::SPTFlow::MerchantSelect.into())?; let next_flow = current_flow.next(user_from_db.clone(), &state).await?; let token = next_flow.get_token(&state).await?; let response = user_api::TokenResponse { token: token.clone(), token_type: next_flow.get_flow().into(), }; auth::cookies::set_cookie_response(response, token) } pub async fn delete_user_role( state: SessionState, user_from_token: auth::UserFromToken, request: user_role_api::DeleteUserRoleRequest, _req_state: ReqState, ) -> UserResponse<()> { let user_from_db: domain::UserFromStorage = state .global_store .find_user_by_email(&domain::UserEmail::from_pii_email(request.email)?) .await .map_err(|e| { if e.current_context().is_db_not_found() { e.change_context(UserErrors::InvalidRoleOperation) .attach_printable("User not found in our records") } else { e.change_context(UserErrors::InternalServerError) } })? .into(); if user_from_db.get_user_id() == user_from_token.user_id { return Err(report!(UserErrors::InvalidDeleteOperation)) .attach_printable("User deleting himself"); } let deletion_requestor_role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; let mut user_role_deleted_flag = false; // Find in V2 let user_role_v2 = match state .global_store .find_user_role_by_user_id_and_lineage( user_from_db.get_user_id(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, UserRoleVersion::V2, ) .await { Ok(user_role) => Some(user_role), Err(e) => { if e.current_context().is_db_not_found() { None } else { return Err(UserErrors::InternalServerError.into()); } } }; if let Some(role_to_be_deleted) = user_role_v2 { let target_role_info = roles::RoleInfo::from_role_id_in_lineage( &state, &role_to_be_deleted.role_id, &user_from_token.merchant_id, &user_from_token.org_id, &user_from_token.profile_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; if !target_role_info.is_deletable() { return Err(report!(UserErrors::InvalidDeleteOperation)).attach_printable(format!( "Invalid operation, role_id = {} is not deletable", role_to_be_deleted.role_id )); } if deletion_requestor_role_info.get_entity_type() < target_role_info.get_entity_type() { return Err(report!(UserErrors::InvalidDeleteOperation)).attach_printable(format!( "Invalid operation, deletion requestor = {} cannot delete target = {}", deletion_requestor_role_info.get_entity_type(), target_role_info.get_entity_type() )); } user_role_deleted_flag = true; state .global_store .delete_user_role_by_user_id_and_lineage( user_from_db.get_user_id(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, UserRoleVersion::V2, ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Error while deleting user role")?; } // Find in V1 let user_role_v1 = match state .global_store .find_user_role_by_user_id_and_lineage( user_from_db.get_user_id(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, UserRoleVersion::V1, ) .await { Ok(user_role) => Some(user_role), Err(e) => { if e.current_context().is_db_not_found() { None } else { return Err(UserErrors::InternalServerError.into()); } } }; if let Some(role_to_be_deleted) = user_role_v1 { let target_role_info = roles::RoleInfo::from_role_id_in_lineage( &state, &role_to_be_deleted.role_id, &user_from_token.merchant_id, &user_from_token.org_id, &user_from_token.profile_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; if !target_role_info.is_deletable() { return Err(report!(UserErrors::InvalidDeleteOperation)).attach_printable(format!( "Invalid operation, role_id = {} is not deletable", role_to_be_deleted.role_id )); } if deletion_requestor_role_info.get_entity_type() < target_role_info.get_entity_type() { return Err(report!(UserErrors::InvalidDeleteOperation)).attach_printable(format!( "Invalid operation, deletion requestor = {} cannot delete target = {}", deletion_requestor_role_info.get_entity_type(), target_role_info.get_entity_type() )); } user_role_deleted_flag = true; state .global_store .delete_user_role_by_user_id_and_lineage( user_from_db.get_user_id(), user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, UserRoleVersion::V1, ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Error while deleting user role")?; } if !user_role_deleted_flag { return Err(report!(UserErrors::InvalidDeleteOperation)) .attach_printable("User is not associated with the merchant"); } // Check if user has any more role associations let remaining_roles = state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: user_from_db.get_user_id(), tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: None, merchant_id: None, profile_id: None, entity_id: None, version: None, status: None, limit: None, }) .await .change_context(UserErrors::InternalServerError)?; // If user has no more role associated with him then deleting user if remaining_roles.is_empty() { state .global_store .delete_user_by_user_id(user_from_db.get_user_id()) .await .change_context(UserErrors::InternalServerError) .attach_printable("Error while deleting user entry")?; } auth::blacklist::insert_user_in_blacklist(&state, user_from_db.get_user_id()).await?; Ok(ApplicationResponse::StatusOk) } pub async fn list_users_in_lineage( state: SessionState, user_from_token: auth::UserFromToken, request: user_role_api::ListUsersInEntityRequest, ) -> UserResponse<Vec<user_role_api::ListUsersInEntityResponse>> { let requestor_role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; let user_roles_set: HashSet<_> = match utils::user_role::get_min_entity( requestor_role_info.get_entity_type(), request.entity_type, )? { EntityType::Tenant => { let mut org_users = utils::user_role::fetch_user_roles_by_payload( &state, ListUserRolesByOrgIdPayload { user_id: None, tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: &user_from_token.org_id, merchant_id: None, profile_id: None, version: None, limit: None, }, request.entity_type, ) .await?; // Fetch tenant user let tenant_user = state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: &user_from_token.user_id, tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: None, merchant_id: None, profile_id: None, entity_id: None, version: None, status: None, limit: None, }) .await .change_context(UserErrors::InternalServerError)?; org_users.extend(tenant_user); org_users } EntityType::Organization => { utils::user_role::fetch_user_roles_by_payload( &state, ListUserRolesByOrgIdPayload { user_id: None, tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: &user_from_token.org_id, merchant_id: None, profile_id: None, version: None, limit: None, }, request.entity_type, ) .await? } EntityType::Merchant => { utils::user_role::fetch_user_roles_by_payload( &state, ListUserRolesByOrgIdPayload { user_id: None, tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: &user_from_token.org_id, merchant_id: Some(&user_from_token.merchant_id), profile_id: None, version: None, limit: None, }, request.entity_type, ) .await? } EntityType::Profile => { utils::user_role::fetch_user_roles_by_payload( &state, ListUserRolesByOrgIdPayload { user_id: None, tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: &user_from_token.org_id, merchant_id: Some(&user_from_token.merchant_id), profile_id: Some(&user_from_token.profile_id), version: None, limit: None, }, request.entity_type, ) .await? } }; // This filtering is needed because for org level users in V1, merchant_id is present. // Due to this, we get org level users in merchant level users list. let user_roles_set = user_roles_set .into_iter() .filter_map(|user_role| { let (_entity_id, entity_type) = user_role.get_entity_id_and_type()?; (entity_type <= requestor_role_info.get_entity_type()).then_some(user_role) }) .collect::<HashSet<_>>(); let mut email_map = state .global_store .find_users_by_user_ids( user_roles_set .iter() .map(|user_role| user_role.user_id.clone()) .collect(), ) .await .change_context(UserErrors::InternalServerError)? .into_iter() .map(|user| (user.user_id.clone(), user.email)) .collect::<HashMap<_, _>>(); let role_info_map = futures::future::try_join_all(user_roles_set.iter().map(|user_role| async { roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_role.role_id, &user_from_token.org_id, user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), ) .await .map(|role_info| { ( user_role.role_id.clone(), user_role_api::role::MinimalRoleInfo { role_id: user_role.role_id.clone(), role_name: role_info.get_role_name().to_string(), }, ) }) })) .await .change_context(UserErrors::InternalServerError)? .into_iter() .collect::<HashMap<_, _>>(); let user_role_map = user_roles_set .into_iter() .fold(HashMap::new(), |mut map, user_role| { map.entry(user_role.user_id) .or_insert(Vec::with_capacity(1)) .push(user_role.role_id); map }); Ok(ApplicationResponse::Json( user_role_map .into_iter() .map(|(user_id, role_id_vec)| { Ok::<_, error_stack::Report<UserErrors>>(user_role_api::ListUsersInEntityResponse { email: email_map .remove(&user_id) .ok_or(UserErrors::InternalServerError)?, roles: role_id_vec .into_iter() .map(|role_id| { role_info_map .get(&role_id) .cloned() .ok_or(UserErrors::InternalServerError) }) .collect::<Result<Vec<_>, _>>()?, }) }) .collect::<Result<Vec<_>, _>>()?, )) } pub async fn list_invitations_for_user( state: SessionState, user_from_token: auth::UserIdFromAuth, ) -> UserResponse<Vec<user_role_api::ListInvitationForUserResponse>> { let user_roles = state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: &user_from_token.user_id, tenant_id: user_from_token .tenant_id .as_ref() .unwrap_or(&state.tenant.tenant_id), org_id: None, merchant_id: None, profile_id: None, entity_id: None, version: None, status: Some(UserStatus::InvitationSent), limit: None, }) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to list user roles by user id and invitation sent")? .into_iter() .collect::<HashSet<_>>(); let (org_ids, merchant_ids, profile_ids_with_merchant_ids) = user_roles.iter().try_fold( (Vec::new(), Vec::new(), Vec::new()), |(mut org_ids, mut merchant_ids, mut profile_ids_with_merchant_ids), user_role| { let (_, entity_type) = user_role .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError) .attach_printable("Failed to compute entity id and type")?; match entity_type { EntityType::Tenant => { return Err(report!(UserErrors::InternalServerError)) .attach_printable("Tenant roles are not allowed for this operation"); } EntityType::Organization => org_ids.push( user_role .org_id .clone() .ok_or(UserErrors::InternalServerError)?, ), EntityType::Merchant => merchant_ids.push( user_role .merchant_id .clone() .ok_or(UserErrors::InternalServerError)?, ), EntityType::Profile => profile_ids_with_merchant_ids.push(( user_role .profile_id .clone() .ok_or(UserErrors::InternalServerError)?, user_role .merchant_id .clone() .ok_or(UserErrors::InternalServerError)?, )), } Ok::<_, error_stack::Report<UserErrors>>(( org_ids, merchant_ids, profile_ids_with_merchant_ids, )) }, )?; let org_name_map = futures::future::try_join_all(org_ids.into_iter().map(|org_id| async { let org_name = state .accounts_store .find_organization_by_org_id(&org_id) .await .change_context(UserErrors::InternalServerError)? .get_organization_name() .map(Secret::new); Ok::<_, error_stack::Report<UserErrors>>((org_id, org_name)) })) .await? .into_iter() .collect::<HashMap<_, _>>(); let key_manager_state = &(&state).into(); let merchant_name_map = state .store .list_multiple_merchant_accounts(key_manager_state, merchant_ids) .await .change_context(UserErrors::InternalServerError)? .into_iter() .map(|merchant| { ( merchant.get_id().clone(), merchant .merchant_name .map(|encryptable_name| encryptable_name.into_inner()), ) }) .collect::<HashMap<_, _>>(); let master_key = &state.store.get_master_key().to_vec().into(); let profile_name_map = futures::future::try_join_all(profile_ids_with_merchant_ids.iter().map( |(profile_id, merchant_id)| async { let merchant_key_store = state .store .get_merchant_key_store_by_merchant_id(key_manager_state, merchant_id, master_key) .await .change_context(UserErrors::InternalServerError)?; let business_profile = state .store .find_business_profile_by_profile_id( key_manager_state, &merchant_key_store, profile_id, ) .await .change_context(UserErrors::InternalServerError)?; Ok::<_, error_stack::Report<UserErrors>>(( profile_id.clone(), Secret::new(business_profile.profile_name), )) }, )) .await? .into_iter() .collect::<HashMap<_, _>>(); user_roles .into_iter() .map(|user_role| { let (entity_id, entity_type) = user_role .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError) .attach_printable("Failed to compute entity id and type")?; let entity_name = match entity_type { EntityType::Tenant => { return Err(report!(UserErrors::InternalServerError)) .attach_printable("Tenant roles are not allowed for this operation"); } EntityType::Organization => user_role .org_id .as_ref() .and_then(|org_id| org_name_map.get(org_id).cloned()) .ok_or(UserErrors::InternalServerError)?, EntityType::Merchant => user_role .merchant_id .as_ref() .and_then(|merchant_id| merchant_name_map.get(merchant_id).cloned()) .ok_or(UserErrors::InternalServerError)?, EntityType::Profile => user_role .profile_id .as_ref() .map(|profile_id| profile_name_map.get(profile_id).cloned()) .ok_or(UserErrors::InternalServerError)?, }; Ok(user_role_api::ListInvitationForUserResponse { entity_id, entity_type, entity_name, role_id: user_role.role_id, }) }) .collect::<Result<Vec<_>, _>>() .map(ApplicationResponse::Json) }
7,674
1,579
hyperswitch
crates/router/src/core/verification.rs
.rs
pub mod utils; use api_models::verifications::{self, ApplepayMerchantResponse}; use common_utils::{errors::CustomResult, request::RequestContent}; use error_stack::ResultExt; use masking::ExposeInterface; use crate::{core::errors, headers, logger, routes::SessionState, services}; const APPLEPAY_INTERNAL_MERCHANT_NAME: &str = "Applepay_merchant"; pub async fn verify_merchant_creds_for_applepay( state: SessionState, body: verifications::ApplepayMerchantVerificationRequest, merchant_id: common_utils::id_type::MerchantId, profile_id: Option<common_utils::id_type::ProfileId>, ) -> CustomResult<services::ApplicationResponse<ApplepayMerchantResponse>, errors::ApiErrorResponse> { let applepay_merchant_configs = state.conf.applepay_merchant_configs.get_inner(); let applepay_internal_merchant_identifier = applepay_merchant_configs .common_merchant_identifier .clone() .expose(); let cert_data = applepay_merchant_configs.merchant_cert.clone(); let key_data = applepay_merchant_configs.merchant_cert_key.clone(); let applepay_endpoint = &applepay_merchant_configs.applepay_endpoint; let request_body = verifications::ApplepayMerchantVerificationConfigs { domain_names: body.domain_names.clone(), encrypt_to: applepay_internal_merchant_identifier.clone(), partner_internal_merchant_identifier: applepay_internal_merchant_identifier, partner_merchant_name: APPLEPAY_INTERNAL_MERCHANT_NAME.to_string(), }; let apple_pay_merch_verification_req = services::RequestBuilder::new() .method(services::Method::Post) .url(applepay_endpoint) .attach_default_headers() .headers(vec![( headers::CONTENT_TYPE.to_string(), "application/json".to_string().into(), )]) .set_body(RequestContent::Json(Box::new(request_body))) .add_certificate(Some(cert_data)) .add_certificate_key(Some(key_data)) .build(); let response = services::call_connector_api( &state, apple_pay_merch_verification_req, "verify_merchant_creds_for_applepay", ) .await; utils::log_applepay_verification_response_if_error(&response); let applepay_response = response.change_context(errors::ApiErrorResponse::InternalServerError)?; // Error is already logged match applepay_response { Ok(_) => { utils::check_existence_and_add_domain_to_db( &state, merchant_id, profile_id, body.merchant_connector_account_id.clone(), body.domain_names.clone(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; Ok(services::api::ApplicationResponse::Json( ApplepayMerchantResponse { status_message: "Applepay verification Completed".to_string(), }, )) } Err(error) => { logger::error!(?error); Err(errors::ApiErrorResponse::InvalidRequestData { message: "Applepay verification Failed".to_string(), } .into()) } } } pub async fn get_verified_apple_domains_with_mid_mca_id( state: SessionState, merchant_id: common_utils::id_type::MerchantId, merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, ) -> CustomResult< services::ApplicationResponse<verifications::ApplepayVerifiedDomainsResponse>, errors::ApiErrorResponse, > { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &db.get_master_key().to_vec().into(), ) .await .change_context(errors::ApiErrorResponse::MerchantAccountNotFound)?; #[cfg(feature = "v1")] let verified_domains = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, &merchant_id, &merchant_connector_id, &key_store, ) .await .change_context(errors::ApiErrorResponse::ResourceIdNotFound)? .applepay_verified_domains .unwrap_or_default(); #[cfg(feature = "v2")] let verified_domains = { let _ = merchant_connector_id; let _ = key_store; todo!() }; Ok(services::api::ApplicationResponse::Json( verifications::ApplepayVerifiedDomainsResponse { verified_domains }, )) }
961
1,580
hyperswitch
crates/router/src/core/unified_authentication_service.rs
.rs
pub mod types; pub mod utils; use api_models::payments; use diesel_models::authentication::{Authentication, AuthenticationNew}; use error_stack::ResultExt; use hyperswitch_domain_models::{ errors::api_error_response::ApiErrorResponse, payment_method_data, router_request_types::{ authentication::{MessageCategory, PreAuthenticationData}, unified_authentication_service::{ AuthenticationInfo, PaymentDetails, ServiceSessionIds, TransactionDetails, UasAuthenticationRequestData, UasConfirmationRequestData, UasPostAuthenticationRequestData, UasPreAuthenticationRequestData, }, BrowserInformation, }, types::{ UasAuthenticationRouterData, UasPostAuthenticationRouterData, UasPreAuthenticationRouterData, }, }; use masking::ExposeInterface; use super::{errors::RouterResult, payments::helpers::MerchantConnectorAccountType}; use crate::{ core::{ errors::utils::StorageErrorExt, payments::PaymentData, unified_authentication_service::types::{ ClickToPay, ExternalAuthentication, UnifiedAuthenticationService, UNIFIED_AUTHENTICATION_SERVICE, }, }, db::domain, routes::SessionState, }; #[cfg(feature = "v1")] #[async_trait::async_trait] impl<F: Clone + Sync> UnifiedAuthenticationService<F> for ClickToPay { fn get_pre_authentication_request_data( payment_data: &PaymentData<F>, ) -> RouterResult<UasPreAuthenticationRequestData> { let service_details = hyperswitch_domain_models::router_request_types::unified_authentication_service::CtpServiceDetails { service_session_ids: Some(ServiceSessionIds { merchant_transaction_id: payment_data .service_details .as_ref() .and_then(|details| details.merchant_transaction_id.clone()), correlation_id: payment_data .service_details .as_ref() .and_then(|details| details.correlation_id.clone()), x_src_flow_id: payment_data .service_details .as_ref() .and_then(|details| details.x_src_flow_id.clone()), }), payment_details: None, }; let amount = payment_data.payment_attempt.net_amount.get_order_amount(); let transaction_details = TransactionDetails { amount: Some(amount), currency: payment_data.payment_attempt.currency, device_channel: None, message_category: None, }; let authentication_info = Some(AuthenticationInfo { authentication_type: None, authentication_reasons: None, consent_received: false, // This is not relevant in this flow so keeping it as false is_authenticated: false, // This is not relevant in this flow so keeping it as false locale: None, supported_card_brands: None, encypted_payload: payment_data .service_details .as_ref() .and_then(|details| details.encypted_payload.clone()), }); Ok(UasPreAuthenticationRequestData { service_details: Some(service_details), transaction_details: Some(transaction_details), payment_details: None, authentication_info, }) } async fn pre_authentication( state: &SessionState, _key_store: &domain::MerchantKeyStore, _business_profile: &domain::Profile, payment_data: &PaymentData<F>, merchant_connector_account: &MerchantConnectorAccountType, connector_name: &str, authentication_id: &str, payment_method: common_enums::PaymentMethod, ) -> RouterResult<UasPreAuthenticationRouterData> { let pre_authentication_data = Self::get_pre_authentication_request_data(payment_data)?; let pre_auth_router_data: UasPreAuthenticationRouterData = utils::construct_uas_router_data( state, connector_name.to_string(), payment_method, payment_data.payment_attempt.merchant_id.clone(), None, pre_authentication_data, merchant_connector_account, Some(authentication_id.to_owned()), payment_data.payment_intent.payment_id.clone(), )?; utils::do_auth_connector_call( state, UNIFIED_AUTHENTICATION_SERVICE.to_string(), pre_auth_router_data, ) .await } async fn post_authentication( state: &SessionState, _key_store: &domain::MerchantKeyStore, _business_profile: &domain::Profile, payment_data: &PaymentData<F>, merchant_connector_account: &MerchantConnectorAccountType, connector_name: &str, payment_method: common_enums::PaymentMethod, _authentication: Option<Authentication>, ) -> RouterResult<UasPostAuthenticationRouterData> { let authentication_id = payment_data .payment_attempt .authentication_id .clone() .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("Missing authentication id in payment attempt")?; let post_authentication_data = UasPostAuthenticationRequestData { threeds_server_transaction_id: None, }; let post_auth_router_data: UasPostAuthenticationRouterData = utils::construct_uas_router_data( state, connector_name.to_string(), payment_method, payment_data.payment_attempt.merchant_id.clone(), None, post_authentication_data, merchant_connector_account, Some(authentication_id.clone()), payment_data.payment_intent.payment_id.clone(), )?; utils::do_auth_connector_call( state, UNIFIED_AUTHENTICATION_SERVICE.to_string(), post_auth_router_data, ) .await } async fn confirmation( state: &SessionState, _key_store: &domain::MerchantKeyStore, _business_profile: &domain::Profile, payment_data: &PaymentData<F>, merchant_connector_account: &MerchantConnectorAccountType, connector_name: &str, payment_method: common_enums::PaymentMethod, ) -> RouterResult<()> { let authentication_id = payment_data .payment_attempt .authentication_id .clone() .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("Missing authentication id in payment attempt")?; let currency = payment_data.payment_attempt.currency.ok_or( ApiErrorResponse::MissingRequiredField { field_name: "currency", }, )?; let current_time = common_utils::date_time::now(); let payment_attempt_status = payment_data.payment_attempt.status; let (checkout_event_status, confirmation_reason) = utils::get_checkout_event_status_and_reason(payment_attempt_status); let click_to_pay_details = payment_data.service_details.clone(); let authentication_confirmation_data = UasConfirmationRequestData { x_src_flow_id: payment_data .service_details .as_ref() .and_then(|details| details.x_src_flow_id.clone()), transaction_amount: payment_data.payment_attempt.net_amount.get_order_amount(), transaction_currency: currency, checkout_event_type: Some("01".to_string()), // hardcoded to '01' since only authorise flow is implemented checkout_event_status: checkout_event_status.clone(), confirmation_status: checkout_event_status.clone(), confirmation_reason, confirmation_timestamp: Some(current_time), network_authorization_code: Some("01".to_string()), // hardcoded to '01' since only authorise flow is implemented network_transaction_identifier: Some("01".to_string()), // hardcoded to '01' since only authorise flow is implemented correlation_id: click_to_pay_details .clone() .and_then(|details| details.correlation_id), merchant_transaction_id: click_to_pay_details .and_then(|details| details.merchant_transaction_id), }; let authentication_confirmation_router_data : hyperswitch_domain_models::types::UasAuthenticationConfirmationRouterData = utils::construct_uas_router_data( state, connector_name.to_string(), payment_method, payment_data.payment_attempt.merchant_id.clone(), None, authentication_confirmation_data, merchant_connector_account, Some(authentication_id.clone()), payment_data.payment_intent.payment_id.clone() )?; utils::do_auth_connector_call( state, UNIFIED_AUTHENTICATION_SERVICE.to_string(), authentication_confirmation_router_data, ) .await .ok(); // marking this as .ok() since this is not a required step at our end for completing the transaction Ok(()) } } #[cfg(feature = "v1")] #[async_trait::async_trait] impl<F: Clone + Sync> UnifiedAuthenticationService<F> for ExternalAuthentication { fn get_pre_authentication_request_data( payment_data: &PaymentData<F>, ) -> RouterResult<UasPreAuthenticationRequestData> { let payment_method_data = payment_data .payment_method_data .as_ref() .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("payment_data.payment_method_data is missing")?; let payment_details = if let payment_method_data::PaymentMethodData::Card(card) = payment_method_data { Some(PaymentDetails { pan: card.card_number.clone(), digital_card_id: None, payment_data_type: None, encrypted_src_card_details: None, card_expiry_date: card.card_exp_year.clone(), cardholder_name: card.card_holder_name.clone(), card_token_number: card.card_cvc.clone(), account_type: card.card_network.clone(), }) } else { None }; Ok(UasPreAuthenticationRequestData { service_details: None, transaction_details: None, payment_details, authentication_info: None, }) } #[allow(clippy::too_many_arguments)] async fn pre_authentication( state: &SessionState, _key_store: &domain::MerchantKeyStore, _business_profile: &domain::Profile, payment_data: &PaymentData<F>, merchant_connector_account: &MerchantConnectorAccountType, connector_name: &str, authentication_id: &str, payment_method: common_enums::PaymentMethod, ) -> RouterResult<UasPreAuthenticationRouterData> { let pre_authentication_data = Self::get_pre_authentication_request_data(payment_data)?; let pre_auth_router_data: UasPreAuthenticationRouterData = utils::construct_uas_router_data( state, connector_name.to_string(), payment_method, payment_data.payment_attempt.merchant_id.clone(), None, pre_authentication_data, merchant_connector_account, Some(authentication_id.to_owned()), payment_data.payment_intent.payment_id.clone(), )?; utils::do_auth_connector_call( state, UNIFIED_AUTHENTICATION_SERVICE.to_string(), pre_auth_router_data, ) .await } fn get_authentication_request_data( payment_method_data: domain::PaymentMethodData, billing_address: hyperswitch_domain_models::address::Address, shipping_address: Option<hyperswitch_domain_models::address::Address>, browser_details: Option<BrowserInformation>, amount: Option<common_utils::types::MinorUnit>, currency: Option<common_enums::Currency>, message_category: MessageCategory, device_channel: payments::DeviceChannel, authentication: Authentication, return_url: Option<String>, sdk_information: Option<payments::SdkInformation>, threeds_method_comp_ind: payments::ThreeDsCompletionIndicator, email: Option<common_utils::pii::Email>, webhook_url: String, three_ds_requestor_url: String, ) -> RouterResult<UasAuthenticationRequestData> { Ok(UasAuthenticationRequestData { payment_method_data, billing_address, shipping_address, browser_details, transaction_details: TransactionDetails { amount, currency, device_channel: Some(device_channel), message_category: Some(message_category), }, pre_authentication_data: PreAuthenticationData { threeds_server_transaction_id: authentication.threeds_server_transaction_id.ok_or( ApiErrorResponse::MissingRequiredField { field_name: "authentication.threeds_server_transaction_id", }, )?, message_version: authentication.message_version.ok_or( ApiErrorResponse::MissingRequiredField { field_name: "authentication.message_version", }, )?, acquirer_bin: authentication.acquirer_bin, acquirer_merchant_id: authentication.acquirer_merchant_id, acquirer_country_code: authentication.acquirer_country_code, connector_metadata: authentication.connector_metadata, }, return_url, sdk_information, email, threeds_method_comp_ind, three_ds_requestor_url, webhook_url, }) } #[allow(clippy::too_many_arguments)] async fn authentication( state: &SessionState, business_profile: &domain::Profile, payment_method: common_enums::PaymentMethod, payment_method_data: domain::PaymentMethodData, billing_address: hyperswitch_domain_models::address::Address, shipping_address: Option<hyperswitch_domain_models::address::Address>, browser_details: Option<BrowserInformation>, amount: Option<common_utils::types::MinorUnit>, currency: Option<common_enums::Currency>, message_category: MessageCategory, device_channel: payments::DeviceChannel, authentication: Authentication, return_url: Option<String>, sdk_information: Option<payments::SdkInformation>, threeds_method_comp_ind: payments::ThreeDsCompletionIndicator, email: Option<common_utils::pii::Email>, webhook_url: String, three_ds_requestor_url: String, merchant_connector_account: &MerchantConnectorAccountType, connector_name: &str, payment_id: common_utils::id_type::PaymentId, ) -> RouterResult<UasAuthenticationRouterData> { let authentication_data = <Self as UnifiedAuthenticationService<F>>::get_authentication_request_data( payment_method_data, billing_address, shipping_address, browser_details, amount, currency, message_category, device_channel, authentication.clone(), return_url, sdk_information, threeds_method_comp_ind, email, webhook_url, three_ds_requestor_url, )?; let auth_router_data: UasAuthenticationRouterData = utils::construct_uas_router_data( state, connector_name.to_string(), payment_method, business_profile.merchant_id.clone(), None, authentication_data, merchant_connector_account, Some(authentication.authentication_id.to_owned()), payment_id, )?; Box::pin(utils::do_auth_connector_call( state, UNIFIED_AUTHENTICATION_SERVICE.to_string(), auth_router_data, )) .await } fn get_post_authentication_request_data( authentication: Option<Authentication>, ) -> RouterResult<UasPostAuthenticationRequestData> { Ok(UasPostAuthenticationRequestData { // authentication.threeds_server_transaction_id is mandatory for post-authentication in ExternalAuthentication threeds_server_transaction_id: Some( authentication .and_then(|auth| auth.threeds_server_transaction_id) .ok_or(ApiErrorResponse::MissingRequiredField { field_name: "authentication.threeds_server_transaction_id", })?, ), }) } async fn post_authentication( state: &SessionState, _key_store: &domain::MerchantKeyStore, business_profile: &domain::Profile, payment_data: &PaymentData<F>, merchant_connector_account: &MerchantConnectorAccountType, connector_name: &str, payment_method: common_enums::PaymentMethod, authentication: Option<Authentication>, ) -> RouterResult<UasPostAuthenticationRouterData> { let authentication_data = <Self as UnifiedAuthenticationService<F>>::get_post_authentication_request_data( authentication.clone(), )?; let auth_router_data: UasPostAuthenticationRouterData = utils::construct_uas_router_data( state, connector_name.to_string(), payment_method, business_profile.merchant_id.clone(), None, authentication_data, merchant_connector_account, authentication.map(|auth| auth.authentication_id), payment_data.payment_intent.payment_id.clone(), )?; utils::do_auth_connector_call( state, UNIFIED_AUTHENTICATION_SERVICE.to_string(), auth_router_data, ) .await } } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[allow(clippy::too_many_arguments)] pub async fn create_new_authentication( state: &SessionState, merchant_id: common_utils::id_type::MerchantId, authentication_connector: String, profile_id: common_utils::id_type::ProfileId, payment_id: Option<common_utils::id_type::PaymentId>, merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, authentication_id: &str, service_details: Option<payments::CtpServiceDetails>, authentication_status: common_enums::AuthenticationStatus, network_token: Option<payment_method_data::NetworkTokenData>, organization_id: common_utils::id_type::OrganizationId, ) -> RouterResult<Authentication> { let service_details_value = service_details .map(serde_json::to_value) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable( "unable to parse service details into json value while inserting to DB", )?; let new_authorization = AuthenticationNew { authentication_id: authentication_id.to_owned(), merchant_id, authentication_connector, connector_authentication_id: None, payment_method_id: "".to_string(), authentication_type: None, authentication_status, authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus::Unused, error_message: None, error_code: None, connector_metadata: None, maximum_supported_version: None, threeds_server_transaction_id: None, cavv: network_token .clone() .and_then(|data| data.token_cryptogram.map(|cavv| cavv.expose())), authentication_flow_type: None, message_version: None, eci: network_token.and_then(|data| data.eci), trans_status: None, acquirer_bin: None, acquirer_merchant_id: None, three_ds_method_data: None, three_ds_method_url: None, acs_url: None, challenge_request: None, acs_reference_number: None, acs_trans_id: None, acs_signed_content: None, profile_id, payment_id, merchant_connector_id, ds_trans_id: None, directory_server_id: None, acquirer_country_code: None, service_details: service_details_value, organization_id, }; state .store .insert_authentication(new_authorization) .await .to_duplicate_response(ApiErrorResponse::GenericDuplicateError { message: format!( "Authentication with authentication_id {} already exists", authentication_id ), }) }
3,975
1,581
hyperswitch
crates/router/src/core/surcharge_decision_config.rs
.rs
use api_models::surcharge_decision_configs::{ SurchargeDecisionConfigReq, SurchargeDecisionManagerRecord, SurchargeDecisionManagerResponse, }; use common_utils::ext_traits::StringExt; use error_stack::ResultExt; use crate::{ core::errors::{self, RouterResponse}, routes::SessionState, services::api as service_api, types::domain, }; #[cfg(feature = "v1")] pub async fn upsert_surcharge_decision_config( state: SessionState, key_store: domain::MerchantKeyStore, merchant_account: domain::MerchantAccount, request: SurchargeDecisionConfigReq, ) -> RouterResponse<SurchargeDecisionManagerRecord> { use common_utils::ext_traits::{Encode, OptionExt, ValueExt}; use diesel_models::configs; use storage_impl::redis::cache; use super::routing::helpers::update_merchant_active_algorithm_ref; let db = state.store.as_ref(); let name = request.name; let program = request .algorithm .get_required_value("algorithm") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "algorithm", }) .attach_printable("Program for config not given")?; let merchant_surcharge_configs = request.merchant_surcharge_configs; let timestamp = common_utils::date_time::now_unix_timestamp(); let mut algo_id: api_models::routing::RoutingAlgorithmRef = merchant_account .routing_algorithm .clone() .map(|val| val.parse_value("routing algorithm")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not decode the routing algorithm")? .unwrap_or_default(); let key = merchant_account .get_id() .get_payment_method_surcharge_routing_id(); let read_config_key = db.find_config_by_key(&key).await; euclid::frontend::ast::lowering::lower_program(program.clone()) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid Request Data".to_string(), }) .attach_printable("The Request has an Invalid Comparison")?; let surcharge_cache_key = merchant_account.get_id().get_surcharge_dsk_key(); match read_config_key { Ok(config) => { let previous_record: SurchargeDecisionManagerRecord = config .config .parse_struct("SurchargeDecisionManagerRecord") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("The Payment Config Key Not Found")?; let new_algo = SurchargeDecisionManagerRecord { name: name.unwrap_or(previous_record.name), algorithm: program, modified_at: timestamp, created_at: previous_record.created_at, merchant_surcharge_configs, }; let serialize_updated_str = new_algo .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to serialize config to string")?; let updated_config = configs::ConfigUpdate::Update { config: Some(serialize_updated_str), }; db.update_config_by_key(&key, updated_config) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error serializing the config")?; algo_id.update_surcharge_config_id(key.clone()); let config_key = cache::CacheKind::Surcharge(surcharge_cache_key.into()); update_merchant_active_algorithm_ref(&state, &key_store, config_key, algo_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update routing algorithm ref")?; Ok(service_api::ApplicationResponse::Json(new_algo)) } Err(e) if e.current_context().is_db_not_found() => { let new_rec = SurchargeDecisionManagerRecord { name: name .get_required_value("name") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "name", }) .attach_printable("name of the config not found")?, algorithm: program, merchant_surcharge_configs, modified_at: timestamp, created_at: timestamp, }; let serialized_str = new_rec .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error serializing the config")?; let new_config = configs::ConfigNew { key: key.clone(), config: serialized_str, }; db.insert_config(new_config) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error fetching the config")?; algo_id.update_surcharge_config_id(key.clone()); let config_key = cache::CacheKind::Surcharge(surcharge_cache_key.into()); update_merchant_active_algorithm_ref(&state, &key_store, config_key, algo_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update routing algorithm ref")?; Ok(service_api::ApplicationResponse::Json(new_rec)) } Err(e) => Err(e) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error fetching payment config"), } } #[cfg(feature = "v2")] pub async fn upsert_surcharge_decision_config( _state: SessionState, _key_store: domain::MerchantKeyStore, _merchant_account: domain::MerchantAccount, _request: SurchargeDecisionConfigReq, ) -> RouterResponse<SurchargeDecisionManagerRecord> { todo!(); } #[cfg(feature = "v1")] pub async fn delete_surcharge_decision_config( state: SessionState, key_store: domain::MerchantKeyStore, merchant_account: domain::MerchantAccount, ) -> RouterResponse<()> { use common_utils::ext_traits::ValueExt; use storage_impl::redis::cache; use super::routing::helpers::update_merchant_active_algorithm_ref; let db = state.store.as_ref(); let key = merchant_account .get_id() .get_payment_method_surcharge_routing_id(); let mut algo_id: api_models::routing::RoutingAlgorithmRef = merchant_account .routing_algorithm .clone() .map(|value| value.parse_value("routing algorithm")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not decode the surcharge conditional_config algorithm")? .unwrap_or_default(); algo_id.surcharge_config_algo_id = None; let surcharge_cache_key = merchant_account.get_id().get_surcharge_dsk_key(); let config_key = cache::CacheKind::Surcharge(surcharge_cache_key.into()); update_merchant_active_algorithm_ref(&state, &key_store, config_key, algo_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update deleted algorithm ref")?; db.delete_config_by_key(&key) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to delete routing config from DB")?; Ok(service_api::ApplicationResponse::StatusOk) } #[cfg(feature = "v2")] pub async fn delete_surcharge_decision_config( _state: SessionState, _key_store: domain::MerchantKeyStore, _merchant_account: domain::MerchantAccount, ) -> RouterResponse<()> { todo!() } pub async fn retrieve_surcharge_decision_config( state: SessionState, merchant_account: domain::MerchantAccount, ) -> RouterResponse<SurchargeDecisionManagerResponse> { let db = state.store.as_ref(); let algorithm_id = merchant_account .get_id() .get_payment_method_surcharge_routing_id(); let algo_config = db .find_config_by_key(&algorithm_id) .await .change_context(errors::ApiErrorResponse::ResourceIdNotFound) .attach_printable("The surcharge conditional config was not found in the DB")?; let record: SurchargeDecisionManagerRecord = algo_config .config .parse_struct("SurchargeDecisionConfigsRecord") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("The Surcharge Decision Config Record was not found")?; Ok(service_api::ApplicationResponse::Json(record)) }
1,771
1,582
hyperswitch
crates/router/src/core/payment_methods.rs
.rs
pub mod cards; #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] pub mod migration; pub mod network_tokenization; pub mod surcharge_decision_configs; #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] pub mod tokenize; pub mod transformers; pub mod utils; mod validator; pub mod vault; use std::borrow::Cow; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use std::collections::HashSet; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] use std::str::FromStr; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub use api_models::enums as api_enums; pub use api_models::enums::Connector; use api_models::payment_methods; #[cfg(feature = "payouts")] pub use api_models::{enums::PayoutConnectors, payouts as payout_types}; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use common_utils::ext_traits::{Encode, OptionExt}; use common_utils::{consts::DEFAULT_LOCALE, id_type}; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] use common_utils::{ crypto::Encryptable, errors::CustomResult, ext_traits::{AsyncExt, Encode, ValueExt}, fp_utils::when, generate_id, types as util_types, }; use diesel_models::{ enums, GenericLinkNew, PaymentMethodCollectLink, PaymentMethodCollectLinkData, }; use error_stack::{report, ResultExt}; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use hyperswitch_domain_models::api::{GenericLinks, GenericLinksData}; #[cfg(all( feature = "v2", feature = "payment_methods_v2", feature = "customer_v2" ))] use hyperswitch_domain_models::mandates::CommonMandateReference; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] use hyperswitch_domain_models::payment_method_data; use hyperswitch_domain_models::payments::{ payment_attempt::PaymentAttempt, PaymentIntent, VaultData, }; use masking::{PeekInterface, Secret}; use router_env::{instrument, tracing}; use time::Duration; #[cfg(feature = "v2")] use super::payments::tokenization; use super::{ errors::{RouterResponse, StorageErrorExt}, pm_auth, }; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] use crate::{ configs::settings, core::{payment_methods::transformers as pm_transforms, payments as payments_core}, db::errors::ConnectorErrorExt, headers, logger, routes::{self, payment_methods as pm_routes}, services::encryption, types::{ self, api::{self, payment_methods::PaymentMethodCreateExt}, domain::types as domain_types, payment_methods as pm_types, storage::{ephemeral_key, PaymentMethodListContext}, transformers::{ForeignFrom, ForeignTryFrom}, Tokenizable, }, utils::ext_traits::OptionExt, }; use crate::{ consts, core::{ errors::{ProcessTrackerError, RouterResult}, payments::helpers as payment_helpers, }, errors, routes::{app::StorageInterface, SessionState}, services, types::{ domain, storage::{self, enums as storage_enums}, }, }; const PAYMENT_METHOD_STATUS_UPDATE_TASK: &str = "PAYMENT_METHOD_STATUS_UPDATE"; const PAYMENT_METHOD_STATUS_TAG: &str = "PAYMENT_METHOD_STATUS"; #[instrument(skip_all)] pub async fn retrieve_payment_method_core( pm_data: &Option<domain::PaymentMethodData>, state: &SessionState, payment_intent: &PaymentIntent, payment_attempt: &PaymentAttempt, merchant_key_store: &domain::MerchantKeyStore, business_profile: Option<&domain::Profile>, ) -> RouterResult<(Option<domain::PaymentMethodData>, Option<String>)> { match pm_data { pm_opt @ Some(pm @ domain::PaymentMethodData::Card(_)) => { let payment_token = payment_helpers::store_payment_method_data_in_vault( state, payment_attempt, payment_intent, enums::PaymentMethod::Card, pm, merchant_key_store, business_profile, ) .await?; Ok((pm_opt.to_owned(), payment_token)) } pm_opt @ Some(pm @ domain::PaymentMethodData::BankDebit(_)) => { let payment_token = payment_helpers::store_payment_method_data_in_vault( state, payment_attempt, payment_intent, enums::PaymentMethod::BankDebit, pm, merchant_key_store, business_profile, ) .await?; Ok((pm_opt.to_owned(), payment_token)) } pm @ Some(domain::PaymentMethodData::PayLater(_)) => Ok((pm.to_owned(), None)), pm @ Some(domain::PaymentMethodData::Crypto(_)) => Ok((pm.to_owned(), None)), pm @ Some(domain::PaymentMethodData::Upi(_)) => Ok((pm.to_owned(), None)), pm @ Some(domain::PaymentMethodData::Voucher(_)) => Ok((pm.to_owned(), None)), pm @ Some(domain::PaymentMethodData::Reward) => Ok((pm.to_owned(), None)), pm @ Some(domain::PaymentMethodData::RealTimePayment(_)) => Ok((pm.to_owned(), None)), pm @ Some(domain::PaymentMethodData::CardRedirect(_)) => Ok((pm.to_owned(), None)), pm @ Some(domain::PaymentMethodData::GiftCard(_)) => Ok((pm.to_owned(), None)), pm @ Some(domain::PaymentMethodData::OpenBanking(_)) => Ok((pm.to_owned(), None)), pm @ Some(domain::PaymentMethodData::MobilePayment(_)) => Ok((pm.to_owned(), None)), pm @ Some(domain::PaymentMethodData::NetworkToken(_)) => Ok((pm.to_owned(), None)), pm_opt @ Some(pm @ domain::PaymentMethodData::BankTransfer(_)) => { let payment_token = payment_helpers::store_payment_method_data_in_vault( state, payment_attempt, payment_intent, enums::PaymentMethod::BankTransfer, pm, merchant_key_store, business_profile, ) .await?; Ok((pm_opt.to_owned(), payment_token)) } pm_opt @ Some(pm @ domain::PaymentMethodData::Wallet(_)) => { let payment_token = payment_helpers::store_payment_method_data_in_vault( state, payment_attempt, payment_intent, enums::PaymentMethod::Wallet, pm, merchant_key_store, business_profile, ) .await?; Ok((pm_opt.to_owned(), payment_token)) } pm_opt @ Some(pm @ domain::PaymentMethodData::BankRedirect(_)) => { let payment_token = payment_helpers::store_payment_method_data_in_vault( state, payment_attempt, payment_intent, enums::PaymentMethod::BankRedirect, pm, merchant_key_store, business_profile, ) .await?; Ok((pm_opt.to_owned(), payment_token)) } _ => Ok((None, None)), } } pub async fn initiate_pm_collect_link( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: payment_methods::PaymentMethodCollectLinkRequest, ) -> RouterResponse<payment_methods::PaymentMethodCollectLinkResponse> { // Validate request and initiate flow let pm_collect_link_data = validator::validate_request_and_initiate_payment_method_collect_link( &state, &merchant_account, &key_store, &req, ) .await?; // Create DB entrie let pm_collect_link = create_pm_collect_db_entry( &state, &merchant_account, &pm_collect_link_data, req.return_url.clone(), ) .await?; let customer_id = id_type::CustomerId::try_from(Cow::from(pm_collect_link.primary_reference)) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "customer_id", })?; // Return response let url = pm_collect_link.url.peek(); let response = payment_methods::PaymentMethodCollectLinkResponse { pm_collect_link_id: pm_collect_link.link_id, customer_id, expiry: pm_collect_link.expiry, link: url::Url::parse(url) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!("Failed to parse the payment method collect link - {}", url) })? .into(), return_url: pm_collect_link.return_url, ui_config: pm_collect_link.link_data.ui_config, enabled_payment_methods: pm_collect_link.link_data.enabled_payment_methods, }; Ok(services::ApplicationResponse::Json(response)) } pub async fn create_pm_collect_db_entry( state: &SessionState, merchant_account: &domain::MerchantAccount, pm_collect_link_data: &PaymentMethodCollectLinkData, return_url: Option<String>, ) -> RouterResult<PaymentMethodCollectLink> { let db: &dyn StorageInterface = &*state.store; let link_data = serde_json::to_value(pm_collect_link_data) .map_err(|_| report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable("Failed to convert PaymentMethodCollectLinkData to Value")?; let pm_collect_link = GenericLinkNew { link_id: pm_collect_link_data.pm_collect_link_id.to_string(), primary_reference: pm_collect_link_data .customer_id .get_string_repr() .to_string(), merchant_id: merchant_account.get_id().to_owned(), link_type: common_enums::GenericLinkType::PaymentMethodCollect, link_data, url: pm_collect_link_data.link.clone(), return_url, expiry: common_utils::date_time::now() + Duration::seconds(pm_collect_link_data.session_expiry.into()), ..Default::default() }; db.insert_pm_collect_link(pm_collect_link) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: "payment method collect link already exists".to_string(), }) } #[cfg(all(feature = "v2", feature = "customer_v2"))] pub async fn render_pm_collect_link( _state: SessionState, _merchant_account: domain::MerchantAccount, _key_store: domain::MerchantKeyStore, _req: payment_methods::PaymentMethodCollectLinkRenderRequest, ) -> RouterResponse<services::GenericLinkFormData> { todo!() } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] pub async fn render_pm_collect_link( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: payment_methods::PaymentMethodCollectLinkRenderRequest, ) -> RouterResponse<services::GenericLinkFormData> { let db: &dyn StorageInterface = &*state.store; // Fetch pm collect link let pm_collect_link = db .find_pm_collect_link_by_link_id(&req.pm_collect_link_id) .await .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { message: "payment method collect link not found".to_string(), })?; // Check status and return form data accordingly let has_expired = common_utils::date_time::now() > pm_collect_link.expiry; let status = pm_collect_link.link_status; let link_data = pm_collect_link.link_data; let default_config = &state.conf.generic_link.payment_method_collect; let default_ui_config = default_config.ui_config.clone(); let ui_config_data = common_utils::link_utils::GenericLinkUiConfigFormData { merchant_name: link_data .ui_config .merchant_name .unwrap_or(default_ui_config.merchant_name), logo: link_data.ui_config.logo.unwrap_or(default_ui_config.logo), theme: link_data .ui_config .theme .clone() .unwrap_or(default_ui_config.theme.clone()), }; match status { common_utils::link_utils::PaymentMethodCollectStatus::Initiated => { // if expired, send back expired status page if has_expired { let expired_link_data = services::GenericExpiredLinkData { title: "Payment collect link has expired".to_string(), message: "This payment collect link has expired.".to_string(), theme: link_data.ui_config.theme.unwrap_or(default_ui_config.theme), }; Ok(services::ApplicationResponse::GenericLinkForm(Box::new( GenericLinks { allowed_domains: HashSet::from([]), data: GenericLinksData::ExpiredLink(expired_link_data), locale: DEFAULT_LOCALE.to_string(), }, ))) // else, send back form link } else { let customer_id = id_type::CustomerId::try_from(Cow::from( pm_collect_link.primary_reference.clone(), )) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "customer_id", })?; // Fetch customer let customer = db .find_customer_by_customer_id_merchant_id( &(&state).into(), &customer_id, &req.merchant_id, &key_store, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InvalidRequestData { message: format!( "Customer [{}] not found for link_id - {}", pm_collect_link.primary_reference, pm_collect_link.link_id ), }) .attach_printable(format!( "customer [{}] not found", pm_collect_link.primary_reference ))?; let js_data = payment_methods::PaymentMethodCollectLinkDetails { publishable_key: Secret::new(merchant_account.publishable_key), client_secret: link_data.client_secret.clone(), pm_collect_link_id: pm_collect_link.link_id, customer_id: customer.customer_id, session_expiry: pm_collect_link.expiry, return_url: pm_collect_link.return_url, ui_config: ui_config_data, enabled_payment_methods: link_data.enabled_payment_methods, }; let serialized_css_content = String::new(); let serialized_js_content = format!( "window.__PM_COLLECT_DETAILS = {}", js_data .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize PaymentMethodCollectLinkDetails")? ); let generic_form_data = services::GenericLinkFormData { js_data: serialized_js_content, css_data: serialized_css_content, sdk_url: default_config.sdk_url.to_string(), html_meta_tags: String::new(), }; Ok(services::ApplicationResponse::GenericLinkForm(Box::new( GenericLinks { allowed_domains: HashSet::from([]), data: GenericLinksData::PaymentMethodCollect(generic_form_data), locale: DEFAULT_LOCALE.to_string(), }, ))) } } // Send back status page status => { let js_data = payment_methods::PaymentMethodCollectLinkStatusDetails { pm_collect_link_id: pm_collect_link.link_id, customer_id: link_data.customer_id, session_expiry: pm_collect_link.expiry, return_url: pm_collect_link .return_url .as_ref() .map(|url| url::Url::parse(url)) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to parse return URL for payment method collect's status link", )?, ui_config: ui_config_data, status, }; let serialized_css_content = String::new(); let serialized_js_content = format!( "window.__PM_COLLECT_DETAILS = {}", js_data .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to serialize PaymentMethodCollectLinkStatusDetails" )? ); let generic_status_data = services::GenericLinkStatusData { js_data: serialized_js_content, css_data: serialized_css_content, }; Ok(services::ApplicationResponse::GenericLinkForm(Box::new( GenericLinks { allowed_domains: HashSet::from([]), data: GenericLinksData::PaymentMethodCollectStatus(generic_status_data), locale: DEFAULT_LOCALE.to_string(), }, ))) } } } fn generate_task_id_for_payment_method_status_update_workflow( key_id: &str, runner: storage::ProcessTrackerRunner, task: &str, ) -> String { format!("{runner}_{task}_{key_id}") } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] pub async fn add_payment_method_status_update_task( db: &dyn StorageInterface, payment_method: &domain::PaymentMethod, prev_status: enums::PaymentMethodStatus, curr_status: enums::PaymentMethodStatus, merchant_id: &id_type::MerchantId, ) -> Result<(), ProcessTrackerError> { let created_at = payment_method.created_at; let schedule_time = created_at.saturating_add(Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)); let tracking_data = storage::PaymentMethodStatusTrackingData { payment_method_id: payment_method.get_id().clone(), prev_status, curr_status, merchant_id: merchant_id.to_owned(), }; let runner = storage::ProcessTrackerRunner::PaymentMethodStatusUpdateWorkflow; let task = PAYMENT_METHOD_STATUS_UPDATE_TASK; let tag = [PAYMENT_METHOD_STATUS_TAG]; let process_tracker_id = generate_task_id_for_payment_method_status_update_workflow( payment_method.get_id().as_str(), runner, task, ); let process_tracker_entry = storage::ProcessTrackerNew::new( process_tracker_id, task, runner, tag, tracking_data, None, schedule_time, common_types::consts::API_VERSION, ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct PAYMENT_METHOD_STATUS_UPDATE process tracker task")?; db .insert_process(process_tracker_entry) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed while inserting PAYMENT_METHOD_STATUS_UPDATE reminder to process_tracker for payment_method_id: {}", payment_method.get_id().clone() ) })?; Ok(()) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn retrieve_payment_method_with_token( _state: &SessionState, _merchant_key_store: &domain::MerchantKeyStore, _token_data: &storage::PaymentTokenData, _payment_intent: &PaymentIntent, _card_token_data: Option<&domain::CardToken>, _customer: &Option<domain::Customer>, _storage_scheme: common_enums::enums::MerchantStorageScheme, _mandate_id: Option<api_models::payments::MandateIds>, _payment_method_info: Option<domain::PaymentMethod>, _business_profile: &domain::Profile, ) -> RouterResult<storage::PaymentMethodDataWithId> { todo!() } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn retrieve_payment_method_with_token( state: &SessionState, merchant_key_store: &domain::MerchantKeyStore, token_data: &storage::PaymentTokenData, payment_intent: &PaymentIntent, payment_attempt: &PaymentAttempt, card_token_data: Option<&domain::CardToken>, customer: &Option<domain::Customer>, storage_scheme: common_enums::enums::MerchantStorageScheme, mandate_id: Option<api_models::payments::MandateIds>, payment_method_info: Option<domain::PaymentMethod>, business_profile: &domain::Profile, should_retry_with_pan: bool, vault_data: Option<&VaultData>, ) -> RouterResult<storage::PaymentMethodDataWithId> { let token = match token_data { storage::PaymentTokenData::TemporaryGeneric(generic_token) => { payment_helpers::retrieve_payment_method_with_temporary_token( state, &generic_token.token, payment_intent, payment_attempt, merchant_key_store, card_token_data, ) .await? .map( |(payment_method_data, payment_method)| storage::PaymentMethodDataWithId { payment_method_data: Some(payment_method_data), payment_method: Some(payment_method), payment_method_id: None, }, ) .unwrap_or_default() } storage::PaymentTokenData::Temporary(generic_token) => { payment_helpers::retrieve_payment_method_with_temporary_token( state, &generic_token.token, payment_intent, payment_attempt, merchant_key_store, card_token_data, ) .await? .map( |(payment_method_data, payment_method)| storage::PaymentMethodDataWithId { payment_method_data: Some(payment_method_data), payment_method: Some(payment_method), payment_method_id: None, }, ) .unwrap_or_default() } storage::PaymentTokenData::Permanent(card_token) => { payment_helpers::retrieve_payment_method_data_with_permanent_token( state, card_token.locker_id.as_ref().unwrap_or(&card_token.token), card_token .payment_method_id .as_ref() .unwrap_or(&card_token.token), payment_intent, card_token_data, merchant_key_store, storage_scheme, mandate_id, payment_method_info .get_required_value("PaymentMethod") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("PaymentMethod not found")?, business_profile, payment_attempt.connector.clone(), should_retry_with_pan, vault_data, ) .await .map(|card| Some((card, enums::PaymentMethod::Card)))? .map( |(payment_method_data, payment_method)| storage::PaymentMethodDataWithId { payment_method_data: Some(payment_method_data), payment_method: Some(payment_method), payment_method_id: Some( card_token .payment_method_id .as_ref() .unwrap_or(&card_token.token) .to_string(), ), }, ) .unwrap_or_default() } storage::PaymentTokenData::PermanentCard(card_token) => { payment_helpers::retrieve_payment_method_data_with_permanent_token( state, card_token.locker_id.as_ref().unwrap_or(&card_token.token), card_token .payment_method_id .as_ref() .unwrap_or(&card_token.token), payment_intent, card_token_data, merchant_key_store, storage_scheme, mandate_id, payment_method_info .get_required_value("PaymentMethod") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("PaymentMethod not found")?, business_profile, payment_attempt.connector.clone(), should_retry_with_pan, vault_data, ) .await .map(|card| Some((card, enums::PaymentMethod::Card)))? .map( |(payment_method_data, payment_method)| storage::PaymentMethodDataWithId { payment_method_data: Some(payment_method_data), payment_method: Some(payment_method), payment_method_id: Some( card_token .payment_method_id .as_ref() .unwrap_or(&card_token.token) .to_string(), ), }, ) .unwrap_or_default() } storage::PaymentTokenData::AuthBankDebit(auth_token) => { pm_auth::retrieve_payment_method_from_auth_service( state, merchant_key_store, auth_token, payment_intent, customer, ) .await? .map( |(payment_method_data, payment_method)| storage::PaymentMethodDataWithId { payment_method_data: Some(payment_method_data), payment_method: Some(payment_method), payment_method_id: None, }, ) .unwrap_or_default() } storage::PaymentTokenData::WalletToken(_) => storage::PaymentMethodDataWithId { payment_method: None, payment_method_data: None, payment_method_id: None, }, }; Ok(token) } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[instrument(skip_all)] pub(crate) fn get_payment_method_create_request( payment_method_data: &api_models::payments::PaymentMethodData, payment_method_type: storage_enums::PaymentMethod, payment_method_subtype: storage_enums::PaymentMethodType, customer_id: id_type::GlobalCustomerId, billing_address: Option<&api_models::payments::Address>, payment_method_session: Option<&domain::payment_methods::PaymentMethodSession>, ) -> RouterResult<payment_methods::PaymentMethodCreate> { match payment_method_data { api_models::payments::PaymentMethodData::Card(card) => { let card_detail = payment_methods::CardDetail { card_number: card.card_number.clone(), card_exp_month: card.card_exp_month.clone(), card_exp_year: card.card_exp_year.clone(), card_holder_name: card.card_holder_name.clone(), nick_name: card.nick_name.clone(), card_issuing_country: card .card_issuing_country .as_ref() .map(|c| api_enums::CountryAlpha2::from_str(c)) .transpose() .ok() .flatten(), card_network: card.card_network.clone(), card_issuer: card.card_issuer.clone(), card_type: card .card_type .as_ref() .map(|c| payment_methods::CardType::from_str(c)) .transpose() .ok() .flatten(), card_cvc: Some(card.card_cvc.clone()), }; let payment_method_request = payment_methods::PaymentMethodCreate { payment_method_type, payment_method_subtype, metadata: None, customer_id: customer_id.clone(), payment_method_data: payment_methods::PaymentMethodCreateData::Card(card_detail), billing: billing_address.map(ToOwned::to_owned), psp_tokenization: payment_method_session .and_then(|pm_session| pm_session.psp_tokenization.clone()), network_tokenization: payment_method_session .and_then(|pm_session| pm_session.network_tokenization.clone()), }; Ok(payment_method_request) } _ => Err(report!(errors::ApiErrorResponse::UnprocessableEntity { message: "only card payment methods are supported for tokenization".to_string() }) .attach_printable("Payment method data is incorrect")), } } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[instrument(skip_all)] pub(crate) async fn get_payment_method_create_request( payment_method_data: Option<&domain::PaymentMethodData>, payment_method: Option<storage_enums::PaymentMethod>, payment_method_type: Option<storage_enums::PaymentMethodType>, customer_id: &Option<id_type::CustomerId>, billing_name: Option<Secret<String>>, payment_method_billing_address: Option<&hyperswitch_domain_models::address::Address>, ) -> RouterResult<payment_methods::PaymentMethodCreate> { match payment_method_data { Some(pm_data) => match payment_method { Some(payment_method) => match pm_data { domain::PaymentMethodData::Card(card) => { let card_detail = payment_methods::CardDetail { card_number: card.card_number.clone(), card_exp_month: card.card_exp_month.clone(), card_exp_year: card.card_exp_year.clone(), card_holder_name: billing_name, nick_name: card.nick_name.clone(), card_issuing_country: card.card_issuing_country.clone(), card_network: card.card_network.clone(), card_issuer: card.card_issuer.clone(), card_type: card.card_type.clone(), }; let payment_method_request = payment_methods::PaymentMethodCreate { payment_method: Some(payment_method), payment_method_type, payment_method_issuer: card.card_issuer.clone(), payment_method_issuer_code: None, #[cfg(feature = "payouts")] bank_transfer: None, #[cfg(feature = "payouts")] wallet: None, card: Some(card_detail), metadata: None, customer_id: customer_id.clone(), card_network: card .card_network .as_ref() .map(|card_network| card_network.to_string()), client_secret: None, payment_method_data: None, //TODO: why are we using api model in router internally billing: payment_method_billing_address.cloned().map(From::from), connector_mandate_details: None, network_transaction_id: None, }; Ok(payment_method_request) } _ => { let payment_method_request = payment_methods::PaymentMethodCreate { payment_method: Some(payment_method), payment_method_type, payment_method_issuer: None, payment_method_issuer_code: None, #[cfg(feature = "payouts")] bank_transfer: None, #[cfg(feature = "payouts")] wallet: None, card: None, metadata: None, customer_id: customer_id.clone(), card_network: None, client_secret: None, payment_method_data: None, billing: None, connector_mandate_details: None, network_transaction_id: None, }; Ok(payment_method_request) } }, None => Err(report!(errors::ApiErrorResponse::MissingRequiredField { field_name: "payment_method_type" }) .attach_printable("PaymentMethodType Required")), }, None => Err(report!(errors::ApiErrorResponse::MissingRequiredField { field_name: "payment_method_data" }) .attach_printable("PaymentMethodData required Or Card is already saved")), } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[instrument(skip_all)] pub async fn create_payment_method( state: &SessionState, request_state: &routes::app::ReqState, req: api::PaymentMethodCreate, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, profile: &domain::Profile, ) -> RouterResponse<api::PaymentMethodResponse> { let response = create_payment_method_core( state, request_state, req, merchant_account, key_store, profile, ) .await?; Ok(services::ApplicationResponse::Json(response)) } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[instrument(skip_all)] pub async fn create_payment_method_core( state: &SessionState, _request_state: &routes::app::ReqState, req: api::PaymentMethodCreate, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, profile: &domain::Profile, ) -> RouterResult<api::PaymentMethodResponse> { use common_utils::ext_traits::ValueExt; req.validate()?; let db = &*state.store; let merchant_id = merchant_account.get_id(); let customer_id = req.customer_id.to_owned(); let key_manager_state = &(state).into(); db.find_customer_by_global_id( key_manager_state, &customer_id, merchant_account.get_id(), key_store, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound) .attach_printable("Customer not found for the payment method")?; let payment_method_billing_address = req .billing .clone() .async_map(|billing| cards::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")? .map(|encoded_address| { encoded_address.deserialize_inner_value(|value| value.parse_value("Address")) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to parse Payment method billing address")?; let payment_method_id = id_type::GlobalPaymentMethodId::generate(&state.conf.cell_information.id) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to generate GlobalPaymentMethodId")?; let payment_method = create_payment_method_for_intent( state, req.metadata.clone(), &customer_id, payment_method_id, merchant_id, key_store, merchant_account.storage_scheme, payment_method_billing_address, ) .await .attach_printable("Failed to add Payment method to DB")?; let payment_method_data = domain::PaymentMethodVaultingData::from(req.payment_method_data) .populate_bin_details_for_payment_method(state) .await; let vaulting_result = vault_payment_method( state, &payment_method_data, merchant_account, key_store, None, &customer_id, ) .await; let network_tokenization_resp = network_tokenize_and_vault_the_pmd( state, &payment_method_data, merchant_account, key_store, req.network_tokenization.clone(), profile.is_network_tokenization_enabled, &customer_id, ) .await; let (response, payment_method) = match vaulting_result { Ok((vaulting_resp, fingerprint_id)) => { let pm_update = create_pm_additional_data_update( Some(&payment_method_data), state, key_store, Some(vaulting_resp.vault_id.get_string_repr().clone()), Some(fingerprint_id), &payment_method, None, network_tokenization_resp, Some(req.payment_method_type), Some(req.payment_method_subtype), ) .await .attach_printable("Unable to create Payment method data")?; let payment_method = db .update_payment_method( &(state.into()), key_store, payment_method, pm_update, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update payment method in db")?; let resp = pm_transforms::generate_payment_method_response(&payment_method, &None)?; Ok((resp, payment_method)) } Err(e) => { let pm_update = storage::PaymentMethodUpdate::StatusUpdate { status: Some(enums::PaymentMethodStatus::Inactive), }; db.update_payment_method( &(state.into()), key_store, payment_method, pm_update, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update payment method in db")?; Err(e) } }?; Ok(response) } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Clone, Debug)] pub struct NetworkTokenPaymentMethodDetails { network_token_requestor_reference_id: String, network_token_locker_id: String, network_token_pmd: Encryptable<Secret<serde_json::Value>>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub async fn network_tokenize_and_vault_the_pmd( state: &SessionState, payment_method_data: &domain::PaymentMethodVaultingData, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, network_tokenization_enabled_for_profile: bool, customer_id: &id_type::GlobalCustomerId, ) -> Option<NetworkTokenPaymentMethodDetails> { let network_token_pm_details_result: CustomResult< NetworkTokenPaymentMethodDetails, errors::NetworkTokenizationError, > = async { when(!network_tokenization_enabled_for_profile, || { Err(report!( errors::NetworkTokenizationError::NetworkTokenizationNotEnabledForProfile )) })?; let is_network_tokenization_enabled_for_pm = network_tokenization .as_ref() .map(|nt| matches!(nt.enable, common_enums::NetworkTokenizationToggle::Enable)) .unwrap_or(false); let card_data = payment_method_data .get_card() .and_then(|card| is_network_tokenization_enabled_for_pm.then_some(card)) .ok_or_else(|| { report!(errors::NetworkTokenizationError::NotSupported { message: "Payment method".to_string(), }) })?; let (resp, network_token_req_ref_id) = network_tokenization::make_card_network_tokenization_request( state, card_data, customer_id, ) .await?; let network_token_vaulting_data = domain::PaymentMethodVaultingData::NetworkToken(resp); let vaulting_resp = vault::add_payment_method_to_vault( state, merchant_account, &network_token_vaulting_data, None, ) .await .change_context(errors::NetworkTokenizationError::SaveNetworkTokenFailed) .attach_printable("Failed to vault network token")?; let key_manager_state = &(state).into(); let network_token_pmd = cards::create_encrypted_data( key_manager_state, key_store, network_token_vaulting_data.get_payment_methods_data(), ) .await .change_context(errors::NetworkTokenizationError::NetworkTokenDetailsEncryptionFailed) .attach_printable("Failed to encrypt PaymentMethodsData")?; Ok(NetworkTokenPaymentMethodDetails { network_token_requestor_reference_id: network_token_req_ref_id, network_token_locker_id: vaulting_resp.vault_id.get_string_repr().clone(), network_token_pmd, }) } .await; network_token_pm_details_result.ok() } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub async fn populate_bin_details_for_payment_method( state: &SessionState, payment_method_data: &domain::PaymentMethodVaultingData, ) -> domain::PaymentMethodVaultingData { match payment_method_data { domain::PaymentMethodVaultingData::Card(card) => { let card_isin = card.card_number.get_card_isin(); if card.card_issuer.is_some() && card.card_network.is_some() && card.card_type.is_some() && card.card_issuing_country.is_some() { domain::PaymentMethodVaultingData::Card(card.clone()) } else { let card_info = state .store .get_card_info(&card_isin) .await .map_err(|error| services::logger::error!(card_info_error=?error)) .ok() .flatten(); domain::PaymentMethodVaultingData::Card(payment_methods::CardDetail { card_number: card.card_number.clone(), card_exp_month: card.card_exp_month.clone(), card_exp_year: card.card_exp_year.clone(), card_holder_name: card.card_holder_name.clone(), nick_name: card.nick_name.clone(), card_issuing_country: card_info.as_ref().and_then(|val| { val.card_issuing_country .as_ref() .map(|c| api_enums::CountryAlpha2::from_str(c)) .transpose() .ok() .flatten() }), card_network: card_info.as_ref().and_then(|val| val.card_network.clone()), card_issuer: card_info.as_ref().and_then(|val| val.card_issuer.clone()), card_type: card_info.as_ref().and_then(|val| { val.card_type .as_ref() .map(|c| payment_methods::CardType::from_str(c)) .transpose() .ok() .flatten() }), card_cvc: card.card_cvc.clone(), }) } } _ => payment_method_data.clone(), } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[async_trait::async_trait] pub trait PaymentMethodExt { async fn populate_bin_details_for_payment_method(&self, state: &SessionState) -> Self; } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[async_trait::async_trait] impl PaymentMethodExt for domain::PaymentMethodVaultingData { async fn populate_bin_details_for_payment_method(&self, state: &SessionState) -> Self { match self { Self::Card(card) => { let card_isin = card.card_number.get_card_isin(); if card.card_issuer.is_some() && card.card_network.is_some() && card.card_type.is_some() && card.card_issuing_country.is_some() { Self::Card(card.clone()) } else { let card_info = state .store .get_card_info(&card_isin) .await .map_err(|error| services::logger::error!(card_info_error=?error)) .ok() .flatten(); Self::Card(payment_methods::CardDetail { card_number: card.card_number.clone(), card_exp_month: card.card_exp_month.clone(), card_exp_year: card.card_exp_year.clone(), card_holder_name: card.card_holder_name.clone(), nick_name: card.nick_name.clone(), card_issuing_country: card_info.as_ref().and_then(|val| { val.card_issuing_country .as_ref() .map(|c| api_enums::CountryAlpha2::from_str(c)) .transpose() .ok() .flatten() }), card_network: card_info.as_ref().and_then(|val| val.card_network.clone()), card_issuer: card_info.as_ref().and_then(|val| val.card_issuer.clone()), card_type: card_info.as_ref().and_then(|val| { val.card_type .as_ref() .map(|c| payment_methods::CardType::from_str(c)) .transpose() .ok() .flatten() }), card_cvc: card.card_cvc.clone(), }) } } _ => self.clone(), } } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[instrument(skip_all)] pub async fn payment_method_intent_create( state: &SessionState, req: api::PaymentMethodIntentCreate, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> RouterResponse<api::PaymentMethodResponse> { let db = &*state.store; let merchant_id = merchant_account.get_id(); let customer_id = req.customer_id.to_owned(); let key_manager_state = &(state).into(); db.find_customer_by_global_id( key_manager_state, &customer_id, merchant_account.get_id(), key_store, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound) .attach_printable("Customer not found for the payment method")?; let payment_method_billing_address = req .billing .clone() .async_map(|billing| cards::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")? .map(|encoded_address| { encoded_address.deserialize_inner_value(|value| value.parse_value("Address")) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to parse Payment method billing address")?; // create pm entry let payment_method_id = id_type::GlobalPaymentMethodId::generate(&state.conf.cell_information.id) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to generate GlobalPaymentMethodId")?; let payment_method = create_payment_method_for_intent( state, req.metadata.clone(), &customer_id, payment_method_id, merchant_id, key_store, merchant_account.storage_scheme, payment_method_billing_address, ) .await .attach_printable("Failed to add Payment method to DB")?; let resp = pm_transforms::generate_payment_method_response(&payment_method, &None)?; Ok(services::ApplicationResponse::Json(resp)) } #[cfg(feature = "v2")] trait PerformFilteringOnEnabledPaymentMethods { fn perform_filtering(self) -> FilteredPaymentMethodsEnabled; } #[cfg(feature = "v2")] impl PerformFilteringOnEnabledPaymentMethods for hyperswitch_domain_models::merchant_connector_account::FlattenedPaymentMethodsEnabled { fn perform_filtering(self) -> FilteredPaymentMethodsEnabled { FilteredPaymentMethodsEnabled(self.payment_methods_enabled) } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[instrument(skip_all)] pub async fn list_payment_methods_for_session( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, profile: domain::Profile, payment_method_session_id: id_type::GlobalPaymentMethodSessionId, ) -> RouterResponse<api::PaymentMethodListResponse> { let key_manager_state = &(&state).into(); let db = &*state.store; let payment_method_session = db .get_payment_methods_session(key_manager_state, &key_store, &payment_method_session_id) .await .change_context(errors::ApiErrorResponse::PaymentMethodNotFound) .attach_printable("Unable to find payment method")?; let payment_connector_accounts = db .list_enabled_connector_accounts_by_profile_id( key_manager_state, profile.get_id(), &key_store, common_enums::ConnectorType::PaymentProcessor, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error when fetching merchant connector accounts")?; let customer_payment_methods = list_customer_payment_method_core( &state, &merchant_account, &key_store, &payment_method_session.customer_id, ) .await?; let response = hyperswitch_domain_models::merchant_connector_account::FlattenedPaymentMethodsEnabled::from_payment_connectors_list(payment_connector_accounts) .perform_filtering() .get_required_fields(RequiredFieldsInput::new(state.conf.required_fields.clone())) .generate_response(customer_payment_methods.customer_payment_methods); Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( response, )) } #[cfg(all(feature = "v2", feature = "olap"))] #[instrument(skip_all)] pub async fn list_saved_payment_methods_for_customer( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, customer_id: id_type::GlobalCustomerId, ) -> RouterResponse<api::CustomerPaymentMethodsListResponse> { let customer_payment_methods = list_customer_payment_method_core(&state, &merchant_account, &key_store, &customer_id) .await?; Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( customer_payment_methods, )) } #[cfg(all(feature = "v2", feature = "olap"))] #[instrument(skip_all)] pub async fn get_total_saved_payment_methods_for_merchant( state: SessionState, merchant_account: domain::MerchantAccount, ) -> RouterResponse<api::TotalPaymentMethodCountResponse> { let total_payment_method_count = get_total_payment_method_count_core(&state, &merchant_account).await?; Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( total_payment_method_count, )) } #[cfg(feature = "v2")] /// Container for the inputs required for the required fields struct RequiredFieldsInput { required_fields_config: settings::RequiredFields, } #[cfg(feature = "v2")] impl RequiredFieldsInput { fn new(required_fields_config: settings::RequiredFields) -> Self { Self { required_fields_config, } } } #[cfg(feature = "v2")] /// Container for the filtered payment methods struct FilteredPaymentMethodsEnabled( Vec<hyperswitch_domain_models::merchant_connector_account::PaymentMethodsEnabledForConnector>, ); #[cfg(feature = "v2")] trait GetRequiredFields { fn get_required_fields( &self, payment_method_enabled: &hyperswitch_domain_models::merchant_connector_account::PaymentMethodsEnabledForConnector, ) -> Option<&settings::RequiredFieldFinal>; } #[cfg(feature = "v2")] impl GetRequiredFields for settings::RequiredFields { fn get_required_fields( &self, payment_method_enabled: &hyperswitch_domain_models::merchant_connector_account::PaymentMethodsEnabledForConnector, ) -> Option<&settings::RequiredFieldFinal> { self.0 .get(&payment_method_enabled.payment_method) .and_then(|required_fields_for_payment_method| { required_fields_for_payment_method.0.get( &payment_method_enabled .payment_methods_enabled .payment_method_subtype, ) }) .map(|connector_fields| &connector_fields.fields) .and_then(|connector_hashmap| connector_hashmap.get(&payment_method_enabled.connector)) } } #[cfg(feature = "v2")] impl FilteredPaymentMethodsEnabled { fn get_required_fields( self, input: RequiredFieldsInput, ) -> RequiredFieldsForEnabledPaymentMethodTypes { let required_fields_config = input.required_fields_config; let required_fields_info = self .0 .into_iter() .map(|payment_methods_enabled| { let required_fields = required_fields_config.get_required_fields(&payment_methods_enabled); let required_fields = required_fields .map(|required_fields| { let common_required_fields = required_fields .common .iter() .flatten() .map(ToOwned::to_owned); // Collect mandate required fields because this is for zero auth mandates only let mandate_required_fields = required_fields .mandate .iter() .flatten() .map(ToOwned::to_owned); // Combine both common and mandate required fields common_required_fields .chain(mandate_required_fields) .collect::<Vec<_>>() }) .unwrap_or_default(); RequiredFieldsForEnabledPaymentMethod { required_fields, payment_method_type: payment_methods_enabled.payment_method, payment_method_subtype: payment_methods_enabled .payment_methods_enabled .payment_method_subtype, } }) .collect(); RequiredFieldsForEnabledPaymentMethodTypes(required_fields_info) } } #[cfg(feature = "v2")] /// Element container to hold the filtered payment methods with required fields struct RequiredFieldsForEnabledPaymentMethod { required_fields: Vec<payment_methods::RequiredFieldInfo>, payment_method_subtype: common_enums::PaymentMethodType, payment_method_type: common_enums::PaymentMethod, } #[cfg(feature = "v2")] /// Container to hold the filtered payment methods enabled with required fields struct RequiredFieldsForEnabledPaymentMethodTypes(Vec<RequiredFieldsForEnabledPaymentMethod>); #[cfg(feature = "v2")] impl RequiredFieldsForEnabledPaymentMethodTypes { fn generate_response( self, customer_payment_methods: Vec<payment_methods::CustomerPaymentMethod>, ) -> payment_methods::PaymentMethodListResponse { let response_payment_methods = self .0 .into_iter() .map( |payment_methods_enabled| payment_methods::ResponsePaymentMethodTypes { payment_method_type: payment_methods_enabled.payment_method_type, payment_method_subtype: payment_methods_enabled.payment_method_subtype, required_fields: payment_methods_enabled.required_fields, extra_information: None, }, ) .collect(); payment_methods::PaymentMethodListResponse { payment_methods_enabled: response_payment_methods, customer_payment_methods, } } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn create_payment_method_for_intent( state: &SessionState, metadata: Option<common_utils::pii::SecretSerdeValue>, customer_id: &id_type::GlobalCustomerId, payment_method_id: id_type::GlobalPaymentMethodId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, payment_method_billing_address: Option< Encryptable<hyperswitch_domain_models::address::Address>, >, ) -> CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> { let db = &*state.store; 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(), id: payment_method_id, locker_id: None, payment_method_type: None, payment_method_subtype: None, payment_method_data: None, connector_mandate_details: None, customer_acceptance: None, client_secret: None, status: enums::PaymentMethodStatus::AwaitingData, network_transaction_id: 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, locker_fingerprint_id: None, network_token_locker_id: None, network_token_payment_method_data: None, network_token_requestor_reference_id: None, }, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add payment method in db")?; Ok(response) } #[cfg(feature = "v2")] /// Update the connector_mandate_details of the payment method with /// new token details for the payment fn create_connector_token_details_update( token_details: payment_methods::ConnectorTokenDetails, payment_method: &domain::PaymentMethod, ) -> hyperswitch_domain_models::mandates::CommonMandateReference { let connector_id = token_details.connector_id.clone(); let reference_record = hyperswitch_domain_models::mandates::ConnectorTokenReferenceRecord::foreign_from( token_details, ); let connector_token_details = payment_method.connector_mandate_details.clone(); match connector_token_details { Some(mut connector_mandate_reference) => { connector_mandate_reference .insert_payment_token_reference_record(&connector_id, reference_record); connector_mandate_reference } None => { let reference_record_hash_map = std::collections::HashMap::from([(connector_id, reference_record)]); let payments_mandate_reference = hyperswitch_domain_models::mandates::PaymentsTokenReference( reference_record_hash_map, ); hyperswitch_domain_models::mandates::CommonMandateReference { payments: Some(payments_mandate_reference), payouts: None, } } } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[allow(clippy::too_many_arguments)] pub async fn create_pm_additional_data_update( pmd: Option<&domain::PaymentMethodVaultingData>, state: &SessionState, key_store: &domain::MerchantKeyStore, vault_id: Option<String>, vault_fingerprint_id: Option<String>, payment_method: &domain::PaymentMethod, connector_token_details: Option<payment_methods::ConnectorTokenDetails>, nt_data: Option<NetworkTokenPaymentMethodDetails>, payment_method_type: Option<common_enums::PaymentMethod>, payment_method_subtype: Option<common_enums::PaymentMethodType>, ) -> RouterResult<storage::PaymentMethodUpdate> { let encrypted_payment_method_data = pmd .map( |payment_method_vaulting_data| match payment_method_vaulting_data { domain::PaymentMethodVaultingData::Card(card) => { payment_method_data::PaymentMethodsData::Card( payment_method_data::CardDetailsPaymentMethod::from(card.clone()), ) } domain::PaymentMethodVaultingData::NetworkToken(network_token) => { payment_method_data::PaymentMethodsData::NetworkToken( payment_method_data::NetworkTokenDetailsPaymentMethod::from( network_token.clone(), ), ) } }, ) .async_map(|payment_method_details| async { let key_manager_state = &(state).into(); cards::create_encrypted_data(key_manager_state, key_store, payment_method_details) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt Payment method data") }) .await .transpose()? .map(From::from); let connector_mandate_details_update = connector_token_details .map(|connector_token| { create_connector_token_details_update(connector_token, payment_method) }) .map(From::from); let pm_update = storage::PaymentMethodUpdate::GenericUpdate { status: Some(enums::PaymentMethodStatus::Active), locker_id: vault_id, payment_method_type_v2: payment_method_type, payment_method_subtype, payment_method_data: encrypted_payment_method_data, network_token_requestor_reference_id: nt_data .clone() .map(|data| data.network_token_requestor_reference_id), network_token_locker_id: nt_data.clone().map(|data| data.network_token_locker_id), network_token_payment_method_data: nt_data.map(|data| data.network_token_pmd.into()), connector_mandate_details: connector_mandate_details_update, locker_fingerprint_id: vault_fingerprint_id, }; Ok(pm_update) } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[instrument(skip_all)] pub async fn vault_payment_method( state: &SessionState, pmd: &domain::PaymentMethodVaultingData, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, existing_vault_id: Option<domain::VaultId>, customer_id: &id_type::GlobalCustomerId, ) -> RouterResult<(pm_types::AddVaultResponse, String)> { let db = &*state.store; // get fingerprint_id from vault let fingerprint_id_from_vault = vault::get_fingerprint_id_from_vault(state, pmd, customer_id.get_string_repr().to_owned()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get fingerprint_id from vault")?; // throw back error if payment method is duplicated when( db.find_payment_method_by_fingerprint_id( &(state.into()), key_store, &fingerprint_id_from_vault, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to find payment method by fingerprint_id") .inspect_err(|e| logger::error!("Vault Fingerprint_id error: {:?}", e)) .is_ok(), || { Err(report!(errors::ApiErrorResponse::DuplicatePaymentMethod) .attach_printable("Cannot vault duplicate payment method")) }, )?; let resp_from_vault = vault::add_payment_method_to_vault(state, merchant_account, pmd, existing_vault_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add payment method in vault")?; Ok((resp_from_vault, fingerprint_id_from_vault)) } // TODO: check if this function will be used for listing the customer payment methods for payments #[allow(unused)] #[cfg(all( feature = "v2", feature = "payment_methods_v2", feature = "customer_v2" ))] fn get_pm_list_context( payment_method_type: enums::PaymentMethod, payment_method: &domain::PaymentMethod, is_payment_associated: bool, ) -> Result<Option<PaymentMethodListContext>, error_stack::Report<errors::ApiErrorResponse>> { let payment_method_data = payment_method .payment_method_data .clone() .map(|payment_method_data| payment_method_data.into_inner()); let payment_method_retrieval_context = match payment_method_data { Some(payment_methods::PaymentMethodsData::Card(card)) => { Some(PaymentMethodListContext::Card { card_details: api::CardDetailFromLocker::from(card), token_data: is_payment_associated.then_some( storage::PaymentTokenData::permanent_card( Some(payment_method.get_id().clone()), payment_method .locker_id .as_ref() .map(|id| id.get_string_repr().to_owned()) .or_else(|| Some(payment_method.get_id().get_string_repr().to_owned())), payment_method .locker_id .as_ref() .map(|id| id.get_string_repr().to_owned()) .unwrap_or_else(|| { payment_method.get_id().get_string_repr().to_owned() }), ), ), }) } Some(payment_methods::PaymentMethodsData::BankDetails(bank_details)) => { let get_bank_account_token_data = || -> CustomResult<payment_methods::BankAccountTokenData,errors::ApiErrorResponse> { let connector_details = bank_details .connector_details .first() .cloned() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to obtain bank account connector details")?; let payment_method_subtype = payment_method .get_payment_method_subtype() .get_required_value("payment_method_subtype") .attach_printable("PaymentMethodType not found")?; Ok(payment_methods::BankAccountTokenData { payment_method_type: payment_method_subtype, payment_method: payment_method_type, connector_details, }) }; // Retrieve the pm_auth connector details so that it can be tokenized let bank_account_token_data = get_bank_account_token_data() .inspect_err(|error| logger::error!(?error)) .ok(); bank_account_token_data.map(|data| { let token_data = storage::PaymentTokenData::AuthBankDebit(data); PaymentMethodListContext::Bank { token_data: is_payment_associated.then_some(token_data), } }) } Some(payment_methods::PaymentMethodsData::WalletDetails(_)) | None => { Some(PaymentMethodListContext::TemporaryToken { token_data: is_payment_associated.then_some( storage::PaymentTokenData::temporary_generic(generate_id( consts::ID_LENGTH, "token", )), ), }) } }; Ok(payment_method_retrieval_context) } #[cfg(all(feature = "v2", feature = "olap"))] pub async fn list_customer_payment_method_core( state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, customer_id: &id_type::GlobalCustomerId, ) -> RouterResult<api::CustomerPaymentMethodsListResponse> { let db = &*state.store; let key_manager_state = &(state).into(); let saved_payment_methods = db .find_payment_method_by_global_customer_id_merchant_id_status( key_manager_state, key_store, customer_id, merchant_account.get_id(), common_enums::PaymentMethodStatus::Active, None, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; let customer_payment_methods = saved_payment_methods .into_iter() .map(ForeignTryFrom::foreign_try_from) .collect::<Result<Vec<api::CustomerPaymentMethod>, _>>() .change_context(errors::ApiErrorResponse::InternalServerError)?; let response = api::CustomerPaymentMethodsListResponse { customer_payment_methods, }; Ok(response) } #[cfg(all(feature = "v2", feature = "olap"))] pub async fn get_total_payment_method_count_core( state: &SessionState, merchant_account: &domain::MerchantAccount, ) -> RouterResult<api::TotalPaymentMethodCountResponse> { let db = &*state.store; let total_count = db .get_payment_method_count_by_merchant_id_status( merchant_account.get_id(), common_enums::PaymentMethodStatus::Active, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to get total payment method count")?; let response = api::TotalPaymentMethodCountResponse { total_count }; Ok(response) } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[instrument(skip_all)] pub async fn retrieve_payment_method( state: SessionState, pm: api::PaymentMethodId, key_store: domain::MerchantKeyStore, merchant_account: domain::MerchantAccount, ) -> RouterResponse<api::PaymentMethodResponse> { let db = state.store.as_ref(); let pm_id = id_type::GlobalPaymentMethodId::generate_from_string(pm.payment_method_id) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to generate GlobalPaymentMethodId")?; let payment_method = db .find_payment_method( &((&state).into()), &key_store, &pm_id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; let single_use_token_in_cache = get_single_use_token_from_store( &state.clone(), payment_method_data::SingleUseTokenKey::store_key(&pm_id.clone()), ) .await .unwrap_or_default(); transformers::generate_payment_method_response(&payment_method, &single_use_token_in_cache) .map(services::ApplicationResponse::Json) } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[instrument(skip_all)] pub async fn update_payment_method( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: api::PaymentMethodUpdate, payment_method_id: &id_type::GlobalPaymentMethodId, ) -> RouterResponse<api::PaymentMethodResponse> { let response = update_payment_method_core( &state, &merchant_account, &key_store, req, payment_method_id, ) .await?; Ok(services::ApplicationResponse::Json(response)) } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[instrument(skip_all)] pub async fn update_payment_method_core( state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, request: api::PaymentMethodUpdate, payment_method_id: &id_type::GlobalPaymentMethodId, ) -> RouterResult<api::PaymentMethodResponse> { let db = state.store.as_ref(); let payment_method = db .find_payment_method( &((state).into()), key_store, payment_method_id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; let current_vault_id = payment_method.locker_id.clone(); when( payment_method.status == enums::PaymentMethodStatus::AwaitingData, || { Err(errors::ApiErrorResponse::InvalidRequestData { message: "This Payment method is awaiting data and hence cannot be updated" .to_string(), }) }, )?; let pmd: domain::PaymentMethodVaultingData = vault::retrieve_payment_method_from_vault(state, merchant_account, &payment_method) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to retrieve payment method from vault")? .data; let vault_request_data = request.payment_method_data.map(|payment_method_data| { pm_transforms::generate_pm_vaulting_req_from_update_request(pmd, payment_method_data) }); let (vaulting_response, fingerprint_id) = match vault_request_data { // cannot use async map because of problems related to lifetimes // to overcome this, we will have to use a move closure and add some clones Some(ref vault_request_data) => { Some( vault_payment_method( state, vault_request_data, merchant_account, key_store, // using current vault_id for now, // will have to refactor this to generate new one on each vaulting later on current_vault_id, &payment_method.customer_id, ) .await .attach_printable("Failed to add payment method in vault")?, ) } None => None, } .unzip(); let vault_id = vaulting_response .map(|vaulting_response| vaulting_response.vault_id.get_string_repr().clone()); let pm_update = create_pm_additional_data_update( vault_request_data.as_ref(), state, key_store, vault_id, fingerprint_id, &payment_method, request.connector_token_details, None, None, None, ) .await .attach_printable("Unable to create Payment method data")?; let payment_method = db .update_payment_method( &((state).into()), key_store, payment_method, pm_update, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update payment method in db")?; let response = pm_transforms::generate_payment_method_response(&payment_method, &None)?; // Add a PT task to handle payment_method delete from vault Ok(response) } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[instrument(skip_all)] pub async fn delete_payment_method( state: SessionState, pm_id: api::PaymentMethodId, key_store: domain::MerchantKeyStore, merchant_account: domain::MerchantAccount, ) -> RouterResponse<api::PaymentMethodDeleteResponse> { let pm_id = id_type::GlobalPaymentMethodId::generate_from_string(pm_id.payment_method_id) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to generate GlobalPaymentMethodId")?; let response = delete_payment_method_core(state, pm_id, key_store, merchant_account).await?; Ok(services::ApplicationResponse::Json(response)) } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[instrument(skip_all)] pub async fn delete_payment_method_core( state: SessionState, pm_id: id_type::GlobalPaymentMethodId, key_store: domain::MerchantKeyStore, merchant_account: domain::MerchantAccount, ) -> RouterResult<api::PaymentMethodDeleteResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let payment_method = db .find_payment_method( &((&state).into()), &key_store, &pm_id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; when( payment_method.status == enums::PaymentMethodStatus::Inactive, || Err(errors::ApiErrorResponse::PaymentMethodNotFound), )?; let vault_id = payment_method .locker_id .clone() .get_required_value("locker_id") .attach_printable("Missing locker_id in PaymentMethod")?; let _customer = db .find_customer_by_global_id( key_manager_state, &payment_method.customer_id, merchant_account.get_id(), &key_store, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable("Customer not found for the payment method")?; // Soft delete let pm_update = storage::PaymentMethodUpdate::StatusUpdate { status: Some(enums::PaymentMethodStatus::Inactive), }; db.update_payment_method( &((&state).into()), &key_store, payment_method, pm_update, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update payment method in db")?; vault::delete_payment_method_data_from_vault(&state, &merchant_account, vault_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to delete payment method from vault")?; let response = api::PaymentMethodDeleteResponse { id: pm_id }; Ok(response) } #[cfg(feature = "v2")] #[async_trait::async_trait] trait EncryptableData { type Output; async fn encrypt_data( &self, key_manager_state: &common_utils::types::keymanager::KeyManagerState, key_store: &domain::MerchantKeyStore, ) -> RouterResult<Self::Output>; } #[cfg(feature = "v2")] #[async_trait::async_trait] impl EncryptableData for payment_methods::PaymentMethodSessionRequest { type Output = hyperswitch_domain_models::payment_methods::DecryptedPaymentMethodSession; async fn encrypt_data( &self, key_manager_state: &common_utils::types::keymanager::KeyManagerState, key_store: &domain::MerchantKeyStore, ) -> RouterResult<Self::Output> { use common_utils::types::keymanager::ToEncryptable; let encrypted_billing_address = self .billing .clone() .map(|address| address.encode_to_value()) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encode billing address")? .map(Secret::new); let batch_encrypted_data = domain_types::crypto_operation( key_manager_state, common_utils::type_name!(hyperswitch_domain_models::payment_methods::PaymentMethodSession), domain_types::CryptoOperation::BatchEncrypt( hyperswitch_domain_models::payment_methods::FromRequestEncryptablePaymentMethodSession::to_encryptable( hyperswitch_domain_models::payment_methods::FromRequestEncryptablePaymentMethodSession { billing: encrypted_billing_address, }, ), ), common_utils::types::keymanager::Identifier::Merchant(key_store.merchant_id.clone()), key_store.key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting payment methods session details".to_string())?; let encrypted_data = hyperswitch_domain_models::payment_methods::FromRequestEncryptablePaymentMethodSession::from_encryptable( batch_encrypted_data, ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting payment methods session detailss")?; Ok(encrypted_data) } } #[cfg(feature = "v2")] #[async_trait::async_trait] impl EncryptableData for payment_methods::PaymentMethodsSessionUpdateRequest { type Output = hyperswitch_domain_models::payment_methods::DecryptedPaymentMethodSession; async fn encrypt_data( &self, key_manager_state: &common_utils::types::keymanager::KeyManagerState, key_store: &domain::MerchantKeyStore, ) -> RouterResult<Self::Output> { use common_utils::types::keymanager::ToEncryptable; let encrypted_billing_address = self .billing .clone() .map(|address| address.encode_to_value()) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encode billing address")? .map(Secret::new); let batch_encrypted_data = domain_types::crypto_operation( key_manager_state, common_utils::type_name!(hyperswitch_domain_models::payment_methods::PaymentMethodSession), domain_types::CryptoOperation::BatchEncrypt( hyperswitch_domain_models::payment_methods::FromRequestEncryptablePaymentMethodSession::to_encryptable( hyperswitch_domain_models::payment_methods::FromRequestEncryptablePaymentMethodSession { billing: encrypted_billing_address, }, ), ), common_utils::types::keymanager::Identifier::Merchant(key_store.merchant_id.clone()), key_store.key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting payment methods session details".to_string())?; let encrypted_data = hyperswitch_domain_models::payment_methods::FromRequestEncryptablePaymentMethodSession::from_encryptable( batch_encrypted_data, ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting payment methods session detailss")?; Ok(encrypted_data) } } #[cfg(feature = "v2")] pub async fn payment_methods_session_create( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, request: payment_methods::PaymentMethodSessionRequest, ) -> RouterResponse<payment_methods::PaymentMethodSessionResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); db.find_customer_by_global_id( key_manager_state, &request.customer_id, merchant_account.get_id(), &key_store, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; let payment_methods_session_id = id_type::GlobalPaymentMethodSessionId::generate(&state.conf.cell_information.id) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to generate GlobalPaymentMethodSessionId")?; let encrypted_data = request .encrypt_data(key_manager_state, &key_store) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encrypt payment methods session data")?; let billing = encrypted_data .billing .as_ref() .map(|data| { data.clone() .deserialize_inner_value(|value| value.parse_value("Address")) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to decode billing address")?; // If not passed in the request, use the default value from constants let expires_in = request .expires_in .unwrap_or(consts::DEFAULT_PAYMENT_METHOD_SESSION_EXPIRY) .into(); let expires_at = common_utils::date_time::now().saturating_add(Duration::seconds(expires_in)); let client_secret = payment_helpers::create_client_secret( &state, merchant_account.get_id(), util_types::authentication::ResourceId::PaymentMethodSession( payment_methods_session_id.clone(), ), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to create client secret")?; let payment_method_session_domain_model = hyperswitch_domain_models::payment_methods::PaymentMethodSession { id: payment_methods_session_id, customer_id: request.customer_id, billing, psp_tokenization: request.psp_tokenization, network_tokenization: request.network_tokenization, expires_at, return_url: request.return_url, associated_payment_methods: None, associated_payment: None, }; db.insert_payment_methods_session( key_manager_state, &key_store, payment_method_session_domain_model.clone(), expires_in, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to insert payment methods session in db")?; let response = transformers::generate_payment_method_session_response( payment_method_session_domain_model, client_secret.secret, None, ); Ok(services::ApplicationResponse::Json(response)) } #[cfg(feature = "v2")] pub async fn payment_methods_session_update( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, payment_method_session_id: id_type::GlobalPaymentMethodSessionId, request: payment_methods::PaymentMethodsSessionUpdateRequest, ) -> RouterResponse<payment_methods::PaymentMethodSessionResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let existing_payment_method_session_state = db .get_payment_methods_session(key_manager_state, &key_store, &payment_method_session_id) .await .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { message: "payment methods session does not exist or has expired".to_string(), }) .attach_printable("Failed to retrieve payment methods session from db")?; let encrypted_data = request .encrypt_data(key_manager_state, &key_store) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encrypt payment methods session data")?; let billing = encrypted_data .billing .as_ref() .map(|data| { data.clone() .deserialize_inner_value(|value| value.parse_value("Address")) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to decode billing address")?; let payment_method_session_domain_model = hyperswitch_domain_models::payment_methods::PaymentMethodsSessionUpdateEnum::GeneralUpdate{ billing, psp_tokenization: request.psp_tokenization, network_tokenization: request.network_tokenization, }; let update_state_change = db .update_payment_method_session( key_manager_state, &key_store, &payment_method_session_id, payment_method_session_domain_model, existing_payment_method_session_state.clone(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update payment methods session in db")?; let response = transformers::generate_payment_method_session_response( update_state_change, Secret::new("CLIENT_SECRET_REDACTED".to_string()), None, // TODO: send associated payments response based on the expandable param ); Ok(services::ApplicationResponse::Json(response)) } #[cfg(feature = "v2")] pub async fn payment_methods_session_retrieve( state: SessionState, _merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, payment_method_session_id: id_type::GlobalPaymentMethodSessionId, ) -> RouterResponse<payment_methods::PaymentMethodSessionResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let payment_method_session_domain_model = db .get_payment_methods_session(key_manager_state, &key_store, &payment_method_session_id) .await .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { message: "payment methods session does not exist or has expired".to_string(), }) .attach_printable("Failed to retrieve payment methods session from db")?; let response = transformers::generate_payment_method_session_response( payment_method_session_domain_model, Secret::new("CLIENT_SECRET_REDACTED".to_string()), None, // TODO: send associated payments response based on the expandable param ); Ok(services::ApplicationResponse::Json(response)) } #[cfg(feature = "v2")] pub async fn payment_methods_session_update_payment_method( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, payment_method_session_id: id_type::GlobalPaymentMethodSessionId, request: payment_methods::PaymentMethodSessionUpdateSavedPaymentMethod, ) -> RouterResponse<payment_methods::PaymentMethodResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); // Validate if the session still exists db.get_payment_methods_session(key_manager_state, &key_store, &payment_method_session_id) .await .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { message: "payment methods session does not exist or has expired".to_string(), }) .attach_printable("Failed to retrieve payment methods session from db")?; let payment_method_update_request = request.payment_method_update_request; let updated_payment_method = update_payment_method_core( &state, &merchant_account, &key_store, payment_method_update_request, &request.payment_method_id, ) .await .attach_printable("Failed to update saved payment method")?; Ok(services::ApplicationResponse::Json(updated_payment_method)) } #[cfg(feature = "v2")] pub async fn payment_methods_session_delete_payment_method( state: SessionState, key_store: domain::MerchantKeyStore, merchant_account: domain::MerchantAccount, pm_id: id_type::GlobalPaymentMethodId, payment_method_session_id: id_type::GlobalPaymentMethodSessionId, ) -> RouterResponse<api::PaymentMethodDeleteResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); // Validate if the session still exists db.get_payment_methods_session(key_manager_state, &key_store, &payment_method_session_id) .await .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { message: "payment methods session does not exist or has expired".to_string(), }) .attach_printable("Failed to retrieve payment methods session from db")?; let response = delete_payment_method_core(state, pm_id, key_store, merchant_account) .await .attach_printable("Failed to delete saved payment method")?; Ok(services::ApplicationResponse::Json(response)) } #[cfg(feature = "v2")] fn construct_zero_auth_payments_request( confirm_request: &payment_methods::PaymentMethodSessionConfirmRequest, payment_method_session: &hyperswitch_domain_models::payment_methods::PaymentMethodSession, payment_method: &payment_methods::PaymentMethodResponse, ) -> RouterResult<api_models::payments::PaymentsRequest> { use api_models::payments; Ok(payments::PaymentsRequest { amount_details: payments::AmountDetails::new_for_zero_auth_payment( common_enums::Currency::USD, ), payment_method_data: confirm_request.payment_method_data.clone(), payment_method_type: confirm_request.payment_method_type, payment_method_subtype: confirm_request.payment_method_subtype, customer_id: Some(payment_method_session.customer_id.clone()), customer_present: Some(enums::PresenceOfCustomerDuringPayment::Present), setup_future_usage: Some(common_enums::FutureUsage::OffSession), payment_method_id: Some(payment_method.id.clone()), merchant_reference_id: None, routing_algorithm_id: None, capture_method: None, authentication_type: None, // We have already passed payment method billing address billing: None, shipping: None, description: None, return_url: payment_method_session.return_url.clone(), apply_mit_exemption: None, statement_descriptor: None, order_details: None, allowed_payment_method_types: None, metadata: None, connector_metadata: None, feature_metadata: None, payment_link_enabled: None, payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, customer_acceptance: None, browser_info: None, force_3ds_challenge: None, }) } #[cfg(feature = "v2")] async fn create_zero_auth_payment( state: SessionState, req_state: routes::app::ReqState, merchant_account: domain::MerchantAccount, profile: domain::Profile, key_store: domain::MerchantKeyStore, request: api_models::payments::PaymentsRequest, ) -> RouterResult<api_models::payments::PaymentsResponse> { let response = Box::pin(payments_core::payments_create_and_confirm_intent( state, req_state, merchant_account, profile, key_store, request, hyperswitch_domain_models::payments::HeaderPayload::default(), None, )) .await?; logger::info!(associated_payments_response=?response); response .get_json_body() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unexpected response from payments core") } #[cfg(feature = "v2")] pub async fn payment_methods_session_confirm( state: SessionState, req_state: routes::app::ReqState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, profile: domain::Profile, payment_method_session_id: id_type::GlobalPaymentMethodSessionId, request: payment_methods::PaymentMethodSessionConfirmRequest, ) -> RouterResponse<payment_methods::PaymentMethodSessionResponse> { let db: &dyn StorageInterface = state.store.as_ref(); let key_manager_state = &(&state).into(); // Validate if the session still exists let payment_method_session = db .get_payment_methods_session(key_manager_state, &key_store, &payment_method_session_id) .await .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { message: "payment methods session does not exist or has expired".to_string(), }) .attach_printable("Failed to retrieve payment methods session from db")?; let payment_method_session_billing = payment_method_session .billing .clone() .map(|billing| billing.into_inner()) .map(From::from); // Unify the billing address that we receive from the session and from the confirm request let unified_billing_address = request .payment_method_data .billing .clone() .map(|payment_method_billing| { payment_method_billing.unify_address(payment_method_session_billing.as_ref()) }) .or_else(|| payment_method_session_billing.clone()); let create_payment_method_request = get_payment_method_create_request( request .payment_method_data .payment_method_data .as_ref() .get_required_value("payment_method_data")?, request.payment_method_type, request.payment_method_subtype, payment_method_session.customer_id.clone(), unified_billing_address.as_ref(), Some(&payment_method_session), ) .attach_printable("Failed to create payment method request")?; let payment_method = create_payment_method_core( &state, &req_state, create_payment_method_request.clone(), &merchant_account, &key_store, &profile, ) .await?; let payments_response = match &payment_method_session.psp_tokenization { Some(common_types::payment_methods::PspTokenization { tokenization_type: common_enums::TokenizationType::MultiUse, .. }) => { let zero_auth_request = construct_zero_auth_payments_request( &request, &payment_method_session, &payment_method, )?; let payments_response = Box::pin(create_zero_auth_payment( state.clone(), req_state, merchant_account.clone(), profile.clone(), key_store.clone(), zero_auth_request, )) .await?; Some(payments_response) } Some(common_types::payment_methods::PspTokenization { tokenization_type: common_enums::TokenizationType::SingleUse, .. }) => { Box::pin(create_single_use_tokenization_flow( state.clone(), req_state.clone(), merchant_account.clone(), profile.clone(), key_store.clone(), &create_payment_method_request.clone(), &payment_method, &payment_method_session, )) .await?; None } None => None, }; //TODO: update the payment method session with the payment id and payment method id let payment_method_session_response = transformers::generate_payment_method_session_response( payment_method_session, Secret::new("CLIENT_SECRET_REDACTED".to_string()), payments_response, ); Ok(services::ApplicationResponse::Json( payment_method_session_response, )) } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl pm_types::SavedPMLPaymentsInfo { pub async fn form_payments_info( payment_intent: PaymentIntent, merchant_account: &domain::MerchantAccount, profile: domain::Profile, db: &dyn StorageInterface, key_manager_state: &util_types::keymanager::KeyManagerState, key_store: &domain::MerchantKeyStore, ) -> RouterResult<Self> { let collect_cvv_during_payment = profile.should_collect_cvv_during_payment; let off_session_payment_flag = matches!( payment_intent.setup_future_usage, common_enums::FutureUsage::OffSession ); let is_connector_agnostic_mit_enabled = profile.is_connector_agnostic_mit_enabled.unwrap_or(false); Ok(Self { payment_intent, profile, collect_cvv_during_payment, off_session_payment_flag, is_connector_agnostic_mit_enabled, }) } pub async fn perform_payment_ops( &self, state: &SessionState, parent_payment_method_token: Option<String>, pma: &api::CustomerPaymentMethod, pm_list_context: PaymentMethodListContext, ) -> RouterResult<()> { let token = parent_payment_method_token .as_ref() .get_required_value("parent_payment_method_token")?; let token_data = pm_list_context .get_token_data() .get_required_value("PaymentTokenData")?; let intent_fulfillment_time = self .profile .get_order_fulfillment_time() .unwrap_or(common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME); pm_routes::ParentPaymentMethodToken::create_key_for_token((token, pma.payment_method_type)) .insert(intent_fulfillment_time, token_data, state) .await?; Ok(()) } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[allow(clippy::too_many_arguments)] async fn create_single_use_tokenization_flow( state: SessionState, req_state: routes::app::ReqState, merchant_account: domain::MerchantAccount, profile: domain::Profile, key_store: domain::MerchantKeyStore, payment_method_create_request: &payment_methods::PaymentMethodCreate, payment_method: &api::PaymentMethodResponse, payment_method_session: &domain::payment_methods::PaymentMethodSession, ) -> RouterResult<()> { let customer_id = payment_method_create_request.customer_id.to_owned(); let connector_id = payment_method_create_request .get_tokenize_connector_id() .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "psp_tokenization.connector_id", }) .attach_printable("Failed to get tokenize connector id")?; let db = &state.store; let merchant_connector_account_details = db .find_merchant_connector_account_by_id(&(&state).into(), &connector_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: connector_id.get_string_repr().to_owned(), }) .attach_printable("error while fetching merchant_connector_account from connector_id")?; let auth_type = merchant_connector_account_details .get_connector_account_details() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while parsing value for ConnectorAuthType")?; let payment_method_data_request = types::PaymentMethodTokenizationData { payment_method_data: payment_method_data::PaymentMethodData::try_from( payment_method_create_request.payment_method_data.clone(), ) .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "card_cvc", }) .attach_printable( "Failed to convert type from Payment Method Create Data to Payment Method Data", )?, browser_info: None, currency: api_models::enums::Currency::default(), amount: None, }; let payment_method_session_address = types::PaymentAddress::new( None, payment_method_session .billing .clone() .map(|address| address.into_inner()), None, None, ); let mut router_data = types::RouterData::<api::PaymentMethodToken, _, types::PaymentsResponseData> { flow: std::marker::PhantomData, merchant_id: merchant_account.get_id().clone(), customer_id: None, connector_customer: None, connector: merchant_connector_account_details .connector_name .to_string(), payment_id: consts::IRRELEVANT_PAYMENT_INTENT_ID.to_string(), //Static attempt_id: consts::IRRELEVANT_PAYMENT_ATTEMPT_ID.to_string(), //Static tenant_id: state.tenant.tenant_id.clone(), status: common_enums::enums::AttemptStatus::default(), payment_method: common_enums::enums::PaymentMethod::Card, connector_auth_type: auth_type, description: None, address: payment_method_session_address, auth_type: common_enums::enums::AuthenticationType::default(), connector_meta_data: None, connector_wallets_details: None, amount_captured: None, access_token: None, session_token: None, reference_id: None, payment_method_token: None, recurring_mandate_payment_data: None, preprocessing_id: None, payment_method_balance: None, connector_api_version: None, request: payment_method_data_request.clone(), response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()), connector_request_reference_id: payment_method_session.id.get_string_repr().to_string(), #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, test_mode: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, dispute_id: None, refund_id: None, connector_response: None, payment_method_status: None, minor_amount_captured: 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, }; let payment_method_token_response = tokenization::add_token_for_payment_method( &mut router_data, payment_method_data_request.clone(), state.clone(), &merchant_connector_account_details.clone(), ) .await?; let token_response = payment_method_token_response.token.map_err(|err| { errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: (merchant_connector_account_details.clone()) .connector_name .to_string(), status_code: err.status_code, reason: err.reason, } })?; let value = payment_method_data::SingleUsePaymentMethodToken::get_single_use_token_from_payment_method_token( token_response.clone().into(), connector_id.clone() ); let key = payment_method_data::SingleUseTokenKey::store_key(&payment_method.id); add_single_use_token_to_store(&state, key, value) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to store single use token")?; Ok(()) } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] async fn add_single_use_token_to_store( state: &SessionState, key: payment_method_data::SingleUseTokenKey, value: payment_method_data::SingleUsePaymentMethodToken, ) -> CustomResult<(), errors::StorageError> { let redis_connection = state .store .get_redis_conn() .map_err(Into::<errors::StorageError>::into)?; redis_connection .serialize_and_set_key_with_expiry( &payment_method_data::SingleUseTokenKey::get_store_key(&key).into(), value, consts::DEFAULT_PAYMENT_METHOD_STORE_TTL, ) .await .change_context(errors::StorageError::KVError) .attach_printable("Failed to insert payment method token to redis")?; Ok(()) } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] async fn get_single_use_token_from_store( state: &SessionState, key: payment_method_data::SingleUseTokenKey, ) -> CustomResult<Option<payment_method_data::SingleUsePaymentMethodToken>, errors::StorageError> { let redis_connection = state .store .get_redis_conn() .map_err(Into::<errors::StorageError>::into)?; redis_connection .get_and_deserialize_key::<Option<payment_method_data::SingleUsePaymentMethodToken>>( &payment_method_data::SingleUseTokenKey::get_store_key(&key).into(), "SingleUsePaymentMethodToken", ) .await .change_context(errors::StorageError::KVError) .attach_printable("Failed to get payment method token from redis") }
21,982
1,583
hyperswitch
crates/router/src/core/configs.rs
.rs
use error_stack::ResultExt; use crate::{ core::errors::{self, utils::StorageErrorExt, RouterResponse}, routes::SessionState, services::ApplicationResponse, types::{api, transformers::ForeignInto}, }; pub async fn set_config(state: SessionState, config: api::Config) -> RouterResponse<api::Config> { let store = state.store.as_ref(); let config = store .insert_config(diesel_models::configs::ConfigNew { key: config.key, config: config.value, }) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicateConfig) .attach_printable("Unknown error, while setting config key")?; Ok(ApplicationResponse::Json(config.foreign_into())) } pub async fn read_config(state: SessionState, key: &str) -> RouterResponse<api::Config> { let store = state.store.as_ref(); let config = store .find_config_by_key(key) .await .to_not_found_response(errors::ApiErrorResponse::ConfigNotFound)?; Ok(ApplicationResponse::Json(config.foreign_into())) } pub async fn update_config( state: SessionState, config_update: &api::ConfigUpdate, ) -> RouterResponse<api::Config> { let store = state.store.as_ref(); let config = store .update_config_by_key(&config_update.key, config_update.foreign_into()) .await .to_not_found_response(errors::ApiErrorResponse::ConfigNotFound)?; Ok(ApplicationResponse::Json(config.foreign_into())) } pub async fn config_delete(state: SessionState, key: String) -> RouterResponse<api::Config> { let store = state.store.as_ref(); let config = store .delete_config_by_key(&key) .await .to_not_found_response(errors::ApiErrorResponse::ConfigNotFound)?; Ok(ApplicationResponse::Json(config.foreign_into())) }
408
1,584
hyperswitch
crates/router/src/core/blocklist.rs
.rs
pub mod transformers; pub mod utils; use api_models::blocklist as api_blocklist; use crate::{ core::errors::{self, RouterResponse}, routes::SessionState, services, types::domain, }; pub async fn add_entry_to_blocklist( state: SessionState, merchant_account: domain::MerchantAccount, body: api_blocklist::AddToBlocklistRequest, ) -> RouterResponse<api_blocklist::AddToBlocklistResponse> { utils::insert_entry_into_blocklist(&state, merchant_account.get_id(), body) .await .map(services::ApplicationResponse::Json) } pub async fn remove_entry_from_blocklist( state: SessionState, merchant_account: domain::MerchantAccount, body: api_blocklist::DeleteFromBlocklistRequest, ) -> RouterResponse<api_blocklist::DeleteFromBlocklistResponse> { utils::delete_entry_from_blocklist(&state, merchant_account.get_id(), body) .await .map(services::ApplicationResponse::Json) } pub async fn list_blocklist_entries( state: SessionState, merchant_account: domain::MerchantAccount, query: api_blocklist::ListBlocklistQuery, ) -> RouterResponse<Vec<api_blocklist::BlocklistResponse>> { utils::list_blocklist_entries_for_merchant(&state, merchant_account.get_id(), query) .await .map(services::ApplicationResponse::Json) } pub async fn toggle_blocklist_guard( state: SessionState, merchant_account: domain::MerchantAccount, query: api_blocklist::ToggleBlocklistQuery, ) -> RouterResponse<api_blocklist::ToggleBlocklistResponse> { utils::toggle_blocklist_guard_for_merchant(&state, merchant_account.get_id(), query) .await .map(services::ApplicationResponse::Json) }
393
1,585
hyperswitch
crates/router/src/core/poll.rs
.rs
use api_models::poll::PollResponse; use common_utils::ext_traits::StringExt; use error_stack::ResultExt; use router_env::{instrument, tracing}; use super::errors; use crate::{ core::errors::RouterResponse, services::ApplicationResponse, types::domain, SessionState, }; #[instrument(skip_all)] pub async fn retrieve_poll_status( state: SessionState, req: crate::types::api::PollId, merchant_account: domain::MerchantAccount, ) -> RouterResponse<PollResponse> { let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let request_poll_id = req.poll_id; // prepend 'poll_{merchant_id}_' to restrict access to only fetching Poll IDs, as this is a freely passed string in the request let poll_id = super::utils::get_poll_id(merchant_account.get_id(), request_poll_id.clone()); let redis_value = redis_conn .get_key::<Option<String>>(&poll_id.as_str().into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Error while fetching the value for {} from redis", poll_id.clone() ) })? .ok_or(errors::ApiErrorResponse::PollNotFound { id: request_poll_id.clone(), })?; let status = redis_value .parse_enum("PollStatus") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while parsing PollStatus")?; let poll_response = PollResponse { poll_id: request_poll_id, status, }; Ok(ApplicationResponse::Json(poll_response)) }
381
1,586
hyperswitch
crates/router/src/core/files.rs
.rs
pub mod helpers; use api_models::files; use error_stack::ResultExt; use super::errors::{self, RouterResponse}; use crate::{ consts, routes::SessionState, services::ApplicationResponse, types::{api, domain}, }; pub async fn files_create_core( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, create_file_request: api::CreateFileRequest, ) -> RouterResponse<files::CreateFileResponse> { helpers::validate_file_upload( &state, merchant_account.clone(), create_file_request.clone(), ) .await?; let file_id = common_utils::generate_id(consts::ID_LENGTH, "file"); let file_key = format!( "{}/{}", merchant_account.get_id().get_string_repr(), file_id ); let file_new = diesel_models::file::FileMetadataNew { file_id: file_id.clone(), merchant_id: merchant_account.get_id().clone(), file_name: create_file_request.file_name.clone(), file_size: create_file_request.file_size, file_type: create_file_request.file_type.to_string(), provider_file_id: None, file_upload_provider: None, available: false, connector_label: None, profile_id: None, merchant_connector_id: None, }; let file_metadata_object = state .store .insert_file_metadata(file_new) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to insert file_metadata")?; let (provider_file_id, file_upload_provider, profile_id, merchant_connector_id) = helpers::upload_and_get_provider_provider_file_id_profile_id( &state, &merchant_account, &key_store, &create_file_request, file_key.clone(), ) .await?; // Update file metadata let update_file_metadata = diesel_models::file::FileMetadataUpdate::Update { provider_file_id: Some(provider_file_id), file_upload_provider: Some(file_upload_provider), available: true, profile_id, merchant_connector_id, }; state .store .as_ref() .update_file_metadata(file_metadata_object, update_file_metadata) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!("Unable to update file_metadata with file_id: {}", file_id) })?; Ok(ApplicationResponse::Json(files::CreateFileResponse { file_id, })) } pub async fn files_delete_core( state: SessionState, merchant_account: domain::MerchantAccount, req: api::FileId, ) -> RouterResponse<serde_json::Value> { helpers::delete_file_using_file_id(&state, req.file_id.clone(), &merchant_account).await?; state .store .as_ref() .delete_file_metadata_by_merchant_id_file_id(merchant_account.get_id(), &req.file_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to delete file_metadata")?; Ok(ApplicationResponse::StatusOk) } pub async fn files_retrieve_core( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: api::FileId, ) -> RouterResponse<serde_json::Value> { let file_metadata_object = state .store .as_ref() .find_file_metadata_by_merchant_id_file_id(merchant_account.get_id(), &req.file_id) .await .change_context(errors::ApiErrorResponse::FileNotFound) .attach_printable("Unable to retrieve file_metadata")?; let file_info = helpers::retrieve_file_and_provider_file_id_from_file_id( &state, Some(req.file_id), &merchant_account, &key_store, api::FileDataRequired::Required, ) .await?; let content_type = file_metadata_object .file_type .parse::<mime::Mime>() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse file content type")?; Ok(ApplicationResponse::FileData(( file_info .file_data .ok_or(errors::ApiErrorResponse::FileNotAvailable) .attach_printable("File data not found")?, content_type, ))) }
949
1,587
hyperswitch
crates/router/src/core/cards_info.rs
.rs
use actix_multipart::form::{bytes::Bytes, MultipartForm}; use api_models::cards_info as cards_info_api_types; use common_utils::fp_utils::when; use csv::Reader; use diesel_models::cards_info as card_info_models; use error_stack::{report, ResultExt}; use rdkafka::message::ToBytes; use router_env::{instrument, tracing}; use crate::{ core::{ errors::{self, RouterResponse, RouterResult, StorageErrorExt}, payments::helpers, }, db::cards_info::CardsInfoInterface, routes, services::ApplicationResponse, types::{ domain, transformers::{ForeignFrom, ForeignInto}, }, }; fn verify_iin_length(card_iin: &str) -> Result<(), errors::ApiErrorResponse> { let is_bin_length_in_range = card_iin.len() == 6 || card_iin.len() == 8; when(!is_bin_length_in_range, || { Err(errors::ApiErrorResponse::InvalidCardIinLength) }) } #[instrument(skip_all)] pub async fn retrieve_card_info( state: routes::SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, request: cards_info_api_types::CardsInfoRequest, ) -> RouterResponse<cards_info_api_types::CardInfoResponse> { let db = state.store.as_ref(); verify_iin_length(&request.card_iin)?; helpers::verify_payment_intent_time_and_client_secret( &state, &merchant_account, &key_store, request.client_secret, ) .await?; let card_info = db .get_card_info(&request.card_iin) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to retrieve card information")? .ok_or(report!(errors::ApiErrorResponse::InvalidCardIin))?; Ok(ApplicationResponse::Json( cards_info_api_types::CardInfoResponse::foreign_from(card_info), )) } #[instrument(skip_all)] pub async fn create_card_info( state: routes::SessionState, card_info_request: cards_info_api_types::CardInfoCreateRequest, ) -> RouterResponse<cards_info_api_types::CardInfoResponse> { let db = state.store.as_ref(); CardsInfoInterface::add_card_info(db, card_info_request.foreign_into()) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: "CardInfo with given key already exists in our records".to_string(), }) .map(|card_info| ApplicationResponse::Json(card_info.foreign_into())) } #[instrument(skip_all)] pub async fn update_card_info( state: routes::SessionState, card_info_request: cards_info_api_types::CardInfoUpdateRequest, ) -> RouterResponse<cards_info_api_types::CardInfoResponse> { let db = state.store.as_ref(); CardsInfoInterface::update_card_info( db, card_info_request.card_iin, card_info_models::UpdateCardInfo { card_issuer: card_info_request.card_issuer, card_network: card_info_request.card_network, card_type: card_info_request.card_type, card_subtype: card_info_request.card_subtype, card_issuing_country: card_info_request.card_issuing_country, bank_code_id: card_info_request.bank_code_id, bank_code: card_info_request.bank_code, country_code: card_info_request.country_code, last_updated: Some(common_utils::date_time::now()), last_updated_provider: card_info_request.last_updated_provider, }, ) .await .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { message: "Card info with given key does not exist in our records".to_string(), }) .attach_printable("Failed while updating card info") .map(|card_info| ApplicationResponse::Json(card_info.foreign_into())) } #[derive(Debug, MultipartForm)] pub struct CardsInfoUpdateForm { #[multipart(limit = "1MB")] pub file: Bytes, } fn parse_cards_bin_csv( data: &[u8], ) -> csv::Result<Vec<cards_info_api_types::CardInfoUpdateRequest>> { let mut csv_reader = Reader::from_reader(data); let mut records = Vec::new(); let mut id_counter = 0; for result in csv_reader.deserialize() { let mut record: cards_info_api_types::CardInfoUpdateRequest = result?; id_counter += 1; record.line_number = Some(id_counter); records.push(record); } Ok(records) } pub fn get_cards_bin_records( form: CardsInfoUpdateForm, ) -> Result<Vec<cards_info_api_types::CardInfoUpdateRequest>, errors::ApiErrorResponse> { match parse_cards_bin_csv(form.file.data.to_bytes()) { Ok(records) => Ok(records), Err(e) => Err(errors::ApiErrorResponse::PreconditionFailed { message: e.to_string(), }), } } #[instrument(skip_all)] pub async fn migrate_cards_info( state: routes::SessionState, card_info_records: Vec<cards_info_api_types::CardInfoUpdateRequest>, ) -> RouterResponse<Vec<cards_info_api_types::CardInfoMigrationResponse>> { let mut result = Vec::new(); for record in card_info_records { let res = card_info_flow(record.clone(), state.clone()).await; result.push(cards_info_api_types::CardInfoMigrationResponse::from(( match res { Ok(ApplicationResponse::Json(response)) => Ok(response), Err(e) => Err(e.to_string()), _ => Err("Failed to migrate card info".to_string()), }, record, ))); } Ok(ApplicationResponse::Json(result)) } pub trait State {} pub trait TransitionTo<S: State> {} // Available states for card info migration pub struct CardInfoFetch; pub struct CardInfoAdd; pub struct CardInfoUpdate; pub struct CardInfoResponse; impl State for CardInfoFetch {} impl State for CardInfoAdd {} impl State for CardInfoUpdate {} impl State for CardInfoResponse {} // State transitions for card info migration impl TransitionTo<CardInfoAdd> for CardInfoFetch {} impl TransitionTo<CardInfoUpdate> for CardInfoFetch {} impl TransitionTo<CardInfoResponse> for CardInfoAdd {} impl TransitionTo<CardInfoResponse> for CardInfoUpdate {} // Async executor pub struct CardInfoMigrateExecutor<'a> { state: &'a routes::SessionState, record: &'a cards_info_api_types::CardInfoUpdateRequest, } impl<'a> CardInfoMigrateExecutor<'a> { fn new( state: &'a routes::SessionState, record: &'a cards_info_api_types::CardInfoUpdateRequest, ) -> Self { Self { state, record } } async fn fetch_card_info(&self) -> RouterResult<Option<card_info_models::CardInfo>> { let db = self.state.store.as_ref(); let maybe_card_info = db .get_card_info(&self.record.card_iin) .await .change_context(errors::ApiErrorResponse::InvalidCardIin)?; Ok(maybe_card_info) } async fn add_card_info(&self) -> RouterResult<card_info_models::CardInfo> { let db = self.state.store.as_ref(); let card_info = CardsInfoInterface::add_card_info(db, self.record.clone().foreign_into()) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: "CardInfo with given key already exists in our records".to_string(), })?; Ok(card_info) } async fn update_card_info(&self) -> RouterResult<card_info_models::CardInfo> { let db = self.state.store.as_ref(); let card_info = CardsInfoInterface::update_card_info( db, self.record.card_iin.clone(), card_info_models::UpdateCardInfo { card_issuer: self.record.card_issuer.clone(), card_network: self.record.card_network.clone(), card_type: self.record.card_type.clone(), card_subtype: self.record.card_subtype.clone(), card_issuing_country: self.record.card_issuing_country.clone(), bank_code_id: self.record.bank_code_id.clone(), bank_code: self.record.bank_code.clone(), country_code: self.record.country_code.clone(), last_updated: Some(common_utils::date_time::now()), last_updated_provider: self.record.last_updated_provider.clone(), }, ) .await .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { message: "Card info with given key does not exist in our records".to_string(), }) .attach_printable("Failed while updating card info")?; Ok(card_info) } } // Builder pub struct CardInfoBuilder<S: State> { state: std::marker::PhantomData<S>, pub card_info: Option<card_info_models::CardInfo>, } impl CardInfoBuilder<CardInfoFetch> { fn new() -> Self { Self { state: std::marker::PhantomData, card_info: None, } } } impl CardInfoBuilder<CardInfoFetch> { fn set_card_info( self, card_info: card_info_models::CardInfo, ) -> CardInfoBuilder<CardInfoUpdate> { CardInfoBuilder { state: std::marker::PhantomData, card_info: Some(card_info), } } fn transition(self) -> CardInfoBuilder<CardInfoAdd> { CardInfoBuilder { state: std::marker::PhantomData, card_info: None, } } } impl CardInfoBuilder<CardInfoUpdate> { fn set_updated_card_info( self, card_info: card_info_models::CardInfo, ) -> CardInfoBuilder<CardInfoResponse> { CardInfoBuilder { state: std::marker::PhantomData, card_info: Some(card_info), } } } impl CardInfoBuilder<CardInfoAdd> { fn set_added_card_info( self, card_info: card_info_models::CardInfo, ) -> CardInfoBuilder<CardInfoResponse> { CardInfoBuilder { state: std::marker::PhantomData, card_info: Some(card_info), } } } impl CardInfoBuilder<CardInfoResponse> { pub fn build(self) -> cards_info_api_types::CardInfoMigrateResponseRecord { match self.card_info { Some(card_info) => cards_info_api_types::CardInfoMigrateResponseRecord { card_iin: Some(card_info.card_iin), card_issuer: card_info.card_issuer, card_network: card_info.card_network.map(|cn| cn.to_string()), card_type: card_info.card_type, card_sub_type: card_info.card_subtype, card_issuing_country: card_info.card_issuing_country, }, None => cards_info_api_types::CardInfoMigrateResponseRecord { card_iin: None, card_issuer: None, card_network: None, card_type: None, card_sub_type: None, card_issuing_country: None, }, } } } async fn card_info_flow( record: cards_info_api_types::CardInfoUpdateRequest, state: routes::SessionState, ) -> RouterResponse<cards_info_api_types::CardInfoMigrateResponseRecord> { let builder = CardInfoBuilder::new(); let executor = CardInfoMigrateExecutor::new(&state, &record); let fetched_card_info_details = executor.fetch_card_info().await?; let builder = match fetched_card_info_details { Some(card_info) => { let builder = builder.set_card_info(card_info); let updated_card_info = executor.update_card_info().await?; builder.set_updated_card_info(updated_card_info) } None => { let builder = builder.transition(); let added_card_info = executor.add_card_info().await?; builder.set_added_card_info(added_card_info) } }; Ok(ApplicationResponse::Json(builder.build())) }
2,582
1,588
hyperswitch
crates/router/src/core/refunds/validator.rs
.rs
use error_stack::report; use router_env::{instrument, tracing}; use time::PrimitiveDateTime; use crate::{ core::errors::{self, CustomResult, RouterResult}, types::{ self, api::enums as api_enums, storage::{self, enums}, }, utils::{self, OptionExt}, }; // Limit constraints for refunds list flow pub const LOWER_LIMIT: i64 = 1; pub const UPPER_LIMIT: i64 = 100; pub const DEFAULT_LIMIT: i64 = 10; #[derive(Debug, thiserror::Error)] pub enum RefundValidationError { #[error("The payment attempt was not successful")] UnsuccessfulPaymentAttempt, #[error("The refund amount exceeds the amount captured")] RefundAmountExceedsPaymentAmount, #[error("The order has expired")] OrderExpired, #[error("The maximum refund count for this payment attempt")] MaxRefundCountReached, #[error("There is already another refund request for this payment attempt")] DuplicateRefund, } #[instrument(skip_all)] pub fn validate_success_transaction( transaction: &storage::PaymentAttempt, ) -> CustomResult<(), RefundValidationError> { if transaction.status != enums::AttemptStatus::Charged { Err(report!(RefundValidationError::UnsuccessfulPaymentAttempt))? } Ok(()) } #[instrument(skip_all)] pub fn validate_refund_amount( amount_captured: i64, all_refunds: &[storage::Refund], refund_amount: i64, ) -> CustomResult<(), RefundValidationError> { let total_refunded_amount: i64 = all_refunds .iter() .filter_map(|refund| { if refund.refund_status != enums::RefundStatus::Failure && refund.refund_status != enums::RefundStatus::TransactionFailure { Some(refund.refund_amount.get_amount_as_i64()) } else { None } }) .sum(); utils::when( refund_amount > (amount_captured - total_refunded_amount), || { Err(report!( RefundValidationError::RefundAmountExceedsPaymentAmount )) }, ) } #[instrument(skip_all)] pub fn validate_payment_order_age( created_at: &PrimitiveDateTime, refund_max_age: i64, ) -> CustomResult<(), RefundValidationError> { let current_time = common_utils::date_time::now(); utils::when( (current_time - *created_at).whole_days() > refund_max_age, || Err(report!(RefundValidationError::OrderExpired)), ) } #[instrument(skip_all)] pub fn validate_maximum_refund_against_payment_attempt( all_refunds: &[storage::Refund], refund_max_attempts: usize, ) -> CustomResult<(), RefundValidationError> { utils::when(all_refunds.len() > refund_max_attempts, || { Err(report!(RefundValidationError::MaxRefundCountReached)) }) } pub fn validate_refund_list(limit: Option<i64>) -> CustomResult<i64, errors::ApiErrorResponse> { match limit { Some(limit_val) => { if !(LOWER_LIMIT..=UPPER_LIMIT).contains(&limit_val) { Err(errors::ApiErrorResponse::InvalidRequestData { message: "limit should be in between 1 and 100".to_string(), } .into()) } else { Ok(limit_val) } } None => Ok(DEFAULT_LIMIT), } } pub fn validate_for_valid_refunds( payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, connector: api_models::enums::Connector, ) -> RouterResult<()> { let payment_method = payment_attempt .payment_method .as_ref() .get_required_value("payment_method")?; match payment_method { diesel_models::enums::PaymentMethod::PayLater | diesel_models::enums::PaymentMethod::Wallet => { let payment_method_type = payment_attempt .payment_method_type .get_required_value("payment_method_type")?; utils::when( matches!( (connector, payment_method_type), ( api_models::enums::Connector::Braintree, diesel_models::enums::PaymentMethodType::Paypal, ) ), || { Err(errors::ApiErrorResponse::RefundNotPossible { connector: connector.to_string(), } .into()) }, ) } _ => Ok(()), } } pub fn validate_stripe_charge_refund( charge_type_option: Option<api_enums::PaymentChargeType>, split_refund_request: &Option<common_types::refunds::SplitRefund>, ) -> RouterResult<types::ChargeRefundsOptions> { let charge_type = charge_type_option.ok_or_else(|| { report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Missing `charge_type` in PaymentAttempt.") })?; let refund_request = match split_refund_request { Some(common_types::refunds::SplitRefund::StripeSplitRefund(stripe_split_refund)) => { stripe_split_refund } _ => Err(errors::ApiErrorResponse::MissingRequiredField { field_name: "stripe_split_refund", })?, }; let options = match charge_type { api_enums::PaymentChargeType::Stripe(api_enums::StripeChargeType::Direct) => { types::ChargeRefundsOptions::Direct(types::DirectChargeRefund { revert_platform_fee: refund_request .revert_platform_fee .get_required_value("revert_platform_fee")?, }) } api_enums::PaymentChargeType::Stripe(api_enums::StripeChargeType::Destination) => { types::ChargeRefundsOptions::Destination(types::DestinationChargeRefund { revert_platform_fee: refund_request .revert_platform_fee .get_required_value("revert_platform_fee")?, revert_transfer: refund_request .revert_transfer .get_required_value("revert_transfer")?, }) } }; Ok(options) } pub fn validate_adyen_charge_refund( adyen_split_payment_response: &common_types::domain::AdyenSplitData, adyen_split_refund_request: &common_types::domain::AdyenSplitData, ) -> RouterResult<()> { if adyen_split_refund_request.store != adyen_split_payment_response.store { return Err(report!(errors::ApiErrorResponse::InvalidDataValue { field_name: "split_payments.adyen_split_payment.store", })); }; for refund_split_item in adyen_split_refund_request.split_items.iter() { let refund_split_reference = refund_split_item.reference.clone(); let matching_payment_split_item = adyen_split_payment_response .split_items .iter() .find(|payment_split_item| refund_split_reference == payment_split_item.reference); if let Some(payment_split_item) = matching_payment_split_item { if let Some((refund_amount, payment_amount)) = refund_split_item.amount.zip(payment_split_item.amount) { if refund_amount > payment_amount { return Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: format!( "Invalid refund amount for split item, reference: {}", refund_split_reference ), })); } } if let Some((refund_account, payment_account)) = refund_split_item .account .as_ref() .zip(payment_split_item.account.as_ref()) { if !refund_account.eq(payment_account) { return Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: format!( "Invalid refund account for split item, reference: {}", refund_split_reference ), })); } } if refund_split_item.split_type != payment_split_item.split_type { return Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: format!( "Invalid refund split_type for split item, reference: {}", refund_split_reference ), })); } } else { return Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: format!( "No matching payment split item found for reference: {}", refund_split_reference ), })); } } Ok(()) } pub fn validate_xendit_charge_refund( xendit_split_payment_response: &common_types::payments::XenditChargeResponseData, xendit_split_refund_request: &common_types::domain::XenditSplitSubMerchantData, ) -> RouterResult<Option<String>> { match xendit_split_payment_response { common_types::payments::XenditChargeResponseData::MultipleSplits( payment_sub_merchant_data, ) => { if payment_sub_merchant_data.for_user_id != Some(xendit_split_refund_request.for_user_id.clone()) { return Err(errors::ApiErrorResponse::InvalidDataValue { field_name: "xendit_split_refund.for_user_id does not match xendit_split_payment.for_user_id", }.into()); } Ok(Some(xendit_split_refund_request.for_user_id.clone())) } common_types::payments::XenditChargeResponseData::SingleSplit( payment_sub_merchant_data, ) => { if payment_sub_merchant_data.for_user_id != xendit_split_refund_request.for_user_id { return Err(errors::ApiErrorResponse::InvalidDataValue { field_name: "xendit_split_refund.for_user_id does not match xendit_split_payment.for_user_id", }.into()); } Ok(Some(xendit_split_refund_request.for_user_id.clone())) } } }
2,081
1,589
hyperswitch
crates/router/src/core/refunds/transformers.rs
.rs
pub struct SplitRefundInput { pub refund_request: Option<common_types::refunds::SplitRefund>, pub payment_charges: Option<common_types::payments::ConnectorChargeResponseData>, pub split_payment_request: Option<common_types::payments::SplitPaymentsRequest>, pub charge_id: Option<String>, }
68
1,590
hyperswitch
crates/router/src/core/webhooks/outgoing.rs
.rs
use std::collections::HashMap; use api_models::{ webhook_events::{OutgoingWebhookRequestContent, OutgoingWebhookResponseContent}, webhooks, }; use common_utils::{ ext_traits::{Encode, StringExt}, request::RequestContent, type_name, types::keymanager::{Identifier, KeyManagerState}, }; use diesel_models::process_tracker::business_status; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation}; use hyperswitch_interfaces::consts; use masking::{ExposeInterface, Mask, PeekInterface, Secret}; use router_env::{ instrument, tracing::{self, Instrument}, }; use super::{types, utils, MERCHANT_ID}; #[cfg(feature = "stripe")] use crate::compatibility::stripe::webhooks as stripe_webhooks; use crate::{ core::{ errors::{self, CustomResult}, metrics, }, db::StorageInterface, events::outgoing_webhook_logs::{ OutgoingWebhookEvent, OutgoingWebhookEventContent, OutgoingWebhookEventMetric, }, logger, routes::{app::SessionStateInfo, SessionState}, services, types::{ api, domain::{self}, storage::{self, enums}, transformers::ForeignFrom, }, utils::{OptionExt, ValueExt}, workflows::outgoing_webhook_retry, }; const OUTGOING_WEBHOOK_TIMEOUT_SECS: u64 = 5; #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub(crate) async fn create_event_and_trigger_outgoing_webhook( state: SessionState, merchant_account: domain::MerchantAccount, business_profile: domain::Profile, merchant_key_store: &domain::MerchantKeyStore, event_type: enums::EventType, event_class: enums::EventClass, primary_object_id: String, primary_object_type: enums::EventObjectType, content: api::OutgoingWebhookContent, primary_object_created_at: Option<time::PrimitiveDateTime>, ) -> CustomResult<(), errors::ApiErrorResponse> { let delivery_attempt = enums::WebhookDeliveryAttempt::InitialAttempt; let idempotent_event_id = utils::get_idempotent_event_id(&primary_object_id, event_type, delivery_attempt); let webhook_url_result = get_webhook_url_from_business_profile(&business_profile); if !state.conf.webhooks.outgoing_enabled || webhook_url_result.is_err() || webhook_url_result.as_ref().is_ok_and(String::is_empty) { logger::debug!( business_profile_id=?business_profile.get_id(), %idempotent_event_id, "Outgoing webhooks are disabled in application configuration, or merchant webhook URL \ could not be obtained; skipping outgoing webhooks for event" ); return Ok(()); } let event_id = utils::generate_event_id(); let merchant_id = business_profile.merchant_id.clone(); let now = common_utils::date_time::now(); let outgoing_webhook = api::OutgoingWebhook { merchant_id: merchant_id.clone(), event_id: event_id.clone(), event_type, content: content.clone(), timestamp: now, }; let request_content = get_outgoing_webhook_request(&merchant_account, outgoing_webhook, &business_profile) .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("Failed to construct outgoing webhook request content")?; let event_metadata = storage::EventMetadata::foreign_from(&content); let key_manager_state = &(&state).into(); let new_event = domain::Event { event_id: event_id.clone(), event_type, event_class, is_webhook_notified: false, primary_object_id, primary_object_type, created_at: now, merchant_id: Some(business_profile.merchant_id.clone()), business_profile_id: Some(business_profile.get_id().to_owned()), primary_object_created_at, idempotent_event_id: Some(idempotent_event_id.clone()), initial_attempt_id: Some(event_id.clone()), request: Some( crypto_operation( key_manager_state, type_name!(domain::Event), CryptoOperation::Encrypt( request_content .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("Failed to encode outgoing webhook request content") .map(Secret::new)?, ), Identifier::Merchant(merchant_key_store.merchant_id.clone()), merchant_key_store.key.get_inner().peek(), ) .await .and_then(|val| val.try_into_operation()) .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("Failed to encrypt outgoing webhook request content")?, ), response: None, delivery_attempt: Some(delivery_attempt), metadata: Some(event_metadata), is_overall_delivery_successful: Some(false), }; let event_insert_result = state .store .insert_event(key_manager_state, new_event, merchant_key_store) .await; let event = match event_insert_result { Ok(event) => Ok(event), Err(error) => { if error.current_context().is_db_unique_violation() { logger::debug!("Event with idempotent ID `{idempotent_event_id}` already exists in the database"); return Ok(()); } else { logger::error!(event_insertion_failure=?error); Err(error .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("Failed to insert event in events table")) } } }?; let process_tracker = add_outgoing_webhook_retry_task_to_process_tracker( &*state.store, &business_profile, &event, ) .await .inspect_err(|error| { logger::error!( ?error, "Failed to add outgoing webhook retry task to process tracker" ); }) .ok(); let cloned_key_store = merchant_key_store.clone(); // Using a tokio spawn here and not arbiter because not all caller of this function // may have an actix arbiter tokio::spawn( async move { Box::pin(trigger_webhook_and_raise_event( state, business_profile, &cloned_key_store, event, request_content, delivery_attempt, Some(content), process_tracker, )) .await; } .in_current_span(), ); Ok(()) } #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub(crate) async fn trigger_webhook_and_raise_event( state: SessionState, business_profile: domain::Profile, merchant_key_store: &domain::MerchantKeyStore, event: domain::Event, request_content: OutgoingWebhookRequestContent, delivery_attempt: enums::WebhookDeliveryAttempt, content: Option<api::OutgoingWebhookContent>, process_tracker: Option<storage::ProcessTracker>, ) { logger::debug!( event_id=%event.event_id, idempotent_event_id=?event.idempotent_event_id, initial_attempt_id=?event.initial_attempt_id, "Attempting to send webhook" ); let merchant_id = business_profile.merchant_id.clone(); let trigger_webhook_result = trigger_webhook_to_merchant( state.clone(), business_profile, merchant_key_store, event.clone(), request_content, delivery_attempt, process_tracker, ) .await; let _ = raise_webhooks_analytics_event( state, trigger_webhook_result, content, merchant_id, event, merchant_key_store, ) .await; } async fn trigger_webhook_to_merchant( state: SessionState, business_profile: domain::Profile, merchant_key_store: &domain::MerchantKeyStore, event: domain::Event, request_content: OutgoingWebhookRequestContent, delivery_attempt: enums::WebhookDeliveryAttempt, process_tracker: Option<storage::ProcessTracker>, ) -> CustomResult<(), errors::WebhooksFlowError> { let webhook_url = match ( get_webhook_url_from_business_profile(&business_profile), process_tracker.clone(), ) { (Ok(webhook_url), _) => Ok(webhook_url), (Err(error), Some(process_tracker)) => { if !error .current_context() .is_webhook_delivery_retryable_error() { logger::debug!("Failed to obtain merchant webhook URL, aborting retries"); state .store .as_scheduler() .finish_process_with_business_status(process_tracker, business_status::FAILURE) .await .change_context( errors::WebhooksFlowError::OutgoingWebhookProcessTrackerTaskUpdateFailed, )?; } Err(error) } (Err(error), None) => Err(error), }?; let event_id = event.event_id; let headers = request_content .headers .into_iter() .map(|(name, value)| (name, value.into_masked())) .collect(); let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&webhook_url) .attach_default_headers() .headers(headers) .set_body(RequestContent::RawBytes( request_content.body.expose().into_bytes(), )) .build(); let response = state .api_client .send_request(&state, request, 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(()) } async fn raise_webhooks_analytics_event( state: SessionState, trigger_webhook_result: CustomResult<(), errors::WebhooksFlowError>, content: Option<api::OutgoingWebhookContent>, merchant_id: common_utils::id_type::MerchantId, event: domain::Event, merchant_key_store: &domain::MerchantKeyStore, ) { let key_manager_state: &KeyManagerState = &(&state).into(); let event_id = event.event_id; let error = if let Err(error) = trigger_webhook_result { logger::error!(?error, "Failed to send webhook to merchant"); serde_json::to_value(error.current_context()) .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) .inspect_err(|error| { logger::error!(?error, "Failed to serialize outgoing webhook error as JSON"); }) .ok() } else { None }; let outgoing_webhook_event_content = content .as_ref() .and_then(api::OutgoingWebhookContent::get_outgoing_webhook_event_content) .or_else(|| get_outgoing_webhook_event_content_from_event_metadata(event.metadata)); // Fetch updated_event from db let updated_event = state .store .find_event_by_merchant_id_event_id( key_manager_state, &merchant_id, &event_id, merchant_key_store, ) .await .attach_printable_lazy(|| format!("event not found for id: {}", &event_id)) .map_err(|error| { logger::error!(?error); error }) .ok(); // Get status_code from webhook response let status_code = updated_event.and_then(|updated_event| { let webhook_response: Option<OutgoingWebhookResponseContent> = updated_event.response.and_then(|res| { res.peek() .parse_struct("OutgoingWebhookResponseContent") .map_err(|error| { logger::error!(?error, "Error deserializing webhook response"); error }) .ok() }); webhook_response.and_then(|res| res.status_code) }); let webhook_event = OutgoingWebhookEvent::new( state.tenant.tenant_id.clone(), merchant_id, event_id, event.event_type, outgoing_webhook_event_content, error, event.initial_attempt_id, status_code, event.delivery_attempt, ); state.event_handler().log_event(&webhook_event); } pub(crate) async fn add_outgoing_webhook_retry_task_to_process_tracker( db: &dyn StorageInterface, business_profile: &domain::Profile, event: &domain::Event, ) -> CustomResult<storage::ProcessTracker, errors::StorageError> { let schedule_time = outgoing_webhook_retry::get_webhook_delivery_retry_schedule_time( db, &business_profile.merchant_id, 0, ) .await .ok_or(errors::StorageError::ValueNotFound( "Process tracker schedule time".into(), // Can raise a better error here )) .attach_printable("Failed to obtain initial process tracker schedule time")?; let tracking_data = types::OutgoingWebhookTrackingData { merchant_id: business_profile.merchant_id.clone(), business_profile_id: business_profile.get_id().to_owned(), event_type: event.event_type, event_class: event.event_class, primary_object_id: event.primary_object_id.clone(), primary_object_type: event.primary_object_type, initial_attempt_id: event.initial_attempt_id.clone(), }; let runner = storage::ProcessTrackerRunner::OutgoingWebhookRetryWorkflow; let task = "OUTGOING_WEBHOOK_RETRY"; let tag = ["OUTGOING_WEBHOOKS"]; let process_tracker_id = scheduler::utils::get_process_tracker_id( runner, task, &event.event_id, &business_profile.merchant_id, ); let process_tracker_entry = storage::ProcessTrackerNew::new( process_tracker_id, task, runner, tag, tracking_data, None, schedule_time, common_types::consts::API_VERSION, ) .map_err(errors::StorageError::from)?; let attributes = router_env::metric_attributes!(("flow", "OutgoingWebhookRetry")); match db.insert_process(process_tracker_entry).await { Ok(process_tracker) => { crate::routes::metrics::TASKS_ADDED_COUNT.add(1, attributes); Ok(process_tracker) } Err(error) => { crate::routes::metrics::TASK_ADDITION_FAILURES_COUNT.add(1, attributes); Err(error) } } } fn get_webhook_url_from_business_profile( business_profile: &domain::Profile, ) -> CustomResult<String, errors::WebhooksFlowError> { let webhook_details = business_profile .webhook_details .clone() .get_required_value("webhook_details") .change_context(errors::WebhooksFlowError::MerchantWebhookDetailsNotFound)?; webhook_details .webhook_url .get_required_value("webhook_url") .change_context(errors::WebhooksFlowError::MerchantWebhookUrlNotConfigured) .map(ExposeInterface::expose) } pub(crate) fn get_outgoing_webhook_request( merchant_account: &domain::MerchantAccount, outgoing_webhook: api::OutgoingWebhook, business_profile: &domain::Profile, ) -> CustomResult<OutgoingWebhookRequestContent, errors::WebhooksFlowError> { #[inline] fn get_outgoing_webhook_request_inner<WebhookType: types::OutgoingWebhookType>( outgoing_webhook: api::OutgoingWebhook, business_profile: &domain::Profile, ) -> CustomResult<OutgoingWebhookRequestContent, errors::WebhooksFlowError> { let mut headers = vec![ ( reqwest::header::CONTENT_TYPE.to_string(), mime::APPLICATION_JSON.essence_str().into(), ), ( reqwest::header::USER_AGENT.to_string(), consts::USER_AGENT.to_string().into(), ), ]; let transformed_outgoing_webhook = WebhookType::from(outgoing_webhook); let payment_response_hash_key = business_profile.payment_response_hash_key.clone(); let custom_headers = business_profile .outgoing_webhook_custom_http_headers .clone() .map(|headers| { headers .into_inner() .expose() .parse_value::<HashMap<String, String>>("HashMap<String,String>") .change_context(errors::WebhooksFlowError::OutgoingWebhookEncodingFailed) .attach_printable("Failed to deserialize outgoing webhook custom HTTP headers") }) .transpose()?; if let Some(ref map) = custom_headers { headers.extend( map.iter() .map(|(key, value)| (key.clone(), value.clone().into_masked())), ); }; let outgoing_webhooks_signature = transformed_outgoing_webhook .get_outgoing_webhooks_signature(payment_response_hash_key)?; if let Some(signature) = outgoing_webhooks_signature.signature { WebhookType::add_webhook_header(&mut headers, signature) } Ok(OutgoingWebhookRequestContent { body: outgoing_webhooks_signature.payload, headers: headers .into_iter() .map(|(name, value)| (name, Secret::new(value.into_inner()))) .collect(), }) } match merchant_account.get_compatible_connector() { #[cfg(feature = "stripe")] Some(api_models::enums::Connector::Stripe) => get_outgoing_webhook_request_inner::< stripe_webhooks::StripeOutgoingWebhook, >(outgoing_webhook, business_profile), _ => get_outgoing_webhook_request_inner::<webhooks::OutgoingWebhook>( outgoing_webhook, business_profile, ), } } #[derive(Debug)] enum ScheduleWebhookRetry { WithProcessTracker(Box<storage::ProcessTracker>), NoSchedule, } async fn update_event_if_client_error( state: SessionState, merchant_key_store: domain::MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, error_message: String, ) -> CustomResult<domain::Event, errors::WebhooksFlowError> { let is_webhook_notified = false; let key_manager_state = &(&state).into(); let response_to_store = OutgoingWebhookResponseContent { body: None, headers: None, status_code: None, error_message: Some(error_message), }; let event_update = domain::EventUpdate::UpdateResponse { is_webhook_notified, response: Some( crypto_operation( key_manager_state, type_name!(domain::Event), CryptoOperation::Encrypt( response_to_store .encode_to_string_of_json() .change_context( errors::WebhooksFlowError::OutgoingWebhookResponseEncodingFailed, ) .map(Secret::new)?, ), Identifier::Merchant(merchant_key_store.merchant_id.clone()), merchant_key_store.key.get_inner().peek(), ) .await .and_then(|val| val.try_into_operation()) .change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed) .attach_printable("Failed to encrypt outgoing webhook response content")?, ), }; state .store .update_event_by_merchant_id_event_id( key_manager_state, merchant_id, event_id, event_update, &merchant_key_store, ) .await .change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed) } async fn api_client_error_handler( state: SessionState, merchant_key_store: domain::MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, client_error: error_stack::Report<errors::ApiClientError>, delivery_attempt: enums::WebhookDeliveryAttempt, schedule_webhook_retry: ScheduleWebhookRetry, ) -> CustomResult<(), errors::WebhooksFlowError> { // Not including detailed error message in response information since it contains too // much of diagnostic information to be exposed to the merchant. update_event_if_client_error( state.clone(), merchant_key_store, merchant_id, event_id, "Unable to send request to merchant server".to_string(), ) .await?; let error = client_error.change_context(errors::WebhooksFlowError::CallToMerchantFailed); logger::error!( ?error, ?delivery_attempt, "An error occurred when sending webhook to merchant" ); if let ScheduleWebhookRetry::WithProcessTracker(process_tracker) = schedule_webhook_retry { // Schedule a retry attempt for webhook delivery outgoing_webhook_retry::retry_webhook_delivery_task( &*state.store, merchant_id, *process_tracker, ) .await .change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed)?; } Err(error) } async fn update_event_in_storage( state: SessionState, merchant_key_store: domain::MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, response: reqwest::Response, ) -> CustomResult<domain::Event, errors::WebhooksFlowError> { let status_code = response.status(); let is_webhook_notified = status_code.is_success(); let key_manager_state = &(&state).into(); let response_headers = response .headers() .iter() .map(|(name, value)| { ( name.as_str().to_owned(), value .to_str() .map(|s| Secret::from(String::from(s))) .unwrap_or_else(|error| { logger::warn!( "Response header {} contains non-UTF-8 characters: {error:?}", name.as_str() ); Secret::from(String::from("Non-UTF-8 header value")) }), ) }) .collect::<Vec<_>>(); let response_body = response .text() .await .map(Secret::from) .unwrap_or_else(|error| { logger::warn!("Response contains non-UTF-8 characters: {error:?}"); Secret::from(String::from("Non-UTF-8 response body")) }); let response_to_store = OutgoingWebhookResponseContent { body: Some(response_body), headers: Some(response_headers), status_code: Some(status_code.as_u16()), error_message: None, }; let event_update = domain::EventUpdate::UpdateResponse { is_webhook_notified, response: Some( crypto_operation( key_manager_state, type_name!(domain::Event), CryptoOperation::Encrypt( response_to_store .encode_to_string_of_json() .change_context( errors::WebhooksFlowError::OutgoingWebhookResponseEncodingFailed, ) .map(Secret::new)?, ), Identifier::Merchant(merchant_key_store.merchant_id.clone()), merchant_key_store.key.get_inner().peek(), ) .await .and_then(|val| val.try_into_operation()) .change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed) .attach_printable("Failed to encrypt outgoing webhook response content")?, ), }; state .store .update_event_by_merchant_id_event_id( key_manager_state, merchant_id, event_id, event_update, &merchant_key_store, ) .await .change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed) } async fn update_overall_delivery_status_in_storage( state: SessionState, merchant_key_store: domain::MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, updated_event: domain::Event, ) -> CustomResult<(), errors::WebhooksFlowError> { let key_manager_state = &(&state).into(); let update_overall_delivery_status = domain::EventUpdate::OverallDeliveryStatusUpdate { is_overall_delivery_successful: true, }; let initial_attempt_id = updated_event.initial_attempt_id.as_ref(); let delivery_attempt = updated_event.delivery_attempt; if let Some(( initial_attempt_id, enums::WebhookDeliveryAttempt::InitialAttempt | enums::WebhookDeliveryAttempt::AutomaticRetry, )) = initial_attempt_id.zip(delivery_attempt) { state .store .update_event_by_merchant_id_event_id( key_manager_state, merchant_id, initial_attempt_id.as_str(), update_overall_delivery_status, &merchant_key_store, ) .await .change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed) .attach_printable("Failed to update initial delivery attempt")?; } Ok(()) } fn increment_webhook_outgoing_received_count(merchant_id: &common_utils::id_type::MerchantId) { metrics::WEBHOOK_OUTGOING_RECEIVED_COUNT.add( 1, router_env::metric_attributes!((MERCHANT_ID, merchant_id.clone())), ) } async fn success_response_handler( state: SessionState, merchant_id: &common_utils::id_type::MerchantId, process_tracker: Option<storage::ProcessTracker>, business_status: &'static str, ) -> CustomResult<(), errors::WebhooksFlowError> { increment_webhook_outgoing_received_count(merchant_id); match process_tracker { Some(process_tracker) => state .store .as_scheduler() .finish_process_with_business_status(process_tracker, business_status) .await .change_context( errors::WebhooksFlowError::OutgoingWebhookProcessTrackerTaskUpdateFailed, ), None => Ok(()), } } async fn error_response_handler( state: SessionState, merchant_id: &common_utils::id_type::MerchantId, delivery_attempt: enums::WebhookDeliveryAttempt, status_code: u16, log_message: &'static str, schedule_webhook_retry: ScheduleWebhookRetry, ) -> CustomResult<(), errors::WebhooksFlowError> { metrics::WEBHOOK_OUTGOING_NOT_RECEIVED_COUNT.add( 1, router_env::metric_attributes!((MERCHANT_ID, merchant_id.clone())), ); let error = report!(errors::WebhooksFlowError::NotReceivedByMerchant); logger::warn!(?error, ?delivery_attempt, status_code, %log_message); if let ScheduleWebhookRetry::WithProcessTracker(process_tracker) = schedule_webhook_retry { // Schedule a retry attempt for webhook delivery outgoing_webhook_retry::retry_webhook_delivery_task( &*state.store, merchant_id, *process_tracker, ) .await .change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed)?; } Err(error) } impl ForeignFrom<&api::OutgoingWebhookContent> for storage::EventMetadata { fn foreign_from(content: &api::OutgoingWebhookContent) -> Self { match content { webhooks::OutgoingWebhookContent::PaymentDetails(payments_response) => Self::Payment { payment_id: payments_response.payment_id.clone(), }, webhooks::OutgoingWebhookContent::RefundDetails(refund_response) => Self::Refund { payment_id: refund_response.payment_id.clone(), refund_id: refund_response.refund_id.clone(), }, webhooks::OutgoingWebhookContent::DisputeDetails(dispute_response) => Self::Dispute { payment_id: dispute_response.payment_id.clone(), attempt_id: dispute_response.attempt_id.clone(), dispute_id: dispute_response.dispute_id.clone(), }, webhooks::OutgoingWebhookContent::MandateDetails(mandate_response) => Self::Mandate { payment_method_id: mandate_response.payment_method_id.clone(), mandate_id: mandate_response.mandate_id.clone(), }, #[cfg(feature = "payouts")] webhooks::OutgoingWebhookContent::PayoutDetails(payout_response) => Self::Payout { payout_id: payout_response.payout_id.clone(), }, } } } fn get_outgoing_webhook_event_content_from_event_metadata( event_metadata: Option<storage::EventMetadata>, ) -> Option<OutgoingWebhookEventContent> { event_metadata.map(|metadata| match metadata { diesel_models::EventMetadata::Payment { payment_id } => { OutgoingWebhookEventContent::Payment { payment_id, content: serde_json::Value::Null, } } diesel_models::EventMetadata::Payout { payout_id } => OutgoingWebhookEventContent::Payout { payout_id, content: serde_json::Value::Null, }, diesel_models::EventMetadata::Refund { payment_id, refund_id, } => OutgoingWebhookEventContent::Refund { payment_id, refund_id, content: serde_json::Value::Null, }, diesel_models::EventMetadata::Dispute { payment_id, attempt_id, dispute_id, } => OutgoingWebhookEventContent::Dispute { payment_id, attempt_id, dispute_id, content: serde_json::Value::Null, }, diesel_models::EventMetadata::Mandate { payment_method_id, mandate_id, } => OutgoingWebhookEventContent::Mandate { payment_method_id, mandate_id, content: serde_json::Value::Null, }, }) }
7,231
1,591
hyperswitch
crates/router/src/core/webhooks/incoming.rs
.rs
use std::{str::FromStr, time::Instant}; use actix_web::FromRequest; #[cfg(feature = "payouts")] use api_models::payouts as payout_models; use api_models::webhooks::{self, WebhookResponseTracker}; use common_utils::{errors::ReportSwitchExt, events::ApiEventsType}; use diesel_models::ConnectorMandateReferenceId; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ mandates::CommonMandateReference, payments::{payment_attempt::PaymentAttempt, HeaderPayload}, router_request_types::VerifyWebhookSourceRequestData, router_response_types::{VerifyWebhookSourceResponseData, VerifyWebhookStatus}, }; use hyperswitch_interfaces::webhooks::{IncomingWebhookFlowError, IncomingWebhookRequestDetails}; use masking::{ExposeInterface, PeekInterface}; use router_env::{instrument, tracing, tracing_actix_web::RequestId}; use super::{types, utils, MERCHANT_ID}; use crate::{ consts, core::{ api_locking, errors::{self, ConnectorErrorExt, CustomResult, RouterResponse, StorageErrorExt}, metrics, payments::{self, tokenization}, refunds, relay, utils as core_utils, webhooks::utils::construct_webhook_router_data, }, db::StorageInterface, events::api_logs::ApiEvent, logger, routes::{ app::{ReqState, SessionStateInfo}, lock_utils, SessionState, }, services::{ self, authentication as auth, connector_integration_interface::ConnectorEnum, ConnectorValidation, }, types::{ api::{ self, mandates::MandateResponseExt, ConnectorCommon, ConnectorData, GetToken, IncomingWebhook, }, domain, storage::{self, enums}, transformers::{ForeignFrom, ForeignInto, ForeignTryFrom}, }, utils::{self as helper_utils, ext_traits::OptionExt, generate_id}, }; #[cfg(feature = "payouts")] use crate::{core::payouts, types::storage::PayoutAttemptUpdate}; #[allow(clippy::too_many_arguments)] pub async fn incoming_webhooks_wrapper<W: types::OutgoingWebhookType>( flow: &impl router_env::types::FlowMetric, state: SessionState, req_state: ReqState, req: &actix_web::HttpRequest, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, connector_name_or_mca_id: &str, body: actix_web::web::Bytes, is_relay_webhook: bool, ) -> RouterResponse<serde_json::Value> { let start_instant = Instant::now(); let (application_response, webhooks_response_tracker, serialized_req) = Box::pin(incoming_webhooks_core::<W>( state.clone(), req_state, req, merchant_account.clone(), key_store, connector_name_or_mca_id, body.clone(), is_relay_webhook, )) .await?; logger::info!(incoming_webhook_payload = ?serialized_req); let request_duration = Instant::now() .saturating_duration_since(start_instant) .as_millis(); let request_id = RequestId::extract(req) .await .attach_printable("Unable to extract request id from request") .change_context(errors::ApiErrorResponse::InternalServerError)?; let auth_type = auth::AuthenticationType::WebhookAuth { merchant_id: merchant_account.get_id().clone(), }; let status_code = 200; let api_event = ApiEventsType::Webhooks { connector: connector_name_or_mca_id.to_string(), payment_id: webhooks_response_tracker.get_payment_id(), }; let response_value = serde_json::to_value(&webhooks_response_tracker) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not convert webhook effect to string")?; let api_event = ApiEvent::new( state.tenant.tenant_id.clone(), Some(merchant_account.get_id().clone()), flow, &request_id, request_duration, status_code, serialized_req, Some(response_value), None, auth_type, None, api_event, req, req.method(), ); state.event_handler().log_event(&api_event); Ok(application_response) } #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( state: SessionState, req_state: ReqState, req: &actix_web::HttpRequest, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, connector_name_or_mca_id: &str, body: actix_web::web::Bytes, is_relay_webhook: bool, ) -> errors::RouterResult<( services::ApplicationResponse<serde_json::Value>, WebhookResponseTracker, serde_json::Value, )> { 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)) } fn handle_incoming_webhook_error( error: error_stack::Report<errors::ApiErrorResponse>, connector: &ConnectorEnum, connector_name: &str, request_details: &IncomingWebhookRequestDetails<'_>, ) -> errors::RouterResult<( services::ApplicationResponse<serde_json::Value>, WebhookResponseTracker, serde_json::Value, )> { logger::error!(?error, "Incoming webhook flow failed"); // fetch the connector enum from the connector name let connector_enum = api_models::connector_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:?}"))?; // get the error response from the connector if connector_enum.should_acknowledge_webhook_for_resource_not_found_errors() { let response = connector .get_webhook_api_response( request_details, Some(IncomingWebhookFlowError::from(error.current_context())), ) .switch() .attach_printable("Failed to get incoming webhook api response from connector")?; Ok(( response, WebhookResponseTracker::NoEffect, serde_json::Value::Null, )) } else { Err(error) } } #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] async fn payments_incoming_webhook_flow( state: SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, business_profile: domain::Profile, key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, source_verified: bool, connector: &ConnectorEnum, request_details: &IncomingWebhookRequestDetails<'_>, event_type: webhooks::IncomingWebhookEvent, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { let consume_or_trigger_flow = if source_verified { payments::CallConnectorAction::HandleResponse(webhook_details.resource_object) } else { payments::CallConnectorAction::Trigger }; let payments_response = match webhook_details.object_reference_id { webhooks::ObjectReferenceId::PaymentId(ref id) => { let payment_id = get_payment_id( state.store.as_ref(), id, merchant_account.get_id(), merchant_account.storage_scheme, ) .await?; let lock_action = api_locking::LockAction::Hold { input: api_locking::LockingInput { unique_locking_key: payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::Payments, override_lock_retries: None, }, }; lock_action .clone() .perform_locking_action(&state, merchant_account.get_id().to_owned()) .await?; let response = Box::pin(payments::payments_core::< api::PSync, api::PaymentsResponse, _, _, _, payments::PaymentData<api::PSync>, >( state.clone(), req_state, merchant_account.clone(), None, key_store.clone(), payments::operations::PaymentStatus, api::PaymentsRetrieveRequest { resource_id: id.clone(), merchant_id: Some(merchant_account.get_id().clone()), force_sync: true, connector: None, param: None, merchant_connector_details: None, client_secret: None, expand_attempts: None, expand_captures: None, }, services::AuthFlow::Merchant, consume_or_trigger_flow.clone(), None, HeaderPayload::default(), None, //Platform merchant account )) .await; // When mandate details are present in successful webhooks, and consuming webhooks are skipped during payment sync if the payment status is already updated to charged, this function is used to update the connector mandate details. if should_update_connector_mandate_details(source_verified, event_type) { update_connector_mandate_details( &state, &merchant_account, &key_store, webhook_details.object_reference_id.clone(), connector, request_details, ) .await? }; lock_action .free_lock_action(&state, merchant_account.get_id().to_owned()) .await?; match response { Ok(value) => value, Err(err) if matches!( err.current_context(), &errors::ApiErrorResponse::PaymentNotFound ) && state .conf .webhooks .ignore_error .payment_not_found .unwrap_or(true) => { metrics::WEBHOOK_PAYMENT_NOT_FOUND.add( 1, router_env::metric_attributes!(( "merchant_id", merchant_account.get_id().clone() )), ); return Ok(WebhookResponseTracker::NoEffect); } error @ Err(_) => error?, } } _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure).attach_printable( "Did not get payment id as object reference id in webhook payments flow", )?, }; match payments_response { services::ApplicationResponse::JsonWithHeaders((payments_response, _)) => { let payment_id = payments_response.payment_id.clone(); let status = payments_response.status; let event_type: Option<enums::EventType> = payments_response.status.foreign_into(); // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook if let Some(outgoing_event_type) = event_type { let primary_object_created_at = payments_response.created; Box::pin(super::create_event_and_trigger_outgoing_webhook( state, merchant_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("received non-json response from payments core")?, } } #[cfg(feature = "payouts")] #[instrument(skip_all)] async fn payouts_incoming_webhook_flow( state: SessionState, merchant_account: domain::MerchantAccount, business_profile: domain::Profile, key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, event_type: webhooks::IncomingWebhookEvent, source_verified: bool, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { metrics::INCOMING_PAYOUT_WEBHOOK_METRIC.add(1, &[]); if source_verified { let db = &*state.store; //find payout_attempt by object_reference_id let payout_attempt = match webhook_details.object_reference_id { webhooks::ObjectReferenceId::PayoutId(payout_id_type) => match payout_id_type { webhooks::PayoutIdType::PayoutAttemptId(id) => db .find_payout_attempt_by_merchant_id_payout_attempt_id( merchant_account.get_id(), &id, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::WebhookResourceNotFound) .attach_printable("Failed to fetch the payout attempt")?, webhooks::PayoutIdType::ConnectorPayoutId(id) => db .find_payout_attempt_by_merchant_id_connector_payout_id( merchant_account.get_id(), &id, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::WebhookResourceNotFound) .attach_printable("Failed to fetch the payout attempt")?, }, _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("received a non-payout id when processing payout webhooks")?, }; let payouts = db .find_payout_by_merchant_id_payout_id( merchant_account.get_id(), &payout_attempt.payout_id, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::WebhookResourceNotFound) .attach_printable("Failed to fetch the payout")?; let payout_attempt_update = PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_attempt.connector_payout_id.clone(), status: common_enums::PayoutStatus::foreign_try_from(event_type) .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("failed payout status mapping from event type")?, error_message: None, error_code: None, is_eligible: payout_attempt.is_eligible, unified_code: None, unified_message: None, }; let action_req = payout_models::PayoutRequest::PayoutActionRequest(payout_models::PayoutActionRequest { payout_id: payouts.payout_id.clone(), }); let payout_data = payouts::make_payout_data( &state, &merchant_account, None, &key_store, &action_req, common_utils::consts::DEFAULT_LOCALE, ) .await?; let updated_payout_attempt = db .update_payout_attempt( &payout_attempt, payout_attempt_update, &payout_data.payouts, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::WebhookResourceNotFound) .attach_printable_lazy(|| { format!( "Failed while updating payout attempt: payout_attempt_id: {}", payout_attempt.payout_attempt_id ) })?; let event_type: Option<enums::EventType> = updated_payout_attempt.status.foreign_into(); // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook if let Some(outgoing_event_type) = event_type { let router_response = payouts::response_handler(&state, &merchant_account, &payout_data).await?; let payout_create_response: payout_models::PayoutCreateResponse = match router_response { services::ApplicationResponse::Json(response) => response, _ => Err(errors::ApiErrorResponse::WebhookResourceNotFound) .attach_printable("Failed to fetch the payout create response")?, }; Box::pin(super::create_event_and_trigger_outgoing_webhook( state, merchant_account, business_profile, &key_store, outgoing_event_type, enums::EventClass::Payouts, updated_payout_attempt.payout_id.clone(), enums::EventObjectType::PayoutDetails, api::OutgoingWebhookContent::PayoutDetails(Box::new(payout_create_response)), Some(updated_payout_attempt.created_at), )) .await?; } Ok(WebhookResponseTracker::Payout { payout_id: updated_payout_attempt.payout_id, status: updated_payout_attempt.status, }) } else { metrics::INCOMING_PAYOUT_WEBHOOK_SIGNATURE_FAILURE_METRIC.add(1, &[]); Err(report!( errors::ApiErrorResponse::WebhookAuthenticationFailed )) } } async fn relay_refunds_incoming_webhook_flow( state: SessionState, merchant_account: domain::MerchantAccount, business_profile: domain::Profile, merchant_key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, event_type: webhooks::IncomingWebhookEvent, source_verified: bool, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { let db = &*state.store; let key_manager_state = &(&state).into(); let relay_record = match webhook_details.object_reference_id { webhooks::ObjectReferenceId::RefundId(refund_id_type) => match refund_id_type { webhooks::RefundIdType::RefundId(refund_id) => { let relay_id = common_utils::id_type::RelayId::from_str(&refund_id) .change_context(errors::ValidationError::IncorrectValueProvided { field_name: "relay_id", }) .change_context(errors::ApiErrorResponse::InternalServerError)?; db.find_relay_by_id(key_manager_state, &merchant_key_store, &relay_id) .await .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound) .attach_printable("Failed to fetch the relay record")? } webhooks::RefundIdType::ConnectorRefundId(connector_refund_id) => db .find_relay_by_profile_id_connector_reference_id( key_manager_state, &merchant_key_store, business_profile.get_id(), &connector_refund_id, ) .await .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound) .attach_printable("Failed to fetch the relay record")?, }, _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("received a non-refund id when processing relay refund webhooks")?, }; // if source_verified then update relay status else trigger relay force sync let relay_response = if source_verified { let relay_update = hyperswitch_domain_models::relay::RelayUpdate::StatusUpdate { connector_reference_id: None, status: common_enums::RelayStatus::foreign_try_from(event_type) .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("failed relay refund status mapping from event type")?, }; db.update_relay( key_manager_state, &merchant_key_store, relay_record, relay_update, ) .await .map(api_models::relay::RelayResponse::from) .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound) .attach_printable("Failed to update relay")? } else { let relay_retrieve_request = api_models::relay::RelayRetrieveRequest { force_sync: true, id: relay_record.id, }; let relay_force_sync_response = Box::pin(relay::relay_retrieve( state, merchant_account, Some(business_profile.get_id().clone()), merchant_key_store, relay_retrieve_request, )) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to force sync relay")?; if let hyperswitch_domain_models::api::ApplicationResponse::Json(response) = relay_force_sync_response { response } else { Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unexpected response from force sync relay")? } }; Ok(WebhookResponseTracker::Relay { relay_id: relay_response.id, status: relay_response.status, }) } #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] async fn refunds_incoming_webhook_flow( state: SessionState, merchant_account: domain::MerchantAccount, business_profile: domain::Profile, key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, connector_name: &str, source_verified: bool, event_type: webhooks::IncomingWebhookEvent, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { let db = &*state.store; //find refund by connector refund id let refund = match webhook_details.object_reference_id { webhooks::ObjectReferenceId::RefundId(refund_id_type) => match refund_id_type { webhooks::RefundIdType::RefundId(id) => db .find_refund_by_merchant_id_refund_id( merchant_account.get_id(), &id, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::WebhookResourceNotFound) .attach_printable("Failed to fetch the refund")?, webhooks::RefundIdType::ConnectorRefundId(id) => db .find_refund_by_merchant_id_connector_refund_id_connector( merchant_account.get_id(), &id, connector_name, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::WebhookResourceNotFound) .attach_printable("Failed to fetch the refund")?, }, _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("received a non-refund id when processing refund webhooks")?, }; let refund_id = refund.refund_id.to_owned(); //if source verified then update refund status else trigger refund sync let updated_refund = if source_verified { let refund_update = storage::RefundUpdate::StatusUpdate { connector_refund_id: None, sent_to_gateway: true, refund_status: common_enums::RefundStatus::foreign_try_from(event_type) .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("failed refund status mapping from event type")?, updated_by: merchant_account.storage_scheme.to_string(), processor_refund_data: None, }; db.update_refund( refund.to_owned(), refund_update, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound) .attach_printable_lazy(|| format!("Failed while updating refund: refund_id: {refund_id}"))? } else { Box::pin(refunds::refund_retrieve_core_with_refund_id( state.clone(), merchant_account.clone(), None, key_store.clone(), api_models::refunds::RefundsRetrieveRequest { refund_id: refund_id.to_owned(), force_sync: Some(true), merchant_connector_details: None, }, )) .await .attach_printable_lazy(|| format!("Failed while updating refund: refund_id: {refund_id}"))? }; let event_type: Option<enums::EventType> = updated_refund.refund_status.foreign_into(); // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook if let Some(outgoing_event_type) = event_type { let refund_response: api_models::refunds::RefundResponse = updated_refund.clone().foreign_into(); Box::pin(super::create_event_and_trigger_outgoing_webhook( state, merchant_account, business_profile, &key_store, outgoing_event_type, enums::EventClass::Refunds, refund_id, enums::EventObjectType::RefundDetails, api::OutgoingWebhookContent::RefundDetails(Box::new(refund_response)), Some(updated_refund.created_at), )) .await?; } Ok(WebhookResponseTracker::Refund { payment_id: updated_refund.payment_id, refund_id: updated_refund.refund_id, status: updated_refund.refund_status, }) } async fn relay_incoming_webhook_flow( state: SessionState, merchant_account: domain::MerchantAccount, business_profile: domain::Profile, merchant_key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, event_type: webhooks::IncomingWebhookEvent, source_verified: bool, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { let flow_type: api::WebhookFlow = event_type.into(); let result_response = match flow_type { webhooks::WebhookFlow::Refund => Box::pin(relay_refunds_incoming_webhook_flow( state, merchant_account, business_profile, merchant_key_store, webhook_details, event_type, source_verified, )) .await .attach_printable("Incoming webhook flow for relay refund failed")?, webhooks::WebhookFlow::Payment | webhooks::WebhookFlow::Payout | webhooks::WebhookFlow::Dispute | webhooks::WebhookFlow::Subscription | webhooks::WebhookFlow::ReturnResponse | webhooks::WebhookFlow::BankTransfer | webhooks::WebhookFlow::Mandate | webhooks::WebhookFlow::ExternalAuthentication | webhooks::WebhookFlow::FraudCheck => Err(errors::ApiErrorResponse::NotSupported { message: "Relay webhook flow types not supported".to_string(), })?, }; Ok(result_response) } 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")?, } } #[allow(clippy::too_many_arguments)] async fn get_or_update_dispute_object( state: SessionState, option_dispute: Option<diesel_models::dispute::Dispute>, dispute_details: api::disputes::DisputePayload, merchant_id: &common_utils::id_type::MerchantId, organization_id: &common_utils::id_type::OrganizationId, payment_attempt: &PaymentAttempt, event_type: webhooks::IncomingWebhookEvent, business_profile: &domain::Profile, connector_name: &str, ) -> CustomResult<diesel_models::dispute::Dispute, errors::ApiErrorResponse> { let db = &*state.store; match option_dispute { None => { metrics::INCOMING_DISPUTE_WEBHOOK_NEW_RECORD_METRIC.add(1, &[]); let dispute_id = generate_id(consts::ID_LENGTH, "dp"); let new_dispute = diesel_models::dispute::DisputeNew { dispute_id, amount: dispute_details.amount.clone(), currency: dispute_details.currency.to_string(), dispute_stage: dispute_details.dispute_stage, dispute_status: common_enums::DisputeStatus::foreign_try_from(event_type) .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("event type to dispute status mapping failed")?, payment_id: payment_attempt.payment_id.to_owned(), connector: connector_name.to_owned(), attempt_id: payment_attempt.attempt_id.to_owned(), merchant_id: merchant_id.to_owned(), connector_status: dispute_details.connector_status, connector_dispute_id: dispute_details.connector_dispute_id, connector_reason: dispute_details.connector_reason, connector_reason_code: dispute_details.connector_reason_code, challenge_required_by: dispute_details.challenge_required_by, connector_created_at: dispute_details.created_at, connector_updated_at: dispute_details.updated_at, profile_id: Some(business_profile.get_id().to_owned()), evidence: None, merchant_connector_id: payment_attempt.merchant_connector_id.clone(), dispute_amount: dispute_details.amount.parse::<i64>().unwrap_or(0), organization_id: organization_id.clone(), dispute_currency: Some(dispute_details.currency), }; state .store .insert_dispute(new_dispute.clone()) .await .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound) } Some(dispute) => { logger::info!("Dispute Already exists, Updating the dispute details"); metrics::INCOMING_DISPUTE_WEBHOOK_UPDATE_RECORD_METRIC.add(1, &[]); let dispute_status = diesel_models::enums::DisputeStatus::foreign_try_from(event_type) .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("event type to dispute state conversion failure")?; crate::core::utils::validate_dispute_stage_and_dispute_status( dispute.dispute_stage, dispute.dispute_status, dispute_details.dispute_stage, dispute_status, ) .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("dispute stage and status validation failed")?; let update_dispute = diesel_models::dispute::DisputeUpdate::Update { dispute_stage: dispute_details.dispute_stage, dispute_status, connector_status: dispute_details.connector_status, connector_reason: dispute_details.connector_reason, connector_reason_code: dispute_details.connector_reason_code, challenge_required_by: dispute_details.challenge_required_by, connector_updated_at: dispute_details.updated_at, }; db.update_dispute(dispute, update_dispute) .await .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound) } } } #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] async fn external_authentication_incoming_webhook_flow( state: SessionState, req_state: ReqState, merchant_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 )) } } #[instrument(skip_all)] async fn mandates_incoming_webhook_flow( state: SessionState, merchant_account: domain::MerchantAccount, business_profile: domain::Profile, key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, source_verified: bool, event_type: webhooks::IncomingWebhookEvent, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { if source_verified { let db = &*state.store; let mandate = match webhook_details.object_reference_id { webhooks::ObjectReferenceId::MandateId(webhooks::MandateIdType::MandateId( 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 )) } } #[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) .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 )) } } #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] async fn disputes_incoming_webhook_flow( state: SessionState, merchant_account: domain::MerchantAccount, business_profile: domain::Profile, key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, source_verified: bool, connector: &ConnectorEnum, request_details: &IncomingWebhookRequestDetails<'_>, event_type: webhooks::IncomingWebhookEvent, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { metrics::INCOMING_DISPUTE_WEBHOOK_METRIC.add(1, &[]); if source_verified { 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 )) } } #[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, &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")?, } } async fn get_payment_id( db: &dyn StorageInterface, payment_id: &api::PaymentIdType, merchant_id: &common_utils::id_type::MerchantId, storage_scheme: enums::MerchantStorageScheme, ) -> errors::RouterResult<common_utils::id_type::PaymentId> { let pay_id = || async { match payment_id { api_models::payments::PaymentIdType::PaymentIntentId(ref id) => Ok(id.to_owned()), api_models::payments::PaymentIdType::ConnectorTransactionId(ref id) => db .find_payment_attempt_by_merchant_id_connector_txn_id( merchant_id, id, storage_scheme, ) .await .map(|p| p.payment_id), api_models::payments::PaymentIdType::PaymentAttemptId(ref id) => db .find_payment_attempt_by_attempt_id_merchant_id(id, merchant_id, storage_scheme) .await .map(|p| p.payment_id), api_models::payments::PaymentIdType::PreprocessingId(ref id) => db .find_payment_attempt_by_preprocessing_id_merchant_id( id, merchant_id, storage_scheme, ) .await .map(|p| p.payment_id), } }; pay_id() .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) } #[inline] async fn verify_webhook_source_verification_call( connector: ConnectorEnum, state: &SessionState, merchant_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), } } fn get_connector_by_connector_name( state: &SessionState, connector_name: &str, merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, ) -> CustomResult<(ConnectorEnum, String), errors::ApiErrorResponse> { let authentication_connector = api_models::enums::convert_authentication_connector(connector_name); #[cfg(feature = "frm")] { let frm_connector = api_models::enums::convert_frm_connector(connector_name); if frm_connector.is_some() { let frm_connector_data = api::FraudCheckConnectorData::get_connector_by_name(connector_name)?; return Ok(( frm_connector_data.connector, frm_connector_data.connector_name.to_string(), )); } } let (connector, connector_name) = if authentication_connector.is_some() { let authentication_connector_data = api::AuthenticationConnectorData::get_connector_by_name(connector_name)?; ( authentication_connector_data.connector, authentication_connector_data.connector_name.to_string(), ) } else { let connector_data = ConnectorData::get_connector_by_name( &state.conf.connectors, connector_name, GetToken::Connector, merchant_connector_id, ) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "invalid connector name received".to_string(), }) .attach_printable("Failed construction of ConnectorData")?; ( connector_data.connector, connector_data.connector_name.to_string(), ) }; Ok((connector, connector_name)) } /// This function fetches the merchant connector account ( if the url used is /{merchant_connector_id}) /// if merchant connector id is not passed in the request, then this will return None for mca async fn fetch_optional_mca_and_connector( state: &SessionState, merchant_account: &domain::MerchantAccount, connector_name_or_mca_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult< ( Option<domain::MerchantConnectorAccount>, ConnectorEnum, String, ), errors::ApiErrorResponse, > { let db = &state.store; if connector_name_or_mca_id.starts_with("mca_") { #[cfg(feature = "v1")] let mca = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( &state.into(), merchant_account.get_id(), &common_utils::id_type::MerchantConnectorAccountId::wrap( connector_name_or_mca_id.to_owned(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Error while converting MerchanConnectorAccountId from string ", )?, key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: connector_name_or_mca_id.to_string(), }) .attach_printable( "error while fetching merchant_connector_account from connector_id", )?; #[cfg(feature = "v2")] let mca: domain::MerchantConnectorAccount = { let _ = merchant_account; let _ = key_store; let _ = db; todo!() }; let (connector, connector_name) = get_connector_by_connector_name(state, &mca.connector_name, Some(mca.get_id()))?; Ok((Some(mca), connector, connector_name)) } else { // Merchant connector account is already being queried, it is safe to set connector id as None let (connector, connector_name) = get_connector_by_connector_name(state, connector_name_or_mca_id, None)?; Ok((None, connector, connector_name)) } } fn should_update_connector_mandate_details( source_verified: bool, event_type: webhooks::IncomingWebhookEvent, ) -> bool { source_verified && event_type == webhooks::IncomingWebhookEvent::PaymentIntentSuccess } async fn update_connector_mandate_details( state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, object_ref_id: api::ObjectReferenceId, connector: &ConnectorEnum, request_details: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<(), errors::ApiErrorResponse> { let webhook_connector_mandate_details = connector .get_mandate_details(request_details) .switch() .attach_printable("Could not find connector mandate details in incoming webhook body")?; let webhook_connector_network_transaction_id = connector .get_network_txn_id(request_details) .switch() .attach_printable( "Could not find connector network transaction id in incoming webhook body", )?; // Either one OR both of the fields are present if webhook_connector_mandate_details.is_some() || webhook_connector_network_transaction_id.is_some() { let payment_attempt = get_payment_attempt_from_object_reference_id(state, object_ref_id, merchant_account) .await?; if let Some(ref payment_method_id) = payment_attempt.payment_method_id { let key_manager_state = &state.into(); let payment_method_info = state .store .find_payment_method( key_manager_state, key_store, payment_method_id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; // Update connector's mandate details let updated_connector_mandate_details = if let Some(webhook_mandate_details) = webhook_connector_mandate_details { let mandate_details = payment_method_info .get_common_mandate_reference() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to deserialize to Payment Mandate Reference")?; let merchant_connector_account_id = payment_attempt .merchant_connector_id .clone() .get_required_value("merchant_connector_id")?; if mandate_details.payments.as_ref().map_or(true, |payments| { !payments.0.contains_key(&merchant_connector_account_id) }) { // Update the payment attempt to maintain consistency across tables. let (mandate_metadata, connector_mandate_request_reference_id) = payment_attempt .connector_mandate_detail .as_ref() .map(|details| { ( details.mandate_metadata.clone(), details.connector_mandate_request_reference_id.clone(), ) }) .unwrap_or((None, None)); let connector_mandate_reference_id = ConnectorMandateReferenceId { connector_mandate_id: Some( webhook_mandate_details .connector_mandate_id .peek() .to_string(), ), payment_method_id: Some(payment_method_id.to_string()), mandate_metadata, connector_mandate_request_reference_id, }; let attempt_update = storage::PaymentAttemptUpdate::ConnectorMandateDetailUpdate { connector_mandate_detail: Some(connector_mandate_reference_id), updated_by: merchant_account.storage_scheme.to_string(), }; state .store .update_payment_attempt_with_attempt_id( payment_attempt.clone(), attempt_update, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; insert_mandate_details( &payment_attempt, &webhook_mandate_details, Some(mandate_details), )? } else { logger::info!( "Skipping connector mandate details update since they are already present." ); None } } else { None }; let connector_mandate_details_value = updated_connector_mandate_details .map(|common_mandate| { common_mandate.get_mandate_details_value().map_err(|err| { router_env::logger::error!( "Failed to get get_mandate_details_value : {:?}", err ); errors::ApiErrorResponse::MandateUpdateFailed }) }) .transpose()?; let pm_update = diesel_models::PaymentMethodUpdate::ConnectorNetworkTransactionIdAndMandateDetailsUpdate { connector_mandate_details: connector_mandate_details_value.map(masking::Secret::new), network_transaction_id: webhook_connector_network_transaction_id .map(|webhook_network_transaction_id| webhook_network_transaction_id.get_id().clone()), }; state .store .update_payment_method( key_manager_state, key_store, payment_method_info, pm_update, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update payment method in db")?; } } Ok(()) } fn insert_mandate_details( payment_attempt: &PaymentAttempt, webhook_mandate_details: &hyperswitch_domain_models::router_flow_types::ConnectorMandateDetails, payment_method_mandate_details: Option<CommonMandateReference>, ) -> CustomResult<Option<CommonMandateReference>, errors::ApiErrorResponse> { let (mandate_metadata, connector_mandate_request_reference_id) = payment_attempt .connector_mandate_detail .clone() .map(|mandate_reference| { ( mandate_reference.mandate_metadata, mandate_reference.connector_mandate_request_reference_id, ) }) .unwrap_or((None, None)); let connector_mandate_details = tokenization::update_connector_mandate_details( payment_method_mandate_details, payment_attempt.payment_method_type, Some( payment_attempt .net_amount .get_total_amount() .get_amount_as_i64(), ), payment_attempt.currency, payment_attempt.merchant_connector_id.clone(), Some( webhook_mandate_details .connector_mandate_id .peek() .to_string(), ), mandate_metadata, connector_mandate_request_reference_id, )?; Ok(connector_mandate_details) }
16,306
1,592
hyperswitch
crates/router/src/core/webhooks/utils.rs
.rs
use std::marker::PhantomData; use common_utils::{errors::CustomResult, ext_traits::ValueExt}; use error_stack::ResultExt; use crate::{ core::{ errors::{self}, payments::helpers, }, db::{get_and_deserialize_key, StorageInterface}, services::logger, types::{self, api, domain, PaymentAddress}, SessionState, }; const IRRELEVANT_ATTEMPT_ID_IN_SOURCE_VERIFICATION_FLOW: &str = "irrelevant_attempt_id_in_source_verification_flow"; const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_SOURCE_VERIFICATION_FLOW: &str = "irrelevant_connector_request_reference_id_in_source_verification_flow"; /// Check whether the merchant has configured to disable the webhook `event` for the `connector` /// First check for the key "whconf_{merchant_id}_{connector_id}" in redis, /// if not found, fetch from configs table in database pub async fn is_webhook_event_disabled( db: &dyn StorageInterface, connector_id: &str, merchant_id: &common_utils::id_type::MerchantId, event: &api::IncomingWebhookEvent, ) -> bool { let redis_key = merchant_id.get_webhook_config_disabled_events_key(connector_id); let merchant_webhook_disable_config_result: CustomResult< api::MerchantWebhookConfig, redis_interface::errors::RedisError, > = get_and_deserialize_key(db, &redis_key, "MerchantWebhookConfig").await; match merchant_webhook_disable_config_result { Ok(merchant_webhook_config) => merchant_webhook_config.contains(event), Err(..) => { //if failed to fetch from redis. fetch from db and populate redis db.find_config_by_key(&redis_key) .await .map(|config| { match serde_json::from_str::<api::MerchantWebhookConfig>(&config.config) { Ok(set) => set.contains(event), Err(err) => { logger::warn!(?err, "error while parsing merchant webhook config"); false } } }) .unwrap_or_else(|err| { logger::warn!(?err, "error while fetching merchant webhook config"); false }) } } } pub async fn construct_webhook_router_data( state: &SessionState, connector_name: &str, merchant_connector_account: domain::MerchantConnectorAccount, merchant_account: &domain::MerchantAccount, connector_wh_secrets: &api_models::webhooks::ConnectorWebhookSecrets, request_details: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<types::VerifyWebhookSourceRouterData, errors::ApiErrorResponse> { let auth_type: types::ConnectorAuthType = helpers::MerchantConnectorAccountType::DbVal(Box::new(merchant_connector_account.clone())) .get_connector_account_details() .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InternalServerError)?; let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_account.get_id().clone(), connector: connector_name.to_string(), customer_id: None, tenant_id: state.tenant.tenant_id.clone(), payment_id: common_utils::id_type::PaymentId::get_irrelevant_id("source_verification_flow") .get_string_repr() .to_owned(), attempt_id: IRRELEVANT_ATTEMPT_ID_IN_SOURCE_VERIFICATION_FLOW.to_string(), status: diesel_models::enums::AttemptStatus::default(), payment_method: diesel_models::enums::PaymentMethod::default(), connector_auth_type: auth_type, description: None, address: PaymentAddress::default(), auth_type: diesel_models::enums::AuthenticationType::default(), connector_meta_data: None, connector_wallets_details: None, amount_captured: None, minor_amount_captured: None, request: types::VerifyWebhookSourceRequestData { webhook_headers: request_details.headers.clone(), webhook_body: request_details.body.to_vec().clone(), merchant_secret: connector_wh_secrets.to_owned(), }, response: Err(types::ErrorResponse::default()), access_token: None, session_token: None, reference_id: None, payment_method_token: None, connector_customer: None, recurring_mandate_payment_data: None, preprocessing_id: None, connector_request_reference_id: IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_SOURCE_VERIFICATION_FLOW.to_string(), #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, test_mode: None, payment_method_balance: None, payment_method_status: None, connector_api_version: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, }; Ok(router_data) } #[inline] pub(crate) fn get_idempotent_event_id( primary_object_id: &str, event_type: types::storage::enums::EventType, delivery_attempt: types::storage::enums::WebhookDeliveryAttempt, ) -> String { use crate::types::storage::enums::WebhookDeliveryAttempt; const EVENT_ID_SUFFIX_LENGTH: usize = 8; let common_prefix = format!("{primary_object_id}_{event_type}"); match delivery_attempt { WebhookDeliveryAttempt::InitialAttempt => common_prefix, WebhookDeliveryAttempt::AutomaticRetry | WebhookDeliveryAttempt::ManualRetry => { common_utils::generate_id(EVENT_ID_SUFFIX_LENGTH, &common_prefix) } } } #[inline] pub(crate) fn generate_event_id() -> String { common_utils::generate_time_ordered_id("evt") }
1,296
1,593
hyperswitch
crates/router/src/core/webhooks/recovery_incoming.rs
.rs
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, }; #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] #[cfg(feature = "revenue_recovery")] 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) } } } #[derive(Debug)] pub struct RevenueRecoveryInvoice(revenue_recovery::RevenueRecoveryInvoiceData); #[derive(Debug)] pub struct RevenueRecoveryAttempt(revenue_recovery::RevenueRecoveryAttemptData); impl RevenueRecoveryInvoice { fn get_recovery_invoice_details( connector_enum: &connector_integration_interface::ConnectorEnum, request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>, billing_connector_payment_details: Option< &revenue_recovery_response::BillingConnectorPaymentsSyncResponse, >, ) -> CustomResult<Self, errors::RevenueRecoveryError> { billing_connector_payment_details.map_or_else( || { interface_webhooks::IncomingWebhook::get_revenue_recovery_invoice_details( connector_enum, request_details, ) .change_context(errors::RevenueRecoveryError::InvoiceWebhookProcessingFailed) .attach_printable("Failed while getting revenue recovery invoice details") .map(RevenueRecoveryInvoice) }, |data| { Ok(Self(revenue_recovery::RevenueRecoveryInvoiceData::from( data, ))) }, ) } async fn get_payment_intent( &self, state: &SessionState, req_state: &ReqState, merchant_account: &domain::MerchantAccount, profile: &domain::Profile, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Option<revenue_recovery::RecoveryPaymentIntent>, errors::RevenueRecoveryError> { let payment_response = Box::pin(payments::payments_get_intent_using_merchant_reference( state.clone(), merchant_account.clone(), profile.clone(), key_store.clone(), req_state.clone(), &self.0.merchant_reference_id, hyperswitch_domain_models::payments::HeaderPayload::default(), None, )) .await; let response = match payment_response { Ok(services::ApplicationResponse::JsonWithHeaders((payments_response, _))) => { let payment_id = payments_response.id.clone(); let status = payments_response.status; let feature_metadata = payments_response.feature_metadata; Ok(Some(revenue_recovery::RecoveryPaymentIntent { payment_id, status, feature_metadata, })) } Err(err) if matches!( err.current_context(), &errors::ApiErrorResponse::PaymentNotFound ) => { Ok(None) } Ok(_) => Err(errors::RevenueRecoveryError::PaymentIntentFetchFailed) .attach_printable("Unexpected response from payment intent core"), error @ Err(_) => { router_env::logger::error!(?error); Err(errors::RevenueRecoveryError::PaymentIntentFetchFailed) .attach_printable("failed to fetch payment intent recovery webhook flow") } }?; Ok(response) } async fn create_payment_intent( &self, state: &SessionState, req_state: &ReqState, merchant_account: &domain::MerchantAccount, profile: &domain::Profile, key_store: &domain::MerchantKeyStore, ) -> CustomResult<revenue_recovery::RecoveryPaymentIntent, errors::RevenueRecoveryError> { let payload = api_payments::PaymentsCreateIntentRequest::from(&self.0); let global_payment_id = id_type::GlobalPaymentId::generate(&state.conf.cell_information.id); let create_intent_response = Box::pin(payments::payments_intent_core::< router_flow_types::payments::PaymentCreateIntent, api_payments::PaymentsIntentResponse, _, _, hyperswitch_domain_models::payments::PaymentIntentData< router_flow_types::payments::PaymentCreateIntent, >, >( state.clone(), req_state.clone(), merchant_account.clone(), profile.clone(), key_store.clone(), payments::operations::PaymentIntentCreate, payload, global_payment_id, hyperswitch_domain_models::payments::HeaderPayload::default(), None, )) .await .change_context(errors::RevenueRecoveryError::PaymentIntentCreateFailed)?; let response = create_intent_response .get_json_body() .change_context(errors::RevenueRecoveryError::PaymentIntentCreateFailed) .attach_printable("expected json response")?; Ok(revenue_recovery::RecoveryPaymentIntent { payment_id: response.id, status: response.status, feature_metadata: response.feature_metadata, }) } } impl RevenueRecoveryAttempt { 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, ))) }, ) } async fn get_payment_attempt( &self, state: &SessionState, req_state: &ReqState, merchant_account: &domain::MerchantAccount, profile: &domain::Profile, key_store: &domain::MerchantKeyStore, payment_id: id_type::GlobalPaymentId, ) -> CustomResult<Option<revenue_recovery::RecoveryPaymentAttempt>, errors::RevenueRecoveryError> { let attempt_response = Box::pin(payments::payments_core::< router_flow_types::payments::PSync, api_payments::PaymentsResponse, _, _, _, hyperswitch_domain_models::payments::PaymentStatusData< router_flow_types::payments::PSync, >, >( state.clone(), req_state.clone(), merchant_account.clone(), profile.clone(), key_store.clone(), payments::operations::PaymentGet, api_payments::PaymentsRetrieveRequest { force_sync: false, expand_attempts: true, param: None, }, payment_id.clone(), payments::CallConnectorAction::Avoid, hyperswitch_domain_models::payments::HeaderPayload::default(), )) .await; let response = match attempt_response { Ok(services::ApplicationResponse::JsonWithHeaders((payments_response, _))) => { let final_attempt = self.0 .connector_transaction_id .as_ref() .and_then(|transaction_id| { payments_response .find_attempt_in_attempts_list_using_connector_transaction_id( transaction_id, ) }); let payment_attempt = final_attempt.map(|attempt_res| revenue_recovery::RecoveryPaymentAttempt { attempt_id: attempt_res.id.to_owned(), attempt_status: attempt_res.status.to_owned(), feature_metadata: attempt_res.feature_metadata.to_owned(), }); Ok(payment_attempt) } Ok(_) => Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed) .attach_printable("Unexpected response from payment intent core"), error @ Err(_) => { router_env::logger::error!(?error); Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed) .attach_printable("failed to fetch payment attempt in recovery webhook flow") } }?; Ok(response) } #[allow(clippy::too_many_arguments)] async fn record_payment_attempt( &self, state: &SessionState, req_state: &ReqState, merchant_account: &domain::MerchantAccount, profile: &domain::Profile, key_store: &domain::MerchantKeyStore, payment_id: id_type::GlobalPaymentId, billing_connector_account_id: &id_type::MerchantConnectorAccountId, payment_connector_account: Option<domain::MerchantConnectorAccount>, ) -> CustomResult<revenue_recovery::RecoveryPaymentAttempt, errors::RevenueRecoveryError> { let request_payload = self .create_payment_record_request(billing_connector_account_id, payment_connector_account); let attempt_response = Box::pin(payments::record_attempt_core( state.clone(), req_state.clone(), merchant_account.clone(), profile.clone(), key_store.clone(), request_payload, payment_id.clone(), hyperswitch_domain_models::payments::HeaderPayload::default(), None, )) .await; let response = match attempt_response { Ok(services::ApplicationResponse::JsonWithHeaders((attempt_response, _))) => { Ok(revenue_recovery::RecoveryPaymentAttempt { attempt_id: attempt_response.id, attempt_status: attempt_response.status, feature_metadata: attempt_response.feature_metadata, }) } Ok(_) => Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed) .attach_printable("Unexpected response from record attempt core"), error @ Err(_) => { router_env::logger::error!(?error); Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed) .attach_printable("failed to record attempt in recovery webhook flow") } }?; Ok(response) } 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(), } } pub async fn find_payment_merchant_connector_account( &self, state: &SessionState, key_store: &domain::MerchantKeyStore, billing_connector_account: &domain::MerchantConnectorAccount, ) -> CustomResult<Option<domain::MerchantConnectorAccount>, errors::RevenueRecoveryError> { let payment_merchant_connector_account_id = billing_connector_account .get_payment_merchant_connector_account_id_using_account_reference_id( self.0.connector_account_reference_id.clone(), ); let db = &*state.store; let key_manager_state = &(state).into(); let payment_merchant_connector_account = payment_merchant_connector_account_id .as_ref() .async_map(|mca_id| async move { db.find_merchant_connector_account_by_id(key_manager_state, mca_id, key_store) .await }) .await .transpose() .change_context(errors::RevenueRecoveryError::PaymentMerchantConnectorAccountNotFound) .attach_printable( "failed to fetch payment merchant connector id using account reference id", )?; Ok(payment_merchant_connector_account) } #[allow(clippy::too_many_arguments)] async fn get_recovery_payment_attempt( is_recovery_transaction_event: bool, billing_connector_account: &domain::MerchantConnectorAccount, state: &SessionState, 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) } 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, }) } } pub struct BillingConnectorPaymentsSyncResponseData( revenue_recovery_response::BillingConnectorPaymentsSyncResponse, ); pub struct BillingConnectorPaymentsSyncFlowRouterData( router_types::BillingConnectorPaymentsSyncRouterData, ); impl BillingConnectorPaymentsSyncResponseData { async fn handle_billing_connector_payment_sync_call( state: &SessionState, merchant_account: &domain::MerchantAccount, merchant_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, connector_name: &str, id: &str, ) -> CustomResult<Self, errors::RevenueRecoveryError> { let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, connector_name, api::GetToken::Connector, None, ) .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)) } 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) } fn inner(self) -> revenue_recovery_response::BillingConnectorPaymentsSyncResponse { self.0 } } impl BillingConnectorPaymentsSyncFlowRouterData { async fn construct_router_data_for_billing_connector_payment_sync_call( state: &SessionState, connector_name: &str, merchant_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, merchant_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)) } fn inner(self) -> router_types::BillingConnectorPaymentsSyncRouterData { self.0 } }
6,169
1,594
hyperswitch
crates/router/src/core/webhooks/types.rs
.rs
use api_models::webhooks; use common_utils::{crypto::SignMessage, ext_traits::Encode}; use error_stack::ResultExt; use masking::Secret; use serde::Serialize; use crate::{core::errors, headers, services::request::Maskable, types::storage::enums}; pub struct OutgoingWebhookPayloadWithSignature { pub payload: Secret<String>, pub signature: Option<String>, } pub trait OutgoingWebhookType: Serialize + From<webhooks::OutgoingWebhook> + Sync + Send + std::fmt::Debug + 'static { fn get_outgoing_webhooks_signature( &self, payment_response_hash_key: Option<impl AsRef<[u8]>>, ) -> errors::CustomResult<OutgoingWebhookPayloadWithSignature, errors::WebhooksFlowError>; fn add_webhook_header(header: &mut Vec<(String, Maskable<String>)>, signature: String); } impl OutgoingWebhookType for webhooks::OutgoingWebhook { fn get_outgoing_webhooks_signature( &self, payment_response_hash_key: Option<impl AsRef<[u8]>>, ) -> errors::CustomResult<OutgoingWebhookPayloadWithSignature, errors::WebhooksFlowError> { let webhook_signature_payload = self .encode_to_string_of_json() .change_context(errors::WebhooksFlowError::OutgoingWebhookEncodingFailed) .attach_printable("failed encoding outgoing webhook payload")?; let signature = payment_response_hash_key .map(|key| { common_utils::crypto::HmacSha512::sign_message( &common_utils::crypto::HmacSha512, key.as_ref(), webhook_signature_payload.as_bytes(), ) }) .transpose() .change_context(errors::WebhooksFlowError::OutgoingWebhookSigningFailed) .attach_printable("Failed to sign the message")? .map(hex::encode); Ok(OutgoingWebhookPayloadWithSignature { payload: webhook_signature_payload.into(), signature, }) } fn add_webhook_header(header: &mut Vec<(String, Maskable<String>)>, signature: String) { header.push((headers::X_WEBHOOK_SIGNATURE.to_string(), signature.into())) } } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub(crate) struct OutgoingWebhookTrackingData { pub(crate) merchant_id: common_utils::id_type::MerchantId, pub(crate) business_profile_id: common_utils::id_type::ProfileId, pub(crate) event_type: enums::EventType, pub(crate) event_class: enums::EventClass, pub(crate) primary_object_id: String, pub(crate) primary_object_type: enums::EventObjectType, pub(crate) initial_attempt_id: Option<String>, }
599
1,595
hyperswitch
crates/router/src/core/webhooks/incoming_v2.rs
.rs
use std::{marker::PhantomData, str::FromStr, time::Instant}; use actix_web::FromRequest; use api_models::webhooks::{self, WebhookResponseTracker}; use common_utils::{ errors::ReportSwitchExt, events::ApiEventsType, types::keymanager::KeyManagerState, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ payments::{HeaderPayload, PaymentStatusData}, router_request_types::VerifyWebhookSourceRequestData, router_response_types::{VerifyWebhookSourceResponseData, VerifyWebhookStatus}, }; use hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails; use router_env::{instrument, tracing, tracing_actix_web::RequestId}; use super::{types, utils, MERCHANT_ID}; #[cfg(feature = "revenue_recovery")] use crate::core::webhooks::recovery_incoming; use crate::{ core::{ api_locking, errors::{self, ConnectorErrorExt, CustomResult, RouterResponse, StorageErrorExt}, metrics, payments::{ self, transformers::{GenerateResponse, ToResponse}, }, webhooks::utils::construct_webhook_router_data, }, db::StorageInterface, events::api_logs::ApiEvent, logger, routes::{ app::{ReqState, SessionStateInfo}, lock_utils, SessionState, }, services::{ self, authentication as auth, connector_integration_interface::ConnectorEnum, ConnectorValidation, }, types::{ api::{self, ConnectorData, GetToken, IncomingWebhook}, domain, storage::enums, transformers::ForeignInto, }, }; #[allow(clippy::too_many_arguments)] pub async fn incoming_webhooks_wrapper<W: types::OutgoingWebhookType>( flow: &impl router_env::types::FlowMetric, state: SessionState, req_state: ReqState, req: &actix_web::HttpRequest, merchant_account: domain::MerchantAccount, profile: domain::Profile, key_store: domain::MerchantKeyStore, connector_id: &common_utils::id_type::MerchantConnectorAccountId, body: actix_web::web::Bytes, is_relay_webhook: bool, ) -> RouterResponse<serde_json::Value> { let start_instant = Instant::now(); let (application_response, webhooks_response_tracker, serialized_req) = Box::pin(incoming_webhooks_core::<W>( state.clone(), req_state, req, merchant_account.clone(), profile, key_store, connector_id, body.clone(), is_relay_webhook, )) .await?; logger::info!(incoming_webhook_payload = ?serialized_req); let request_duration = Instant::now() .saturating_duration_since(start_instant) .as_millis(); let request_id = RequestId::extract(req) .await .attach_printable("Unable to extract request id from request") .change_context(errors::ApiErrorResponse::InternalServerError)?; let auth_type = auth::AuthenticationType::WebhookAuth { merchant_id: merchant_account.get_id().clone(), }; let status_code = 200; let api_event = ApiEventsType::Webhooks { connector: connector_id.clone(), payment_id: webhooks_response_tracker.get_payment_id(), }; let response_value = serde_json::to_value(&webhooks_response_tracker) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not convert webhook effect to string")?; let api_event = ApiEvent::new( state.tenant.tenant_id.clone(), Some(merchant_account.get_id().clone()), flow, &request_id, request_duration, status_code, serialized_req, Some(response_value), None, auth_type, None, api_event, req, req.method(), ); state.event_handler().log_event(&api_event); Ok(application_response) } #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( state: SessionState, req_state: ReqState, req: &actix_web::HttpRequest, merchant_account: domain::MerchantAccount, profile: domain::Profile, key_store: domain::MerchantKeyStore, connector_id: &common_utils::id_type::MerchantConnectorAccountId, body: actix_web::web::Bytes, _is_relay_webhook: bool, ) -> errors::RouterResult<( services::ApplicationResponse<serde_json::Value>, WebhookResponseTracker, serde_json::Value, )> { metrics::WEBHOOK_INCOMING_COUNT.add( 1, router_env::metric_attributes!((MERCHANT_ID, merchant_account.get_id().clone())), ); let mut request_details = IncomingWebhookRequestDetails { method: req.method().clone(), uri: req.uri().clone(), headers: req.headers(), query_params: req.query_string().to_string(), body: &body, }; // Fetch the merchant connector account to get the webhooks source secret // `webhooks source secret` is a secret shared between the merchant and connector // This is used for source verification and webhooks integrity let (merchant_connector_account, connector, connector_name) = fetch_mca_and_connector(&state, connector_id, &key_store).await?; let decoded_body = connector .decode_webhook_body( &request_details, merchant_account.get_id(), merchant_connector_account.connector_webhook_details.clone(), connector_name.as_str(), ) .await .switch() .attach_printable("There was an error in incoming webhook body decoding")?; request_details.body = &decoded_body; let event_type = match connector .get_webhook_event_type(&request_details) .allow_webhook_event_type_not_found( state .clone() .conf .webhooks .ignore_error .event_type .unwrap_or(true), ) .switch() .attach_printable("Could not find event type in incoming webhook body")? { Some(event_type) => event_type, // Early return allows us to acknowledge the webhooks that we do not support None => { logger::error!( webhook_payload =? request_details.body, "Failed while identifying the event type", ); metrics::WEBHOOK_EVENT_TYPE_IDENTIFICATION_FAILURE_COUNT.add( 1, router_env::metric_attributes!( (MERCHANT_ID, merchant_account.get_id().clone()), ("connector", connector_name) ), ); let response = connector .get_webhook_api_response(&request_details, None) .switch() .attach_printable("Failed while early return in case of event type parsing")?; return Ok(( response, WebhookResponseTracker::NoEffect, serde_json::Value::Null, )); } }; logger::info!(event_type=?event_type); let is_webhook_event_supported = !matches!( event_type, webhooks::IncomingWebhookEvent::EventNotSupported ); let is_webhook_event_enabled = !utils::is_webhook_event_disabled( &*state.clone().store, connector_name.as_str(), merchant_account.get_id(), &event_type, ) .await; //process webhook further only if webhook event is enabled and is not event_not_supported let process_webhook_further = is_webhook_event_enabled && is_webhook_event_supported; logger::info!(process_webhook=?process_webhook_further); let flow_type: api::WebhookFlow = event_type.into(); let mut event_object: Box<dyn masking::ErasedMaskSerialize> = Box::new(serde_json::Value::Null); let webhook_effect = if process_webhook_further && !matches!(flow_type, api::WebhookFlow::ReturnResponse) { let object_ref_id = connector .get_webhook_object_reference_id(&request_details) .switch() .attach_printable("Could not find object reference id in incoming webhook body")?; let connector_enum = api_models::enums::Connector::from_str(&connector_name) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "connector", }) .attach_printable_lazy(|| { format!("unable to parse connector name {connector_name:?}") })?; let connectors_with_source_verification_call = &state.conf.webhook_source_verification_call; let source_verified = if connectors_with_source_verification_call .connectors_with_webhook_source_verification_call .contains(&connector_enum) { verify_webhook_source_verification_call( connector.clone(), &state, &merchant_account, merchant_connector_account.clone(), &connector_name, &request_details, ) .await .or_else(|error| match error.current_context() { errors::ConnectorError::WebhookSourceVerificationFailed => { logger::error!(?error, "Source Verification Failed"); Ok(false) } _ => Err(error), }) .switch() .attach_printable("There was an issue in incoming webhook source verification")? } else { connector .clone() .verify_webhook_source( &request_details, merchant_account.get_id(), merchant_connector_account.connector_webhook_details.clone(), merchant_connector_account.connector_account_details.clone(), connector_name.as_str(), ) .await .or_else(|error| match error.current_context() { errors::ConnectorError::WebhookSourceVerificationFailed => { logger::error!(?error, "Source Verification Failed"); Ok(false) } _ => Err(error), }) .switch() .attach_printable("There was an issue in incoming webhook source verification")? }; logger::info!(source_verified=?source_verified); if source_verified { metrics::WEBHOOK_SOURCE_VERIFIED_COUNT.add( 1, router_env::metric_attributes!((MERCHANT_ID, merchant_account.get_id().clone())), ); } // If source verification is mandatory and source is not verified, fail with webhook authentication error // else continue the flow match ( connector.is_webhook_source_verification_mandatory(), source_verified, ) { (true, false) => Err(errors::ApiErrorResponse::WebhookAuthenticationFailed)?, _ => { event_object = connector .get_webhook_resource_object(&request_details) .switch() .attach_printable("Could not find resource object in incoming webhook body")?; let webhook_details = api::IncomingWebhookDetails { object_reference_id: object_ref_id.clone(), resource_object: serde_json::to_vec(&event_object) .change_context(errors::ParsingError::EncodeError("byte-vec")) .attach_printable("Unable to convert webhook payload to a value") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "There was an issue when encoding the incoming webhook body to bytes", )?, }; match flow_type { api::WebhookFlow::Payment => Box::pin(payments_incoming_webhook_flow( state.clone(), req_state, merchant_account, profile, key_store, webhook_details, source_verified, )) .await .attach_printable("Incoming webhook flow for payments failed")?, api::WebhookFlow::Refund => todo!(), api::WebhookFlow::Dispute => todo!(), api::WebhookFlow::BankTransfer => todo!(), api::WebhookFlow::ReturnResponse => WebhookResponseTracker::NoEffect, api::WebhookFlow::Mandate => todo!(), api::WebhookFlow::ExternalAuthentication => todo!(), api::WebhookFlow::FraudCheck => todo!(), #[cfg(feature = "payouts")] api::WebhookFlow::Payout => todo!(), api::WebhookFlow::Subscription => todo!(), #[cfg(all(feature = "revenue_recovery", feature = "v2"))] api::WebhookFlow::Recovery => { Box::pin(recovery_incoming::recovery_incoming_webhook_flow( state.clone(), merchant_account, profile, key_store, webhook_details, source_verified, &connector, merchant_connector_account, &connector_name, &request_details, event_type, req_state, &object_ref_id, )) .await .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("Failed to process recovery incoming webhook")? } } } } } else { metrics::WEBHOOK_INCOMING_FILTERED_COUNT.add( 1, router_env::metric_attributes!((MERCHANT_ID, merchant_account.get_id().clone())), ); WebhookResponseTracker::NoEffect }; let response = connector .get_webhook_api_response(&request_details, None) .switch() .attach_printable("Could not get incoming webhook api response from connector")?; let serialized_request = event_object .masked_serialize() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not convert webhook effect to string")?; Ok((response, webhook_effect, serialized_request)) } #[instrument(skip_all)] async fn payments_incoming_webhook_flow( state: SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, profile: domain::Profile, key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, source_verified: bool, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { let consume_or_trigger_flow = if source_verified { payments::CallConnectorAction::HandleResponse(webhook_details.resource_object) } else { payments::CallConnectorAction::Trigger }; let key_manager_state = &(&state).into(); let payments_response = match webhook_details.object_reference_id { webhooks::ObjectReferenceId::PaymentId(id) => { let get_trackers_response = get_trackers_response_for_payment_get_operation( state.store.as_ref(), &id, profile.get_id(), key_manager_state, &key_store, merchant_account.storage_scheme, ) .await?; let payment_id = get_trackers_response.payment_data.get_payment_id(); let lock_action = api_locking::LockAction::Hold { input: api_locking::LockingInput { unique_locking_key: payment_id.get_string_repr().to_owned(), api_identifier: lock_utils::ApiIdentifier::Payments, override_lock_retries: None, }, }; lock_action .clone() .perform_locking_action(&state, merchant_account.get_id().to_owned()) .await?; let (payment_data, _req, customer, connector_http_status_code, external_latency) = Box::pin(payments::payments_operation_core::< api::PSync, _, _, _, PaymentStatusData<api::PSync>, >( &state, req_state, merchant_account.clone(), key_store.clone(), &profile, payments::operations::PaymentGet, api::PaymentsRetrieveRequest { force_sync: true, expand_attempts: false, param: None, }, get_trackers_response, consume_or_trigger_flow, HeaderPayload::default(), )) .await?; let response = payment_data.generate_response( &state, connector_http_status_code, external_latency, None, &merchant_account, &profile, ); lock_action .free_lock_action(&state, merchant_account.get_id().to_owned()) .await?; match response { Ok(value) => value, Err(err) if matches!( err.current_context(), &errors::ApiErrorResponse::PaymentNotFound ) && state .clone() .conf .webhooks .ignore_error .payment_not_found .unwrap_or(true) => { metrics::WEBHOOK_PAYMENT_NOT_FOUND.add( 1, router_env::metric_attributes!(( "merchant_id", merchant_account.get_id().clone() )), ); return Ok(WebhookResponseTracker::NoEffect); } error @ Err(_) => error?, } } _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure).attach_printable( "Did not get payment id as object reference id in webhook payments flow", )?, }; match payments_response { services::ApplicationResponse::JsonWithHeaders((payments_response, _)) => { let payment_id = payments_response.id.clone(); let status = payments_response.status; let event_type: Option<enums::EventType> = payments_response.status.foreign_into(); // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook if let Some(_outgoing_event_type) = event_type { let _primary_object_created_at = payments_response.created; // TODO: trigger an outgoing webhook to merchant // Box::pin(super::create_event_and_trigger_outgoing_webhook( // state, // merchant_account, // 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)), // Some(primary_object_created_at), // )) // .await?; }; let response = WebhookResponseTracker::Payment { payment_id, status }; Ok(response) } _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("received non-json response from payments core")?, } } async fn get_trackers_response_for_payment_get_operation<F>( db: &dyn StorageInterface, payment_id: &api::PaymentIdType, profile_id: &common_utils::id_type::ProfileId, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> errors::RouterResult<payments::operations::GetTrackerResponse<PaymentStatusData<F>>> where F: Clone, { let (payment_intent, payment_attempt) = match payment_id { api_models::payments::PaymentIdType::PaymentIntentId(ref id) => { let payment_intent = db .find_payment_intent_by_id( key_manager_state, id, merchant_key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let payment_attempt = db .find_payment_attempt_by_id( key_manager_state, merchant_key_store, &payment_intent .active_attempt_id .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("active_attempt_id not present in payment_attempt")?, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; (payment_intent, payment_attempt) } api_models::payments::PaymentIdType::ConnectorTransactionId(ref id) => { let payment_attempt = db .find_payment_attempt_by_profile_id_connector_transaction_id( key_manager_state, merchant_key_store, profile_id, id, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let payment_intent = db .find_payment_intent_by_id( key_manager_state, &payment_attempt.payment_id, merchant_key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; (payment_intent, payment_attempt) } api_models::payments::PaymentIdType::PaymentAttemptId(ref id) => { let global_attempt_id = common_utils::id_type::GlobalAttemptId::try_from( std::borrow::Cow::Owned(id.to_owned()), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while getting GlobalAttemptId")?; let payment_attempt = db .find_payment_attempt_by_id( key_manager_state, merchant_key_store, &global_attempt_id, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let payment_intent = db .find_payment_intent_by_id( key_manager_state, &payment_attempt.payment_id, merchant_key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; (payment_intent, payment_attempt) } api_models::payments::PaymentIdType::PreprocessingId(ref _id) => todo!(), }; // We need the address here to send it in the response // In case we need to send an outgoing webhook, we might have to send the billing address and shipping address let payment_address = hyperswitch_domain_models::payment_address::PaymentAddress::new( payment_intent .shipping_address .clone() .map(|address| address.into_inner()), payment_intent .billing_address .clone() .map(|address| address.into_inner()), payment_attempt .payment_method_billing_address .clone() .map(|address| address.into_inner()), Some(true), ); Ok(payments::operations::GetTrackerResponse { payment_data: PaymentStatusData { flow: PhantomData, payment_intent, payment_attempt: Some(payment_attempt), attempts: None, should_sync_with_connector: true, payment_address, }, }) } #[inline] 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), } } fn get_connector_by_connector_name( state: &SessionState, connector_name: &str, merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, ) -> CustomResult<(ConnectorEnum, String), errors::ApiErrorResponse> { let authentication_connector = api_models::enums::convert_authentication_connector(connector_name); #[cfg(feature = "frm")] { let frm_connector = api_models::enums::convert_frm_connector(connector_name); if frm_connector.is_some() { let frm_connector_data = api::FraudCheckConnectorData::get_connector_by_name(connector_name)?; return Ok(( frm_connector_data.connector, frm_connector_data.connector_name.to_string(), )); } } let (connector, connector_name) = if authentication_connector.is_some() { let authentication_connector_data = api::AuthenticationConnectorData::get_connector_by_name(connector_name)?; ( authentication_connector_data.connector, authentication_connector_data.connector_name.to_string(), ) } else { let connector_data = ConnectorData::get_connector_by_name( &state.conf.connectors, connector_name, GetToken::Connector, merchant_connector_id, ) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "invalid connector name received".to_string(), }) .attach_printable("Failed construction of ConnectorData")?; ( connector_data.connector, connector_data.connector_name.to_string(), ) }; Ok((connector, connector_name)) } /// This function fetches the merchant connector account and connector details async fn fetch_mca_and_connector( state: &SessionState, connector_id: &common_utils::id_type::MerchantConnectorAccountId, key_store: &domain::MerchantKeyStore, ) -> CustomResult<(domain::MerchantConnectorAccount, ConnectorEnum, String), errors::ApiErrorResponse> { let db = &state.store; let mca = db .find_merchant_connector_account_by_id(&state.into(), connector_id, key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: connector_id.get_string_repr().to_owned(), }) .attach_printable("error while fetching merchant_connector_account from connector_id")?; let (connector, connector_name) = get_connector_by_connector_name( state, &mca.connector_name.to_string(), Some(mca.get_id()), )?; Ok((mca, connector, connector_name)) }
5,675
1,596
hyperswitch
crates/router/src/core/webhooks/webhook_events.rs
.rs
use common_utils::{self, fp_utils}; use error_stack::ResultExt; use masking::PeekInterface; use router_env::{instrument, tracing}; use crate::{ core::errors::{self, RouterResponse, StorageErrorExt}, routes::SessionState, services::ApplicationResponse, types::{api, domain, storage, transformers::ForeignTryFrom}, utils::{OptionExt, StringExt}, }; const INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_LIMIT: i64 = 100; const INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_DAYS: i64 = 90; #[derive(Debug)] enum MerchantAccountOrProfile { MerchantAccount(Box<domain::MerchantAccount>), Profile(Box<domain::Profile>), } #[instrument(skip(state))] pub async fn list_initial_delivery_attempts( state: SessionState, merchant_id: common_utils::id_type::MerchantId, api_constraints: api::webhook_events::EventListConstraints, ) -> RouterResponse<api::webhook_events::TotalEventsResponse> { let profile_id = api_constraints.profile_id.clone(); let constraints = api::webhook_events::EventListConstraintsInternal::foreign_try_from( api_constraints.clone(), )?; let store = state.store.as_ref(); let key_manager_state = &(&state).into(); let (account, key_store) = get_account_and_key_store(state.clone(), merchant_id.clone(), profile_id.clone()).await?; let now = common_utils::date_time::now(); let events_list_begin_time = (now.date() - time::Duration::days(INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_DAYS)).midnight(); let events = match constraints { api_models::webhook_events::EventListConstraintsInternal::ObjectIdFilter { object_id } => { match account { MerchantAccountOrProfile::MerchantAccount(merchant_account) => store .list_initial_events_by_merchant_id_primary_object_id(key_manager_state, merchant_account.get_id(), &object_id, &key_store, ) .await, MerchantAccountOrProfile::Profile(business_profile) => store .list_initial_events_by_profile_id_primary_object_id(key_manager_state, business_profile.get_id(), &object_id, &key_store, ) .await, } } api_models::webhook_events::EventListConstraintsInternal::GenericFilter { created_after, created_before, limit, offset, is_delivered } => { let limit = match limit { Some(limit) if limit <= INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_LIMIT => Ok(Some(limit)), Some(limit) if limit > INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_LIMIT => Err( errors::ApiErrorResponse::InvalidRequestData{ message: format!("`limit` must be a number less than {INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_LIMIT}") } ), _ => Ok(Some(INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_LIMIT)), }?; let offset = match offset { Some(offset) if offset > 0 => Some(offset), _ => None, }; fp_utils::when(!created_after.zip(created_before).map(|(created_after,created_before)| created_after<=created_before).unwrap_or(true), || { Err(errors::ApiErrorResponse::InvalidRequestData { message: "The `created_after` timestamp must be an earlier timestamp compared to the `created_before` timestamp".to_string() }) })?; let created_after = match created_after { Some(created_after) => { if created_after < events_list_begin_time { Err(errors::ApiErrorResponse::InvalidRequestData { message: format!("`created_after` must be a timestamp within the past {INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_DAYS} days.") }) }else{ Ok(created_after) } }, None => Ok(events_list_begin_time) }?; let created_before = match created_before{ Some(created_before) => { if created_before < events_list_begin_time{ Err(errors::ApiErrorResponse::InvalidRequestData { message: format!("`created_before` must be a timestamp within the past {INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_DAYS} days.") }) } else{ Ok(created_before) } }, None => Ok(now) }?; match account { MerchantAccountOrProfile::MerchantAccount(merchant_account) => store .list_initial_events_by_merchant_id_constraints(key_manager_state, merchant_account.get_id(), created_after, created_before, limit, offset, is_delivered, &key_store, ) .await, MerchantAccountOrProfile::Profile(business_profile) => store .list_initial_events_by_profile_id_constraints(key_manager_state, business_profile.get_id(), created_after, created_before, limit, offset, is_delivered, &key_store, ) .await, } } } .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to list events with specified constraints")?; let events = events .into_iter() .map(api::webhook_events::EventListItemResponse::try_from) .collect::<Result<Vec<_>, _>>()?; let created_after = api_constraints .created_after .unwrap_or(events_list_begin_time); let created_before = api_constraints.created_before.unwrap_or(now); let is_delivered = api_constraints.is_delivered; let total_count = store .count_initial_events_by_constraints( &merchant_id, profile_id, created_after, created_before, is_delivered, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get total events count")?; Ok(ApplicationResponse::Json( api::webhook_events::TotalEventsResponse::new(total_count, events), )) } #[instrument(skip(state))] pub async fn list_delivery_attempts( state: SessionState, merchant_id: common_utils::id_type::MerchantId, initial_attempt_id: String, ) -> RouterResponse<Vec<api::webhook_events::EventRetrieveResponse>> { let store = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = store .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &store.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let events = store .list_events_by_merchant_id_initial_attempt_id( key_manager_state, &merchant_id, &initial_attempt_id, &key_store, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to list delivery attempts for initial event")?; if events.is_empty() { Err(error_stack::report!( errors::ApiErrorResponse::EventNotFound )) .attach_printable("No delivery attempts found with the specified `initial_attempt_id`") } else { Ok(ApplicationResponse::Json( events .into_iter() .map(api::webhook_events::EventRetrieveResponse::try_from) .collect::<Result<Vec<_>, _>>()?, )) } } #[instrument(skip(state))] #[cfg(feature = "v1")] pub async fn retry_delivery_attempt( state: SessionState, merchant_id: common_utils::id_type::MerchantId, event_id: String, ) -> RouterResponse<api::webhook_events::EventRetrieveResponse> { let store = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = store .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &store.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let event_to_retry = store .find_event_by_merchant_id_event_id( key_manager_state, &key_store.merchant_id, &event_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::EventNotFound)?; let business_profile_id = event_to_retry .business_profile_id .get_required_value("business_profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to read business profile ID from event to retry")?; let business_profile = store .find_business_profile_by_profile_id(key_manager_state, &key_store, &business_profile_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to find business profile")?; let delivery_attempt = storage::enums::WebhookDeliveryAttempt::ManualRetry; let new_event_id = super::utils::generate_event_id(); let idempotent_event_id = super::utils::get_idempotent_event_id( &event_to_retry.primary_object_id, event_to_retry.event_type, delivery_attempt, ); let now = common_utils::date_time::now(); let new_event = domain::Event { event_id: new_event_id.clone(), event_type: event_to_retry.event_type, event_class: event_to_retry.event_class, is_webhook_notified: false, primary_object_id: event_to_retry.primary_object_id, primary_object_type: event_to_retry.primary_object_type, created_at: now, merchant_id: Some(business_profile.merchant_id.clone()), business_profile_id: Some(business_profile.get_id().to_owned()), primary_object_created_at: event_to_retry.primary_object_created_at, idempotent_event_id: Some(idempotent_event_id), initial_attempt_id: event_to_retry.initial_attempt_id, request: event_to_retry.request, response: None, delivery_attempt: Some(delivery_attempt), metadata: event_to_retry.metadata, is_overall_delivery_successful: Some(false), }; let event = store .insert_event(key_manager_state, new_event, &key_store) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to insert event")?; // We only allow retrying deliveries for events with `request` populated. let request_content = event .request .as_ref() .get_required_value("request") .change_context(errors::ApiErrorResponse::InternalServerError)? .peek() .parse_struct("OutgoingWebhookRequestContent") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse webhook event request information")?; Box::pin(super::outgoing::trigger_webhook_and_raise_event( state.clone(), business_profile, &key_store, event, request_content, delivery_attempt, None, None, )) .await; let updated_event = store .find_event_by_merchant_id_event_id( key_manager_state, &key_store.merchant_id, &new_event_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::EventNotFound)?; Ok(ApplicationResponse::Json( api::webhook_events::EventRetrieveResponse::try_from(updated_event)?, )) } async fn get_account_and_key_store( state: SessionState, merchant_id: common_utils::id_type::MerchantId, profile_id: Option<common_utils::id_type::ProfileId>, ) -> errors::RouterResult<(MerchantAccountOrProfile, domain::MerchantKeyStore)> { let store = state.store.as_ref(); let key_manager_state = &(&state).into(); let merchant_key_store = store .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &store.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; match profile_id { // If profile ID is specified, return business profile, since a business profile is more // specific than a merchant account. Some(profile_id) => { let business_profile = store .find_business_profile_by_merchant_id_profile_id( key_manager_state, &merchant_key_store, &merchant_id, &profile_id, ) .await .attach_printable_lazy(|| { format!( "Failed to find business profile by merchant_id `{merchant_id:?}` and profile_id `{profile_id:?}`. \ The merchant_id associated with the business profile `{profile_id:?}` may be \ different than the merchant_id specified (`{merchant_id:?}`)." ) }) .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; Ok(( MerchantAccountOrProfile::Profile(Box::new(business_profile)), merchant_key_store, )) } None => { let merchant_account = store .find_merchant_account_by_merchant_id( key_manager_state, &merchant_id, &merchant_key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; Ok(( MerchantAccountOrProfile::MerchantAccount(Box::new(merchant_account)), merchant_key_store, )) } } }
2,884
1,597
hyperswitch
crates/router/src/core/payments/operations.rs
.rs
#[cfg(feature = "v1")] pub mod payment_approve; #[cfg(feature = "v1")] pub mod payment_cancel; #[cfg(feature = "v1")] pub mod payment_capture; #[cfg(feature = "v1")] pub mod payment_complete_authorize; #[cfg(feature = "v1")] pub mod payment_confirm; #[cfg(feature = "v1")] pub mod payment_create; #[cfg(feature = "v1")] pub mod payment_post_session_tokens; #[cfg(feature = "v1")] pub mod payment_reject; pub mod payment_response; #[cfg(feature = "v1")] pub mod payment_session; #[cfg(feature = "v2")] pub mod payment_session_intent; #[cfg(feature = "v1")] pub mod payment_start; #[cfg(feature = "v1")] pub mod payment_status; #[cfg(feature = "v1")] pub mod payment_update; #[cfg(feature = "v1")] pub mod payments_incremental_authorization; #[cfg(feature = "v1")] pub mod tax_calculation; #[cfg(feature = "v2")] pub mod payment_attempt_record; #[cfg(feature = "v2")] pub mod payment_confirm_intent; #[cfg(feature = "v2")] pub mod proxy_payments_intent; #[cfg(feature = "v2")] pub mod payment_create_intent; #[cfg(feature = "v2")] pub mod payment_get_intent; #[cfg(feature = "v2")] pub mod payment_update_intent; #[cfg(feature = "v2")] pub mod payment_get; #[cfg(feature = "v2")] pub mod payment_capture_v2; use api_models::enums::FrmSuggestion; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use api_models::routing::RoutableConnectorChoice; use async_trait::async_trait; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; #[cfg(feature = "v2")] pub use self::payment_get::PaymentGet; #[cfg(feature = "v2")] pub use self::payment_get_intent::PaymentGetIntent; pub use self::payment_response::PaymentResponse; #[cfg(feature = "v2")] pub use self::payment_update_intent::PaymentUpdateIntent; #[cfg(feature = "v1")] pub use self::{ payment_approve::PaymentApprove, payment_cancel::PaymentCancel, payment_capture::PaymentCapture, payment_confirm::PaymentConfirm, payment_create::PaymentCreate, payment_post_session_tokens::PaymentPostSessionTokens, payment_reject::PaymentReject, payment_session::PaymentSession, payment_start::PaymentStart, payment_status::PaymentStatus, payment_update::PaymentUpdate, payments_incremental_authorization::PaymentIncrementalAuthorization, tax_calculation::PaymentSessionUpdate, }; #[cfg(feature = "v2")] pub use self::{ payment_confirm_intent::PaymentIntentConfirm, payment_create_intent::PaymentIntentCreate, payment_session_intent::PaymentSessionIntent, }; use super::{helpers, CustomerDetails, OperationSessionGetters, OperationSessionSetters}; use crate::{ core::errors::{self, CustomResult, RouterResult}, routes::{app::ReqState, SessionState}, services, types::{ self, api::{self, ConnectorCallType}, domain, storage::{self, enums}, PaymentsResponseData, }, }; pub type BoxedOperation<'a, F, T, D> = Box<dyn Operation<F, T, Data = D> + Send + Sync + 'a>; pub trait Operation<F: Clone, T>: Send + std::fmt::Debug { type Data; fn to_validate_request( &self, ) -> RouterResult<&(dyn ValidateRequest<F, T, Self::Data> + Send + Sync)> { Err(report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| format!("validate request interface not found for {self:?}")) } fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<F, Self::Data, T> + Send + Sync)> { Err(report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| format!("get tracker interface not found for {self:?}")) } fn to_domain(&self) -> RouterResult<&dyn Domain<F, T, Self::Data>> { Err(report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| format!("domain interface not found for {self:?}")) } fn to_update_tracker( &self, ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, T> + Send + Sync)> { Err(report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| format!("update tracker interface not found for {self:?}")) } fn to_post_update_tracker( &self, ) -> RouterResult<&(dyn PostUpdateTracker<F, Self::Data, T> + Send + Sync)> { Err(report!(errors::ApiErrorResponse::InternalServerError)).attach_printable_lazy(|| { format!("post connector update tracker not found for {self:?}") }) } } #[cfg(feature = "v1")] #[derive(Clone)] pub struct ValidateResult { pub merchant_id: common_utils::id_type::MerchantId, pub payment_id: api::PaymentIdType, pub storage_scheme: enums::MerchantStorageScheme, pub requeue: bool, } #[cfg(feature = "v2")] #[derive(Clone)] pub struct ValidateResult { pub merchant_id: common_utils::id_type::MerchantId, pub storage_scheme: enums::MerchantStorageScheme, pub requeue: bool, } #[cfg(feature = "v1")] #[allow(clippy::type_complexity)] pub trait ValidateRequest<F, R, D> { fn validate_request<'b>( &'b self, request: &R, merchant_account: &domain::MerchantAccount, ) -> RouterResult<(BoxedOperation<'b, F, R, D>, ValidateResult)>; } #[cfg(feature = "v2")] pub trait ValidateRequest<F, R, D> { fn validate_request( &self, request: &R, merchant_account: &domain::MerchantAccount, ) -> RouterResult<ValidateResult>; } #[cfg(feature = "v2")] pub struct GetTrackerResponse<D> { pub payment_data: D, } #[cfg(feature = "v1")] pub struct GetTrackerResponse<'a, F: Clone, R, D> { pub operation: BoxedOperation<'a, F, R, D>, pub customer_details: Option<CustomerDetails>, pub payment_data: D, pub business_profile: domain::Profile, pub mandate_type: Option<api::MandateTransactionType>, } /// This trait is used to fetch / create all the tracker related information for a payment /// This functions returns the session data that is used by subsequent functions #[async_trait] pub trait GetTracker<F: Clone, D, R>: Send { #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, request: &R, merchant_account: &domain::MerchantAccount, mechant_key_store: &domain::MerchantKeyStore, auth_flow: services::AuthFlow, header_payload: &hyperswitch_domain_models::payments::HeaderPayload, platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<GetTrackerResponse<'a, F, R, D>>; #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &common_utils::id_type::GlobalPaymentId, request: &R, merchant_account: &domain::MerchantAccount, profile: &domain::Profile, mechant_key_store: &domain::MerchantKeyStore, header_payload: &hyperswitch_domain_models::payments::HeaderPayload, platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<GetTrackerResponse<D>>; async fn validate_request_with_state( &self, _state: &SessionState, _request: &R, _payment_data: &mut D, _business_profile: &domain::Profile, ) -> RouterResult<()> { Ok(()) } } #[async_trait] pub trait Domain<F: Clone, R, D>: Send + Sync { #[cfg(feature = "v1")] /// This will fetch customer details, (this operation is flow specific) async fn get_or_create_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut D, request: Option<CustomerDetails>, merchant_key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<(BoxedOperation<'a, F, R, D>, Option<domain::Customer>), errors::StorageError>; #[cfg(feature = "v2")] /// This will fetch customer details, (this operation is flow specific) async fn get_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut D, merchant_key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<(BoxedOperation<'a, F, R, D>, Option<domain::Customer>), errors::StorageError>; #[cfg(feature = "v2")] /// This will run the decision manager for the payment async fn run_decision_manager<'a>( &'a self, state: &SessionState, payment_data: &mut D, business_profile: &domain::Profile, ) -> CustomResult<(), errors::ApiErrorResponse> { Ok(()) } #[allow(clippy::too_many_arguments)] async fn make_pm_data<'a>( &'a self, state: &'a SessionState, payment_data: &mut D, storage_scheme: enums::MerchantStorageScheme, merchant_key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, business_profile: &domain::Profile, should_retry_with_pan: bool, ) -> RouterResult<( BoxedOperation<'a, F, R, D>, Option<domain::PaymentMethodData>, Option<String>, )>; async fn add_task_to_process_tracker<'a>( &'a self, _db: &'a SessionState, _payment_attempt: &storage::PaymentAttempt, _requeue: bool, _schedule_time: Option<time::PrimitiveDateTime>, ) -> CustomResult<(), errors::ApiErrorResponse> { Ok(()) } #[cfg(feature = "v1")] async fn get_connector<'a>( &'a self, merchant_account: &domain::MerchantAccount, state: &SessionState, request: &R, payment_intent: &storage::PaymentIntent, mechant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse>; #[cfg(feature = "v2")] async fn perform_routing<'a>( &'a self, merchant_account: &domain::MerchantAccount, business_profile: &domain::Profile, state: &SessionState, // TODO: do not take the whole payment data here payment_data: &mut D, mechant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<ConnectorCallType, errors::ApiErrorResponse>; async fn populate_payment_data<'a>( &'a self, _state: &SessionState, _payment_data: &mut D, _merchant_account: &domain::MerchantAccount, _business_profile: &domain::Profile, _connector_data: &api::ConnectorData, ) -> CustomResult<(), errors::ApiErrorResponse> { Ok(()) } #[allow(clippy::too_many_arguments)] async fn call_external_three_ds_authentication_if_eligible<'a>( &'a self, _state: &SessionState, _payment_data: &mut D, _should_continue_confirm_transaction: &mut bool, _connector_call_type: &ConnectorCallType, _merchant_account: &domain::Profile, _key_store: &domain::MerchantKeyStore, _mandate_type: Option<api_models::payments::MandateTransactionType>, ) -> CustomResult<(), errors::ApiErrorResponse> { Ok(()) } #[allow(clippy::too_many_arguments)] async fn call_unified_authentication_service_if_eligible<'a>( &'a self, _state: &SessionState, _payment_data: &mut D, _should_continue_confirm_transaction: &mut bool, _connector_call_type: &ConnectorCallType, _business_profile: &domain::Profile, _key_store: &domain::MerchantKeyStore, _mandate_type: Option<api_models::payments::MandateTransactionType>, _do_authorization_confirmation: &bool, ) -> CustomResult<(), errors::ApiErrorResponse> { Ok(()) } #[allow(clippy::too_many_arguments)] async fn payments_dynamic_tax_calculation<'a>( &'a self, _state: &SessionState, _payment_data: &mut D, _connector_call_type: &ConnectorCallType, _business_profile: &domain::Profile, _key_store: &domain::MerchantKeyStore, _merchant_account: &domain::MerchantAccount, ) -> CustomResult<(), errors::ApiErrorResponse> { Ok(()) } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, _payment_data: &mut D, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } async fn store_extended_card_info_temporarily<'a>( &'a self, _state: &SessionState, _payment_id: &common_utils::id_type::PaymentId, _business_profile: &domain::Profile, _payment_method_data: Option<&domain::PaymentMethodData>, ) -> CustomResult<(), errors::ApiErrorResponse> { Ok(()) } // #[cfg(feature = "v2")] // async fn call_connector<'a, RouterDataReq>( // &'a self, // _state: &SessionState, // _req_state: ReqState, // _merchant_account: &domain::MerchantAccount, // _key_store: &domain::MerchantKeyStore, // _business_profile: &domain::Profile, // _payment_method_data: Option<&domain::PaymentMethodData>, // _connector: api::ConnectorData, // _customer: &Option<domain::Customer>, // _payment_data: &mut D, // _call_connector_action: common_enums::CallConnectorAction, // ) -> CustomResult< // hyperswitch_domain_models::router_data::RouterData<F, RouterDataReq, PaymentsResponseData>, // errors::ApiErrorResponse, // > { // // TODO: raise an error here // todo!(); // } } #[async_trait] #[allow(clippy::too_many_arguments)] pub trait UpdateTracker<F, D, Req>: Send { /// Update the tracker information with the new data from request or calculated by the operations performed after get trackers /// This will persist the SessionData ( PaymentData ) in the database /// /// In case we are calling a processor / connector, we persist all the data in the database and then call the connector async fn update_trackers<'b>( &'b self, db: &'b SessionState, req_state: ReqState, payment_data: D, customer: Option<domain::Customer>, storage_scheme: enums::MerchantStorageScheme, updated_customer: Option<storage::CustomerUpdate>, mechant_key_store: &domain::MerchantKeyStore, frm_suggestion: Option<FrmSuggestion>, header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<(BoxedOperation<'b, F, Req, D>, D)> where F: 'b + Send; } #[cfg(feature = "v2")] #[async_trait] #[allow(clippy::too_many_arguments)] pub trait CallConnector<F, D, RouterDReq: Send>: Send { async fn call_connector<'b>( &'b self, db: &'b SessionState, req_state: ReqState, payment_data: D, key_store: &domain::MerchantKeyStore, call_connector_action: common_enums::CallConnectorAction, connector_data: api::ConnectorData, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<types::RouterData<F, RouterDReq, PaymentsResponseData>> where F: 'b + Send + Sync, D: super::flows::ConstructFlowSpecificData<F, RouterDReq, PaymentsResponseData>, types::RouterData<F, RouterDReq, PaymentsResponseData>: super::flows::Feature<F, RouterDReq> + Send; } #[async_trait] #[allow(clippy::too_many_arguments)] pub trait PostUpdateTracker<F, D, R: Send>: Send { /// Update the tracker information with the response from the connector /// The response from routerdata is used to update paymentdata and also persist this in the database #[cfg(feature = "v1")] async fn update_tracker<'b>( &'b self, db: &'b SessionState, payment_data: D, response: types::RouterData<F, R, PaymentsResponseData>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, locale: &Option<String>, #[cfg(feature = "dynamic_routing")] routable_connector: Vec<RoutableConnectorChoice>, #[cfg(feature = "dynamic_routing")] business_profile: &domain::Profile, ) -> RouterResult<D> where F: 'b + Send + Sync; #[cfg(feature = "v2")] async fn update_tracker<'b>( &'b self, db: &'b SessionState, payment_data: D, response: types::RouterData<F, R, PaymentsResponseData>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<D> where F: 'b + Send + Sync, types::RouterData<F, R, PaymentsResponseData>: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<F, R, D>; async fn save_pm_and_mandate<'b>( &self, _state: &SessionState, _resp: &types::RouterData<F, R, PaymentsResponseData>, _merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, _payment_data: &mut D, _business_profile: &domain::Profile, ) -> CustomResult<(), errors::ApiErrorResponse> where F: 'b + Clone + Send + Sync, { Ok(()) } } #[cfg(feature = "v1")] #[async_trait] impl< D, F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsRetrieveRequest, Data = D>, > Domain<F, api::PaymentsRetrieveRequest, D> for Op where for<'a> &'a Op: Operation<F, api::PaymentsRetrieveRequest, Data = D>, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send, { #[instrument(skip_all)] #[cfg(feature = "v1")] async fn get_or_create_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut D, _request: Option<CustomerDetails>, merchant_key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation<'a, F, api::PaymentsRetrieveRequest, D>, Option<domain::Customer>, ), errors::StorageError, > { let db = &*state.store; let customer = match payment_data.get_payment_intent().customer_id.as_ref() { None => None, Some(customer_id) => { // This function is to retrieve customer details. If the customer is deleted, it returns // customer details that contains the fields as Redacted db.find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id( &state.into(), customer_id, &merchant_key_store.merchant_id, merchant_key_store, storage_scheme, ) .await? } }; if let Some(email) = customer.as_ref().and_then(|inner| inner.email.clone()) { payment_data.set_email_if_not_present(email.into()); } Ok((Box::new(self), customer)) } async fn get_connector<'a>( &'a self, _merchant_account: &domain::MerchantAccount, state: &SessionState, _request: &api::PaymentsRetrieveRequest, _payment_intent: &storage::PaymentIntent, _merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, None).await } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, _state: &'a SessionState, _payment_data: &mut D, _storage_scheme: enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsRetrieveRequest, D>, Option<domain::PaymentMethodData>, Option<String>, )> { Ok((Box::new(self), None, None)) } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, _payment_data: &mut D, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } } #[cfg(feature = "v1")] #[async_trait] impl<D, F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsCaptureRequest, Data = D>> Domain<F, api::PaymentsCaptureRequest, D> for Op where for<'a> &'a Op: Operation<F, api::PaymentsCaptureRequest, Data = D>, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send, { #[instrument(skip_all)] #[cfg(feature = "v1")] async fn get_or_create_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut D, _request: Option<CustomerDetails>, merchant_key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation<'a, F, api::PaymentsCaptureRequest, D>, Option<domain::Customer>, ), errors::StorageError, > { let db = &*state.store; let customer = match payment_data.get_payment_intent().customer_id.as_ref() { None => None, Some(customer_id) => { db.find_customer_optional_by_customer_id_merchant_id( &state.into(), customer_id, &merchant_key_store.merchant_id, merchant_key_store, storage_scheme, ) .await? } }; if let Some(email) = customer.as_ref().and_then(|inner| inner.email.clone()) { payment_data.set_email_if_not_present(email.into()); } Ok((Box::new(self), customer)) } #[instrument(skip_all)] #[cfg(feature = "v2")] async fn get_customer_details<'a>( &'a self, _state: &SessionState, _payment_data: &mut D, _merchant_key_store: &domain::MerchantKeyStore, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation<'a, F, api::PaymentsCaptureRequest, D>, Option<domain::Customer>, ), errors::StorageError, > { todo!() } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, _state: &'a SessionState, _payment_data: &mut D, _storage_scheme: enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsCaptureRequest, D>, Option<domain::PaymentMethodData>, Option<String>, )> { Ok((Box::new(self), None, None)) } async fn get_connector<'a>( &'a self, _merchant_account: &domain::MerchantAccount, state: &SessionState, _request: &api::PaymentsCaptureRequest, _payment_intent: &storage::PaymentIntent, _merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, None).await } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, _payment_data: &mut D, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } } #[cfg(feature = "v1")] #[async_trait] impl<D, F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsCancelRequest, Data = D>> Domain<F, api::PaymentsCancelRequest, D> for Op where for<'a> &'a Op: Operation<F, api::PaymentsCancelRequest, Data = D>, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send, { #[instrument(skip_all)] #[cfg(feature = "v1")] async fn get_or_create_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut D, _request: Option<CustomerDetails>, merchant_key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation<'a, F, api::PaymentsCancelRequest, D>, Option<domain::Customer>, ), errors::StorageError, > { let db = &*state.store; let customer = match payment_data.get_payment_intent().customer_id.as_ref() { None => None, Some(customer_id) => { db.find_customer_optional_by_customer_id_merchant_id( &state.into(), customer_id, &merchant_key_store.merchant_id, merchant_key_store, storage_scheme, ) .await? } }; if let Some(email) = customer.as_ref().and_then(|inner| inner.email.clone()) { payment_data.set_email_if_not_present(email.into()); } Ok((Box::new(self), customer)) } #[instrument(skip_all)] #[cfg(feature = "v2")] async fn get_customer_details<'a>( &'a self, _state: &SessionState, _payment_data: &mut D, _merchant_key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation<'a, F, api::PaymentsCancelRequest, D>, Option<domain::Customer>, ), errors::StorageError, > { todo!() } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, _state: &'a SessionState, _payment_data: &mut D, _storage_scheme: enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsCancelRequest, D>, Option<domain::PaymentMethodData>, Option<String>, )> { Ok((Box::new(self), None, None)) } async fn get_connector<'a>( &'a self, _merchant_account: &domain::MerchantAccount, state: &SessionState, _request: &api::PaymentsCancelRequest, _payment_intent: &storage::PaymentIntent, _merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, None).await } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, _payment_data: &mut D, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } } #[cfg(feature = "v1")] #[async_trait] impl<D, F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsRejectRequest, Data = D>> Domain<F, api::PaymentsRejectRequest, D> for Op where for<'a> &'a Op: Operation<F, api::PaymentsRejectRequest, Data = D>, { #[cfg(feature = "v1")] #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, _state: &SessionState, _payment_data: &mut D, _request: Option<CustomerDetails>, _merchant_key_store: &domain::MerchantKeyStore, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation<'a, F, api::PaymentsRejectRequest, D>, Option<domain::Customer>, ), errors::StorageError, > { Ok((Box::new(self), None)) } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn get_customer_details<'a>( &'a self, _state: &SessionState, _payment_data: &mut D, _merchant_key_store: &domain::MerchantKeyStore, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation<'a, F, api::PaymentsRejectRequest, D>, Option<domain::Customer>, ), errors::StorageError, > { Ok((Box::new(self), None)) } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, _state: &'a SessionState, _payment_data: &mut D, _storage_scheme: enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsRejectRequest, D>, Option<domain::PaymentMethodData>, Option<String>, )> { Ok((Box::new(self), None, None)) } async fn get_connector<'a>( &'a self, _merchant_account: &domain::MerchantAccount, state: &SessionState, _request: &api::PaymentsRejectRequest, _payment_intent: &storage::PaymentIntent, _merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, None).await } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, _payment_data: &mut D, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } } /// Validate if a particular operation can be performed for the given intent status pub trait ValidateStatusForOperation { fn validate_status_for_operation( &self, intent_status: common_enums::IntentStatus, ) -> Result<(), errors::ApiErrorResponse>; } /// Should the connector be called for this operation pub trait ShouldCallConnector { fn should_call_connector( &self, intent_status: common_enums::IntentStatus, force_sync: Option<bool>, ) -> bool; }
7,267
1,598
hyperswitch
crates/router/src/core/payments/access_token.rs
.rs
use std::fmt::Debug; use common_utils::ext_traits::AsyncExt; use error_stack::ResultExt; use crate::{ consts, core::{ errors::{self, RouterResult}, payments, }, routes::{metrics, SessionState}, services::{self, logger}, types::{self, api as api_types, domain}, }; /// After we get the access token, check if there was an error and if the flow should proceed further /// Returns bool /// true - Everything is well, continue with the flow /// false - There was an error, cannot proceed further pub fn update_router_data_with_access_token_result<F, Req, Res>( add_access_token_result: &types::AddAccessTokenResult, router_data: &mut types::RouterData<F, Req, Res>, call_connector_action: &payments::CallConnectorAction, ) -> bool { // Update router data with access token or error only if it will be calling connector let should_update_router_data = matches!( ( add_access_token_result.connector_supports_access_token, call_connector_action ), (true, payments::CallConnectorAction::Trigger) ); if should_update_router_data { match add_access_token_result.access_token_result.as_ref() { Ok(access_token) => { router_data.access_token.clone_from(access_token); true } Err(connector_error) => { router_data.response = Err(connector_error.clone()); false } } } else { true } } pub async fn add_access_token< F: Clone + 'static, Req: Debug + Clone + 'static, Res: Debug + Clone + 'static, >( state: &SessionState, connector: &api_types::ConnectorData, merchant_account: &domain::MerchantAccount, router_data: &types::RouterData<F, Req, Res>, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> { if connector .connector_name .supports_access_token(router_data.payment_method) { let merchant_id = merchant_account.get_id(); let store = &*state.store; // `merchant_connector_id` may not be present in the below cases // - when straight through routing is used without passing the `merchant_connector_id` // - when creds identifier is passed // // In these cases fallback to `connector_name`. // We cannot use multiple merchant connector account in these cases let merchant_connector_id_or_connector_name = connector .merchant_connector_id .clone() .map(|mca_id| mca_id.get_string_repr().to_string()) .or(creds_identifier.map(|id| id.to_string())) .unwrap_or(connector.connector_name.to_string()); let old_access_token = store .get_access_token(merchant_id, &merchant_connector_id_or_connector_name) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("DB error when accessing the access token")?; let res = match old_access_token { Some(access_token) => { router_env::logger::debug!( "Access token found in redis for merchant_id: {:?}, payment_id: {:?}, connector: {} which has expiry of: {} seconds", merchant_account.get_id(), router_data.payment_id, connector.connector_name, access_token.expires ); metrics::ACCESS_TOKEN_CACHE_HIT.add( 1, router_env::metric_attributes!(( "connector", connector.connector_name.to_string() )), ); Ok(Some(access_token)) } None => { metrics::ACCESS_TOKEN_CACHE_MISS.add( 1, router_env::metric_attributes!(( "connector", connector.connector_name.to_string() )), ); 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 move { let store = &*state.store; // The expiry should be adjusted for network delays from the connector // The access token might not have been expired when request is sent // But once it reaches the connector, it might expire because of the network delay // Subtract few seconds from the expiry in order to account for these network delays // This will reduce the expiry time by `REDUCE_ACCESS_TOKEN_EXPIRY_TIME` seconds let modified_access_token_with_expiry = types::AccessToken { expires: access_token .expires .saturating_sub(consts::REDUCE_ACCESS_TOKEN_EXPIRY_TIME.into()), ..access_token }; logger::debug!( access_token_expiry_after_modification = modified_access_token_with_expiry.expires ); if let Err(access_token_set_error) = store .set_access_token( merchant_id, &merchant_connector_id_or_connector_name, modified_access_token_with_expiry.clone(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("DB error when setting the access token") { // If we are not able to set the access token in redis, the error should just be logged and proceed with the payment // Payments should not fail, once the access token is successfully created // The next request will create new access token, if required logger::error!(access_token_set_error=?access_token_set_error); } Some(modified_access_token_with_expiry) }) .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, }) } } 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) }
1,821
1,599
hyperswitch
crates/router/src/core/payments/retry.rs
.rs
use std::{str::FromStr, vec::IntoIter}; use common_utils::{ext_traits::Encode, types::MinorUnit}; use diesel_models::enums as storage_enums; use error_stack::{report, ResultExt}; use router_env::{ logger, tracing::{self, instrument}, }; 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}, }; #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] #[cfg(feature = "v1")] 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) } #[instrument(skip_all)] pub async fn is_step_up_enabled_for_merchant_connector( state: &app::SessionState, merchant_id: &common_utils::id_type::MerchantId, connector_name: types::Connector, ) -> bool { let key = merchant_id.get_step_up_enabled_key(); let db = &*state.store; db.find_config_by_key_unwrap_or(key.as_str(), Some("[]".to_string())) .await .change_context(errors::ApiErrorResponse::InternalServerError) .and_then(|step_up_config| { serde_json::from_str::<Vec<types::Connector>>(&step_up_config.config) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Step-up config parsing failed") }) .map_err(|err| { logger::error!(step_up_config_error=?err); }) .ok() .map(|connectors_enabled| connectors_enabled.contains(&connector_name)) .unwrap_or(false) } #[cfg(feature = "v1")] pub async fn get_merchant_max_auto_retries_enabled( db: &dyn StorageInterface, merchant_id: &common_utils::id_type::MerchantId, ) -> Option<i32> { let key = merchant_id.get_max_auto_retries_enabled(); db.find_config_by_key(key.as_str()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .and_then(|retries_config| { retries_config .config .parse::<i32>() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Retries config parsing failed") }) .map_err(|err| { logger::error!(retries_error=?err); None::<i32> }) .ok() } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn get_retries( state: &app::SessionState, retries: Option<i32>, merchant_id: &common_utils::id_type::MerchantId, profile: &domain::Profile, ) -> Option<i32> { match retries { Some(retries) => Some(retries), None => get_merchant_max_auto_retries_enabled(state.store.as_ref(), merchant_id) .await .or(profile.max_auto_retries_enabled.map(i32::from)), } } #[instrument(skip_all)] pub async fn get_gsm<F, FData>( state: &app::SessionState, router_data: &types::RouterData<F, FData, types::PaymentsResponseData>, ) -> RouterResult<Option<storage::gsm::GatewayStatusMap>> { let error_response = router_data.response.as_ref().err(); let error_code = error_response.map(|err| err.code.to_owned()); let error_message = error_response.map(|err| err.message.to_owned()); let connector_name = router_data.connector.to_string(); let flow = get_flow_name::<F>()?; Ok( payments::helpers::get_gsm_record(state, error_code, error_message, connector_name, flow) .await, ) } #[instrument(skip_all)] 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() } #[inline] 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()) } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] 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) } #[cfg(feature = "v2")] #[instrument(skip_all)] 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!() } #[cfg(feature = "v1")] #[instrument(skip_all)] 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(()) } #[cfg(feature = "v1")] #[instrument(skip_all)] pub fn make_new_payment_attempt( connector: String, old_payment_attempt: storage::PaymentAttempt, new_attempt_count: i16, is_step_up: bool, ) -> storage::PaymentAttemptNew { let created_at @ modified_at @ last_synced = Some(common_utils::date_time::now()); storage::PaymentAttemptNew { connector: Some(connector), 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, status: old_payment_attempt.status, currency: old_payment_attempt.currency, save_to_locker: old_payment_attempt.save_to_locker, offer_amount: old_payment_attempt.offer_amount, payment_method_id: old_payment_attempt.payment_method_id, payment_method: old_payment_attempt.payment_method, payment_method_type: old_payment_attempt.payment_method_type, capture_method: old_payment_attempt.capture_method, capture_on: old_payment_attempt.capture_on, confirm: old_payment_attempt.confirm, authentication_type: if is_step_up { Some(storage_enums::AuthenticationType::ThreeDs) } else { old_payment_attempt.authentication_type }, amount_to_capture: old_payment_attempt.amount_to_capture, mandate_id: old_payment_attempt.mandate_id, browser_info: old_payment_attempt.browser_info, payment_token: old_payment_attempt.payment_token, client_source: old_payment_attempt.client_source, client_version: old_payment_attempt.client_version, created_at, modified_at, last_synced, profile_id: old_payment_attempt.profile_id, organization_id: old_payment_attempt.organization_id, net_amount: old_payment_attempt.net_amount, error_message: Default::default(), cancellation_reason: Default::default(), error_code: Default::default(), connector_metadata: Default::default(), payment_experience: Default::default(), payment_method_data: Default::default(), business_sub_label: Default::default(), straight_through_algorithm: Default::default(), preprocessing_step_id: Default::default(), mandate_details: Default::default(), error_reason: Default::default(), connector_response_reference_id: Default::default(), multiple_capture_count: Default::default(), amount_capturable: Default::default(), updated_by: Default::default(), authentication_data: Default::default(), encoded_data: Default::default(), merchant_connector_id: Default::default(), unified_code: Default::default(), unified_message: Default::default(), external_three_ds_authentication_attempted: Default::default(), authentication_connector: Default::default(), authentication_id: Default::default(), mandate_data: Default::default(), payment_method_billing_address_id: Default::default(), fingerprint_id: Default::default(), customer_acceptance: Default::default(), connector_mandate_detail: Default::default(), request_extended_authorization: Default::default(), extended_authorization_applied: Default::default(), capture_before: Default::default(), card_discovery: old_payment_attempt.card_discovery, } } #[cfg(feature = "v2")] #[instrument(skip_all)] pub fn make_new_payment_attempt( _connector: String, _old_payment_attempt: storage::PaymentAttempt, _new_attempt_count: i16, _is_step_up: bool, ) -> storage::PaymentAttempt { todo!() } #[cfg(feature = "v1")] pub async fn get_merchant_config_for_gsm( db: &dyn StorageInterface, merchant_id: &common_utils::id_type::MerchantId, ) -> bool { let config = db .find_config_by_key_unwrap_or( &merchant_id.get_should_call_gsm_key(), Some("false".to_string()), ) .await; match config { Ok(conf) => conf.config == "true", Err(error) => { logger::error!(?error); false } } } #[cfg(feature = "v1")] pub async fn config_should_call_gsm( db: &dyn StorageInterface, merchant_id: &common_utils::id_type::MerchantId, profile: &domain::Profile, ) -> bool { let merchant_config_gsm = get_merchant_config_for_gsm(db, merchant_id).await; let profile_config_gsm = profile.is_auto_retries_enabled; merchant_config_gsm || profile_config_gsm } pub trait GsmValidation<F: Send + Clone + Sync, FData: Send + Sync, Resp> { // TODO : move this function to appropriate place later. fn should_call_gsm(&self) -> bool; } impl<F: Send + Clone + Sync, FData: Send + Sync> GsmValidation<F, FData, types::PaymentsResponseData> for types::RouterData<F, FData, types::PaymentsResponseData> { #[inline(always)] fn should_call_gsm(&self) -> bool { if self.response.is_err() { true } else { match self.status { storage_enums::AttemptStatus::Started | storage_enums::AttemptStatus::AuthenticationPending | storage_enums::AttemptStatus::AuthenticationSuccessful | storage_enums::AttemptStatus::Authorized | storage_enums::AttemptStatus::Charged | storage_enums::AttemptStatus::Authorizing | storage_enums::AttemptStatus::CodInitiated | storage_enums::AttemptStatus::Voided | storage_enums::AttemptStatus::VoidInitiated | storage_enums::AttemptStatus::CaptureInitiated | storage_enums::AttemptStatus::RouterDeclined | storage_enums::AttemptStatus::VoidFailed | storage_enums::AttemptStatus::AutoRefunded | storage_enums::AttemptStatus::CaptureFailed | storage_enums::AttemptStatus::PartialCharged | storage_enums::AttemptStatus::PartialChargedAndChargeable | storage_enums::AttemptStatus::Pending | storage_enums::AttemptStatus::PaymentMethodAwaited | storage_enums::AttemptStatus::ConfirmationAwaited | storage_enums::AttemptStatus::Unresolved | storage_enums::AttemptStatus::DeviceDataCollectionPending => false, storage_enums::AttemptStatus::AuthenticationFailed | storage_enums::AttemptStatus::AuthorizationFailed | storage_enums::AttemptStatus::Failure => true, } } } }
5,829
1,600
hyperswitch
crates/router/src/core/payments/helpers.rs
.rs
use std::{borrow::Cow, collections::HashSet, net::IpAddr, str::FromStr}; #[cfg(feature = "v2")] use api_models::ephemeral_key::ClientSecretResponse; use api_models::{ mandates::RecurringDetails, payments::{additional_info as payment_additional_types, RequestSurchargeDetails}, }; use base64::Engine; use common_enums::ConnectorType; #[cfg(feature = "v2")] use common_utils::id_type::GenerateId; use common_utils::{ crypto::Encryptable, ext_traits::{AsyncExt, ByteSliceExt, Encode, ValueExt}, fp_utils, generate_id, id_type::{self}, new_type::{MaskedIban, MaskedSortCode}, pii, type_name, types::{ keymanager::{Identifier, KeyManagerState, ToEncryptable}, MinorUnit, }, }; use diesel_models::enums; // TODO : Evaluate all the helper functions () use error_stack::{report, ResultExt}; use futures::future::Either; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use hyperswitch_domain_models::payments::payment_intent::CustomerData; use hyperswitch_domain_models::{ mandates::MandateData, payment_method_data::{GetPaymentMethodType, PazeWalletData}, payments::{ self as domain_payments, payment_attempt::PaymentAttempt, payment_intent::PaymentIntentFetchConstraints, PaymentIntent, }, router_data::KlarnaSdkResponse, }; use hyperswitch_interfaces::integrity::{CheckIntegrity, FlowIntegrity, GetIntegrityObject}; use josekit::jwe; use masking::{ExposeInterface, PeekInterface, SwitchStrategy}; use openssl::{ derive::Deriver, pkey::PKey, symm::{decrypt_aead, Cipher}, }; #[cfg(feature = "v2")] use redis_interface::errors::RedisError; use router_env::{instrument, logger, tracing}; use serde::{Deserialize, Serialize}; use uuid::Uuid; use x509_parser::parse_x509_certificate; use super::{ operations::{BoxedOperation, Operation, PaymentResponse}, CustomerDetails, PaymentData, }; use crate::{ configs::settings::{ConnectorRequestReferenceIdConfig, TempLockerEnableConfig}, connector, consts::{self, BASE64_ENGINE}, core::{ authentication, errors::{self, CustomResult, RouterResult, StorageErrorExt}, mandate::helpers::MandateGenericData, payment_methods::{ self, cards::{self}, network_tokenization, vault, }, payments, pm_auth::retrieve_payment_method_from_auth_service, }, db::StorageInterface, routes::{metrics, payment_methods as payment_methods_handler, SessionState}, services, types::{ api::{self, admin, enums as api_enums, MandateValidationFieldsExt}, domain::{self, types}, storage::{self, enums as storage_enums, ephemeral_key, CardTokenData}, transformers::{ForeignFrom, ForeignTryFrom}, AdditionalMerchantData, AdditionalPaymentMethodConnectorResponse, ErrorResponse, MandateReference, MerchantAccountData, MerchantRecipientData, PaymentsResponseData, RecipientIdType, RecurringMandatePaymentData, RouterData, }, utils::{ self, crypto::{self, SignMessage}, OptionExt, StringExt, }, }; #[cfg(feature = "v2")] use crate::{core::admin as core_admin, headers}; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use crate::{ core::payment_methods::cards::create_encrypted_data, types::storage::CustomerUpdate::Update, }; #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn create_or_update_address_for_payment_by_request( session_state: &SessionState, req_address: Option<&api::Address>, address_id: Option<&str>, merchant_id: &id_type::MerchantId, customer_id: Option<&id_type::CustomerId>, merchant_key_store: &domain::MerchantKeyStore, payment_id: &id_type::PaymentId, storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Option<domain::Address>, errors::ApiErrorResponse> { let key = merchant_key_store.key.get_inner().peek(); let db = &session_state.store; let key_manager_state = &session_state.into(); Ok(match address_id { Some(id) => match req_address { Some(address) => { let encrypted_data = types::crypto_operation( &session_state.into(), type_name!(domain::Address), types::CryptoOperation::BatchEncrypt( domain::FromRequestEncryptableAddress::to_encryptable( domain::FromRequestEncryptableAddress { line1: address.address.as_ref().and_then(|a| a.line1.clone()), line2: address.address.as_ref().and_then(|a| a.line2.clone()), line3: address.address.as_ref().and_then(|a| a.line3.clone()), state: address.address.as_ref().and_then(|a| a.state.clone()), first_name: address .address .as_ref() .and_then(|a| a.first_name.clone()), last_name: address .address .as_ref() .and_then(|a| a.last_name.clone()), zip: address.address.as_ref().and_then(|a| a.zip.clone()), phone_number: address .phone .as_ref() .and_then(|phone| phone.number.clone()), email: address .email .as_ref() .map(|a| a.clone().expose().switch_strategy()), }, ), ), Identifier::Merchant(merchant_key_store.merchant_id.clone()), key, ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting address")?; let encryptable_address = domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting address")?; let address_update = storage::AddressUpdate::Update { city: address .address .as_ref() .and_then(|value| value.city.clone()), country: address.address.as_ref().and_then(|value| value.country), line1: encryptable_address.line1, line2: encryptable_address.line2, line3: encryptable_address.line3, state: encryptable_address.state, zip: encryptable_address.zip, first_name: encryptable_address.first_name, last_name: encryptable_address.last_name, phone_number: encryptable_address.phone_number, country_code: address .phone .as_ref() .and_then(|value| value.country_code.clone()), updated_by: storage_scheme.to_string(), email: encryptable_address.email.map(|email| { let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), }; let address = db .find_address_by_merchant_id_payment_id_address_id( key_manager_state, merchant_id, payment_id, id, merchant_key_store, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while fetching address")?; Some( db.update_address_for_payments( key_manager_state, address, address_update, payment_id.to_owned(), merchant_key_store, storage_scheme, ) .await .map(|payment_address| payment_address.address) .to_not_found_response(errors::ApiErrorResponse::AddressNotFound)?, ) } None => Some( db.find_address_by_merchant_id_payment_id_address_id( key_manager_state, merchant_id, payment_id, id, merchant_key_store, storage_scheme, ) .await .map(|payment_address| payment_address.address), ) .transpose() .to_not_found_response(errors::ApiErrorResponse::AddressNotFound)?, }, None => match req_address { Some(address) => { let address = get_domain_address(session_state, address, merchant_id, key, storage_scheme) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting address while insert")?; let payment_address = domain::PaymentAddress { address, payment_id: payment_id.clone(), customer_id: customer_id.cloned(), }; Some( db.insert_address_for_payments( key_manager_state, payment_id, payment_address, merchant_key_store, storage_scheme, ) .await .map(|payment_address| payment_address.address) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while inserting new address")?, ) } None => None, }, }) } #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn create_or_find_address_for_payment_by_request( state: &SessionState, req_address: Option<&api::Address>, address_id: Option<&str>, merchant_id: &id_type::MerchantId, customer_id: Option<&id_type::CustomerId>, merchant_key_store: &domain::MerchantKeyStore, payment_id: &id_type::PaymentId, storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Option<domain::Address>, errors::ApiErrorResponse> { let key = merchant_key_store.key.get_inner().peek(); let db = &state.store; let key_manager_state = &state.into(); Ok(match address_id { Some(id) => Some( db.find_address_by_merchant_id_payment_id_address_id( key_manager_state, merchant_id, payment_id, id, merchant_key_store, storage_scheme, ) .await .map(|payment_address| payment_address.address), ) .transpose() .to_not_found_response(errors::ApiErrorResponse::AddressNotFound)?, None => match req_address { Some(address) => { // generate a new address here let address = get_domain_address(state, address, merchant_id, key, storage_scheme) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting address while insert")?; let payment_address = domain::PaymentAddress { address, payment_id: payment_id.clone(), customer_id: customer_id.cloned(), }; Some( db.insert_address_for_payments( key_manager_state, payment_id, payment_address, merchant_key_store, storage_scheme, ) .await .map(|payment_address| payment_address.address) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while inserting new address")?, ) } None => None, }, }) } pub async fn get_domain_address( session_state: &SessionState, address: &api_models::payments::Address, merchant_id: &id_type::MerchantId, key: &[u8], storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<domain::Address, common_utils::errors::CryptoError> { async { let address_details = &address.address.as_ref(); let encrypted_data = types::crypto_operation( &session_state.into(), type_name!(domain::Address), types::CryptoOperation::BatchEncrypt( domain::FromRequestEncryptableAddress::to_encryptable( domain::FromRequestEncryptableAddress { line1: address.address.as_ref().and_then(|a| a.line1.clone()), line2: address.address.as_ref().and_then(|a| a.line2.clone()), line3: address.address.as_ref().and_then(|a| a.line3.clone()), state: address.address.as_ref().and_then(|a| a.state.clone()), first_name: address.address.as_ref().and_then(|a| a.first_name.clone()), last_name: address.address.as_ref().and_then(|a| a.last_name.clone()), zip: address.address.as_ref().and_then(|a| a.zip.clone()), phone_number: address .phone .as_ref() .and_then(|phone| phone.number.clone()), email: address .email .as_ref() .map(|a| a.clone().expose().switch_strategy()), }, ), ), Identifier::Merchant(merchant_id.to_owned()), key, ) .await .and_then(|val| val.try_into_batchoperation())?; let encryptable_address = domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data) .change_context(common_utils::errors::CryptoError::EncodingFailed)?; Ok(domain::Address { phone_number: encryptable_address.phone_number, country_code: address.phone.as_ref().and_then(|a| a.country_code.clone()), merchant_id: merchant_id.to_owned(), address_id: generate_id(consts::ID_LENGTH, "add"), city: address_details.and_then(|address_details| address_details.city.clone()), country: address_details.and_then(|address_details| address_details.country), line1: encryptable_address.line1, line2: encryptable_address.line2, line3: encryptable_address.line3, state: encryptable_address.state, created_at: common_utils::date_time::now(), first_name: encryptable_address.first_name, last_name: encryptable_address.last_name, modified_at: common_utils::date_time::now(), zip: encryptable_address.zip, updated_by: storage_scheme.to_string(), email: encryptable_address.email.map(|email| { let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), }) } .await } pub async fn get_address_by_id( state: &SessionState, address_id: Option<String>, merchant_key_store: &domain::MerchantKeyStore, payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Option<domain::Address>, errors::ApiErrorResponse> { match address_id { None => Ok(None), Some(address_id) => { let db = &*state.store; Ok(db .find_address_by_merchant_id_payment_id_address_id( &state.into(), merchant_id, payment_id, &address_id, merchant_key_store, storage_scheme, ) .await .map(|payment_address| payment_address.address) .ok()) } } } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] pub async fn get_token_pm_type_mandate_details( state: &SessionState, request: &api::PaymentsRequest, mandate_type: Option<api::MandateTransactionType>, merchant_account: &domain::MerchantAccount, merchant_key_store: &domain::MerchantKeyStore, payment_method_id: Option<String>, payment_intent_customer_id: Option<&id_type::CustomerId>, ) -> RouterResult<MandateGenericData> { let mandate_data = request.mandate_data.clone().map(MandateData::foreign_from); let ( payment_token, payment_method, payment_method_type, mandate_data, recurring_payment_data, mandate_connector_details, payment_method_info, ) = match mandate_type { Some(api::MandateTransactionType::NewMandateTransaction) => ( request.payment_token.to_owned(), request.payment_method, request.payment_method_type, mandate_data.clone(), None, None, None, ), Some(api::MandateTransactionType::RecurringMandateTransaction) => { match &request.recurring_details { Some(recurring_details) => { match recurring_details { RecurringDetails::NetworkTransactionIdAndCardDetails(_) => { (None, request.payment_method, None, None, None, None, None) } RecurringDetails::ProcessorPaymentToken(processor_payment_token) => { if let Some(mca_id) = &processor_payment_token.merchant_connector_id { let db = &*state.store; let key_manager_state = &state.into(); #[cfg(feature = "v1")] let connector_name = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_account.get_id(), mca_id, merchant_key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: mca_id.clone().get_string_repr().to_string(), })?.connector_name; #[cfg(feature = "v2")] let connector_name = db .find_merchant_connector_account_by_id(key_manager_state, mca_id, merchant_key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: mca_id.clone().get_string_repr().to_string(), })?.connector_name; ( None, request.payment_method, None, None, None, Some(payments::MandateConnectorDetails { connector: connector_name, merchant_connector_id: Some(mca_id.clone()), }), None, ) } else { (None, request.payment_method, None, None, None, None, None) } } RecurringDetails::MandateId(mandate_id) => { let mandate_generic_data = Box::pin(get_token_for_recurring_mandate( state, request, merchant_account, merchant_key_store, mandate_id.to_owned(), )) .await?; ( mandate_generic_data.token, mandate_generic_data.payment_method, mandate_generic_data .payment_method_type .or(request.payment_method_type), None, mandate_generic_data.recurring_mandate_payment_data, mandate_generic_data.mandate_connector, mandate_generic_data.payment_method_info, ) } RecurringDetails::PaymentMethodId(payment_method_id) => { let payment_method_info = state .store .find_payment_method( &(state.into()), merchant_key_store, payment_method_id, merchant_account.storage_scheme, ) .await .to_not_found_response( errors::ApiErrorResponse::PaymentMethodNotFound, )?; let customer_id = request .get_customer_id() .get_required_value("customer_id")?; verify_mandate_details_for_recurring_payments( &payment_method_info.merchant_id, merchant_account.get_id(), &payment_method_info.customer_id, customer_id, )?; ( None, payment_method_info.get_payment_method_type(), payment_method_info.get_payment_method_subtype(), None, None, None, Some(payment_method_info), ) } } } None => { if let Some(mandate_id) = request.mandate_id.clone() { let mandate_generic_data = Box::pin(get_token_for_recurring_mandate( state, request, merchant_account, merchant_key_store, mandate_id, )) .await?; ( mandate_generic_data.token, mandate_generic_data.payment_method, mandate_generic_data .payment_method_type .or(request.payment_method_type), None, mandate_generic_data.recurring_mandate_payment_data, mandate_generic_data.mandate_connector, mandate_generic_data.payment_method_info, ) } else if request .payment_method_type .map(|payment_method_type_value| { payment_method_type_value .should_check_for_customer_saved_payment_method_type() }) .unwrap_or(false) { let payment_request_customer_id = request.get_customer_id(); if let Some(customer_id) = payment_request_customer_id.or(payment_intent_customer_id) { let customer_saved_pm_option = match state .store .find_payment_method_by_customer_id_merchant_id_list( &(state.into()), merchant_key_store, customer_id, merchant_account.get_id(), None, ) .await { Ok(customer_payment_methods) => Ok(customer_payment_methods .iter() .find(|payment_method| { payment_method.get_payment_method_subtype() == request.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", ) } } }?; ( None, request.payment_method, request.payment_method_type, None, None, None, customer_saved_pm_option, ) } else { ( None, request.payment_method, request.payment_method_type, None, None, None, None, ) } } else { let payment_method_info = payment_method_id .async_map(|payment_method_id| async move { state .store .find_payment_method( &(state.into()), merchant_key_store, &payment_method_id, merchant_account.storage_scheme, ) .await .to_not_found_response( errors::ApiErrorResponse::PaymentMethodNotFound, ) }) .await .transpose()?; ( request.payment_token.to_owned(), request.payment_method, request.payment_method_type, None, None, None, payment_method_info, ) } } } } None => { let payment_method_info = payment_method_id .async_map(|payment_method_id| async move { state .store .find_payment_method( &(state.into()), merchant_key_store, &payment_method_id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound) }) .await .transpose()?; ( request.payment_token.to_owned(), request.payment_method, request.payment_method_type, mandate_data, None, None, payment_method_info, ) } }; Ok(MandateGenericData { token: payment_token, payment_method, payment_method_type, mandate_data, recurring_mandate_payment_data: recurring_payment_data, mandate_connector: mandate_connector_details, payment_method_info, }) } #[cfg(feature = "v1")] pub async fn get_token_for_recurring_mandate( state: &SessionState, req: &api::PaymentsRequest, merchant_account: &domain::MerchantAccount, merchant_key_store: &domain::MerchantKeyStore, mandate_id: String, ) -> RouterResult<MandateGenericData> { let db = &*state.store; let mandate = 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)?; let key_manager_state: KeyManagerState = state.into(); let original_payment_intent = mandate .original_payment_id .as_ref() .async_map(|payment_id| async { db.find_payment_intent_by_payment_id_merchant_id( &key_manager_state, payment_id, &mandate.merchant_id, merchant_key_store, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) .map_err(|err| logger::error!(mandate_original_payment_not_found=?err)) .ok() }) .await .flatten(); let original_payment_attempt = original_payment_intent .as_ref() .async_map(|payment_intent| async { db.find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, &mandate.merchant_id, payment_intent.active_attempt.get_id().as_str(), merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) .map_err(|err| logger::error!(mandate_original_payment_attempt_not_found=?err)) .ok() }) .await .flatten(); let original_payment_authorized_amount = original_payment_attempt .clone() .map(|pa| pa.net_amount.get_total_amount().get_amount_as_i64()); let original_payment_authorized_currency = original_payment_intent.clone().and_then(|pi| pi.currency); let customer = req.get_customer_id().get_required_value("customer_id")?; let payment_method_id = { if &mandate.customer_id != customer { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "customer_id must match mandate customer_id".into() }))? } if mandate.mandate_status != storage_enums::MandateStatus::Active { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "mandate is not active".into() }))? }; mandate.payment_method_id.clone() }; verify_mandate_details( req.amount.get_required_value("amount")?.into(), req.currency.get_required_value("currency")?, mandate.clone(), )?; let payment_method = db .find_payment_method( &(state.into()), merchant_key_store, payment_method_id.as_str(), merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; let token = Uuid::new_v4().to_string(); let payment_method_type = payment_method.get_payment_method_subtype(); let mandate_connector_details = payments::MandateConnectorDetails { connector: mandate.connector, merchant_connector_id: mandate.merchant_connector_id, }; if let Some(enums::PaymentMethod::Card) = payment_method.get_payment_method_type() { if state.conf.locker.locker_enabled { let _ = cards::get_lookup_key_from_locker( state, &token, &payment_method, merchant_key_store, ) .await?; } if let Some(payment_method_from_request) = req.payment_method { let pm: storage_enums::PaymentMethod = payment_method_from_request; if payment_method .get_payment_method_type() .is_some_and(|payment_method| payment_method != pm) { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "payment method in request does not match previously provided payment \ method information" .into() }))? } }; Ok(MandateGenericData { token: Some(token), payment_method: payment_method.get_payment_method_type(), recurring_mandate_payment_data: Some(RecurringMandatePaymentData { payment_method_type, original_payment_authorized_amount, original_payment_authorized_currency, mandate_metadata: None, }), payment_method_type: payment_method.get_payment_method_subtype(), mandate_connector: Some(mandate_connector_details), mandate_data: None, payment_method_info: Some(payment_method), }) } else { Ok(MandateGenericData { token: None, payment_method: payment_method.get_payment_method_type(), recurring_mandate_payment_data: Some(RecurringMandatePaymentData { payment_method_type, original_payment_authorized_amount, original_payment_authorized_currency, mandate_metadata: None, }), payment_method_type: payment_method.get_payment_method_subtype(), mandate_connector: Some(mandate_connector_details), mandate_data: None, payment_method_info: Some(payment_method), }) } } #[instrument(skip_all)] /// Check weather the merchant id in the request /// and merchant id in the merchant account are same. pub fn validate_merchant_id( merchant_id: &id_type::MerchantId, request_merchant_id: Option<&id_type::MerchantId>, ) -> CustomResult<(), errors::ApiErrorResponse> { // Get Merchant Id from the merchant // or get from merchant account let request_merchant_id = request_merchant_id.unwrap_or(merchant_id); utils::when(merchant_id.ne(request_merchant_id), || { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: format!( "Invalid `merchant_id`: {} not found in merchant account", request_merchant_id.get_string_repr() ) })) }) } #[instrument(skip_all)] pub fn validate_request_amount_and_amount_to_capture( op_amount: Option<api::Amount>, op_amount_to_capture: Option<MinorUnit>, surcharge_details: Option<RequestSurchargeDetails>, ) -> CustomResult<(), errors::ApiErrorResponse> { match (op_amount, op_amount_to_capture) { (None, _) => Ok(()), (Some(_amount), None) => Ok(()), (Some(amount), Some(amount_to_capture)) => { match amount { api::Amount::Value(amount_inner) => { // If both amount and amount to capture is present // then amount to be capture should be less than or equal to request amount let total_capturable_amount = MinorUnit::new(amount_inner.get()) + surcharge_details .map(|surcharge_details| surcharge_details.get_total_surcharge_amount()) .unwrap_or_default(); utils::when(!amount_to_capture.le(&total_capturable_amount), || { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: format!( "amount_to_capture is greater than amount capture_amount: {amount_to_capture:?} request_amount: {amount:?}" ) })) }) } api::Amount::Zero => { // If the amount is Null but still amount_to_capture is passed this is invalid and Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "amount_to_capture should not exist for when amount = 0" .to_string() })) } } } } } #[cfg(feature = "v1")] /// if capture method = automatic, amount_to_capture(if provided) must be equal to amount #[instrument(skip_all)] pub fn validate_amount_to_capture_and_capture_method( payment_attempt: Option<&PaymentAttempt>, request: &api_models::payments::PaymentsRequest, ) -> CustomResult<(), errors::ApiErrorResponse> { let option_net_amount = hyperswitch_domain_models::payments::payment_attempt::NetAmount::from_payments_request_and_payment_attempt( request, payment_attempt, ); let capture_method = request .capture_method .or(payment_attempt .map(|payment_attempt| payment_attempt.capture_method.unwrap_or_default())) .unwrap_or_default(); if matches!( capture_method, api_enums::CaptureMethod::Automatic | api_enums::CaptureMethod::SequentialAutomatic ) { let total_capturable_amount = option_net_amount.map(|net_amount| net_amount.get_total_amount()); let amount_to_capture = request .amount_to_capture .or(payment_attempt.and_then(|pa| pa.amount_to_capture)); if let Some((total_capturable_amount, amount_to_capture)) = total_capturable_amount.zip(amount_to_capture) { utils::when(amount_to_capture != total_capturable_amount, || { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "amount_to_capture must be equal to total_capturable_amount when capture_method = automatic".into() })) }) } else { Ok(()) } } else { Ok(()) } } #[instrument(skip_all)] pub fn validate_card_data( payment_method_data: Option<api::PaymentMethodData>, ) -> CustomResult<(), errors::ApiErrorResponse> { if let Some(api::PaymentMethodData::Card(card)) = payment_method_data { let cvc = card.card_cvc.peek().to_string(); if cvc.len() < 3 || cvc.len() > 4 { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "Invalid card_cvc length".to_string() }))? } let card_cvc = cvc.parse::<u16>() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "card_cvc", })?; ::cards::CardSecurityCode::try_from(card_cvc).change_context( errors::ApiErrorResponse::PreconditionFailed { message: "Invalid Card CVC".to_string(), }, )?; validate_card_expiry(&card.card_exp_month, &card.card_exp_year)?; } Ok(()) } #[instrument(skip_all)] pub fn validate_card_expiry( card_exp_month: &masking::Secret<String>, card_exp_year: &masking::Secret<String>, ) -> CustomResult<(), errors::ApiErrorResponse> { let exp_month = card_exp_month .peek() .to_string() .parse::<u8>() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "card_exp_month", })?; let month = ::cards::CardExpirationMonth::try_from(exp_month).change_context( errors::ApiErrorResponse::PreconditionFailed { message: "Invalid Expiry Month".to_string(), }, )?; let mut year_str = card_exp_year.peek().to_string(); if year_str.len() == 2 { year_str = format!("20{}", year_str); } let exp_year = year_str .parse::<u16>() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "card_exp_year", })?; let year = ::cards::CardExpirationYear::try_from(exp_year).change_context( errors::ApiErrorResponse::PreconditionFailed { message: "Invalid Expiry Year".to_string(), }, )?; let card_expiration = ::cards::CardExpiration { month, year }; let is_expired = card_expiration.is_expired().change_context( errors::ApiErrorResponse::PreconditionFailed { message: "Invalid card data".to_string(), }, )?; if is_expired { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "Card Expired".to_string() }))? } Ok(()) } pub fn infer_payment_type( amount: api::Amount, mandate_type: Option<&api::MandateTransactionType>, ) -> api_enums::PaymentType { match mandate_type { Some(api::MandateTransactionType::NewMandateTransaction) => { if let api::Amount::Value(_) = amount { api_enums::PaymentType::NewMandate } else { api_enums::PaymentType::SetupMandate } } Some(api::MandateTransactionType::RecurringMandateTransaction) => { api_enums::PaymentType::RecurringMandate } None => api_enums::PaymentType::Normal, } } pub fn validate_mandate( req: impl Into<api::MandateValidationFields>, is_confirm_operation: bool, ) -> CustomResult<Option<api::MandateTransactionType>, errors::ApiErrorResponse> { let req: api::MandateValidationFields = req.into(); match req.validate_and_get_mandate_type().change_context( errors::ApiErrorResponse::MandateValidationFailed { reason: "Expected one out of recurring_details and mandate_data but got both".into(), }, )? { Some(api::MandateTransactionType::NewMandateTransaction) => { validate_new_mandate_request(req, is_confirm_operation)?; Ok(Some(api::MandateTransactionType::NewMandateTransaction)) } Some(api::MandateTransactionType::RecurringMandateTransaction) => { validate_recurring_mandate(req)?; Ok(Some( api::MandateTransactionType::RecurringMandateTransaction, )) } None => Ok(None), } } pub fn validate_recurring_details_and_token( recurring_details: &Option<RecurringDetails>, payment_token: &Option<String>, mandate_id: &Option<String>, ) -> CustomResult<(), errors::ApiErrorResponse> { utils::when( recurring_details.is_some() && payment_token.is_some(), || { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "Expected one out of recurring_details and payment_token but got both" .into() })) }, )?; utils::when(recurring_details.is_some() && mandate_id.is_some(), || { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "Expected one out of recurring_details and mandate_id but got both".into() })) })?; Ok(()) } fn validate_new_mandate_request( req: api::MandateValidationFields, is_confirm_operation: bool, ) -> RouterResult<()> { // We need not check for customer_id in the confirm request if it is already passed // in create request fp_utils::when(!is_confirm_operation && req.customer_id.is_none(), || { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "`customer_id` is mandatory for mandates".into() })) })?; let mandate_data = req .mandate_data .clone() .get_required_value("mandate_data")?; // Only use this validation if the customer_acceptance is present if mandate_data .customer_acceptance .map(|inner| inner.acceptance_type == api::AcceptanceType::Online && inner.online.is_none()) .unwrap_or(false) { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "`mandate_data.customer_acceptance.online` is required when \ `mandate_data.customer_acceptance.acceptance_type` is `online`" .into() }))? } let mandate_details = match mandate_data.mandate_type { Some(api_models::payments::MandateType::SingleUse(details)) => Some(details), Some(api_models::payments::MandateType::MultiUse(details)) => details, _ => None, }; mandate_details.and_then(|md| md.start_date.zip(md.end_date)).map(|(start_date, end_date)| utils::when (start_date >= end_date, || { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "`mandate_data.mandate_type.{multi_use|single_use}.start_date` should be greater than \ `mandate_data.mandate_type.{multi_use|single_use}.end_date`" .into() })) })).transpose()?; Ok(()) } pub fn validate_customer_id_mandatory_cases( has_setup_future_usage: bool, customer_id: Option<&id_type::CustomerId>, ) -> RouterResult<()> { match (has_setup_future_usage, customer_id) { (true, None) => Err(errors::ApiErrorResponse::PreconditionFailed { message: "customer_id is mandatory when setup_future_usage is given".to_string(), } .into()), _ => Ok(()), } } #[cfg(feature = "v1")] pub fn create_startpay_url( base_url: &str, payment_attempt: &PaymentAttempt, payment_intent: &PaymentIntent, ) -> String { format!( "{}/payments/redirect/{}/{}/{}", base_url, payment_intent.get_id().get_string_repr(), payment_intent.merchant_id.get_string_repr(), payment_attempt.attempt_id ) } pub fn create_redirect_url( router_base_url: &String, payment_attempt: &PaymentAttempt, connector_name: impl std::fmt::Display, creds_identifier: Option<&str>, ) -> String { let creds_identifier_path = creds_identifier.map_or_else(String::new, |cd| format!("/{}", cd)); format!( "{}/payments/{}/{}/redirect/response/{}", router_base_url, payment_attempt.payment_id.get_string_repr(), payment_attempt.merchant_id.get_string_repr(), connector_name, ) + creds_identifier_path.as_ref() } pub fn create_authentication_url( router_base_url: &str, payment_attempt: &PaymentAttempt, ) -> String { format!( "{router_base_url}/payments/{}/3ds/authentication", payment_attempt.payment_id.get_string_repr() ) } pub fn create_authorize_url( router_base_url: &str, payment_attempt: &PaymentAttempt, connector_name: impl std::fmt::Display, ) -> String { format!( "{}/payments/{}/{}/authorize/{}", router_base_url, payment_attempt.payment_id.get_string_repr(), payment_attempt.merchant_id.get_string_repr(), connector_name ) } pub fn create_webhook_url( router_base_url: &str, merchant_id: &id_type::MerchantId, merchant_connector_id_or_connector_name: &str, ) -> String { format!( "{}/webhooks/{}/{}", router_base_url, merchant_id.get_string_repr(), merchant_connector_id_or_connector_name, ) } pub fn create_complete_authorize_url( router_base_url: &String, payment_attempt: &PaymentAttempt, connector_name: impl std::fmt::Display, creds_identifier: Option<&str>, ) -> String { let creds_identifier = creds_identifier.map_or_else(String::new, |creds_identifier| { format!("/{}", creds_identifier) }); format!( "{}/payments/{}/{}/redirect/complete/{}{}", router_base_url, payment_attempt.payment_id.get_string_repr(), payment_attempt.merchant_id.get_string_repr(), connector_name, creds_identifier ) } fn validate_recurring_mandate(req: api::MandateValidationFields) -> RouterResult<()> { let recurring_details = req .recurring_details .get_required_value("recurring_details")?; match recurring_details { RecurringDetails::ProcessorPaymentToken(_) | RecurringDetails::NetworkTransactionIdAndCardDetails(_) => Ok(()), _ => { req.customer_id.check_value_present("customer_id")?; let confirm = req.confirm.get_required_value("confirm")?; if !confirm { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "`confirm` must be `true` for mandates".into() }))? } let off_session = req.off_session.get_required_value("off_session")?; if !off_session { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "`off_session` should be `true` for mandates".into() }))? } Ok(()) } } } pub fn verify_mandate_details( request_amount: MinorUnit, request_currency: api_enums::Currency, mandate: storage::Mandate, ) -> RouterResult<()> { match mandate.mandate_type { storage_enums::MandateType::SingleUse => utils::when( mandate .mandate_amount .map(|mandate_amount| request_amount.get_amount_as_i64() > mandate_amount) .unwrap_or(true), || { Err(report!(errors::ApiErrorResponse::MandateValidationFailed { reason: "request amount is greater than mandate amount".into() })) }, ), storage::enums::MandateType::MultiUse => utils::when( mandate .mandate_amount .map(|mandate_amount| { (mandate.amount_captured.unwrap_or(0) + request_amount.get_amount_as_i64()) > mandate_amount }) .unwrap_or(false), || { Err(report!(errors::ApiErrorResponse::MandateValidationFailed { reason: "request amount is greater than mandate amount".into() })) }, ), }?; utils::when( mandate .mandate_currency .map(|mandate_currency| mandate_currency != request_currency) .unwrap_or(false), || { Err(report!(errors::ApiErrorResponse::MandateValidationFailed { reason: "cross currency mandates not supported".into() })) }, ) } pub fn verify_mandate_details_for_recurring_payments( mandate_merchant_id: &id_type::MerchantId, merchant_id: &id_type::MerchantId, mandate_customer_id: &id_type::CustomerId, customer_id: &id_type::CustomerId, ) -> RouterResult<()> { if mandate_merchant_id != merchant_id { Err(report!(errors::ApiErrorResponse::MandateNotFound))? } if mandate_customer_id != customer_id { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "customer_id must match mandate customer_id".into() }))? } Ok(()) } #[instrument(skip_all)] 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, } } pub fn payment_intent_status_fsm( payment_method_data: Option<&api::PaymentMethodData>, confirm: Option<bool>, ) -> storage_enums::IntentStatus { match payment_method_data { Some(_) => match confirm { Some(true) => storage_enums::IntentStatus::RequiresPaymentMethod, _ => storage_enums::IntentStatus::RequiresConfirmation, }, None => storage_enums::IntentStatus::RequiresPaymentMethod, } } #[cfg(feature = "v1")] pub async fn add_domain_task_to_pt<Op>( operation: &Op, state: &SessionState, payment_attempt: &PaymentAttempt, requeue: bool, schedule_time: Option<time::PrimitiveDateTime>, ) -> CustomResult<(), errors::ApiErrorResponse> where Op: std::fmt::Debug, { if check_if_operation_confirm(operation) { match schedule_time { Some(stime) => { if !requeue { // Here, increment the count of added tasks every time a payment has been confirmed or PSync has been called metrics::TASKS_ADDED_COUNT.add( 1, router_env::metric_attributes!(("flow", format!("{:#?}", operation))), ); super::add_process_sync_task(&*state.store, payment_attempt, stime) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while adding task to process tracker") } else { // When the requeue is true, we reset the tasks count as we reset the task every time it is requeued metrics::TASKS_RESET_COUNT.add( 1, router_env::metric_attributes!(("flow", format!("{:#?}", operation))), ); super::reset_process_sync_task(&*state.store, payment_attempt, stime) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while updating task in process tracker") } } None => Ok(()), } } else { Ok(()) } } pub fn response_operation<'a, F, R, D>() -> BoxedOperation<'a, F, R, D> where F: Send + Clone, PaymentResponse: Operation<F, R, Data = D>, { Box::new(PaymentResponse) } pub fn validate_max_amount( amount: api_models::payments::Amount, ) -> CustomResult<(), errors::ApiErrorResponse> { match amount { api_models::payments::Amount::Value(value) => { utils::when(value.get() > consts::MAX_ALLOWED_AMOUNT, || { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: format!( "amount should not be more than {}", consts::MAX_ALLOWED_AMOUNT ) })) }) } api_models::payments::Amount::Zero => Ok(()), } } #[cfg(feature = "v1")] /// Check whether the customer information that is sent in the root of payments request /// and in the customer object are same, if the values mismatch return an error pub fn validate_customer_information( request: &api_models::payments::PaymentsRequest, ) -> RouterResult<()> { if let Some(mismatched_fields) = request.validate_customer_details_in_request() { let mismatched_fields = mismatched_fields.join(", "); Err(errors::ApiErrorResponse::PreconditionFailed { message: format!( "The field names `{mismatched_fields}` sent in both places is ambiguous" ), })? } else { Ok(()) } } pub async fn validate_card_ip_blocking_for_business_profile( state: &SessionState, ip: IpAddr, fingerprnt: masking::Secret<String>, card_testing_guard_config: &diesel_models::business_profile::CardTestingGuardConfig, ) -> RouterResult<String> { let cache_key = format!( "{}_{}_{}", consts::CARD_IP_BLOCKING_CACHE_KEY_PREFIX, fingerprnt.peek(), ip ); let unsuccessful_payment_threshold = card_testing_guard_config.card_ip_blocking_threshold; validate_blocking_threshold(state, unsuccessful_payment_threshold, cache_key).await } pub async fn validate_guest_user_card_blocking_for_business_profile( state: &SessionState, fingerprnt: masking::Secret<String>, customer_id: Option<id_type::CustomerId>, card_testing_guard_config: &diesel_models::business_profile::CardTestingGuardConfig, ) -> RouterResult<String> { let cache_key = format!( "{}_{}", consts::GUEST_USER_CARD_BLOCKING_CACHE_KEY_PREFIX, fingerprnt.peek() ); let unsuccessful_payment_threshold = card_testing_guard_config.guest_user_card_blocking_threshold; if customer_id.is_none() { Ok(validate_blocking_threshold(state, unsuccessful_payment_threshold, cache_key).await?) } else { Ok(cache_key) } } pub async fn validate_customer_id_blocking_for_business_profile( state: &SessionState, customer_id: id_type::CustomerId, profile_id: &id_type::ProfileId, card_testing_guard_config: &diesel_models::business_profile::CardTestingGuardConfig, ) -> RouterResult<String> { let cache_key = format!( "{}_{}_{}", consts::CUSTOMER_ID_BLOCKING_PREFIX, profile_id.get_string_repr(), customer_id.get_string_repr(), ); let unsuccessful_payment_threshold = card_testing_guard_config.customer_id_blocking_threshold; validate_blocking_threshold(state, unsuccessful_payment_threshold, cache_key).await } pub async fn validate_blocking_threshold( state: &SessionState, unsuccessful_payment_threshold: i32, cache_key: String, ) -> RouterResult<String> { match services::card_testing_guard::get_blocked_count_from_cache(state, &cache_key).await { Ok(Some(unsuccessful_payment_count)) => { if unsuccessful_payment_count >= unsuccessful_payment_threshold { Err(errors::ApiErrorResponse::PreconditionFailed { message: "Blocked due to suspicious activity".to_string(), })? } else { Ok(cache_key) } } Ok(None) => Ok(cache_key), Err(error) => Err(errors::ApiErrorResponse::InternalServerError).attach_printable(error)?, } } #[cfg(feature = "v1")] /// Get the customer details from customer field if present /// or from the individual fields in `PaymentsRequest` #[instrument(skip_all)] pub fn get_customer_details_from_request( request: &api_models::payments::PaymentsRequest, ) -> CustomerDetails { let customer_id = request.get_customer_id().map(ToOwned::to_owned); let customer_name = request .customer .as_ref() .and_then(|customer_details| customer_details.name.clone()) .or(request.name.clone()); let customer_email = request .customer .as_ref() .and_then(|customer_details| customer_details.email.clone()) .or(request.email.clone()); let customer_phone = request .customer .as_ref() .and_then(|customer_details| customer_details.phone.clone()) .or(request.phone.clone()); let customer_phone_code = request .customer .as_ref() .and_then(|customer_details| customer_details.phone_country_code.clone()) .or(request.phone_country_code.clone()); CustomerDetails { customer_id, name: customer_name, email: customer_email, phone: customer_phone, phone_country_code: customer_phone_code, } } pub async fn get_connector_default( _state: &SessionState, request_connector: Option<serde_json::Value>, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { Ok(request_connector.map_or( api::ConnectorChoice::Decide, api::ConnectorChoice::StraightThrough, )) } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[instrument(skip_all)] #[allow(clippy::type_complexity)] pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>( _state: &SessionState, _operation: BoxedOperation<'a, F, R, D>, _payment_data: &mut PaymentData<F>, _req: Option<CustomerDetails>, _merchant_id: &id_type::MerchantId, _key_store: &domain::MerchantKeyStore, _storage_scheme: common_enums::enums::MerchantStorageScheme, ) -> CustomResult<(BoxedOperation<'a, F, R, D>, Option<domain::Customer>), errors::StorageError> { todo!() } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all)] #[allow(clippy::type_complexity)] pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>( state: &SessionState, operation: BoxedOperation<'a, F, R, D>, payment_data: &mut PaymentData<F>, req: Option<CustomerDetails>, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: common_enums::enums::MerchantStorageScheme, ) -> CustomResult<(BoxedOperation<'a, F, R, D>, Option<domain::Customer>), errors::StorageError> { let request_customer_details = req .get_required_value("customer") .change_context(errors::StorageError::ValueNotFound("customer".to_owned()))?; let temp_customer_data = if request_customer_details.name.is_some() || request_customer_details.email.is_some() || request_customer_details.phone.is_some() || request_customer_details.phone_country_code.is_some() { Some(CustomerData { name: request_customer_details.name.clone(), email: request_customer_details.email.clone(), phone: request_customer_details.phone.clone(), phone_country_code: request_customer_details.phone_country_code.clone(), }) } else { None }; // Updation of Customer Details for the cases where both customer_id and specific customer // details are provided in Payment Update Request let raw_customer_details = payment_data .payment_intent .customer_details .clone() .map(|customer_details_encrypted| { customer_details_encrypted .into_inner() .expose() .parse_value::<CustomerData>("CustomerData") }) .transpose() .change_context(errors::StorageError::DeserializationFailed) .attach_printable("Failed to parse customer data from payment intent")? .map(|parsed_customer_data| CustomerData { name: request_customer_details .name .clone() .or(parsed_customer_data.name.clone()), email: request_customer_details .email .clone() .or(parsed_customer_data.email.clone()), phone: request_customer_details .phone .clone() .or(parsed_customer_data.phone.clone()), phone_country_code: request_customer_details .phone_country_code .clone() .or(parsed_customer_data.phone_country_code.clone()), }) .or(temp_customer_data); let key_manager_state = state.into(); payment_data.payment_intent.customer_details = raw_customer_details .clone() .async_map(|customer_details| { create_encrypted_data(&key_manager_state, key_store, customer_details) }) .await .transpose() .change_context(errors::StorageError::EncryptionError) .attach_printable("Unable to encrypt customer details")?; let customer_id = request_customer_details .customer_id .or(payment_data.payment_intent.customer_id.clone()); let db = &*state.store; let key_manager_state = &state.into(); let optional_customer = match customer_id { Some(customer_id) => { let customer_data = db .find_customer_optional_by_customer_id_merchant_id( key_manager_state, &customer_id, merchant_id, key_store, storage_scheme, ) .await?; let key = key_store.key.get_inner().peek(); let encrypted_data = types::crypto_operation( key_manager_state, type_name!(domain::Customer), types::CryptoOperation::BatchEncrypt( domain::FromRequestEncryptableCustomer::to_encryptable( domain::FromRequestEncryptableCustomer { name: request_customer_details.name.clone(), email: request_customer_details .email .as_ref() .map(|e| e.clone().expose().switch_strategy()), phone: request_customer_details.phone.clone(), }, ), ), Identifier::Merchant(key_store.merchant_id.clone()), key, ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(errors::StorageError::SerializationFailed) .attach_printable("Failed while encrypting Customer while Update")?; let encryptable_customer = domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data) .change_context(errors::StorageError::SerializationFailed) .attach_printable("Failed while encrypting Customer while Update")?; Some(match customer_data { Some(c) => { // Update the customer data if new data is passed in the request if request_customer_details.email.is_some() | request_customer_details.name.is_some() | request_customer_details.phone.is_some() | request_customer_details.phone_country_code.is_some() { let customer_update = Update { name: encryptable_customer.name, email: encryptable_customer.email.map(|email| { let encryptable: Encryptable< masking::Secret<String, pii::EmailStrategy>, > = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), phone: Box::new(encryptable_customer.phone), phone_country_code: request_customer_details.phone_country_code, description: None, connector_customer: Box::new(None), metadata: None, address_id: None, }; db.update_customer_by_customer_id_merchant_id( key_manager_state, customer_id, merchant_id.to_owned(), c, customer_update, key_store, storage_scheme, ) .await } else { Ok(c) } } None => { let new_customer = domain::Customer { customer_id, merchant_id: merchant_id.to_owned(), name: encryptable_customer.name, email: encryptable_customer.email.map(|email| { let encryptable: Encryptable< masking::Secret<String, pii::EmailStrategy>, > = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), phone: encryptable_customer.phone, phone_country_code: request_customer_details.phone_country_code.clone(), description: None, created_at: common_utils::date_time::now(), metadata: None, modified_at: common_utils::date_time::now(), connector_customer: None, address_id: None, default_payment_method_id: None, updated_by: None, version: common_types::consts::API_VERSION, }; metrics::CUSTOMER_CREATED.add(1, &[]); db.insert_customer(new_customer, key_manager_state, key_store, storage_scheme) .await } }) } None => match &payment_data.payment_intent.customer_id { None => None, Some(customer_id) => db .find_customer_optional_by_customer_id_merchant_id( key_manager_state, customer_id, merchant_id, key_store, storage_scheme, ) .await? .map(Ok), }, }; Ok(( operation, match optional_customer { Some(customer) => { let customer = customer?; payment_data.payment_intent.customer_id = Some(customer.customer_id.clone()); payment_data.email = payment_data.email.clone().or_else(|| { customer .email .clone() .map(|encrypted_value| encrypted_value.into()) }); Some(customer) } None => None, }, )) } #[cfg(feature = "v1")] pub async fn retrieve_payment_method_with_temporary_token( state: &SessionState, token: &str, payment_intent: &PaymentIntent, payment_attempt: &PaymentAttempt, merchant_key_store: &domain::MerchantKeyStore, card_token_data: Option<&domain::CardToken>, ) -> RouterResult<Option<(domain::PaymentMethodData, enums::PaymentMethod)>> { let (pm, supplementary_data) = vault::Vault::get_payment_method_data_from_locker(state, token, merchant_key_store) .await .attach_printable( "Payment method for given token not found or there was a problem fetching it", )?; utils::when( supplementary_data .customer_id .ne(&payment_intent.customer_id), || { Err(errors::ApiErrorResponse::PreconditionFailed { message: "customer associated with payment method and customer passed in payment are not same".into() }) }, )?; Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(match pm { Some(domain::PaymentMethodData::Card(card)) => { let mut updated_card = card.clone(); let mut is_card_updated = false; // 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 = card_token_data.and_then(|token_data| token_data.card_holder_name.clone()); if let Some(name) = name_on_card.clone() { if !name.peek().is_empty() { is_card_updated = true; updated_card.nick_name = name_on_card; } } if let Some(token_data) = card_token_data { if let Some(cvc) = token_data.card_cvc.clone() { is_card_updated = true; updated_card.card_cvc = cvc; } } // populate additional card details from payment_attempt.payment_method_data (additional_payment_data) if not present in the locker if updated_card.card_issuer.is_none() || updated_card.card_network.is_none() || updated_card.card_type.is_none() || updated_card.card_issuing_country.is_none() { let additional_payment_method_data: Option< api_models::payments::AdditionalPaymentData, > = payment_attempt .payment_method_data .clone() .and_then(|data| match data { serde_json::Value::Null => None, // This is to handle the case when the payment_method_data is null _ => Some(data.parse_value("AdditionalPaymentData")), }) .transpose() .map_err(|err| logger::error!("Failed to parse AdditionalPaymentData {err:?}")) .ok() .flatten(); if let Some(api_models::payments::AdditionalPaymentData::Card(card)) = additional_payment_method_data { is_card_updated = true; updated_card.card_issuer = updated_card.card_issuer.or(card.card_issuer); updated_card.card_network = updated_card.card_network.or(card.card_network); updated_card.card_type = updated_card.card_type.or(card.card_type); updated_card.card_issuing_country = updated_card .card_issuing_country .or(card.card_issuing_country); }; }; if is_card_updated { let updated_pm = domain::PaymentMethodData::Card(updated_card); vault::Vault::store_payment_method_data_in_locker( state, Some(token.to_owned()), &updated_pm, payment_intent.customer_id.to_owned(), enums::PaymentMethod::Card, merchant_key_store, ) .await?; Some((updated_pm, enums::PaymentMethod::Card)) } else { Some(( domain::PaymentMethodData::Card(card), enums::PaymentMethod::Card, )) } } Some(the_pm @ domain::PaymentMethodData::Wallet(_)) => { Some((the_pm, enums::PaymentMethod::Wallet)) } Some(the_pm @ domain::PaymentMethodData::BankTransfer(_)) => { Some((the_pm, enums::PaymentMethod::BankTransfer)) } Some(the_pm @ domain::PaymentMethodData::BankRedirect(_)) => { Some((the_pm, enums::PaymentMethod::BankRedirect)) } Some(the_pm @ domain::PaymentMethodData::BankDebit(_)) => { Some((the_pm, enums::PaymentMethod::BankDebit)) } Some(_) => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Payment method received from locker is unsupported by locker")?, None => None, }) } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub async fn retrieve_card_with_permanent_token( state: &SessionState, locker_id: &str, _payment_method_id: &id_type::GlobalPaymentMethodId, payment_intent: &PaymentIntent, card_token_data: Option<&domain::CardToken>, _merchant_key_store: &domain::MerchantKeyStore, _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<domain::PaymentMethodData> { todo!() } pub enum VaultFetchAction { FetchCardDetailsFromLocker, FetchCardDetailsForNetworkTransactionIdFlowFromLocker, FetchNetworkTokenDataFromTokenizationService(String), FetchNetworkTokenDetailsFromLocker(api_models::payments::NetworkTokenWithNTIRef), NoFetchAction, } pub fn decide_payment_method_retrieval_action( is_network_tokenization_enabled: bool, mandate_id: Option<api_models::payments::MandateIds>, connector: Option<api_enums::Connector>, network_tokenization_supported_connectors: &HashSet<api_enums::Connector>, should_retry_with_pan: bool, network_token_requestor_ref_id: Option<String>, ) -> VaultFetchAction { let standard_flow = || { determine_standard_vault_action( is_network_tokenization_enabled, mandate_id, connector, network_tokenization_supported_connectors, network_token_requestor_ref_id, ) }; should_retry_with_pan .then_some(VaultFetchAction::FetchCardDetailsFromLocker) .unwrap_or_else(standard_flow) } pub fn determine_standard_vault_action( is_network_tokenization_enabled: bool, mandate_id: Option<api_models::payments::MandateIds>, connector: Option<api_enums::Connector>, network_tokenization_supported_connectors: &HashSet<api_enums::Connector>, network_token_requestor_ref_id: Option<String>, ) -> VaultFetchAction { let is_network_transaction_id_flow = mandate_id .as_ref() .map(|mandate_ids| mandate_ids.is_network_transaction_id_flow()) .unwrap_or(false); if !is_network_tokenization_enabled { if is_network_transaction_id_flow { VaultFetchAction::FetchCardDetailsForNetworkTransactionIdFlowFromLocker } else { VaultFetchAction::FetchCardDetailsFromLocker } } else { match mandate_id { Some(mandate_ids) => match mandate_ids.mandate_reference_id { Some(api_models::payments::MandateReferenceId::NetworkTokenWithNTI(nt_data)) => { VaultFetchAction::FetchNetworkTokenDetailsFromLocker(nt_data) } Some(api_models::payments::MandateReferenceId::NetworkMandateId(_)) => { VaultFetchAction::FetchCardDetailsForNetworkTransactionIdFlowFromLocker } Some(api_models::payments::MandateReferenceId::ConnectorMandateId(_)) | None => { VaultFetchAction::NoFetchAction } }, None => { //saved card flow let is_network_token_supported_connector = connector .map(|conn| network_tokenization_supported_connectors.contains(&conn)) .unwrap_or(false); match ( is_network_token_supported_connector, network_token_requestor_ref_id, ) { (true, Some(ref_id)) => { VaultFetchAction::FetchNetworkTokenDataFromTokenizationService(ref_id) } (false, Some(_)) | (true, None) | (false, None) => { VaultFetchAction::FetchCardDetailsFromLocker } } } } } } #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") ))] #[allow(clippy::too_many_arguments)] 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"), } } #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") ))] #[allow(clippy::too_many_arguments)] pub async fn retrieve_card_with_permanent_token_for_external_authentication( state: &SessionState, locker_id: &str, payment_intent: &PaymentIntent, card_token_data: Option<&domain::CardToken>, _merchant_key_store: &domain::MerchantKeyStore, _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<domain::PaymentMethodData> { let customer_id = payment_intent .customer_id .as_ref() .get_required_value("customer_id") .change_context(errors::ApiErrorResponse::UnprocessableEntity { 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")?, )) } #[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 // 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()) } #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") ))] pub async fn fetch_network_token_details_from_locker( state: &SessionState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, network_token_locker_id: &str, network_transaction_data: api_models::payments::NetworkTokenWithNTIRef, ) -> RouterResult<domain::NetworkTokenData> { let mut token_data = cards::get_card_from_locker(state, customer_id, merchant_id, network_token_locker_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "failed to fetch network token information from the permanent locker", )?; 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) } #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") ))] pub async fn fetch_card_details_for_network_transaction_flow_from_locker( state: &SessionState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, locker_id: &str, ) -> RouterResult<domain::PaymentMethodData> { let card_details_from_locker = cards::get_card_from_locker(state, customer_id, merchant_id, locker_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to fetch card details from locker")?; let card_network = card_details_from_locker .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, ), ) } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub async fn retrieve_payment_method_from_db_with_token_data( state: &SessionState, merchant_key_store: &domain::MerchantKeyStore, token_data: &storage::PaymentTokenData, storage_scheme: storage::enums::MerchantStorageScheme, ) -> RouterResult<Option<domain::PaymentMethod>> { todo!() } #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") ))] pub async fn retrieve_payment_method_from_db_with_token_data( state: &SessionState, merchant_key_store: &domain::MerchantKeyStore, token_data: &storage::PaymentTokenData, storage_scheme: storage::enums::MerchantStorageScheme, ) -> RouterResult<Option<domain::PaymentMethod>> { match token_data { storage::PaymentTokenData::PermanentCard(data) => { if let Some(ref payment_method_id) = data.payment_method_id { state .store .find_payment_method( &(state.into()), merchant_key_store, payment_method_id, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound) .attach_printable("error retrieving payment method from DB") .map(Some) } else { Ok(None) } } storage::PaymentTokenData::WalletToken(data) => state .store .find_payment_method( &(state.into()), merchant_key_store, &data.payment_method_id, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound) .attach_printable("error retrieveing payment method from DB") .map(Some), storage::PaymentTokenData::Temporary(_) | storage::PaymentTokenData::TemporaryGeneric(_) | storage::PaymentTokenData::Permanent(_) | storage::PaymentTokenData::AuthBankDebit(_) => Ok(None), } } pub async fn retrieve_payment_token_data( state: &SessionState, token: String, payment_method: Option<storage_enums::PaymentMethod>, ) -> RouterResult<storage::PaymentTokenData> { let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let key = format!( "pm_token_{}_{}_hyperswitch", token, payment_method.get_required_value("payment_method")? ); let token_data_string = redis_conn .get_key::<Option<String>>(&key.into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to fetch the token from redis")? .ok_or(error_stack::Report::new( errors::ApiErrorResponse::UnprocessableEntity { message: "Token is invalid or expired".to_owned(), }, ))?; let token_data_result = token_data_string .clone() .parse_struct("PaymentTokenData") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to deserialize hyperswitch token data"); let token_data = match token_data_result { Ok(data) => data, Err(e) => { // The purpose of this logic is backwards compatibility to support tokens // in redis that might be following the old format. if token_data_string.starts_with('{') { return Err(e); } else { storage::PaymentTokenData::temporary_generic(token_data_string) } } }; Ok(token_data) } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub async fn make_pm_data<'a, F: Clone, R, D>( _operation: BoxedOperation<'a, F, R, D>, _state: &'a SessionState, _payment_data: &mut PaymentData<F>, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _storage_scheme: common_enums::enums::MerchantStorageScheme, _business_profile: Option<&domain::Profile>, ) -> RouterResult<( BoxedOperation<'a, F, R, D>, Option<domain::PaymentMethodData>, Option<String>, )> { todo!() } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[allow(clippy::too_many_arguments)] pub async fn make_pm_data<'a, F: Clone, R, D>( operation: BoxedOperation<'a, F, R, D>, state: &'a SessionState, payment_data: &mut PaymentData<F>, merchant_key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, storage_scheme: common_enums::enums::MerchantStorageScheme, business_profile: &domain::Profile, should_retry_with_pan: bool, ) -> RouterResult<( BoxedOperation<'a, F, R, D>, Option<domain::PaymentMethodData>, Option<String>, )> { use super::OperationSessionSetters; use crate::core::payments::OperationSessionGetters; let request = payment_data.payment_method_data.clone(); let mut card_token_data = payment_data .payment_method_data .clone() .and_then(|pmd| match pmd { domain::PaymentMethodData::CardToken(token_data) => Some(token_data), _ => None, }) .or(Some(domain::CardToken::default())); if let Some(cvc) = payment_data.card_cvc.clone() { if let Some(token_data) = card_token_data.as_mut() { token_data.card_cvc = Some(cvc); } } if payment_data.token_data.is_none() { if let Some(payment_method_info) = &payment_data.payment_method_info { if payment_method_info.get_payment_method_type() == Some(storage_enums::PaymentMethod::Card) { payment_data.token_data = Some(storage::PaymentTokenData::PermanentCard(CardTokenData { payment_method_id: Some(payment_method_info.get_id().clone()), locker_id: payment_method_info .locker_id .clone() .or(Some(payment_method_info.get_id().clone())), token: payment_method_info .locker_id .clone() .unwrap_or(payment_method_info.get_id().clone()), network_token_locker_id: payment_method_info .network_token_requestor_reference_id .clone() .or(Some(payment_method_info.get_id().clone())), })); } } } let mandate_id = payment_data.mandate_id.clone(); // TODO: Handle case where payment method and token both are present in request properly. let (payment_method, pm_id) = match (&request, payment_data.token_data.as_ref()) { (_, Some(hyperswitch_token)) => { let existing_vault_data = payment_data.get_vault_operation(); let vault_data = existing_vault_data.map(|data| match data { domain_payments::VaultOperation::ExistingVaultData(vault_data) => vault_data, }); let pm_data = Box::pin(payment_methods::retrieve_payment_method_with_token( state, merchant_key_store, hyperswitch_token, &payment_data.payment_intent, &payment_data.payment_attempt, card_token_data.as_ref(), customer, storage_scheme, mandate_id, payment_data.payment_method_info.clone(), business_profile, should_retry_with_pan, vault_data, )) .await; let payment_method_details = pm_data.attach_printable("in 'make_pm_data'")?; if let Some(ref payment_method_data) = payment_method_details.payment_method_data { let updated_vault_operation = domain_payments::VaultOperation::get_updated_vault_data( existing_vault_data, payment_method_data, ); if let Some(vault_operation) = updated_vault_operation { payment_data.set_vault_operation(vault_operation); } }; Ok::<_, error_stack::Report<errors::ApiErrorResponse>>( if let Some(payment_method_data) = payment_method_details.payment_method_data { payment_data.payment_attempt.payment_method = payment_method_details.payment_method; ( Some(payment_method_data), payment_method_details.payment_method_id, ) } else { (None, payment_method_details.payment_method_id) }, ) } (Some(_), _) => { let (payment_method_data, payment_token) = payment_methods::retrieve_payment_method_core( &request, state, &payment_data.payment_intent, &payment_data.payment_attempt, merchant_key_store, Some(business_profile), ) .await?; payment_data.token = payment_token; Ok((payment_method_data, None)) } _ => Ok((None, None)), }?; Ok((operation, payment_method, pm_id)) } #[cfg(feature = "v1")] pub async fn store_in_vault_and_generate_ppmt( state: &SessionState, payment_method_data: &domain::PaymentMethodData, payment_intent: &PaymentIntent, payment_attempt: &PaymentAttempt, payment_method: enums::PaymentMethod, merchant_key_store: &domain::MerchantKeyStore, business_profile: Option<&domain::Profile>, ) -> RouterResult<String> { let router_token = vault::Vault::store_payment_method_data_in_locker( state, None, payment_method_data, payment_intent.customer_id.to_owned(), payment_method, merchant_key_store, ) .await?; let parent_payment_method_token = generate_id(consts::ID_LENGTH, "token"); let key_for_hyperswitch_token = payment_attempt.get_payment_method().map(|payment_method| { payment_methods_handler::ParentPaymentMethodToken::create_key_for_token(( &parent_payment_method_token, payment_method, )) }); let intent_fulfillment_time = business_profile .and_then(|b_profile| b_profile.get_order_fulfillment_time()) .unwrap_or(consts::DEFAULT_FULFILLMENT_TIME); if let Some(key_for_hyperswitch_token) = key_for_hyperswitch_token { key_for_hyperswitch_token .insert( intent_fulfillment_time, storage::PaymentTokenData::temporary_generic(router_token), state, ) .await?; }; Ok(parent_payment_method_token) } #[cfg(feature = "v2")] pub async fn store_payment_method_data_in_vault( state: &SessionState, payment_attempt: &PaymentAttempt, payment_intent: &PaymentIntent, payment_method: enums::PaymentMethod, payment_method_data: &domain::PaymentMethodData, merchant_key_store: &domain::MerchantKeyStore, business_profile: Option<&domain::Profile>, ) -> RouterResult<Option<String>> { todo!() } #[cfg(feature = "v1")] pub async fn store_payment_method_data_in_vault( state: &SessionState, payment_attempt: &PaymentAttempt, payment_intent: &PaymentIntent, payment_method: enums::PaymentMethod, payment_method_data: &domain::PaymentMethodData, merchant_key_store: &domain::MerchantKeyStore, business_profile: Option<&domain::Profile>, ) -> RouterResult<Option<String>> { if should_store_payment_method_data_in_vault( &state.conf.temp_locker_enable_config, payment_attempt.connector.clone(), payment_method, ) || payment_intent.request_external_three_ds_authentication == Some(true) { let parent_payment_method_token = store_in_vault_and_generate_ppmt( state, payment_method_data, payment_intent, payment_attempt, payment_method, merchant_key_store, business_profile, ) .await?; return Ok(Some(parent_payment_method_token)); } Ok(None) } pub fn should_store_payment_method_data_in_vault( temp_locker_enable_config: &TempLockerEnableConfig, option_connector: Option<String>, payment_method: enums::PaymentMethod, ) -> bool { option_connector .map(|connector| { temp_locker_enable_config .0 .get(&connector) .map(|config| config.payment_method.contains(&payment_method)) .unwrap_or(false) }) .unwrap_or(true) } #[instrument(skip_all)] pub(crate) fn validate_capture_method( capture_method: storage_enums::CaptureMethod, ) -> RouterResult<()> { utils::when( capture_method == storage_enums::CaptureMethod::Automatic, || { Err(report!(errors::ApiErrorResponse::PaymentUnexpectedState { field_name: "capture_method".to_string(), current_flow: "captured".to_string(), current_value: capture_method.to_string(), states: "manual, manual_multiple, scheduled".to_string() })) }, ) } #[instrument(skip_all)] pub(crate) fn validate_status_with_capture_method( status: storage_enums::IntentStatus, capture_method: storage_enums::CaptureMethod, ) -> RouterResult<()> { if status == storage_enums::IntentStatus::Processing && !(capture_method == storage_enums::CaptureMethod::ManualMultiple) { return Err(report!(errors::ApiErrorResponse::PaymentUnexpectedState { field_name: "capture_method".to_string(), current_flow: "captured".to_string(), current_value: capture_method.to_string(), states: "manual_multiple".to_string() })); } utils::when( status != storage_enums::IntentStatus::RequiresCapture && status != storage_enums::IntentStatus::PartiallyCapturedAndCapturable && status != storage_enums::IntentStatus::Processing, || { Err(report!(errors::ApiErrorResponse::PaymentUnexpectedState { field_name: "payment.status".to_string(), current_flow: "captured".to_string(), current_value: status.to_string(), states: "requires_capture, partially_captured_and_capturable, processing" .to_string() })) }, ) } #[instrument(skip_all)] pub(crate) fn validate_amount_to_capture( amount: i64, amount_to_capture: Option<i64>, ) -> RouterResult<()> { utils::when( amount_to_capture.is_some() && (Some(amount) < amount_to_capture), || { Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: "amount_to_capture is greater than amount".to_string() })) }, ) } #[cfg(feature = "v1")] #[instrument(skip_all)] pub(crate) fn validate_payment_method_fields_present( req: &api_models::payments::PaymentsRequest, ) -> RouterResult<()> { let payment_method_data = req.payment_method_data .as_ref() .and_then(|request_payment_method_data| { request_payment_method_data.payment_method_data.as_ref() }); utils::when( req.payment_method.is_none() && payment_method_data.is_some(), || { Err(errors::ApiErrorResponse::MissingRequiredField { field_name: "payment_method", }) }, )?; utils::when( !matches!( req.payment_method, Some(api_enums::PaymentMethod::Card) | None ) && (req.payment_method_type.is_none()), || { Err(errors::ApiErrorResponse::MissingRequiredField { field_name: "payment_method_type", }) }, )?; utils::when( req.payment_method.is_some() && payment_method_data.is_none() && req.payment_token.is_none() && req.recurring_details.is_none() && req.ctp_service_details.is_none(), || { Err(errors::ApiErrorResponse::MissingRequiredField { field_name: "payment_method_data", }) }, )?; utils::when( req.payment_method.is_some() && req.payment_method_type.is_some(), || { req.payment_method .map_or(Ok(()), |req_payment_method| { req.payment_method_type.map_or(Ok(()), |req_payment_method_type| { if !validate_payment_method_type_against_payment_method(req_payment_method, req_payment_method_type) { Err(errors::ApiErrorResponse::InvalidRequestData { message: ("payment_method_type doesn't correspond to the specified payment_method" .to_string()), }) } else { Ok(()) } }) }) }, )?; let validate_payment_method_and_payment_method_data = |req_payment_method_data, req_payment_method: api_enums::PaymentMethod| { api_enums::PaymentMethod::foreign_try_from(req_payment_method_data).and_then(|payment_method| if req_payment_method != payment_method { Err(errors::ApiErrorResponse::InvalidRequestData { message: ("payment_method_data doesn't correspond to the specified payment_method" .to_string()), }) } else { Ok(()) }) }; utils::when( req.payment_method.is_some() && payment_method_data.is_some(), || { payment_method_data .cloned() .map_or(Ok(()), |payment_method_data| { req.payment_method.map_or(Ok(()), |req_payment_method| { validate_payment_method_and_payment_method_data( payment_method_data, req_payment_method, ) }) }) }, )?; Ok(()) } pub fn validate_payment_method_type_against_payment_method( payment_method: api_enums::PaymentMethod, payment_method_type: api_enums::PaymentMethodType, ) -> bool { match payment_method { api_enums::PaymentMethod::Card => matches!( payment_method_type, api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit ), api_enums::PaymentMethod::PayLater => matches!( payment_method_type, api_enums::PaymentMethodType::Affirm | api_enums::PaymentMethodType::Alma | api_enums::PaymentMethodType::AfterpayClearpay | api_enums::PaymentMethodType::Klarna | api_enums::PaymentMethodType::PayBright | api_enums::PaymentMethodType::Atome | api_enums::PaymentMethodType::Walley ), api_enums::PaymentMethod::Wallet => matches!( payment_method_type, api_enums::PaymentMethodType::AmazonPay | api_enums::PaymentMethodType::ApplePay | api_enums::PaymentMethodType::GooglePay | api_enums::PaymentMethodType::Paypal | api_enums::PaymentMethodType::AliPay | api_enums::PaymentMethodType::AliPayHk | api_enums::PaymentMethodType::Dana | api_enums::PaymentMethodType::MbWay | api_enums::PaymentMethodType::MobilePay | api_enums::PaymentMethodType::SamsungPay | api_enums::PaymentMethodType::Twint | api_enums::PaymentMethodType::Vipps | api_enums::PaymentMethodType::TouchNGo | api_enums::PaymentMethodType::Swish | api_enums::PaymentMethodType::WeChatPay | api_enums::PaymentMethodType::GoPay | api_enums::PaymentMethodType::Gcash | api_enums::PaymentMethodType::Momo | api_enums::PaymentMethodType::KakaoPay | api_enums::PaymentMethodType::Cashapp | api_enums::PaymentMethodType::Mifinity | api_enums::PaymentMethodType::Paze ), api_enums::PaymentMethod::BankRedirect => matches!( payment_method_type, api_enums::PaymentMethodType::Giropay | api_enums::PaymentMethodType::Ideal | api_enums::PaymentMethodType::Sofort | api_enums::PaymentMethodType::Eft | api_enums::PaymentMethodType::Eps | api_enums::PaymentMethodType::BancontactCard | api_enums::PaymentMethodType::Blik | api_enums::PaymentMethodType::LocalBankRedirect | api_enums::PaymentMethodType::OnlineBankingThailand | api_enums::PaymentMethodType::OnlineBankingCzechRepublic | api_enums::PaymentMethodType::OnlineBankingFinland | api_enums::PaymentMethodType::OnlineBankingFpx | api_enums::PaymentMethodType::OnlineBankingPoland | api_enums::PaymentMethodType::OnlineBankingSlovakia | api_enums::PaymentMethodType::Przelewy24 | api_enums::PaymentMethodType::Trustly | api_enums::PaymentMethodType::Bizum | api_enums::PaymentMethodType::Interac | api_enums::PaymentMethodType::OpenBankingUk | api_enums::PaymentMethodType::OpenBankingPIS ), api_enums::PaymentMethod::BankTransfer => matches!( payment_method_type, api_enums::PaymentMethodType::Ach | api_enums::PaymentMethodType::SepaBankTransfer | api_enums::PaymentMethodType::Bacs | api_enums::PaymentMethodType::Multibanco | api_enums::PaymentMethodType::Pix | api_enums::PaymentMethodType::Pse | api_enums::PaymentMethodType::PermataBankTransfer | api_enums::PaymentMethodType::BcaBankTransfer | api_enums::PaymentMethodType::BniVa | api_enums::PaymentMethodType::BriVa | api_enums::PaymentMethodType::CimbVa | api_enums::PaymentMethodType::DanamonVa | api_enums::PaymentMethodType::MandiriVa | api_enums::PaymentMethodType::LocalBankTransfer | api_enums::PaymentMethodType::InstantBankTransfer ), api_enums::PaymentMethod::BankDebit => matches!( payment_method_type, api_enums::PaymentMethodType::Ach | api_enums::PaymentMethodType::Sepa | api_enums::PaymentMethodType::Bacs | api_enums::PaymentMethodType::Becs ), api_enums::PaymentMethod::Crypto => matches!( payment_method_type, api_enums::PaymentMethodType::CryptoCurrency ), api_enums::PaymentMethod::Reward => matches!( payment_method_type, api_enums::PaymentMethodType::Evoucher | api_enums::PaymentMethodType::ClassicReward ), api_enums::PaymentMethod::RealTimePayment => matches!( payment_method_type, api_enums::PaymentMethodType::Fps | api_enums::PaymentMethodType::DuitNow | api_enums::PaymentMethodType::PromptPay | api_enums::PaymentMethodType::VietQr ), api_enums::PaymentMethod::Upi => matches!( payment_method_type, api_enums::PaymentMethodType::UpiCollect | api_enums::PaymentMethodType::UpiIntent ), api_enums::PaymentMethod::Voucher => matches!( payment_method_type, api_enums::PaymentMethodType::Boleto | api_enums::PaymentMethodType::Efecty | api_enums::PaymentMethodType::PagoEfectivo | api_enums::PaymentMethodType::RedCompra | api_enums::PaymentMethodType::RedPagos | api_enums::PaymentMethodType::Indomaret | api_enums::PaymentMethodType::Alfamart | api_enums::PaymentMethodType::Oxxo | api_enums::PaymentMethodType::SevenEleven | api_enums::PaymentMethodType::Lawson | api_enums::PaymentMethodType::MiniStop | api_enums::PaymentMethodType::FamilyMart | api_enums::PaymentMethodType::Seicomart | api_enums::PaymentMethodType::PayEasy ), api_enums::PaymentMethod::GiftCard => { matches!( payment_method_type, api_enums::PaymentMethodType::Givex | api_enums::PaymentMethodType::PaySafeCard ) } api_enums::PaymentMethod::CardRedirect => matches!( payment_method_type, api_enums::PaymentMethodType::Knet | api_enums::PaymentMethodType::Benefit | api_enums::PaymentMethodType::MomoAtm | api_enums::PaymentMethodType::CardRedirect ), api_enums::PaymentMethod::OpenBanking => matches!( payment_method_type, api_enums::PaymentMethodType::OpenBankingPIS ), api_enums::PaymentMethod::MobilePayment => matches!( payment_method_type, api_enums::PaymentMethodType::DirectCarrierBilling ), } } pub fn check_force_psync_precondition(status: storage_enums::AttemptStatus) -> bool { !matches!( status, storage_enums::AttemptStatus::Charged | storage_enums::AttemptStatus::AutoRefunded | storage_enums::AttemptStatus::Voided | storage_enums::AttemptStatus::CodInitiated | storage_enums::AttemptStatus::Started | storage_enums::AttemptStatus::Failure ) } pub fn append_option<T, U, F, V>(func: F, option1: Option<T>, option2: Option<U>) -> Option<V> where F: FnOnce(T, U) -> V, { Some(func(option1?, option2?)) } #[cfg(all(feature = "olap", feature = "v1"))] pub(super) async fn filter_by_constraints( state: &SessionState, constraints: &PaymentIntentFetchConstraints, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Vec<PaymentIntent>, errors::StorageError> { let db = &*state.store; let result = db .filter_payment_intent_by_constraints( &(state).into(), merchant_id, constraints, key_store, storage_scheme, ) .await?; Ok(result) } #[cfg(feature = "olap")] pub(super) fn validate_payment_list_request( req: &api::PaymentListConstraints, ) -> CustomResult<(), errors::ApiErrorResponse> { use common_utils::consts::PAYMENTS_LIST_MAX_LIMIT_V1; utils::when( req.limit > PAYMENTS_LIST_MAX_LIMIT_V1 || req.limit < 1, || { Err(errors::ApiErrorResponse::InvalidRequestData { message: format!( "limit should be in between 1 and {}", PAYMENTS_LIST_MAX_LIMIT_V1 ), }) }, )?; Ok(()) } #[cfg(feature = "olap")] pub(super) fn validate_payment_list_request_for_joins( limit: u32, ) -> CustomResult<(), errors::ApiErrorResponse> { use common_utils::consts::PAYMENTS_LIST_MAX_LIMIT_V2; utils::when(!(1..=PAYMENTS_LIST_MAX_LIMIT_V2).contains(&limit), || { Err(errors::ApiErrorResponse::InvalidRequestData { message: format!( "limit should be in between 1 and {}", PAYMENTS_LIST_MAX_LIMIT_V2 ), }) })?; Ok(()) } #[cfg(feature = "v1")] pub fn get_handle_response_url( payment_id: id_type::PaymentId, business_profile: &domain::Profile, response: &api::PaymentsResponse, connector: String, ) -> RouterResult<api::RedirectionResponse> { let payments_return_url = response.return_url.as_ref(); let redirection_response = make_pg_redirect_response(payment_id, response, connector); let return_url = make_merchant_url_with_response( business_profile, redirection_response, payments_return_url, response.client_secret.as_ref(), response.manual_retry_allowed, ) .attach_printable("Failed to make merchant url with response")?; make_url_with_signature(&return_url, business_profile) } #[cfg(feature = "v1")] pub fn make_merchant_url_with_response( business_profile: &domain::Profile, redirection_response: api::PgRedirectResponse, request_return_url: Option<&String>, client_secret: Option<&masking::Secret<String>>, manual_retry_allowed: Option<bool>, ) -> RouterResult<String> { // take return url if provided in the request else use merchant return url let url = request_return_url .or(business_profile.return_url.as_ref()) .get_required_value("return_url")?; let status_check = redirection_response.status; let payment_client_secret = client_secret .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Expected client secret to be `Some`")?; let payment_id = redirection_response.payment_id.get_string_repr().to_owned(); let merchant_url_with_response = if business_profile.redirect_to_merchant_with_http_post { url::Url::parse_with_params( url, &[ ("status", status_check.to_string()), ("payment_id", payment_id), ( "payment_intent_client_secret", payment_client_secret.peek().to_string(), ), ( "manual_retry_allowed", manual_retry_allowed.unwrap_or(false).to_string(), ), ], ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to parse the url with param")? } else { let amount = redirection_response.amount.get_required_value("amount")?; url::Url::parse_with_params( url, &[ ("status", status_check.to_string()), ("payment_id", payment_id), ( "payment_intent_client_secret", payment_client_secret.peek().to_string(), ), ("amount", amount.to_string()), ( "manual_retry_allowed", manual_retry_allowed.unwrap_or(false).to_string(), ), ], ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to parse the url with param")? }; Ok(merchant_url_with_response.to_string()) } #[cfg(feature = "v1")] pub async fn make_ephemeral_key( state: SessionState, customer_id: id_type::CustomerId, merchant_id: id_type::MerchantId, ) -> errors::RouterResponse<ephemeral_key::EphemeralKey> { let store = &state.store; let id = utils::generate_id(consts::ID_LENGTH, "eki"); let secret = format!("epk_{}", &Uuid::new_v4().simple().to_string()); let ek = ephemeral_key::EphemeralKeyNew { id, customer_id, merchant_id: merchant_id.to_owned(), secret, }; let ek = store .create_ephemeral_key(ek, state.conf.eph_key.validity) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to create ephemeral key")?; Ok(services::ApplicationResponse::Json(ek)) } #[cfg(feature = "v2")] pub async fn make_client_secret( state: SessionState, resource_id: api_models::ephemeral_key::ResourceId, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, headers: &actix_web::http::header::HeaderMap, ) -> errors::RouterResponse<ClientSecretResponse> { let db = &state.store; let key_manager_state = &((&state).into()); match &resource_id { api_models::ephemeral_key::ResourceId::Customer(global_customer_id) => { db.find_customer_by_global_id( key_manager_state, global_customer_id, merchant_account.get_id(), &key_store, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; } } let resource_id = match resource_id { api_models::ephemeral_key::ResourceId::Customer(global_customer_id) => { common_utils::types::authentication::ResourceId::Customer(global_customer_id) } }; let client_secret = create_client_secret(&state, merchant_account.get_id(), resource_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to create client secret")?; let response = ClientSecretResponse::foreign_try_from(client_secret) .attach_printable("Only customer is supported as resource_id in response")?; Ok(services::ApplicationResponse::Json(response)) } #[cfg(feature = "v2")] pub async fn create_client_secret( state: &SessionState, merchant_id: &id_type::MerchantId, resource_id: common_utils::types::authentication::ResourceId, ) -> RouterResult<ephemeral_key::ClientSecretType> { use common_utils::generate_time_ordered_id; let store = &state.store; let id = id_type::ClientSecretId::generate(); let secret = masking::Secret::new(generate_time_ordered_id("cs")); let client_secret = ephemeral_key::ClientSecretTypeNew { id, merchant_id: merchant_id.to_owned(), secret, resource_id, }; let client_secret = store .create_client_secret(client_secret, state.conf.eph_key.validity) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to create client secret")?; Ok(client_secret) } #[cfg(feature = "v1")] pub async fn delete_ephemeral_key( state: SessionState, ek_id: String, ) -> errors::RouterResponse<ephemeral_key::EphemeralKey> { let db = state.store.as_ref(); let ek = db .delete_ephemeral_key(&ek_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to delete ephemeral key")?; Ok(services::ApplicationResponse::Json(ek)) } #[cfg(feature = "v2")] pub async fn delete_client_secret( state: SessionState, ephemeral_key_id: String, ) -> errors::RouterResponse<ClientSecretResponse> { let db = state.store.as_ref(); let ephemeral_key = db .delete_client_secret(&ephemeral_key_id) .await .map_err(|err| match err.current_context() { errors::StorageError::ValueNotFound(_) => { err.change_context(errors::ApiErrorResponse::GenericNotFoundError { message: "Ephemeral Key not found".to_string(), }) } _ => err.change_context(errors::ApiErrorResponse::InternalServerError), }) .attach_printable("Unable to delete ephemeral key")?; let response = ClientSecretResponse::foreign_try_from(ephemeral_key) .attach_printable("Only customer is supported as resource_id in response")?; Ok(services::ApplicationResponse::Json(response)) } #[cfg(feature = "v1")] pub fn make_pg_redirect_response( payment_id: id_type::PaymentId, response: &api::PaymentsResponse, connector: String, ) -> api::PgRedirectResponse { api::PgRedirectResponse { payment_id, status: response.status, gateway_id: connector, customer_id: response.customer_id.to_owned(), amount: Some(response.amount), } } #[cfg(feature = "v1")] pub fn make_url_with_signature( redirect_url: &str, business_profile: &domain::Profile, ) -> RouterResult<api::RedirectionResponse> { let mut url = url::Url::parse(redirect_url) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to parse the url")?; let mut base_url = url.clone(); base_url.query_pairs_mut().clear(); let url = if business_profile.enable_payment_response_hash { let key = business_profile .payment_response_hash_key .as_ref() .get_required_value("payment_response_hash_key")?; let signature = hmac_sha512_sorted_query_params( &mut url.query_pairs().collect::<Vec<_>>(), key.as_str(), )?; url.query_pairs_mut() .append_pair("signature", &signature) .append_pair("signature_algorithm", "HMAC-SHA512"); url.to_owned() } else { url.to_owned() }; let parameters = url .query_pairs() .collect::<Vec<_>>() .iter() .map(|(key, value)| (key.clone().into_owned(), value.clone().into_owned())) .collect::<Vec<_>>(); Ok(api::RedirectionResponse { return_url: base_url.to_string(), params: parameters, return_url_with_query_params: url.to_string(), http_method: if business_profile.redirect_to_merchant_with_http_post { services::Method::Post.to_string() } else { services::Method::Get.to_string() }, headers: Vec::new(), }) } pub fn hmac_sha512_sorted_query_params( params: &mut [(Cow<'_, str>, Cow<'_, str>)], key: &str, ) -> RouterResult<String> { params.sort(); let final_string = params .iter() .map(|(key, value)| format!("{key}={value}")) .collect::<Vec<_>>() .join("&"); let signature = crypto::HmacSha512::sign_message( &crypto::HmacSha512, key.as_bytes(), final_string.as_bytes(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to sign the message")?; Ok(hex::encode(signature)) } pub fn check_if_operation_confirm<Op: std::fmt::Debug>(operations: Op) -> bool { format!("{operations:?}") == "PaymentConfirm" } #[allow(clippy::too_many_arguments)] pub fn generate_mandate( merchant_id: id_type::MerchantId, payment_id: id_type::PaymentId, connector: String, setup_mandate_details: Option<MandateData>, customer_id: &Option<id_type::CustomerId>, payment_method_id: String, connector_mandate_id: Option<pii::SecretSerdeValue>, network_txn_id: Option<String>, payment_method_data_option: Option<domain::payments::PaymentMethodData>, mandate_reference: Option<MandateReference>, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, ) -> CustomResult<Option<storage::MandateNew>, errors::ApiErrorResponse> { match (setup_mandate_details, customer_id) { (Some(data), Some(cus_id)) => { let mandate_id = utils::generate_id(consts::ID_LENGTH, "man"); // The construction of the mandate new must be visible let mut new_mandate = storage::MandateNew::default(); let customer_acceptance = data .customer_acceptance .get_required_value("customer_acceptance")?; new_mandate .set_mandate_id(mandate_id) .set_customer_id(cus_id.clone()) .set_merchant_id(merchant_id) .set_original_payment_id(Some(payment_id)) .set_payment_method_id(payment_method_id) .set_connector(connector) .set_mandate_status(storage_enums::MandateStatus::Active) .set_connector_mandate_ids(connector_mandate_id) .set_network_transaction_id(network_txn_id) .set_customer_ip_address( customer_acceptance .get_ip_address() .map(masking::Secret::new), ) .set_customer_user_agent(customer_acceptance.get_user_agent()) .set_customer_accepted_at(Some(customer_acceptance.get_accepted_at())) .set_metadata(payment_method_data_option.map(|payment_method_data| { pii::SecretSerdeValue::new( serde_json::to_value(payment_method_data).unwrap_or_default(), ) })) .set_connector_mandate_id( mandate_reference.and_then(|reference| reference.connector_mandate_id), ) .set_merchant_connector_id(merchant_connector_id); Ok(Some( match data.mandate_type.get_required_value("mandate_type")? { hyperswitch_domain_models::mandates::MandateDataType::SingleUse(data) => { new_mandate .set_mandate_amount(Some(data.amount.get_amount_as_i64())) .set_mandate_currency(Some(data.currency)) .set_mandate_type(storage_enums::MandateType::SingleUse) .to_owned() } hyperswitch_domain_models::mandates::MandateDataType::MultiUse(op_data) => { match op_data { Some(data) => new_mandate .set_mandate_amount(Some(data.amount.get_amount_as_i64())) .set_mandate_currency(Some(data.currency)) .set_start_date(data.start_date) .set_end_date(data.end_date), // .set_metadata(data.metadata), // we are storing PaymentMethodData in metadata of mandate None => &mut new_mandate, } .set_mandate_type(storage_enums::MandateType::MultiUse) .to_owned() } }, )) } (_, _) => Ok(None), } } #[cfg(feature = "v1")] // A function to manually authenticate the client secret with intent fulfillment time pub fn authenticate_client_secret( request_client_secret: Option<&String>, payment_intent: &PaymentIntent, ) -> Result<(), errors::ApiErrorResponse> { match (request_client_secret, &payment_intent.client_secret) { (Some(req_cs), Some(pi_cs)) => { if req_cs != pi_cs { Err(errors::ApiErrorResponse::ClientSecretInvalid) } else { let current_timestamp = common_utils::date_time::now(); let session_expiry = payment_intent.session_expiry.unwrap_or( payment_intent .created_at .saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)), ); fp_utils::when(current_timestamp > session_expiry, || { Err(errors::ApiErrorResponse::ClientSecretExpired) }) } } // If there is no client in payment intent, then it has expired (Some(_), None) => Err(errors::ApiErrorResponse::ClientSecretExpired), _ => Ok(()), } } #[cfg(feature = "v2")] // A function to manually authenticate the client secret with intent fulfillment time pub fn authenticate_client_secret( request_client_secret: Option<&common_utils::types::ClientSecret>, payment_intent: &PaymentIntent, ) -> Result<(), errors::ApiErrorResponse> { match (request_client_secret, &payment_intent.client_secret) { (Some(req_cs), pi_cs) => { if req_cs != pi_cs { Err(errors::ApiErrorResponse::ClientSecretInvalid) } else { let current_timestamp = common_utils::date_time::now(); let session_expiry = payment_intent.session_expiry; fp_utils::when(current_timestamp > session_expiry, || { Err(errors::ApiErrorResponse::ClientSecretExpired) }) } } _ => Ok(()), } } pub(crate) fn validate_payment_status_against_allowed_statuses( intent_status: storage_enums::IntentStatus, allowed_statuses: &[storage_enums::IntentStatus], action: &'static str, ) -> Result<(), errors::ApiErrorResponse> { fp_utils::when(!allowed_statuses.contains(&intent_status), || { Err(errors::ApiErrorResponse::PreconditionFailed { message: format!( "You cannot {action} this payment because it has status {intent_status}", ), }) }) } pub(crate) fn validate_payment_status_against_not_allowed_statuses( intent_status: storage_enums::IntentStatus, not_allowed_statuses: &[storage_enums::IntentStatus], action: &'static str, ) -> Result<(), errors::ApiErrorResponse> { fp_utils::when(not_allowed_statuses.contains(&intent_status), || { Err(errors::ApiErrorResponse::PreconditionFailed { message: format!( "You cannot {action} this payment because it has status {intent_status}", ), }) }) } #[instrument(skip_all)] pub(crate) fn validate_pm_or_token_given( payment_method: &Option<api_enums::PaymentMethod>, payment_method_data: &Option<api::PaymentMethodData>, payment_method_type: &Option<api_enums::PaymentMethodType>, mandate_type: &Option<api::MandateTransactionType>, token: &Option<String>, ctp_service_details: &Option<api_models::payments::CtpServiceDetails>, ) -> Result<(), errors::ApiErrorResponse> { utils::when( !matches!( payment_method_type, Some(api_enums::PaymentMethodType::Paypal) ) && !matches!( mandate_type, Some(api::MandateTransactionType::RecurringMandateTransaction) ) && token.is_none() && (payment_method_data.is_none() || payment_method.is_none()) && ctp_service_details.is_none(), || { Err(errors::ApiErrorResponse::InvalidRequestData { message: "A payment token or payment method data or ctp service details is required" .to_string(), }) }, ) } #[cfg(feature = "v2")] // A function to perform database lookup and then verify the client secret pub async fn verify_payment_intent_time_and_client_secret( state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, client_secret: Option<String>, ) -> error_stack::Result<Option<PaymentIntent>, errors::ApiErrorResponse> { todo!() } #[cfg(feature = "v1")] // A function to perform database lookup and then verify the client secret pub async fn verify_payment_intent_time_and_client_secret( state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, client_secret: Option<String>, ) -> error_stack::Result<Option<PaymentIntent>, errors::ApiErrorResponse> { let db = &*state.store; client_secret .async_map(|cs| async move { let payment_id = get_payment_id_from_client_secret(&cs)?; let payment_id = id_type::PaymentId::wrap(payment_id).change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "payment_id", }, )?; #[cfg(feature = "v1")] let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &state.into(), &payment_id, merchant_account.get_id(), key_store, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound)?; #[cfg(feature = "v2")] let payment_intent = db .find_payment_intent_by_id( &state.into(), &payment_id, key_store, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound)?; authenticate_client_secret(Some(&cs), &payment_intent)?; Ok(payment_intent) }) .await .transpose() } #[cfg(feature = "v1")] /// Check whether the business details are configured in the merchant account pub fn validate_business_details( business_country: Option<api_enums::CountryAlpha2>, business_label: Option<&String>, merchant_account: &domain::MerchantAccount, ) -> RouterResult<()> { let primary_business_details = merchant_account .primary_business_details .clone() .parse_value::<Vec<api_models::admin::PrimaryBusinessDetails>>("PrimaryBusinessDetails") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to parse primary business details")?; business_country .zip(business_label) .map(|(business_country, business_label)| { primary_business_details .iter() .find(|business_details| { &business_details.business == business_label && business_details.country == business_country }) .ok_or(errors::ApiErrorResponse::PreconditionFailed { message: "business_details are not configured in the merchant account" .to_string(), }) }) .transpose()?; Ok(()) } #[inline] pub(crate) fn get_payment_id_from_client_secret(cs: &str) -> RouterResult<String> { let (payment_id, _) = cs .rsplit_once("_secret_") .ok_or(errors::ApiErrorResponse::ClientSecretInvalid)?; Ok(payment_id.to_string()) } #[cfg(feature = "v1")] #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; #[test] fn test_authenticate_client_secret_session_not_expired() { let payment_intent = PaymentIntent { payment_id: id_type::PaymentId::try_from(Cow::Borrowed("23")).unwrap(), merchant_id: id_type::MerchantId::default(), status: storage_enums::IntentStatus::RequiresCapture, amount: MinorUnit::new(200), currency: None, amount_captured: None, customer_id: None, description: None, return_url: None, metadata: None, connector_id: None, shipping_address_id: None, billing_address_id: None, statement_descriptor_name: None, statement_descriptor_suffix: None, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), last_synced: None, setup_future_usage: None, fingerprint_id: None, off_session: None, client_secret: Some("1".to_string()), active_attempt: hyperswitch_domain_models::RemoteStorageObject::ForeignID( "nopes".to_string(), ), business_country: None, business_label: None, order_details: None, allowed_payment_method_types: None, connector_metadata: None, feature_metadata: None, attempt_count: 1, payment_link_id: None, profile_id: Some(common_utils::generate_profile_id_of_default_length()), merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, updated_by: storage_enums::MerchantStorageScheme::PostgresOnly.to_string(), request_incremental_authorization: Some( common_enums::RequestIncrementalAuthorization::default(), ), incremental_authorization_allowed: None, authorization_count: None, session_expiry: Some( common_utils::date_time::now() .saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)), ), request_external_three_ds_authentication: None, split_payments: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, organization_id: id_type::OrganizationId::default(), shipping_cost: None, tax_details: None, skip_external_tax_calculation: None, request_extended_authorization: None, psd2_sca_exemption_type: None, platform_merchant_id: None, force_3ds_challenge: None, force_3ds_challenge_trigger: None, }; let req_cs = Some("1".to_string()); assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_ok()); // Check if the result is an Ok variant } #[test] fn test_authenticate_client_secret_session_expired() { let created_at = common_utils::date_time::now().saturating_sub(time::Duration::seconds(20 * 60)); let payment_intent = PaymentIntent { payment_id: id_type::PaymentId::try_from(Cow::Borrowed("23")).unwrap(), merchant_id: id_type::MerchantId::default(), status: storage_enums::IntentStatus::RequiresCapture, amount: MinorUnit::new(200), currency: None, amount_captured: None, customer_id: None, description: None, return_url: None, metadata: None, connector_id: None, shipping_address_id: None, billing_address_id: None, statement_descriptor_name: None, statement_descriptor_suffix: None, created_at, modified_at: common_utils::date_time::now(), fingerprint_id: None, last_synced: None, setup_future_usage: None, off_session: None, client_secret: Some("1".to_string()), active_attempt: hyperswitch_domain_models::RemoteStorageObject::ForeignID( "nopes".to_string(), ), business_country: None, business_label: None, order_details: None, allowed_payment_method_types: None, connector_metadata: None, feature_metadata: None, attempt_count: 1, payment_link_id: None, profile_id: Some(common_utils::generate_profile_id_of_default_length()), merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, updated_by: storage_enums::MerchantStorageScheme::PostgresOnly.to_string(), request_incremental_authorization: Some( common_enums::RequestIncrementalAuthorization::default(), ), incremental_authorization_allowed: None, authorization_count: None, session_expiry: Some( created_at.saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)), ), request_external_three_ds_authentication: None, split_payments: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, organization_id: id_type::OrganizationId::default(), shipping_cost: None, tax_details: None, skip_external_tax_calculation: None, request_extended_authorization: None, psd2_sca_exemption_type: None, platform_merchant_id: None, force_3ds_challenge: None, force_3ds_challenge_trigger: None, }; let req_cs = Some("1".to_string()); assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent,).is_err()) } #[test] fn test_authenticate_client_secret_expired() { let payment_intent = PaymentIntent { payment_id: id_type::PaymentId::try_from(Cow::Borrowed("23")).unwrap(), merchant_id: id_type::MerchantId::default(), status: storage_enums::IntentStatus::RequiresCapture, amount: MinorUnit::new(200), currency: None, amount_captured: None, customer_id: None, description: None, return_url: None, metadata: None, connector_id: None, shipping_address_id: None, billing_address_id: None, statement_descriptor_name: None, statement_descriptor_suffix: None, created_at: common_utils::date_time::now().saturating_sub(time::Duration::seconds(20)), modified_at: common_utils::date_time::now(), last_synced: None, setup_future_usage: None, off_session: None, client_secret: None, fingerprint_id: None, active_attempt: hyperswitch_domain_models::RemoteStorageObject::ForeignID( "nopes".to_string(), ), business_country: None, business_label: None, order_details: None, allowed_payment_method_types: None, connector_metadata: None, feature_metadata: None, attempt_count: 1, payment_link_id: None, profile_id: Some(common_utils::generate_profile_id_of_default_length()), merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, updated_by: storage_enums::MerchantStorageScheme::PostgresOnly.to_string(), request_incremental_authorization: Some( common_enums::RequestIncrementalAuthorization::default(), ), incremental_authorization_allowed: None, authorization_count: None, session_expiry: Some( common_utils::date_time::now() .saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)), ), request_external_three_ds_authentication: None, split_payments: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, organization_id: id_type::OrganizationId::default(), shipping_cost: None, tax_details: None, skip_external_tax_calculation: None, request_extended_authorization: None, psd2_sca_exemption_type: None, platform_merchant_id: None, force_3ds_challenge: None, force_3ds_challenge_trigger: None, }; let req_cs = Some("1".to_string()); assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_err()) } } // This function will be removed after moving this functionality to server_wrap and using cache instead of config #[instrument(skip_all)] pub async fn insert_merchant_connector_creds_to_config( db: &dyn StorageInterface, merchant_id: &id_type::MerchantId, merchant_connector_details: admin::MerchantConnectorDetailsWrap, ) -> RouterResult<()> { if let Some(encoded_data) = merchant_connector_details.encoded_data { let redis = &db .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let key = merchant_id.get_creds_identifier_key(&merchant_connector_details.creds_identifier); redis .serialize_and_set_key_with_expiry( &key.as_str().into(), &encoded_data.peek(), consts::CONNECTOR_CREDS_TOKEN_TTL, ) .await .map_or_else( |e| { Err(e .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to insert connector_creds to config")) }, |_| Ok(()), ) } else { Ok(()) } } #[derive(Clone)] pub enum MerchantConnectorAccountType { DbVal(Box<domain::MerchantConnectorAccount>), CacheVal(api_models::admin::MerchantConnectorDetails), } impl MerchantConnectorAccountType { pub fn get_metadata(&self) -> Option<masking::Secret<serde_json::Value>> { match self { Self::DbVal(val) => val.metadata.to_owned(), Self::CacheVal(val) => val.metadata.to_owned(), } } pub fn get_connector_account_details(&self) -> serde_json::Value { match self { Self::DbVal(val) => val.connector_account_details.peek().to_owned(), Self::CacheVal(val) => val.connector_account_details.peek().to_owned(), } } pub fn get_connector_wallets_details(&self) -> Option<masking::Secret<serde_json::Value>> { match self { Self::DbVal(val) => val.connector_wallets_details.as_deref().cloned(), Self::CacheVal(_) => None, } } pub fn is_disabled(&self) -> bool { match self { Self::DbVal(ref inner) => inner.disabled.unwrap_or(false), // Cached merchant connector account, only contains the account details, // the merchant connector account must only be cached if it's not disabled Self::CacheVal(_) => false, } } #[cfg(feature = "v1")] pub fn is_test_mode_on(&self) -> Option<bool> { match self { Self::DbVal(val) => val.test_mode, Self::CacheVal(_) => None, } } #[cfg(feature = "v2")] pub fn is_test_mode_on(&self) -> Option<bool> { None } pub fn get_mca_id(&self) -> Option<id_type::MerchantConnectorAccountId> { match self { Self::DbVal(db_val) => Some(db_val.get_id()), Self::CacheVal(_) => None, } } pub fn get_connector_name(&self) -> Option<String> { match self { Self::DbVal(db_val) => Some(db_val.connector_name.to_string()), Self::CacheVal(_) => None, } } pub fn get_additional_merchant_data( &self, ) -> Option<Encryptable<masking::Secret<serde_json::Value>>> { match self { Self::DbVal(db_val) => db_val.additional_merchant_data.clone(), Self::CacheVal(_) => None, } } } /// Query for merchant connector account either by business label or profile id /// If profile_id is passed use it, or use connector_label to query merchant connector account #[instrument(skip_all)] pub async fn get_merchant_connector_account( state: &SessionState, merchant_id: &id_type::MerchantId, creds_identifier: Option<&str>, key_store: &domain::MerchantKeyStore, profile_id: &id_type::ProfileId, connector_name: &str, merchant_connector_id: Option<&id_type::MerchantConnectorAccountId>, ) -> RouterResult<MerchantConnectorAccountType> { let db = &*state.store; let key_manager_state: &KeyManagerState = &state.into(); match creds_identifier { Some(creds_identifier) => { let key = merchant_id.get_creds_identifier_key(creds_identifier); let cloned_key = key.clone(); let redis_fetch = || async { db.get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection") .async_and_then(|redis| async move { redis .get_and_deserialize_key(&key.as_str().into(), "String") .await .change_context( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: key.clone(), }, ) .attach_printable(key.clone() + ": Not found in Redis") }) .await }; let db_fetch = || async { db.find_config_by_key(cloned_key.as_str()) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: cloned_key.to_owned(), }, ) }; let mca_config: String = redis_fetch() .await .map_or_else( |_| { Either::Left(async { match db_fetch().await { Ok(config_entry) => Ok(config_entry.config), Err(e) => Err(e), } }) }, |result| Either::Right(async { Ok(result) }), ) .await?; let private_key = state .conf .jwekey .get_inner() .tunnel_private_key .peek() .as_bytes(); let decrypted_mca = services::decrypt_jwe(mca_config.as_str(), services::KeyIdCheck::SkipKeyIdCheck, private_key, jwe::RSA_OAEP_256) .await .change_context(errors::ApiErrorResponse::UnprocessableEntity{ message: "decoding merchant_connector_details failed due to invalid data format!".into()}) .attach_printable( "Failed to decrypt merchant_connector_details sent in request and then put in cache", )?; let res = String::into_bytes(decrypted_mca) .parse_struct("MerchantConnectorDetails") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to parse merchant_connector_details sent in request and then put in cache", )?; Ok(MerchantConnectorAccountType::CacheVal(res)) } None => { let mca: RouterResult<domain::MerchantConnectorAccount> = if let Some(merchant_connector_id) = merchant_connector_id { #[cfg(feature = "v1")] { db.find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_id, merchant_connector_id, key_store, ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), }, ) } #[cfg(feature = "v2")] { db.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_string(), }, ) } } else { #[cfg(feature = "v1")] { db.find_merchant_connector_account_by_profile_id_connector_name( key_manager_state, profile_id, connector_name, key_store, ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: format!( "profile id {} and connector name {connector_name}", profile_id.get_string_repr() ), }, ) } #[cfg(feature = "v2")] { todo!() } }; mca.map(Box::new).map(MerchantConnectorAccountType::DbVal) } } } /// This function replaces the request and response type of routerdata with the /// request and response type passed /// # Arguments /// /// * `router_data` - original router data /// * `request` - new request core/helper /// * `response` - new response pub fn router_data_type_conversion<F1, F2, Req1, Req2, Res1, Res2>( router_data: RouterData<F1, Req1, Res1>, request: Req2, response: Result<Res2, ErrorResponse>, ) -> RouterData<F2, Req2, Res2> { RouterData { flow: std::marker::PhantomData, request, response, merchant_id: router_data.merchant_id, tenant_id: router_data.tenant_id, address: router_data.address, amount_captured: router_data.amount_captured, 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, } } #[cfg(feature = "v1")] #[instrument(skip_all)] 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), } } #[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, 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, } } // #[cfg(feature = "v2")] // // 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, // ) -> PaymentAttempt { // todo!() // } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn modify_payment_intent_and_payment_attempt( &self, request: &api_models::payments::PaymentsRequest, fetched_payment_intent: PaymentIntent, fetched_payment_attempt: PaymentAttempt, state: &SessionState, key_store: &domain::MerchantKeyStore, storage_scheme: storage::enums::MerchantStorageScheme, ) -> RouterResult<(PaymentIntent, PaymentAttempt)> { match self { Self::SameOld => Ok((fetched_payment_intent, fetched_payment_attempt)), Self::New => { let db = &*state.store; 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)) } } } } #[inline(always)] pub fn is_manual_retry_allowed( intent_status: &storage_enums::IntentStatus, attempt_status: &storage_enums::AttemptStatus, connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig, merchant_id: &id_type::MerchantId, ) -> Option<bool> { let is_payment_status_eligible_for_retry = match intent_status { enums::IntentStatus::Failed => match attempt_status { enums::AttemptStatus::Started | enums::AttemptStatus::AuthenticationPending | enums::AttemptStatus::AuthenticationSuccessful | enums::AttemptStatus::Authorized | enums::AttemptStatus::Charged | 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) } #[cfg(test)] mod test { #![allow(clippy::unwrap_used)] #[test] fn test_client_secret_parse() { let client_secret1 = "pay_3TgelAms4RQec8xSStjF_secret_fc34taHLw1ekPgNh92qr"; let client_secret2 = "pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret_fc34taHLw1ekPgNh92qr"; let client_secret3 = "pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret__secret_fc34taHLw1ekPgNh92qr"; assert_eq!( "pay_3TgelAms4RQec8xSStjF", super::get_payment_id_from_client_secret(client_secret1).unwrap() ); assert_eq!( "pay_3Tgel__Ams4RQ_secret_ec8xSStjF", super::get_payment_id_from_client_secret(client_secret2).unwrap() ); assert_eq!( "pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret_", super::get_payment_id_from_client_secret(client_secret3).unwrap() ); } } #[instrument(skip_all)] pub async fn get_additional_payment_data( pm_data: &domain::PaymentMethodData, db: &dyn StorageInterface, profile_id: &id_type::ProfileId, ) -> Result< Option<api_models::payments::AdditionalPaymentData>, error_stack::Report<errors::ApiErrorResponse>, > { match pm_data { domain::PaymentMethodData::Card(card_data) => { //todo! let card_isin = Some(card_data.card_number.get_card_isin()); let enable_extended_bin =db .find_config_by_key_unwrap_or( format!("{}_enable_extended_card_bin", profile_id.get_string_repr()).as_str(), Some("false".to_string())) .await.map_err(|err| services::logger::error!(message="Failed to fetch the config", extended_card_bin_error=?err)).ok(); let card_extended_bin = match enable_extended_bin { Some(config) if config.config == "true" => { Some(card_data.card_number.get_extended_card_bin()) } _ => None, }; let card_network = match card_data .card_number .is_cobadged_card() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Card cobadge check failed due to an invalid card network regex", )? { true => card_data.card_network.clone(), false => None, }; let last4 = Some(card_data.card_number.get_last4()); if card_data.card_issuer.is_some() && card_network.is_some() && card_data.card_type.is_some() && card_data.card_issuing_country.is_some() && card_data.bank_code.is_some() { Ok(Some(api_models::payments::AdditionalPaymentData::Card( Box::new(api_models::payments::AdditionalCardInfo { card_issuer: card_data.card_issuer.to_owned(), card_network, card_type: card_data.card_type.to_owned(), card_issuing_country: card_data.card_issuing_country.to_owned(), bank_code: card_data.bank_code.to_owned(), card_exp_month: Some(card_data.card_exp_month.clone()), card_exp_year: Some(card_data.card_exp_year.clone()), card_holder_name: card_data.card_holder_name.clone(), last4: last4.clone(), card_isin: card_isin.clone(), card_extended_bin: card_extended_bin.clone(), // These are filled after calling the processor / connector payment_checks: None, authentication_data: None, }), ))) } else { let card_info = card_isin .clone() .async_and_then(|card_isin| async move { db.get_card_info(&card_isin) .await .map_err(|error| services::logger::warn!(card_info_error=?error)) .ok() }) .await .flatten() .map(|card_info| { api_models::payments::AdditionalPaymentData::Card(Box::new( api_models::payments::AdditionalCardInfo { card_issuer: card_info.card_issuer, card_network: card_network.clone().or(card_info.card_network), bank_code: card_info.bank_code, card_type: card_info.card_type, card_issuing_country: card_info.card_issuing_country, last4: last4.clone(), card_isin: card_isin.clone(), card_extended_bin: card_extended_bin.clone(), card_exp_month: Some(card_data.card_exp_month.clone()), card_exp_year: Some(card_data.card_exp_year.clone()), card_holder_name: card_data.card_holder_name.clone(), // These are filled after calling the processor / connector payment_checks: None, authentication_data: None, }, )) }); Ok(Some(card_info.unwrap_or_else(|| { api_models::payments::AdditionalPaymentData::Card(Box::new( api_models::payments::AdditionalCardInfo { card_issuer: None, card_network, bank_code: None, card_type: None, card_issuing_country: None, last4, card_isin, card_extended_bin, card_exp_month: Some(card_data.card_exp_month.clone()), card_exp_year: Some(card_data.card_exp_year.clone()), card_holder_name: card_data.card_holder_name.clone(), // These are filled after calling the processor / connector payment_checks: None, authentication_data: None, }, )) }))) } } domain::PaymentMethodData::BankRedirect(bank_redirect_data) => match bank_redirect_data { domain::BankRedirectData::Eps { bank_name, .. } => Ok(Some( api_models::payments::AdditionalPaymentData::BankRedirect { bank_name: bank_name.to_owned(), details: None, }, )), domain::BankRedirectData::Eft { .. } => Ok(Some( api_models::payments::AdditionalPaymentData::BankRedirect { bank_name: None, details: None, }, )), domain::BankRedirectData::Ideal { bank_name, .. } => Ok(Some( api_models::payments::AdditionalPaymentData::BankRedirect { bank_name: bank_name.to_owned(), details: None, }, )), domain::BankRedirectData::BancontactCard { card_number, card_exp_month, card_exp_year, card_holder_name, } => Ok(Some( api_models::payments::AdditionalPaymentData::BankRedirect { bank_name: None, details: Some( payment_additional_types::BankRedirectDetails::BancontactCard(Box::new( payment_additional_types::BancontactBankRedirectAdditionalData { last4: card_number.as_ref().map(|c| c.get_last4()), card_exp_month: card_exp_month.clone(), card_exp_year: card_exp_year.clone(), card_holder_name: card_holder_name.clone(), }, )), ), }, )), domain::BankRedirectData::Blik { blik_code } => Ok(Some( api_models::payments::AdditionalPaymentData::BankRedirect { bank_name: None, details: blik_code.as_ref().map(|blik_code| { payment_additional_types::BankRedirectDetails::Blik(Box::new( payment_additional_types::BlikBankRedirectAdditionalData { blik_code: Some(blik_code.to_owned()), }, )) }), }, )), domain::BankRedirectData::Giropay { bank_account_bic, bank_account_iban, country, } => Ok(Some( api_models::payments::AdditionalPaymentData::BankRedirect { bank_name: None, details: Some(payment_additional_types::BankRedirectDetails::Giropay( Box::new( payment_additional_types::GiropayBankRedirectAdditionalData { bic: bank_account_bic .as_ref() .map(|bic| MaskedSortCode::from(bic.to_owned())), iban: bank_account_iban .as_ref() .map(|iban| MaskedIban::from(iban.to_owned())), country: *country, }, ), )), }, )), _ => Ok(Some( api_models::payments::AdditionalPaymentData::BankRedirect { bank_name: None, details: None, }, )), }, domain::PaymentMethodData::Wallet(wallet) => match wallet { domain::WalletData::ApplePay(apple_pay_wallet_data) => { Ok(Some(api_models::payments::AdditionalPaymentData::Wallet { apple_pay: Some(api_models::payments::ApplepayPaymentMethod { display_name: apple_pay_wallet_data.payment_method.display_name.clone(), network: apple_pay_wallet_data.payment_method.network.clone(), pm_type: apple_pay_wallet_data.payment_method.pm_type.clone(), }), google_pay: None, samsung_pay: None, })) } domain::WalletData::GooglePay(google_pay_pm_data) => { Ok(Some(api_models::payments::AdditionalPaymentData::Wallet { apple_pay: None, google_pay: Some(payment_additional_types::WalletAdditionalDataForCard { last4: google_pay_pm_data.info.card_details.clone(), card_network: google_pay_pm_data.info.card_network.clone(), card_type: Some(google_pay_pm_data.pm_type.clone()), }), samsung_pay: None, })) } domain::WalletData::SamsungPay(samsung_pay_pm_data) => { Ok(Some(api_models::payments::AdditionalPaymentData::Wallet { apple_pay: None, google_pay: None, samsung_pay: Some(payment_additional_types::WalletAdditionalDataForCard { last4: samsung_pay_pm_data .payment_credential .card_last_four_digits .clone(), card_network: samsung_pay_pm_data .payment_credential .card_brand .to_string(), card_type: None, }), })) } _ => Ok(Some(api_models::payments::AdditionalPaymentData::Wallet { apple_pay: None, google_pay: None, samsung_pay: None, })), }, domain::PaymentMethodData::PayLater(_) => Ok(Some( api_models::payments::AdditionalPaymentData::PayLater { klarna_sdk: None }, )), domain::PaymentMethodData::BankTransfer(bank_transfer) => Ok(Some( api_models::payments::AdditionalPaymentData::BankTransfer { details: Some((*(bank_transfer.to_owned())).into()), }, )), domain::PaymentMethodData::Crypto(crypto) => { Ok(Some(api_models::payments::AdditionalPaymentData::Crypto { details: Some(crypto.to_owned().into()), })) } domain::PaymentMethodData::BankDebit(bank_debit) => Ok(Some( api_models::payments::AdditionalPaymentData::BankDebit { details: Some(bank_debit.to_owned().into()), }, )), domain::PaymentMethodData::MandatePayment => Ok(Some( api_models::payments::AdditionalPaymentData::MandatePayment {}, )), domain::PaymentMethodData::Reward => { Ok(Some(api_models::payments::AdditionalPaymentData::Reward {})) } domain::PaymentMethodData::RealTimePayment(realtime_payment) => Ok(Some( api_models::payments::AdditionalPaymentData::RealTimePayment { details: Some((*(realtime_payment.to_owned())).into()), }, )), domain::PaymentMethodData::Upi(upi) => { Ok(Some(api_models::payments::AdditionalPaymentData::Upi { details: Some(upi.to_owned().into()), })) } domain::PaymentMethodData::CardRedirect(card_redirect) => Ok(Some( api_models::payments::AdditionalPaymentData::CardRedirect { details: Some(card_redirect.to_owned().into()), }, )), domain::PaymentMethodData::Voucher(voucher) => { Ok(Some(api_models::payments::AdditionalPaymentData::Voucher { details: Some(voucher.to_owned().into()), })) } domain::PaymentMethodData::GiftCard(gift_card) => Ok(Some( api_models::payments::AdditionalPaymentData::GiftCard { details: Some((*(gift_card.to_owned())).into()), }, )), domain::PaymentMethodData::CardToken(card_token) => Ok(Some( api_models::payments::AdditionalPaymentData::CardToken { details: Some(card_token.to_owned().into()), }, )), domain::PaymentMethodData::OpenBanking(open_banking) => Ok(Some( api_models::payments::AdditionalPaymentData::OpenBanking { details: Some(open_banking.to_owned().into()), }, )), domain::PaymentMethodData::CardDetailsForNetworkTransactionId(card_data) => { let card_isin = Some(card_data.card_number.get_card_isin()); let enable_extended_bin =db .find_config_by_key_unwrap_or( format!("{}_enable_extended_card_bin", profile_id.get_string_repr()).as_str(), Some("false".to_string())) .await.map_err(|err| services::logger::error!(message="Failed to fetch the config", extended_card_bin_error=?err)).ok(); let card_extended_bin = match enable_extended_bin { Some(config) if config.config == "true" => { Some(card_data.card_number.get_extended_card_bin()) } _ => None, }; let card_network = match card_data .card_number .is_cobadged_card() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Card cobadge check failed due to an invalid card network regex", )? { true => card_data.card_network.clone(), false => None, }; let last4 = Some(card_data.card_number.get_last4()); if card_data.card_issuer.is_some() && card_network.is_some() && card_data.card_type.is_some() && card_data.card_issuing_country.is_some() && card_data.bank_code.is_some() { Ok(Some(api_models::payments::AdditionalPaymentData::Card( Box::new(api_models::payments::AdditionalCardInfo { card_issuer: card_data.card_issuer.to_owned(), card_network, card_type: card_data.card_type.to_owned(), card_issuing_country: card_data.card_issuing_country.to_owned(), bank_code: card_data.bank_code.to_owned(), card_exp_month: Some(card_data.card_exp_month.clone()), card_exp_year: Some(card_data.card_exp_year.clone()), card_holder_name: card_data.card_holder_name.clone(), last4: last4.clone(), card_isin: card_isin.clone(), card_extended_bin: card_extended_bin.clone(), // These are filled after calling the processor / connector payment_checks: None, authentication_data: None, }), ))) } else { let card_info = card_isin .clone() .async_and_then(|card_isin| async move { db.get_card_info(&card_isin) .await .map_err(|error| services::logger::warn!(card_info_error=?error)) .ok() }) .await .flatten() .map(|card_info| { api_models::payments::AdditionalPaymentData::Card(Box::new( api_models::payments::AdditionalCardInfo { card_issuer: card_info.card_issuer, card_network: card_network.clone().or(card_info.card_network), bank_code: card_info.bank_code, card_type: card_info.card_type, card_issuing_country: card_info.card_issuing_country, last4: last4.clone(), card_isin: card_isin.clone(), card_extended_bin: card_extended_bin.clone(), card_exp_month: Some(card_data.card_exp_month.clone()), card_exp_year: Some(card_data.card_exp_year.clone()), card_holder_name: card_data.card_holder_name.clone(), // These are filled after calling the processor / connector payment_checks: None, authentication_data: None, }, )) }); Ok(Some(card_info.unwrap_or_else(|| { api_models::payments::AdditionalPaymentData::Card(Box::new( api_models::payments::AdditionalCardInfo { card_issuer: None, card_network, bank_code: None, card_type: None, card_issuing_country: None, last4, card_isin, card_extended_bin, card_exp_month: Some(card_data.card_exp_month.clone()), card_exp_year: Some(card_data.card_exp_year.clone()), card_holder_name: card_data.card_holder_name.clone(), // These are filled after calling the processor / connector payment_checks: None, authentication_data: None, }, )) }))) } } domain::PaymentMethodData::MobilePayment(mobile_payment) => Ok(Some( api_models::payments::AdditionalPaymentData::MobilePayment { details: Some(mobile_payment.to_owned().into()), }, )), domain::PaymentMethodData::NetworkToken(_) => Ok(None), } } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] pub async fn populate_bin_details_for_payment_method_create( card_details: api_models::payment_methods::CardDetail, db: &dyn StorageInterface, ) -> api_models::payment_methods::CardDetail { let card_isin: Option<_> = Some(card_details.card_number.get_card_isin()); if card_details.card_issuer.is_some() && card_details.card_network.is_some() && card_details.card_type.is_some() && card_details.card_issuing_country.is_some() { api::CardDetail { card_issuer: card_details.card_issuer.to_owned(), card_network: card_details.card_network.clone(), card_type: card_details.card_type.to_owned(), card_issuing_country: card_details.card_issuing_country.to_owned(), card_exp_month: card_details.card_exp_month.clone(), card_exp_year: card_details.card_exp_year.clone(), card_holder_name: card_details.card_holder_name.clone(), card_number: card_details.card_number.clone(), nick_name: card_details.nick_name.clone(), } } else { let card_info = card_isin .clone() .async_and_then(|card_isin| async move { db.get_card_info(&card_isin) .await .map_err(|error| services::logger::error!(card_info_error=?error)) .ok() }) .await .flatten() .map(|card_info| api::CardDetail { card_issuer: card_info.card_issuer, card_network: card_info.card_network.clone(), card_type: card_info.card_type, card_issuing_country: card_info.card_issuing_country, card_exp_month: card_details.card_exp_month.clone(), card_exp_year: card_details.card_exp_year.clone(), card_holder_name: card_details.card_holder_name.clone(), card_number: card_details.card_number.clone(), nick_name: card_details.nick_name.clone(), }); card_info.unwrap_or_else(|| api::CardDetail { card_issuer: None, card_network: None, card_type: None, card_issuing_country: None, card_exp_month: card_details.card_exp_month.clone(), card_exp_year: card_details.card_exp_year.clone(), card_holder_name: card_details.card_holder_name.clone(), card_number: card_details.card_number.clone(), nick_name: card_details.nick_name.clone(), }) } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub async fn populate_bin_details_for_payment_method_create( _card_details: api_models::payment_methods::CardDetail, _db: &dyn StorageInterface, ) -> api_models::payment_methods::CardDetail { todo!() } #[cfg(feature = "v1")] pub fn validate_customer_access( payment_intent: &PaymentIntent, auth_flow: services::AuthFlow, request: &api::PaymentsRequest, ) -> Result<(), errors::ApiErrorResponse> { if auth_flow == services::AuthFlow::Client && request.get_customer_id().is_some() { let is_same_customer = request.get_customer_id() == payment_intent.customer_id.as_ref(); if !is_same_customer { Err(errors::ApiErrorResponse::GenericUnauthorized { message: "Unauthorised access to update customer".to_string(), })?; } } Ok(()) } pub fn is_apple_pay_simplified_flow( connector_metadata: Option<pii::SecretSerdeValue>, connector_name: Option<&String>, ) -> CustomResult<bool, errors::ApiErrorResponse> { let option_apple_pay_metadata = get_applepay_metadata(connector_metadata) .map_err(|error| { logger::info!( "Apple pay metadata parsing for {:?} in is_apple_pay_simplified_flow {:?}", connector_name, error ) }) .ok(); // return true only if the apple flow type is simplified Ok(matches!( option_apple_pay_metadata, Some( api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined( api_models::payments::ApplePayCombinedMetadata::Simplified { .. } ) ) )) } // This function will return the encrypted connector wallets details with Apple Pay certificates // Currently apple pay certifiactes are stored in the metadata which is not encrypted. // In future we want those certificates to be encrypted and stored in the connector_wallets_details. // As part of migration fallback this function checks apple pay details are present in connector_wallets_details // If yes, it will encrypt connector_wallets_details and store it in the database. // If no, it will check if apple pay details are present in metadata and merge it with connector_wallets_details, encrypt and store it. pub async fn get_connector_wallets_details_with_apple_pay_certificates( connector_metadata: &Option<masking::Secret<tera::Value>>, connector_wallets_details_optional: &Option<api_models::admin::ConnectorWalletDetails>, ) -> RouterResult<Option<masking::Secret<serde_json::Value>>> { let connector_wallet_details_with_apple_pay_metadata_optional = get_apple_pay_metadata_if_needed(connector_metadata, connector_wallets_details_optional) .await?; let connector_wallets_details = connector_wallet_details_with_apple_pay_metadata_optional .map(|details| { serde_json::to_value(details) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize Apple Pay metadata as JSON") }) .transpose()? .map(masking::Secret::new); Ok(connector_wallets_details) } async fn get_apple_pay_metadata_if_needed( connector_metadata: &Option<masking::Secret<tera::Value>>, connector_wallets_details_optional: &Option<api_models::admin::ConnectorWalletDetails>, ) -> RouterResult<Option<api_models::admin::ConnectorWalletDetails>> { if let Some(connector_wallets_details) = connector_wallets_details_optional { if connector_wallets_details.apple_pay_combined.is_some() || connector_wallets_details.apple_pay.is_some() { return Ok(Some(connector_wallets_details.clone())); } // Otherwise, merge Apple Pay metadata return get_and_merge_apple_pay_metadata( connector_metadata.clone(), Some(connector_wallets_details.clone()), ) .await; } // If connector_wallets_details_optional is None, attempt to get Apple Pay metadata get_and_merge_apple_pay_metadata(connector_metadata.clone(), None).await } async fn get_and_merge_apple_pay_metadata( connector_metadata: Option<masking::Secret<tera::Value>>, connector_wallets_details_optional: Option<api_models::admin::ConnectorWalletDetails>, ) -> RouterResult<Option<api_models::admin::ConnectorWalletDetails>> { let apple_pay_metadata_optional = get_applepay_metadata(connector_metadata) .map_err(|error| { logger::error!( "Apple Pay metadata parsing failed in get_encrypted_connector_wallets_details_with_apple_pay_certificates {:?}", error ); }) .ok(); if let Some(apple_pay_metadata) = apple_pay_metadata_optional { let updated_wallet_details = match apple_pay_metadata { api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined( apple_pay_combined_metadata, ) => { let combined_metadata_json = serde_json::to_value(apple_pay_combined_metadata) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize Apple Pay combined metadata as JSON")?; api_models::admin::ConnectorWalletDetails { apple_pay_combined: Some(masking::Secret::new(combined_metadata_json)), apple_pay: connector_wallets_details_optional .as_ref() .and_then(|d| d.apple_pay.clone()), samsung_pay: connector_wallets_details_optional .as_ref() .and_then(|d| d.samsung_pay.clone()), paze: connector_wallets_details_optional .as_ref() .and_then(|d| d.paze.clone()), google_pay: connector_wallets_details_optional .as_ref() .and_then(|d| d.google_pay.clone()), } } api_models::payments::ApplepaySessionTokenMetadata::ApplePay(apple_pay_metadata) => { let metadata_json = serde_json::to_value(apple_pay_metadata) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize Apple Pay metadata as JSON")?; api_models::admin::ConnectorWalletDetails { apple_pay: Some(masking::Secret::new(metadata_json)), apple_pay_combined: connector_wallets_details_optional .as_ref() .and_then(|d| d.apple_pay_combined.clone()), samsung_pay: connector_wallets_details_optional .as_ref() .and_then(|d| d.samsung_pay.clone()), paze: connector_wallets_details_optional .as_ref() .and_then(|d| d.paze.clone()), google_pay: connector_wallets_details_optional .as_ref() .and_then(|d| d.google_pay.clone()), } } }; return Ok(Some(updated_wallet_details)); } // Return connector_wallets_details if no Apple Pay metadata was found Ok(connector_wallets_details_optional) } pub fn get_applepay_metadata( connector_metadata: Option<pii::SecretSerdeValue>, ) -> RouterResult<api_models::payments::ApplepaySessionTokenMetadata> { connector_metadata .clone() .parse_value::<api_models::payments::ApplepayCombinedSessionTokenData>( "ApplepayCombinedSessionTokenData", ) .map(|combined_metadata| { api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined( combined_metadata.apple_pay_combined, ) }) .or_else(|_| { connector_metadata .parse_value::<api_models::payments::ApplepaySessionTokenData>( "ApplepaySessionTokenData", ) .map(|old_metadata| { api_models::payments::ApplepaySessionTokenMetadata::ApplePay( old_metadata.apple_pay, ) }) }) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "connector_metadata".to_string(), expected_format: "applepay_metadata_format".to_string(), }) } #[cfg(all(feature = "retry", feature = "v1"))] pub async fn get_apple_pay_retryable_connectors<F, D>( state: &SessionState, merchant_account: &domain::MerchantAccount, payment_data: &D, key_store: &domain::MerchantKeyStore, pre_routing_connector_data_list: &[api::ConnectorData], merchant_connector_id: Option<&id_type::MerchantConnectorAccountId>, business_profile: domain::Profile, ) -> CustomResult<Option<Vec<api::ConnectorData>>, errors::ApiErrorResponse> where F: Send + Clone, D: payments::OperationSessionGetters<F> + Send, { let profile_id = business_profile.get_id(); let pre_decided_connector_data_first = pre_routing_connector_data_list .first() .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?; let merchant_connector_account_type = get_merchant_connector_account( state, merchant_account.get_id(), payment_data.get_creds_identifier(), key_store, profile_id, &pre_decided_connector_data_first.connector_name.to_string(), merchant_connector_id, ) .await?; let connector_data_list = if is_apple_pay_simplified_flow( merchant_connector_account_type.get_metadata(), merchant_connector_account_type .get_connector_name() .as_ref(), )? { let merchant_connector_account_list = state .store .find_merchant_connector_account_by_merchant_id_and_disabled_list( &state.into(), merchant_account.get_id(), false, key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; let profile_specific_merchant_connector_account_list = merchant_connector_account_list .filter_based_on_profile_and_connector_type( profile_id, ConnectorType::PaymentProcessor, ); let mut connector_data_list = vec![pre_decided_connector_data_first.clone()]; for merchant_connector_account in profile_specific_merchant_connector_account_list { if is_apple_pay_simplified_flow( merchant_connector_account.metadata.clone(), Some(&merchant_connector_account.connector_name), )? { let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &merchant_connector_account.connector_name.to_string(), api::GetToken::Connector, Some(merchant_connector_account.get_id()), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received")?; if !connector_data_list.iter().any(|connector_details| { connector_details.merchant_connector_id == connector_data.merchant_connector_id }) { connector_data_list.push(connector_data) } } } #[cfg(feature = "v1")] let fallback_connetors_list = crate::core::routing::helpers::get_merchant_default_config( &*state.clone().store, profile_id.get_string_repr(), &api_enums::TransactionType::Payment, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get merchant default fallback connectors config")?; #[cfg(feature = "v2")] let fallback_connetors_list = core_admin::ProfileWrapper::new(business_profile) .get_default_fallback_list_of_connector_under_profile() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get merchant default fallback connectors config")?; let mut routing_connector_data_list = Vec::new(); pre_routing_connector_data_list.iter().for_each(|pre_val| { routing_connector_data_list.push(pre_val.merchant_connector_id.clone()) }); fallback_connetors_list.iter().for_each(|fallback_val| { routing_connector_data_list .iter() .all(|val| *val != fallback_val.merchant_connector_id) .then(|| { routing_connector_data_list.push(fallback_val.merchant_connector_id.clone()) }); }); // connector_data_list is the list of connectors for which Apple Pay simplified flow is configured. // This list is arranged in the same order as the merchant's connectors routingconfiguration. let mut ordered_connector_data_list = Vec::new(); routing_connector_data_list .iter() .for_each(|merchant_connector_id| { let connector_data = connector_data_list.iter().find(|connector_data| { *merchant_connector_id == connector_data.merchant_connector_id }); if let Some(connector_data_details) = connector_data { ordered_connector_data_list.push(connector_data_details.clone()); } }); Some(ordered_connector_data_list) } else { None }; Ok(connector_data_list) } #[derive(Debug, Serialize, Deserialize)] pub struct ApplePayData { version: masking::Secret<String>, data: masking::Secret<String>, signature: masking::Secret<String>, header: ApplePayHeader, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplePayHeader { ephemeral_public_key: masking::Secret<String>, public_key_hash: masking::Secret<String>, transaction_id: masking::Secret<String>, } impl ApplePayData { pub fn token_json( wallet_data: domain::WalletData, ) -> CustomResult<Self, errors::ConnectorError> { let json_wallet_data: Self = connector::utils::WalletData::get_wallet_token_as_json( &wallet_data, "Apple Pay".to_string(), )?; Ok(json_wallet_data) } pub async fn decrypt( &self, payment_processing_certificate: &masking::Secret<String>, payment_processing_certificate_key: &masking::Secret<String>, ) -> CustomResult<serde_json::Value, errors::ApplePayDecryptionError> { let merchant_id = self.merchant_id(payment_processing_certificate)?; let shared_secret = self.shared_secret(payment_processing_certificate_key)?; let symmetric_key = self.symmetric_key(&merchant_id, &shared_secret)?; let decrypted = self.decrypt_ciphertext(&symmetric_key)?; let parsed_decrypted: serde_json::Value = serde_json::from_str(&decrypted) .change_context(errors::ApplePayDecryptionError::DecryptionFailed)?; Ok(parsed_decrypted) } pub fn merchant_id( &self, payment_processing_certificate: &masking::Secret<String>, ) -> CustomResult<String, errors::ApplePayDecryptionError> { let cert_data = payment_processing_certificate.clone().expose(); let base64_decode_cert_data = BASE64_ENGINE .decode(cert_data) .change_context(errors::ApplePayDecryptionError::Base64DecodingFailed)?; // Parsing the certificate using x509-parser let (_, certificate) = parse_x509_certificate(&base64_decode_cert_data) .change_context(errors::ApplePayDecryptionError::CertificateParsingFailed) .attach_printable("Error parsing apple pay PPC")?; // Finding the merchant ID extension let apple_pay_m_id = certificate .extensions() .iter() .find(|extension| { extension .oid .to_string() .eq(consts::MERCHANT_ID_FIELD_EXTENSION_ID) }) .map(|ext| { let merchant_id = String::from_utf8_lossy(ext.value) .trim() .trim_start_matches('@') .to_string(); merchant_id }) .ok_or(errors::ApplePayDecryptionError::MissingMerchantId) .attach_printable("Unable to find merchant ID extension in the certificate")?; Ok(apple_pay_m_id) } pub fn shared_secret( &self, payment_processing_certificate_key: &masking::Secret<String>, ) -> CustomResult<Vec<u8>, errors::ApplePayDecryptionError> { let public_ec_bytes = BASE64_ENGINE .decode(self.header.ephemeral_public_key.peek().as_bytes()) .change_context(errors::ApplePayDecryptionError::Base64DecodingFailed)?; let public_key = PKey::public_key_from_der(&public_ec_bytes) .change_context(errors::ApplePayDecryptionError::KeyDeserializationFailed) .attach_printable("Failed to deserialize the public key")?; let decrypted_apple_pay_ppc_key = payment_processing_certificate_key.clone().expose(); // Create PKey objects from EcKey let private_key = PKey::private_key_from_pem(decrypted_apple_pay_ppc_key.as_bytes()) .change_context(errors::ApplePayDecryptionError::KeyDeserializationFailed) .attach_printable("Failed to deserialize the private key")?; // Create the Deriver object and set the peer public key let mut deriver = Deriver::new(&private_key) .change_context(errors::ApplePayDecryptionError::DerivingSharedSecretKeyFailed) .attach_printable("Failed to create a deriver for the private key")?; deriver .set_peer(&public_key) .change_context(errors::ApplePayDecryptionError::DerivingSharedSecretKeyFailed) .attach_printable("Failed to set the peer key for the secret derivation")?; // Compute the shared secret let shared_secret = deriver .derive_to_vec() .change_context(errors::ApplePayDecryptionError::DerivingSharedSecretKeyFailed) .attach_printable("Final key derivation failed")?; Ok(shared_secret) } pub fn symmetric_key( &self, merchant_id: &str, shared_secret: &[u8], ) -> CustomResult<Vec<u8>, errors::ApplePayDecryptionError> { let kdf_algorithm = b"\x0did-aes256-GCM"; let kdf_party_v = hex::decode(merchant_id) .change_context(errors::ApplePayDecryptionError::Base64DecodingFailed)?; let kdf_party_u = b"Apple"; let kdf_info = [&kdf_algorithm[..], kdf_party_u, &kdf_party_v[..]].concat(); let mut hash = openssl::sha::Sha256::new(); hash.update(b"\x00\x00\x00"); hash.update(b"\x01"); hash.update(shared_secret); hash.update(&kdf_info[..]); let symmetric_key = hash.finish(); Ok(symmetric_key.to_vec()) } pub fn decrypt_ciphertext( &self, symmetric_key: &[u8], ) -> CustomResult<String, errors::ApplePayDecryptionError> { logger::info!("Decrypt apple pay token"); let data = BASE64_ENGINE .decode(self.data.peek().as_bytes()) .change_context(errors::ApplePayDecryptionError::Base64DecodingFailed)?; let iv = [0u8; 16]; //Initialization vector IV is typically used in AES-GCM (Galois/Counter Mode) encryption for randomizing the encryption process. let ciphertext = data .get(..data.len() - 16) .ok_or(errors::ApplePayDecryptionError::DecryptionFailed)?; let tag = data .get(data.len() - 16..) .ok_or(errors::ApplePayDecryptionError::DecryptionFailed)?; let cipher = Cipher::aes_256_gcm(); let decrypted_data = decrypt_aead(cipher, symmetric_key, Some(&iv), &[], ciphertext, tag) .change_context(errors::ApplePayDecryptionError::DecryptionFailed)?; let decrypted = String::from_utf8(decrypted_data) .change_context(errors::ApplePayDecryptionError::DecryptionFailed)?; Ok(decrypted) } } // Structs for keys and the main decryptor pub struct GooglePayTokenDecryptor { root_signing_keys: Vec<GooglePayRootSigningKey>, recipient_id: masking::Secret<String>, private_key: PKey<openssl::pkey::Private>, } #[derive(Debug, Clone, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct EncryptedData { signature: String, intermediate_signing_key: IntermediateSigningKey, protocol_version: GooglePayProtocolVersion, #[serde(with = "common_utils::custom_serde::json_string")] signed_message: GooglePaySignedMessage, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct GooglePaySignedMessage { #[serde(with = "common_utils::Base64Serializer")] encrypted_message: masking::Secret<Vec<u8>>, #[serde(with = "common_utils::Base64Serializer")] ephemeral_public_key: masking::Secret<Vec<u8>>, #[serde(with = "common_utils::Base64Serializer")] tag: masking::Secret<Vec<u8>>, } #[derive(Debug, Clone, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct IntermediateSigningKey { signed_key: masking::Secret<String>, signatures: Vec<masking::Secret<String>>, } #[derive(Debug, Clone, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct GooglePaySignedKey { key_value: masking::Secret<String>, key_expiration: String, } #[derive(Debug, Clone, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct GooglePayRootSigningKey { key_value: masking::Secret<String>, key_expiration: String, protocol_version: GooglePayProtocolVersion, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq)] pub enum GooglePayProtocolVersion { #[serde(rename = "ECv2")] EcProtocolVersion2, } // Check expiration date validity fn check_expiration_date_is_valid( expiration: &str, ) -> CustomResult<bool, errors::GooglePayDecryptionError> { let expiration_ms = expiration .parse::<i128>() .change_context(errors::GooglePayDecryptionError::InvalidExpirationTime)?; // convert milliseconds to nanoseconds (1 millisecond = 1_000_000 nanoseconds) to create OffsetDateTime let expiration_time = time::OffsetDateTime::from_unix_timestamp_nanos(expiration_ms * 1_000_000) .change_context(errors::GooglePayDecryptionError::InvalidExpirationTime)?; let now = time::OffsetDateTime::now_utc(); Ok(expiration_time > now) } // Construct little endian format of u32 fn get_little_endian_format(number: u32) -> Vec<u8> { number.to_le_bytes().to_vec() } // Filter and parse the root signing keys based on protocol version and expiration time fn filter_root_signing_keys( root_signing_keys: Vec<GooglePayRootSigningKey>, ) -> CustomResult<Vec<GooglePayRootSigningKey>, errors::GooglePayDecryptionError> { let filtered_root_signing_keys = root_signing_keys .iter() .filter(|key| { key.protocol_version == GooglePayProtocolVersion::EcProtocolVersion2 && matches!( check_expiration_date_is_valid(&key.key_expiration).inspect_err( |err| logger::warn!( "Failed to check expirattion due to invalid format: {:?}", err ) ), Ok(true) ) }) .cloned() .collect::<Vec<GooglePayRootSigningKey>>(); logger::info!( "Filtered {} out of {} root signing keys", filtered_root_signing_keys.len(), root_signing_keys.len() ); Ok(filtered_root_signing_keys) } impl GooglePayTokenDecryptor { pub fn new( root_keys: masking::Secret<String>, recipient_id: masking::Secret<String>, private_key: masking::Secret<String>, ) -> CustomResult<Self, errors::GooglePayDecryptionError> { // base64 decode the private key let decoded_key = BASE64_ENGINE .decode(private_key.expose()) .change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?; // base64 decode the root signing keys let decoded_root_signing_keys = BASE64_ENGINE .decode(root_keys.expose()) .change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?; // create a private key from the decoded key let private_key = PKey::private_key_from_pkcs8(&decoded_key) .change_context(errors::GooglePayDecryptionError::KeyDeserializationFailed) .attach_printable("cannot convert private key from decode_key")?; // parse the root signing keys let root_keys_vector: Vec<GooglePayRootSigningKey> = decoded_root_signing_keys .parse_struct("GooglePayRootSigningKey") .change_context(errors::GooglePayDecryptionError::DeserializationFailed)?; // parse and filter the root signing keys by protocol version let filtered_root_signing_keys = filter_root_signing_keys(root_keys_vector)?; Ok(Self { root_signing_keys: filtered_root_signing_keys, recipient_id, private_key, }) } // Decrypt the Google pay token pub fn decrypt_token( &self, data: String, should_verify_signature: bool, ) -> CustomResult< hyperswitch_domain_models::router_data::GooglePayDecryptedData, errors::GooglePayDecryptionError, > { // parse the encrypted data let encrypted_data: EncryptedData = data .parse_struct("EncryptedData") .change_context(errors::GooglePayDecryptionError::DeserializationFailed)?; // verify the signature if required if should_verify_signature { self.verify_signature(&encrypted_data)?; } let ephemeral_public_key = encrypted_data.signed_message.ephemeral_public_key.peek(); let tag = encrypted_data.signed_message.tag.peek(); let encrypted_message = encrypted_data.signed_message.encrypted_message.peek(); // derive the shared key let shared_key = self.get_shared_key(ephemeral_public_key)?; // derive the symmetric encryption key and MAC key let derived_key = self.derive_key(ephemeral_public_key, &shared_key)?; // First 32 bytes for AES-256 and Remaining bytes for HMAC let (symmetric_encryption_key, mac_key) = derived_key .split_at_checked(32) .ok_or(errors::GooglePayDecryptionError::ParsingFailed)?; // verify the HMAC of the message self.verify_hmac(mac_key, tag, encrypted_message)?; // decrypt the message let decrypted = self.decrypt_message(symmetric_encryption_key, encrypted_message)?; // parse the decrypted data let decrypted_data: hyperswitch_domain_models::router_data::GooglePayDecryptedData = decrypted .parse_struct("GooglePayDecryptedData") .change_context(errors::GooglePayDecryptionError::DeserializationFailed)?; // check the expiration date of the decrypted data if matches!( check_expiration_date_is_valid(&decrypted_data.message_expiration), Ok(true) ) { Ok(decrypted_data) } else { Err(errors::GooglePayDecryptionError::DecryptedTokenExpired.into()) } } // Verify the signature of the token fn verify_signature( &self, encrypted_data: &EncryptedData, ) -> CustomResult<(), errors::GooglePayDecryptionError> { // check the protocol version if encrypted_data.protocol_version != GooglePayProtocolVersion::EcProtocolVersion2 { return Err(errors::GooglePayDecryptionError::InvalidProtocolVersion.into()); } // verify the intermediate signing key self.verify_intermediate_signing_key(encrypted_data)?; // validate and fetch the signed key let signed_key = self.validate_signed_key(&encrypted_data.intermediate_signing_key)?; // verify the signature of the token self.verify_message_signature(encrypted_data, &signed_key) } // Verify the intermediate signing key fn verify_intermediate_signing_key( &self, encrypted_data: &EncryptedData, ) -> CustomResult<(), errors::GooglePayDecryptionError> { let mut signatrues: Vec<openssl::ecdsa::EcdsaSig> = Vec::new(); // decode and parse the signatures for signature in encrypted_data.intermediate_signing_key.signatures.iter() { let signature = BASE64_ENGINE .decode(signature.peek()) .change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?; let ecdsa_signature = openssl::ecdsa::EcdsaSig::from_der(&signature) .change_context(errors::GooglePayDecryptionError::EcdsaSignatureParsingFailed)?; signatrues.push(ecdsa_signature); } // get the sender id i.e. Google let sender_id = String::from_utf8(consts::SENDER_ID.to_vec()) .change_context(errors::GooglePayDecryptionError::DeserializationFailed)?; // construct the signed data let signed_data = self.construct_signed_data_for_intermediate_signing_key_verification( &sender_id, consts::PROTOCOL, encrypted_data.intermediate_signing_key.signed_key.peek(), )?; // check if any of the signatures are valid for any of the root signing keys for key in self.root_signing_keys.iter() { // decode and create public key let public_key = self .load_public_key(key.key_value.peek()) .change_context(errors::GooglePayDecryptionError::DerivingPublicKeyFailed)?; // fetch the ec key from public key let ec_key = public_key .ec_key() .change_context(errors::GooglePayDecryptionError::DerivingEcKeyFailed)?; // hash the signed data let message_hash = openssl::sha::sha256(&signed_data); // verify if any of the signatures is valid against the given key for signature in signatrues.iter() { let result = signature.verify(&message_hash, &ec_key).change_context( errors::GooglePayDecryptionError::SignatureVerificationFailed, )?; if result { return Ok(()); } } } Err(errors::GooglePayDecryptionError::InvalidIntermediateSignature.into()) } // Construct signed data for intermediate signing key verification fn construct_signed_data_for_intermediate_signing_key_verification( &self, sender_id: &str, protocol_version: &str, signed_key: &str, ) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> { let length_of_sender_id = u32::try_from(sender_id.len()) .change_context(errors::GooglePayDecryptionError::ParsingFailed)?; let length_of_protocol_version = u32::try_from(protocol_version.len()) .change_context(errors::GooglePayDecryptionError::ParsingFailed)?; let length_of_signed_key = u32::try_from(signed_key.len()) .change_context(errors::GooglePayDecryptionError::ParsingFailed)?; let mut signed_data: Vec<u8> = Vec::new(); signed_data.append(&mut get_little_endian_format(length_of_sender_id)); signed_data.append(&mut sender_id.as_bytes().to_vec()); signed_data.append(&mut get_little_endian_format(length_of_protocol_version)); signed_data.append(&mut protocol_version.as_bytes().to_vec()); signed_data.append(&mut get_little_endian_format(length_of_signed_key)); signed_data.append(&mut signed_key.as_bytes().to_vec()); Ok(signed_data) } // Validate and parse signed key fn validate_signed_key( &self, intermediate_signing_key: &IntermediateSigningKey, ) -> CustomResult<GooglePaySignedKey, errors::GooglePayDecryptionError> { let signed_key: GooglePaySignedKey = intermediate_signing_key .signed_key .clone() .expose() .parse_struct("GooglePaySignedKey") .change_context(errors::GooglePayDecryptionError::SignedKeyParsingFailure)?; if !matches!( check_expiration_date_is_valid(&signed_key.key_expiration), Ok(true) ) { return Err(errors::GooglePayDecryptionError::SignedKeyExpired)?; } Ok(signed_key) } // Verify the signed message fn verify_message_signature( &self, encrypted_data: &EncryptedData, signed_key: &GooglePaySignedKey, ) -> CustomResult<(), errors::GooglePayDecryptionError> { // create a public key from the intermediate signing key let public_key = self.load_public_key(signed_key.key_value.peek())?; // base64 decode the signature let signature = BASE64_ENGINE .decode(&encrypted_data.signature) .change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?; // parse the signature using ECDSA let ecdsa_signature = openssl::ecdsa::EcdsaSig::from_der(&signature) .change_context(errors::GooglePayDecryptionError::EcdsaSignatureFailed)?; // get the EC key from the public key let ec_key = public_key .ec_key() .change_context(errors::GooglePayDecryptionError::DerivingEcKeyFailed)?; // get the sender id i.e. Google let sender_id = String::from_utf8(consts::SENDER_ID.to_vec()) .change_context(errors::GooglePayDecryptionError::DeserializationFailed)?; // serialize the signed message to string let signed_message = serde_json::to_string(&encrypted_data.signed_message) .change_context(errors::GooglePayDecryptionError::SignedKeyParsingFailure)?; // construct the signed data let signed_data = self.construct_signed_data_for_signature_verification( &sender_id, consts::PROTOCOL, &signed_message, )?; // hash the signed data let message_hash = openssl::sha::sha256(&signed_data); // verify the signature let result = ecdsa_signature .verify(&message_hash, &ec_key) .change_context(errors::GooglePayDecryptionError::SignatureVerificationFailed)?; if result { Ok(()) } else { Err(errors::GooglePayDecryptionError::InvalidSignature)? } } // Fetch the public key fn load_public_key( &self, key: &str, ) -> CustomResult<PKey<openssl::pkey::Public>, errors::GooglePayDecryptionError> { // decode the base64 string let der_data = BASE64_ENGINE .decode(key) .change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?; // parse the DER-encoded data as an EC public key let ec_key = openssl::ec::EcKey::public_key_from_der(&der_data) .change_context(errors::GooglePayDecryptionError::DerivingEcKeyFailed)?; // wrap the EC key in a PKey (a more general-purpose public key type in OpenSSL) let public_key = PKey::from_ec_key(ec_key) .change_context(errors::GooglePayDecryptionError::DerivingPublicKeyFailed)?; Ok(public_key) } // Construct signed data for signature verification fn construct_signed_data_for_signature_verification( &self, sender_id: &str, protocol_version: &str, signed_key: &str, ) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> { let recipient_id = self.recipient_id.clone().expose(); let length_of_sender_id = u32::try_from(sender_id.len()) .change_context(errors::GooglePayDecryptionError::ParsingFailed)?; let length_of_recipient_id = u32::try_from(recipient_id.len()) .change_context(errors::GooglePayDecryptionError::ParsingFailed)?; let length_of_protocol_version = u32::try_from(protocol_version.len()) .change_context(errors::GooglePayDecryptionError::ParsingFailed)?; let length_of_signed_key = u32::try_from(signed_key.len()) .change_context(errors::GooglePayDecryptionError::ParsingFailed)?; let mut signed_data: Vec<u8> = Vec::new(); signed_data.append(&mut get_little_endian_format(length_of_sender_id)); signed_data.append(&mut sender_id.as_bytes().to_vec()); signed_data.append(&mut get_little_endian_format(length_of_recipient_id)); signed_data.append(&mut recipient_id.as_bytes().to_vec()); signed_data.append(&mut get_little_endian_format(length_of_protocol_version)); signed_data.append(&mut protocol_version.as_bytes().to_vec()); signed_data.append(&mut get_little_endian_format(length_of_signed_key)); signed_data.append(&mut signed_key.as_bytes().to_vec()); Ok(signed_data) } // Derive a shared key using ECDH fn get_shared_key( &self, ephemeral_public_key_bytes: &[u8], ) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> { let group = openssl::ec::EcGroup::from_curve_name(openssl::nid::Nid::X9_62_PRIME256V1) .change_context(errors::GooglePayDecryptionError::DerivingEcGroupFailed)?; let mut big_num_context = openssl::bn::BigNumContext::new() .change_context(errors::GooglePayDecryptionError::BigNumAllocationFailed)?; let ec_key = openssl::ec::EcPoint::from_bytes( &group, ephemeral_public_key_bytes, &mut big_num_context, ) .change_context(errors::GooglePayDecryptionError::DerivingEcKeyFailed)?; // create an ephemeral public key from the given bytes let ephemeral_public_key = openssl::ec::EcKey::from_public_key(&group, &ec_key) .change_context(errors::GooglePayDecryptionError::DerivingPublicKeyFailed)?; // wrap the public key in a PKey let ephemeral_pkey = PKey::from_ec_key(ephemeral_public_key) .change_context(errors::GooglePayDecryptionError::DerivingPublicKeyFailed)?; // perform ECDH to derive the shared key let mut deriver = Deriver::new(&self.private_key) .change_context(errors::GooglePayDecryptionError::DerivingSharedSecretKeyFailed)?; deriver .set_peer(&ephemeral_pkey) .change_context(errors::GooglePayDecryptionError::DerivingSharedSecretKeyFailed)?; let shared_key = deriver .derive_to_vec() .change_context(errors::GooglePayDecryptionError::DerivingSharedSecretKeyFailed)?; Ok(shared_key) } // Derive symmetric key and MAC key using HKDF fn derive_key( &self, ephemeral_public_key_bytes: &[u8], shared_key: &[u8], ) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> { // concatenate ephemeral public key and shared key let input_key_material = [ephemeral_public_key_bytes, shared_key].concat(); // initialize HKDF with SHA-256 as the hash function // Salt is not provided as per the Google Pay documentation // https://developers.google.com/pay/api/android/guides/resources/payment-data-cryptography#encrypt-spec let hkdf: ::hkdf::Hkdf<sha2::Sha256> = ::hkdf::Hkdf::new(None, &input_key_material); // derive 64 bytes for the output key (symmetric encryption + MAC key) let mut output_key = vec![0u8; 64]; hkdf.expand(consts::SENDER_ID, &mut output_key) .map_err(|err| { logger::error!( "Failed to derive the shared ephemeral key for Google Pay decryption flow: {:?}", err ); report!(errors::GooglePayDecryptionError::DerivingSharedEphemeralKeyFailed) })?; Ok(output_key) } // Verify the Hmac key // https://developers.google.com/pay/api/android/guides/resources/payment-data-cryptography#encrypt-spec fn verify_hmac( &self, mac_key: &[u8], tag: &[u8], encrypted_message: &[u8], ) -> CustomResult<(), errors::GooglePayDecryptionError> { let hmac_key = ring::hmac::Key::new(ring::hmac::HMAC_SHA256, mac_key); ring::hmac::verify(&hmac_key, encrypted_message, tag) .change_context(errors::GooglePayDecryptionError::HmacVerificationFailed) } // Method to decrypt the AES-GCM encrypted message fn decrypt_message( &self, symmetric_key: &[u8], encrypted_message: &[u8], ) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> { //initialization vector IV is typically used in AES-GCM (Galois/Counter Mode) encryption for randomizing the encryption process. // zero iv is being passed as specified in Google Pay documentation // https://developers.google.com/pay/api/android/guides/resources/payment-data-cryptography#decrypt-token let iv = [0u8; 16]; // extract the tag from the end of the encrypted message let tag = encrypted_message .get(encrypted_message.len() - 16..) .ok_or(errors::GooglePayDecryptionError::ParsingTagError)?; // decrypt the message using AES-256-CTR let cipher = Cipher::aes_256_ctr(); let decrypted_data = decrypt_aead( cipher, symmetric_key, Some(&iv), &[], encrypted_message, tag, ) .change_context(errors::GooglePayDecryptionError::DecryptionFailed)?; Ok(decrypted_data) } } pub fn decrypt_paze_token( paze_wallet_data: PazeWalletData, paze_private_key: masking::Secret<String>, paze_private_key_passphrase: masking::Secret<String>, ) -> CustomResult<serde_json::Value, errors::PazeDecryptionError> { let decoded_paze_private_key = BASE64_ENGINE .decode(paze_private_key.expose().as_bytes()) .change_context(errors::PazeDecryptionError::Base64DecodingFailed)?; let decrypted_private_key = openssl::rsa::Rsa::private_key_from_pem_passphrase( decoded_paze_private_key.as_slice(), paze_private_key_passphrase.expose().as_bytes(), ) .change_context(errors::PazeDecryptionError::CertificateParsingFailed)?; let decrypted_private_key_pem = String::from_utf8( decrypted_private_key .private_key_to_pem() .change_context(errors::PazeDecryptionError::CertificateParsingFailed)?, ) .change_context(errors::PazeDecryptionError::CertificateParsingFailed)?; let decrypter = jwe::RSA_OAEP_256 .decrypter_from_pem(decrypted_private_key_pem) .change_context(errors::PazeDecryptionError::CertificateParsingFailed)?; let paze_complete_response: Vec<&str> = paze_wallet_data .complete_response .peek() .split('.') .collect(); let encrypted_jwe_key = paze_complete_response .get(1) .ok_or(errors::PazeDecryptionError::DecryptionFailed)? .to_string(); let decoded_jwe_key = base64::engine::general_purpose::URL_SAFE_NO_PAD .decode(encrypted_jwe_key) .change_context(errors::PazeDecryptionError::Base64DecodingFailed)?; let jws_body: JwsBody = serde_json::from_slice(&decoded_jwe_key) .change_context(errors::PazeDecryptionError::DecryptionFailed)?; let (deserialized_payload, _deserialized_header) = jwe::deserialize_compact(jws_body.secured_payload.peek(), &decrypter) .change_context(errors::PazeDecryptionError::DecryptionFailed)?; let encoded_secured_payload_element = String::from_utf8(deserialized_payload) .change_context(errors::PazeDecryptionError::DecryptionFailed)? .split('.') .collect::<Vec<&str>>() .get(1) .ok_or(errors::PazeDecryptionError::DecryptionFailed)? .to_string(); let decoded_secured_payload_element = base64::engine::general_purpose::URL_SAFE_NO_PAD .decode(encoded_secured_payload_element) .change_context(errors::PazeDecryptionError::Base64DecodingFailed)?; let parsed_decrypted: serde_json::Value = serde_json::from_slice(&decoded_secured_payload_element) .change_context(errors::PazeDecryptionError::DecryptionFailed)?; Ok(parsed_decrypted) } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct JwsBody { pub payload_id: String, pub session_id: String, pub secured_payload: masking::Secret<String>, } pub fn get_key_params_for_surcharge_details( payment_method_data: &domain::PaymentMethodData, ) -> Option<( common_enums::PaymentMethod, common_enums::PaymentMethodType, Option<common_enums::CardNetwork>, )> { match payment_method_data { domain::PaymentMethodData::Card(card) => { // surcharge generated will always be same for credit as well as debit // since surcharge conditions cannot be defined on card_type Some(( common_enums::PaymentMethod::Card, common_enums::PaymentMethodType::Credit, card.card_network.clone(), )) } domain::PaymentMethodData::CardRedirect(card_redirect_data) => Some(( common_enums::PaymentMethod::CardRedirect, card_redirect_data.get_payment_method_type(), None, )), domain::PaymentMethodData::Wallet(wallet) => Some(( common_enums::PaymentMethod::Wallet, wallet.get_payment_method_type(), None, )), domain::PaymentMethodData::PayLater(pay_later) => Some(( common_enums::PaymentMethod::PayLater, pay_later.get_payment_method_type(), None, )), domain::PaymentMethodData::BankRedirect(bank_redirect) => Some(( common_enums::PaymentMethod::BankRedirect, bank_redirect.get_payment_method_type(), None, )), domain::PaymentMethodData::BankDebit(bank_debit) => Some(( common_enums::PaymentMethod::BankDebit, bank_debit.get_payment_method_type(), None, )), domain::PaymentMethodData::BankTransfer(bank_transfer) => Some(( common_enums::PaymentMethod::BankTransfer, bank_transfer.get_payment_method_type(), None, )), domain::PaymentMethodData::Crypto(crypto) => Some(( common_enums::PaymentMethod::Crypto, crypto.get_payment_method_type(), None, )), domain::PaymentMethodData::MandatePayment => None, domain::PaymentMethodData::Reward => None, domain::PaymentMethodData::RealTimePayment(real_time_payment) => Some(( common_enums::PaymentMethod::RealTimePayment, real_time_payment.get_payment_method_type(), None, )), domain::PaymentMethodData::Upi(upi_data) => Some(( common_enums::PaymentMethod::Upi, upi_data.get_payment_method_type(), None, )), domain::PaymentMethodData::Voucher(voucher) => Some(( common_enums::PaymentMethod::Voucher, voucher.get_payment_method_type(), None, )), domain::PaymentMethodData::GiftCard(gift_card) => Some(( common_enums::PaymentMethod::GiftCard, gift_card.get_payment_method_type(), None, )), domain::PaymentMethodData::OpenBanking(ob_data) => Some(( common_enums::PaymentMethod::OpenBanking, ob_data.get_payment_method_type(), None, )), domain::PaymentMethodData::MobilePayment(mobile_payment) => Some(( common_enums::PaymentMethod::MobilePayment, mobile_payment.get_payment_method_type(), None, )), domain::PaymentMethodData::CardToken(_) | domain::PaymentMethodData::NetworkToken(_) | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => None, } } pub fn validate_payment_link_request( confirm: Option<bool>, ) -> Result<(), errors::ApiErrorResponse> { if let Some(cnf) = confirm { if !cnf { return Ok(()); } else { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "cannot confirm a payment while creating a payment link".to_string(), }); } } Ok(()) } pub async fn get_gsm_record( state: &SessionState, error_code: Option<String>, error_message: Option<String>, connector_name: String, flow: String, ) -> Option<storage::gsm::GatewayStatusMap> { let get_gsm = || async { state.store.find_gsm_rule( connector_name.clone(), flow.clone(), "sub_flow".to_string(), error_code.clone().unwrap_or_default(), // TODO: make changes in connector to get a mandatory code in case of success or error response error_message.clone().unwrap_or_default(), ) .await .map_err(|err| { if err.current_context().is_db_not_found() { logger::warn!( "GSM miss for connector - {}, flow - {}, error_code - {:?}, error_message - {:?}", connector_name, flow, error_code, error_message ); metrics::AUTO_RETRY_GSM_MISS_COUNT.add( 1, &[]); } else { metrics::AUTO_RETRY_GSM_FETCH_FAILURE_COUNT.add( 1, &[]); }; err.change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to fetch decision from gsm") }) }; get_gsm() .await .inspect_err(|err| { // warn log should suffice here because we are not propagating this error logger::warn!(get_gsm_decision_fetch_error=?err, "error fetching gsm decision"); }) .ok() } pub async fn get_unified_translation( state: &SessionState, unified_code: String, unified_message: String, locale: String, ) -> Option<String> { let get_unified_translation = || async { state.store.find_translation( unified_code.clone(), unified_message.clone(), locale.clone(), ) .await .map_err(|err| { if err.current_context().is_db_not_found() { logger::warn!( "Translation missing for unified_code - {:?}, unified_message - {:?}, locale - {:?}", unified_code, unified_message, locale ); } err.change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to fetch translation from unified_translations") }) }; get_unified_translation() .await .inspect_err(|err| { // warn log should suffice here because we are not propagating this error logger::warn!(get_translation_error=?err, "error fetching unified translations"); }) .ok() } pub fn validate_order_details_amount( order_details: Vec<api_models::payments::OrderDetailsWithAmount>, amount: MinorUnit, should_validate: bool, ) -> Result<(), errors::ApiErrorResponse> { if should_validate { let total_order_details_amount: MinorUnit = order_details .iter() .map(|order| order.amount * order.quantity) .sum(); if total_order_details_amount != amount { Err(errors::ApiErrorResponse::InvalidRequestData { message: "Total sum of order details doesn't match amount in payment request" .to_string(), }) } else { Ok(()) } } else { Ok(()) } } // This function validates the client secret expiry set by the merchant in the request pub fn validate_session_expiry(session_expiry: u32) -> Result<(), errors::ApiErrorResponse> { if !(consts::MIN_SESSION_EXPIRY..=consts::MAX_SESSION_EXPIRY).contains(&session_expiry) { Err(errors::ApiErrorResponse::InvalidRequestData { message: "session_expiry should be between 60(1 min) to 7890000(3 months).".to_string(), }) } else { Ok(()) } } pub fn get_recipient_id_for_open_banking( merchant_data: &AdditionalMerchantData, ) -> Result<Option<String>, errors::ApiErrorResponse> { match merchant_data { AdditionalMerchantData::OpenBankingRecipientData(data) => match data { MerchantRecipientData::ConnectorRecipientId(id) => Ok(Some(id.peek().clone())), MerchantRecipientData::AccountData(acc_data) => match acc_data { MerchantAccountData::Bacs { connector_recipient_id, .. } => match connector_recipient_id { Some(RecipientIdType::ConnectorId(id)) => Ok(Some(id.peek().clone())), Some(RecipientIdType::LockerId(id)) => Ok(Some(id.peek().clone())), _ => Err(errors::ApiErrorResponse::InvalidConnectorConfiguration { config: "recipient_id".to_string(), }), }, MerchantAccountData::Iban { connector_recipient_id, .. } => match connector_recipient_id { Some(RecipientIdType::ConnectorId(id)) => Ok(Some(id.peek().clone())), Some(RecipientIdType::LockerId(id)) => Ok(Some(id.peek().clone())), _ => Err(errors::ApiErrorResponse::InvalidConnectorConfiguration { config: "recipient_id".to_string(), }), }, }, _ => Err(errors::ApiErrorResponse::InvalidConnectorConfiguration { config: "recipient_id".to_string(), }), }, } } // This function validates the intent fulfillment time expiry set by the merchant in the request pub fn validate_intent_fulfillment_expiry( intent_fulfillment_time: u32, ) -> Result<(), errors::ApiErrorResponse> { if !(consts::MIN_INTENT_FULFILLMENT_EXPIRY..=consts::MAX_INTENT_FULFILLMENT_EXPIRY) .contains(&intent_fulfillment_time) { Err(errors::ApiErrorResponse::InvalidRequestData { message: "intent_fulfillment_time should be between 60(1 min) to 1800(30 mins)." .to_string(), }) } else { Ok(()) } } pub fn add_connector_response_to_additional_payment_data( additional_payment_data: api_models::payments::AdditionalPaymentData, connector_response_payment_method_data: AdditionalPaymentMethodConnectorResponse, ) -> api_models::payments::AdditionalPaymentData { match ( &additional_payment_data, connector_response_payment_method_data, ) { ( api_models::payments::AdditionalPaymentData::Card(additional_card_data), AdditionalPaymentMethodConnectorResponse::Card { authentication_data, payment_checks, .. }, ) => api_models::payments::AdditionalPaymentData::Card(Box::new( api_models::payments::AdditionalCardInfo { payment_checks, authentication_data, ..*additional_card_data.clone() }, )), ( api_models::payments::AdditionalPaymentData::PayLater { .. }, AdditionalPaymentMethodConnectorResponse::PayLater { klarna_sdk: Some(KlarnaSdkResponse { payment_type }), }, ) => api_models::payments::AdditionalPaymentData::PayLater { klarna_sdk: Some(api_models::payments::KlarnaSdkPaymentMethod { payment_type }), }, _ => additional_payment_data, } } pub fn update_additional_payment_data_with_connector_response_pm_data( additional_payment_data: Option<serde_json::Value>, connector_response_pm_data: Option<AdditionalPaymentMethodConnectorResponse>, ) -> RouterResult<Option<serde_json::Value>> { let parsed_additional_payment_method_data = additional_payment_data .as_ref() .map(|payment_method_data| { payment_method_data .clone() .parse_value::<api_models::payments::AdditionalPaymentData>( "additional_payment_method_data", ) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to parse value into additional_payment_method_data")?; let additional_payment_method_data = parsed_additional_payment_method_data .zip(connector_response_pm_data) .map(|(additional_pm_data, connector_response_pm_data)| { add_connector_response_to_additional_payment_data( additional_pm_data, connector_response_pm_data, ) }); additional_payment_method_data .as_ref() .map(Encode::encode_to_value) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encode additional pm data") } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub async fn get_payment_method_details_from_payment_token( state: &SessionState, payment_attempt: &PaymentAttempt, payment_intent: &PaymentIntent, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<Option<(domain::PaymentMethodData, enums::PaymentMethod)>> { todo!() } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] pub async fn get_payment_method_details_from_payment_token( state: &SessionState, payment_attempt: &PaymentAttempt, payment_intent: &PaymentIntent, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<Option<(domain::PaymentMethodData, enums::PaymentMethod)>> { let hyperswitch_token = if let Some(token) = payment_attempt.payment_token.clone() { let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let key = format!( "pm_token_{}_{}_hyperswitch", token, payment_attempt .payment_method .to_owned() .get_required_value("payment_method")?, ); let token_data_string = redis_conn .get_key::<Option<String>>(&key.into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to fetch the token from redis")? .ok_or(error_stack::Report::new( errors::ApiErrorResponse::UnprocessableEntity { message: "Token is invalid or expired".to_owned(), }, ))?; let token_data_result = token_data_string .clone() .parse_struct("PaymentTokenData") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to deserialize hyperswitch token data"); let token_data = match token_data_result { Ok(data) => data, Err(e) => { // The purpose of this logic is backwards compatibility to support tokens // in redis that might be following the old format. if token_data_string.starts_with('{') { return Err(e); } else { storage::PaymentTokenData::temporary_generic(token_data_string) } } }; Some(token_data) } else { None }; let token = hyperswitch_token .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing hyperswitch_token")?; match token { storage::PaymentTokenData::TemporaryGeneric(generic_token) => { retrieve_payment_method_with_temporary_token( state, &generic_token.token, payment_intent, payment_attempt, key_store, None, ) .await } storage::PaymentTokenData::Temporary(generic_token) => { retrieve_payment_method_with_temporary_token( state, &generic_token.token, payment_intent, payment_attempt, key_store, None, ) .await } storage::PaymentTokenData::Permanent(card_token) => { retrieve_card_with_permanent_token_for_external_authentication( state, &card_token.token, payment_intent, None, key_store, storage_scheme, ) .await .map(|card| Some((card, enums::PaymentMethod::Card))) } storage::PaymentTokenData::PermanentCard(card_token) => { retrieve_card_with_permanent_token_for_external_authentication( state, &card_token.token, payment_intent, None, key_store, storage_scheme, ) .await .map(|card| Some((card, enums::PaymentMethod::Card))) } storage::PaymentTokenData::AuthBankDebit(auth_token) => { retrieve_payment_method_from_auth_service( state, key_store, &auth_token, payment_intent, &None, ) .await } storage::PaymentTokenData::WalletToken(_) => Ok(None), } } // This function validates the mandate_data with its setup_future_usage pub fn validate_mandate_data_and_future_usage( setup_future_usages: Option<api_enums::FutureUsage>, mandate_details_present: bool, ) -> Result<(), errors::ApiErrorResponse> { if mandate_details_present && (Some(api_enums::FutureUsage::OnSession) == setup_future_usages || setup_future_usages.is_none()) { Err(errors::ApiErrorResponse::PreconditionFailed { message: "`setup_future_usage` must be `off_session` for mandates".into(), }) } else { Ok(()) } } #[derive(Debug, Clone)] pub enum UnifiedAuthenticationServiceFlow { ClickToPayInitiate, ExternalAuthenticationInitiate { acquirer_details: Option<authentication::types::AcquirerDetails>, card: Box<hyperswitch_domain_models::payment_method_data::Card>, token: String, }, ExternalAuthenticationPostAuthenticate { authentication_id: String, }, ClickToPayConfirmation, } #[cfg(feature = "v1")] pub async fn decide_action_for_unified_authentication_service<F: Clone>( state: &SessionState, key_store: &domain::MerchantKeyStore, business_profile: &domain::Profile, payment_data: &mut PaymentData<F>, connector_call_type: &api::ConnectorCallType, mandate_type: Option<api_models::payments::MandateTransactionType>, do_authorisation_confirmation: &bool, ) -> RouterResult<Option<UnifiedAuthenticationServiceFlow>> { let external_authentication_flow = get_payment_external_authentication_flow_during_confirm( state, key_store, business_profile, payment_data, connector_call_type, mandate_type, ) .await?; Ok(match external_authentication_flow { Some(PaymentExternalAuthenticationFlow::PreAuthenticationFlow { acquirer_details, card, token, }) => Some( UnifiedAuthenticationServiceFlow::ExternalAuthenticationInitiate { acquirer_details, card, token, }, ), Some(PaymentExternalAuthenticationFlow::PostAuthenticationFlow { authentication_id }) => { Some( UnifiedAuthenticationServiceFlow::ExternalAuthenticationPostAuthenticate { authentication_id, }, ) } None => { if let Some(payment_method) = payment_data.payment_attempt.payment_method { if payment_method == storage_enums::PaymentMethod::Card && business_profile.is_click_to_pay_enabled && payment_data.service_details.is_some() { let should_do_uas_confirmation_call = payment_data .service_details .as_ref() .map(|details| details.is_network_confirmation_call_required()) .unwrap_or(true); if *do_authorisation_confirmation && should_do_uas_confirmation_call { Some(UnifiedAuthenticationServiceFlow::ClickToPayConfirmation) } else { Some(UnifiedAuthenticationServiceFlow::ClickToPayInitiate) } } else { None } } else { logger::info!( payment_method=?payment_data.payment_attempt.payment_method, click_to_pay_enabled=?business_profile.is_click_to_pay_enabled, "skipping unified authentication service call since payment conditions are not satisfied" ); None } } }) } pub enum PaymentExternalAuthenticationFlow { PreAuthenticationFlow { acquirer_details: Option<authentication::types::AcquirerDetails>, card: Box<hyperswitch_domain_models::payment_method_data::Card>, token: String, }, PostAuthenticationFlow { authentication_id: String, }, } #[cfg(feature = "v1")] pub async fn get_payment_external_authentication_flow_during_confirm<F: Clone>( state: &SessionState, key_store: &domain::MerchantKeyStore, business_profile: &domain::Profile, payment_data: &mut PaymentData<F>, connector_call_type: &api::ConnectorCallType, mandate_type: Option<api_models::payments::MandateTransactionType>, ) -> RouterResult<Option<PaymentExternalAuthenticationFlow>> { let authentication_id = payment_data.payment_attempt.authentication_id.clone(); let is_authentication_type_3ds = payment_data.payment_attempt.authentication_type == Some(common_enums::AuthenticationType::ThreeDs); let separate_authentication_requested = payment_data .payment_intent .request_external_three_ds_authentication .unwrap_or(false); let separate_three_ds_authentication_attempted = payment_data .payment_attempt .external_three_ds_authentication_attempted .unwrap_or(false); let connector_supports_separate_authn = authentication::utils::get_connector_data_if_separate_authn_supported(connector_call_type); logger::info!("is_pre_authn_call {:?}", authentication_id.is_none()); logger::info!( "separate_authentication_requested {:?}", separate_authentication_requested ); logger::info!( "payment connector supports external authentication: {:?}", connector_supports_separate_authn.is_some() ); let card = payment_data.payment_method_data.as_ref().and_then(|pmd| { if let domain::PaymentMethodData::Card(card) = pmd { Some(card.clone()) } else { None } }); Ok(if separate_three_ds_authentication_attempted { authentication_id.map(|authentication_id| { PaymentExternalAuthenticationFlow::PostAuthenticationFlow { authentication_id } }) } else if separate_authentication_requested && is_authentication_type_3ds && mandate_type != Some(api_models::payments::MandateTransactionType::RecurringMandateTransaction) { if let Some((connector_data, card)) = connector_supports_separate_authn.zip(card) { let token = payment_data .token .clone() .get_required_value("token") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "payment_data.token should not be None while making pre authentication call", )?; let payment_connector_mca = get_merchant_connector_account( state, &business_profile.merchant_id, None, key_store, business_profile.get_id(), connector_data.connector_name.to_string().as_str(), connector_data.merchant_connector_id.as_ref(), ) .await?; let acquirer_details = payment_connector_mca .get_metadata() .clone() .and_then(|metadata| { metadata .peek() .clone() .parse_value::<authentication::types::AcquirerDetails>("AcquirerDetails") .change_context(errors::ApiErrorResponse::PreconditionFailed { message: "acquirer_bin and acquirer_merchant_id not found in Payment Connector's Metadata" .to_string(), }) .inspect_err(|err| { logger::error!( "Failed to parse acquirer details from Payment Connector's Metadata: {:?}", err ); }) .ok() }); Some(PaymentExternalAuthenticationFlow::PreAuthenticationFlow { card: Box::new(card), token, acquirer_details, }) } else { None } } else { None }) } pub fn get_redis_key_for_extended_card_info( merchant_id: &id_type::MerchantId, payment_id: &id_type::PaymentId, ) -> String { format!( "{}_{}_extended_card_info", merchant_id.get_string_repr(), payment_id.get_string_repr() ) } pub fn check_integrity_based_on_flow<T, Request>( request: &Request, payment_response_data: &Result<PaymentsResponseData, ErrorResponse>, ) -> Result<(), common_utils::errors::IntegrityCheckError> where T: FlowIntegrity, Request: GetIntegrityObject<T> + CheckIntegrity<Request, T>, { let connector_transaction_id = match payment_response_data { Ok(resp_data) => match resp_data { PaymentsResponseData::TransactionResponse { connector_response_reference_id, .. } => connector_response_reference_id, PaymentsResponseData::TransactionUnresolvedResponse { connector_response_reference_id, .. } => connector_response_reference_id, PaymentsResponseData::PreProcessingResponse { connector_response_reference_id, .. } => connector_response_reference_id, _ => &None, }, Err(_) => &None, }; request.check_integrity(request, connector_transaction_id.to_owned()) } pub async fn config_skip_saving_wallet_at_connector( db: &dyn StorageInterface, merchant_id: &id_type::MerchantId, ) -> CustomResult<Option<Vec<storage_enums::PaymentMethodType>>, errors::ApiErrorResponse> { let config = db .find_config_by_key_unwrap_or( &merchant_id.get_skip_saving_wallet_at_connector_key(), Some("[]".to_string()), ) .await; Ok(match config { Ok(conf) => Some( serde_json::from_str::<Vec<storage_enums::PaymentMethodType>>(&conf.config) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("skip_save_wallet_at_connector config parsing failed")?, ), Err(error) => { logger::error!(?error); None } }) } #[cfg(feature = "v1")] pub async fn override_setup_future_usage_to_on_session<F, D>( db: &dyn StorageInterface, payment_data: &mut D, ) -> CustomResult<(), errors::ApiErrorResponse> where F: Clone, D: payments::OperationSessionGetters<F> + payments::OperationSessionSetters<F> + Send, { if payment_data.get_payment_intent().setup_future_usage == Some(enums::FutureUsage::OffSession) { let skip_saving_wallet_at_connector_optional = config_skip_saving_wallet_at_connector( db, &payment_data.get_payment_intent().merchant_id, ) .await?; if let Some(skip_saving_wallet_at_connector) = skip_saving_wallet_at_connector_optional { if let Some(payment_method_type) = payment_data.get_payment_attempt().get_payment_method_type() { if skip_saving_wallet_at_connector.contains(&payment_method_type) { logger::debug!("Override setup_future_usage from off_session to on_session based on the merchant's skip_saving_wallet_at_connector configuration to avoid creating a connector mandate."); payment_data .set_setup_future_usage_in_payment_intent(enums::FutureUsage::OnSession); } } }; }; Ok(()) } #[cfg(feature = "v1")] pub async fn validate_merchant_connector_ids_in_connector_mandate_details( state: &SessionState, key_store: &domain::MerchantKeyStore, connector_mandate_details: &api_models::payment_methods::CommonMandateReference, merchant_id: &id_type::MerchantId, card_network: Option<api_enums::CardNetwork>, ) -> CustomResult<(), errors::ApiErrorResponse> { let db = &*state.store; let merchant_connector_account_list = db .find_merchant_connector_account_by_merchant_id_and_disabled_list( &state.into(), merchant_id, true, key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; let merchant_connector_account_details_hash_map: std::collections::HashMap< id_type::MerchantConnectorAccountId, domain::MerchantConnectorAccount, > = merchant_connector_account_list .iter() .map(|merchant_connector_account| { ( merchant_connector_account.get_id(), merchant_connector_account.clone(), ) }) .collect(); if let Some(payment_mandate_reference) = &connector_mandate_details.payments { let payments_map = payment_mandate_reference.0.clone(); for (migrating_merchant_connector_id, migrating_connector_mandate_details) in payments_map { match ( card_network.clone(), merchant_connector_account_details_hash_map.get(&migrating_merchant_connector_id), ) { (Some(enums::CardNetwork::Discover), Some(merchant_connector_account_details)) => { if let ("cybersource", None) = ( merchant_connector_account_details.connector_name.as_str(), migrating_connector_mandate_details .original_payment_authorized_amount .zip( migrating_connector_mandate_details .original_payment_authorized_currency, ), ) { Err(errors::ApiErrorResponse::MissingRequiredFields { field_names: vec![ "original_payment_authorized_currency", "original_payment_authorized_amount", ], }) .attach_printable(format!( "Invalid connector_mandate_details provided for connector {:?}", migrating_merchant_connector_id ))? } } (_, Some(_)) => (), (_, None) => Err(errors::ApiErrorResponse::InvalidDataValue { field_name: "merchant_connector_id", }) .attach_printable_lazy(|| { format!( "{:?} invalid merchant connector id in connector_mandate_details", migrating_merchant_connector_id ) })?, } } } else { router_env::logger::error!("payment mandate reference not found"); } Ok(()) } pub fn validate_platform_request_for_marketplace( amount: api::Amount, split_payments: Option<common_types::payments::SplitPaymentsRequest>, ) -> Result<(), errors::ApiErrorResponse> { match split_payments { Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment( stripe_split_payment, )) => match amount { api::Amount::Zero => { if stripe_split_payment.application_fees.get_amount_as_i64() != 0 { return Err(errors::ApiErrorResponse::InvalidDataValue { field_name: "split_payments.stripe_split_payment.application_fees", }); } } api::Amount::Value(amount) => { if stripe_split_payment.application_fees.get_amount_as_i64() > amount.into() { return Err(errors::ApiErrorResponse::InvalidDataValue { field_name: "split_payments.stripe_split_payment.application_fees", }); } } }, Some(common_types::payments::SplitPaymentsRequest::AdyenSplitPayment( adyen_split_payment, )) => { let total_split_amount: i64 = adyen_split_payment .split_items .iter() .map(|split_item| { split_item .amount .unwrap_or(MinorUnit::new(0)) .get_amount_as_i64() }) .sum(); match amount { api::Amount::Zero => { if total_split_amount != 0 { return Err(errors::ApiErrorResponse::InvalidDataValue { field_name: "Sum of split amounts should be equal to the total amount", }); } } api::Amount::Value(amount) => { let i64_amount: i64 = amount.into(); if !adyen_split_payment.split_items.is_empty() && i64_amount != total_split_amount { return Err(errors::ApiErrorResponse::PreconditionFailed { message: "Sum of split amounts should be equal to the total amount" .to_string(), }); } } }; adyen_split_payment .split_items .iter() .try_for_each(|split_item| { match split_item.split_type { common_enums::AdyenSplitType::BalanceAccount => { if split_item.account.is_none() { return Err(errors::ApiErrorResponse::MissingRequiredField { field_name: "split_payments.adyen_split_payment.split_items.account", }); } } common_enums::AdyenSplitType::Commission | enums::AdyenSplitType::Vat | enums::AdyenSplitType::TopUp => { if split_item.amount.is_none() { return Err(errors::ApiErrorResponse::MissingRequiredField { field_name: "split_payments.adyen_split_payment.split_items.amount", }); } if let enums::AdyenSplitType::TopUp = split_item.split_type { if split_item.account.is_none() { return Err(errors::ApiErrorResponse::MissingRequiredField { field_name: "split_payments.adyen_split_payment.split_items.account", }); } if adyen_split_payment.store.is_some() { return Err(errors::ApiErrorResponse::PreconditionFailed { message: "Topup split payment is not available via Adyen Platform" .to_string(), }); } } } enums::AdyenSplitType::AcquiringFees | enums::AdyenSplitType::PaymentFee | enums::AdyenSplitType::AdyenFees | enums::AdyenSplitType::AdyenCommission | enums::AdyenSplitType::AdyenMarkup | enums::AdyenSplitType::Interchange | enums::AdyenSplitType::SchemeFee => {} }; Ok(()) })?; } Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment( xendit_split_payment, )) => match xendit_split_payment { common_types::payments::XenditSplitRequest::MultipleSplits( xendit_multiple_split_payment, ) => { match amount { api::Amount::Zero => { let total_split_amount: i64 = xendit_multiple_split_payment .routes .iter() .map(|route| { route .flat_amount .unwrap_or(MinorUnit::new(0)) .get_amount_as_i64() }) .sum(); if total_split_amount != 0 { return Err(errors::ApiErrorResponse::InvalidDataValue { field_name: "Sum of split amounts should be equal to the total amount", }); } } api::Amount::Value(amount) => { let total_payment_amount: i64 = amount.into(); let total_split_amount: i64 = xendit_multiple_split_payment .routes .into_iter() .map(|route| { if route.flat_amount.is_none() && route.percent_amount.is_none() { Err(errors::ApiErrorResponse::InvalidRequestData { message: "Expected either split_payments.xendit_split_payment.routes.flat_amount or split_payments.xendit_split_payment.routes.percent_amount to be provided".to_string(), }) } else if route.flat_amount.is_some() && route.percent_amount.is_some(){ Err(errors::ApiErrorResponse::InvalidRequestData { message: "Expected either split_payments.xendit_split_payment.routes.flat_amount or split_payments.xendit_split_payment.routes.percent_amount, but not both".to_string(), }) } else { Ok(route .flat_amount .map(|amount| amount.get_amount_as_i64()) .or(route.percent_amount.map(|percentage| (percentage * total_payment_amount) / 100)) .unwrap_or(0)) } }) .collect::<Result<Vec<i64>, _>>()? .into_iter() .sum(); if total_payment_amount < total_split_amount { return Err(errors::ApiErrorResponse::PreconditionFailed { message: "The sum of split amounts should not exceed the total amount" .to_string(), }); } } }; } common_types::payments::XenditSplitRequest::SingleSplit(_) => (), }, None => (), } Ok(()) } pub async fn is_merchant_eligible_authentication_service( merchant_id: &id_type::MerchantId, state: &SessionState, ) -> RouterResult<bool> { let merchants_eligible_for_authentication_service = state .store .as_ref() .find_config_by_key_unwrap_or( consts::AUTHENTICATION_SERVICE_ELIGIBLE_CONFIG, Some("[]".to_string()), ) .await; let auth_eligible_array: Vec<String> = match merchants_eligible_for_authentication_service { Ok(config) => serde_json::from_str(&config.config) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to parse authentication service config")?, Err(err) => { logger::error!( "Error fetching authentication service enabled merchant config {:?}", err ); Vec::new() } }; Ok(auth_eligible_array.contains(&merchant_id.get_string_repr().to_owned())) } #[cfg(feature = "v1")] pub async fn validate_allowed_payment_method_types_request( state: &SessionState, profile_id: &id_type::ProfileId, merchant_account: &domain::MerchantAccount, merchant_key_store: &domain::MerchantKeyStore, allowed_payment_method_types: Option<Vec<common_enums::PaymentMethodType>>, ) -> CustomResult<(), errors::ApiErrorResponse> { if let Some(allowed_payment_method_types) = allowed_payment_method_types { let db = &*state.store; let all_connector_accounts = db .find_merchant_connector_account_by_merchant_id_and_disabled_list( &state.into(), merchant_account.get_id(), false, merchant_key_store, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to fetch merchant connector account for given merchant id")?; let filtered_connector_accounts = all_connector_accounts .filter_based_on_profile_and_connector_type( profile_id, ConnectorType::PaymentProcessor, ); let supporting_payment_method_types: HashSet<_> = filtered_connector_accounts .iter() .flat_map(|connector_account| { connector_account .payment_methods_enabled .clone() .unwrap_or_default() .into_iter() .map(|payment_methods_enabled| { payment_methods_enabled .parse_value::<api_models::admin::PaymentMethodsEnabled>( "payment_methods_enabled", ) }) .filter_map(|parsed_payment_method_result| { parsed_payment_method_result .inspect_err(|err| { logger::error!( "Unable to deserialize payment methods enabled: {:?}", err ); }) .ok() }) .flat_map(|parsed_payment_methods_enabled| { parsed_payment_methods_enabled .payment_method_types .unwrap_or_default() .into_iter() .map(|payment_method_type| payment_method_type.payment_method_type) }) }) .collect(); let unsupported_payment_methods: Vec<_> = allowed_payment_method_types .iter() .filter(|allowed_pmt| !supporting_payment_method_types.contains(allowed_pmt)) .collect(); if !unsupported_payment_methods.is_empty() { metrics::PAYMENT_METHOD_TYPES_MISCONFIGURATION_METRIC.add( 1, router_env::metric_attributes!(("merchant_id", merchant_account.get_id().clone())), ); } fp_utils::when( unsupported_payment_methods.len() == allowed_payment_method_types.len(), || { Err(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) .attach_printable(format!( "None of the allowed payment method types {:?} are configured for this merchant connector account.", allowed_payment_method_types )) }, )?; } Ok(()) }
58,180
1,601
hyperswitch
crates/router/src/core/payments/routing.rs
.rs
mod transformers; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use std::collections::hash_map; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use std::hash::{Hash, Hasher}; use std::{collections::HashMap, str::FromStr, sync::Arc}; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use api_models::routing as api_routing; use api_models::{ admin as admin_api, enums::{self as api_enums, CountryAlpha2}, routing::ConnectorSelection, }; #[cfg(feature = "dynamic_routing")] use common_utils::ext_traits::AsyncExt; use diesel_models::enums as storage_enums; use error_stack::ResultExt; use euclid::{ backend::{self, inputs as dsl_inputs, EuclidBackend}, dssa::graph::{self as euclid_graph, CgraphExt}, enums as euclid_enums, frontend::{ast, dir as euclid_dir}, }; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use external_services::grpc_client::dynamic_routing::{ contract_routing_client::ContractBasedDynamicRouting, success_rate_client::{CalSuccessRateResponse, SuccessBasedDynamicRouting}, DynamicRoutingError, }; use hyperswitch_domain_models::address::Address; use kgraph_utils::{ mca as mca_graph, transformers::{IntoContext, IntoDirValue}, types::CountryCurrencyFilter, }; use masking::PeekInterface; use rand::distributions::{self, Distribution}; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use rand::SeedableRng; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use router_env::{instrument, tracing}; use rustc_hash::FxHashMap; use storage_impl::redis::cache::{CacheKey, CGRAPH_CACHE, ROUTING_CACHE}; #[cfg(feature = "v2")] use crate::core::admin; #[cfg(feature = "payouts")] use crate::core::payouts; 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, }; pub enum CachedAlgorithm { Single(Box<routing_types::RoutableConnectorChoice>), Priority(Vec<routing_types::RoutableConnectorChoice>), VolumeSplit(Vec<routing_types::ConnectorVolumeSplit>), Advanced(backend::VirInterpreterBackend<ConnectorSelection>), } #[cfg(feature = "v1")] pub struct SessionFlowRoutingInput<'a> { pub state: &'a SessionState, pub country: Option<CountryAlpha2>, pub key_store: &'a domain::MerchantKeyStore, pub merchant_account: &'a domain::MerchantAccount, pub payment_attempt: &'a oss_storage::PaymentAttempt, pub payment_intent: &'a oss_storage::PaymentIntent, pub chosen: api::SessionConnectorDatas, } #[cfg(feature = "v2")] pub struct SessionFlowRoutingInput<'a> { pub country: Option<CountryAlpha2>, pub payment_intent: &'a oss_storage::PaymentIntent, pub chosen: api::SessionConnectorDatas, } #[allow(dead_code)] #[cfg(feature = "v1")] pub struct SessionRoutingPmTypeInput<'a> { state: &'a SessionState, key_store: &'a domain::MerchantKeyStore, attempt_id: &'a str, routing_algorithm: &'a MerchantAccountRoutingAlgorithm, backend_input: dsl_inputs::BackendInput, allowed_connectors: FxHashMap<String, api::GetToken>, profile_id: &'a common_utils::id_type::ProfileId, } #[cfg(feature = "v2")] pub struct SessionRoutingPmTypeInput<'a> { routing_algorithm: &'a MerchantAccountRoutingAlgorithm, backend_input: dsl_inputs::BackendInput, allowed_connectors: FxHashMap<String, api::GetToken>, profile_id: &'a common_utils::id_type::ProfileId, } type RoutingResult<O> = oss_errors::CustomResult<O, errors::RoutingError>; #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(untagged)] enum MerchantAccountRoutingAlgorithm { V1(routing_types::RoutingAlgorithmRef), } #[cfg(feature = "v1")] impl Default for MerchantAccountRoutingAlgorithm { fn default() -> Self { Self::V1(routing_types::RoutingAlgorithmRef::default()) } } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(untagged)] enum MerchantAccountRoutingAlgorithm { V1(Option<common_utils::id_type::RoutingId>), } #[cfg(feature = "payouts")] pub fn make_dsl_input_for_payouts( payout_data: &payouts::PayoutData, ) -> RoutingResult<dsl_inputs::BackendInput> { let mandate = dsl_inputs::MandateData { mandate_acceptance_type: None, mandate_type: None, payment_type: None, }; let metadata = payout_data .payouts .metadata .clone() .map(|val| val.parse_value("routing_parameters")) .transpose() .change_context(errors::RoutingError::MetadataParsingError) .attach_printable("Unable to parse routing_parameters from metadata of payouts") .unwrap_or(None); let payment = dsl_inputs::PaymentInput { amount: payout_data.payouts.amount, card_bin: None, currency: payout_data.payouts.destination_currency, authentication_type: None, capture_method: None, business_country: payout_data .payout_attempt .business_country .map(api_enums::Country::from_alpha2), billing_country: payout_data .billing_address .as_ref() .and_then(|bic| bic.country) .map(api_enums::Country::from_alpha2), business_label: payout_data.payout_attempt.business_label.clone(), setup_future_usage: None, }; let payment_method = dsl_inputs::PaymentMethodInput { payment_method: payout_data .payouts .payout_type .map(api_enums::PaymentMethod::foreign_from), payment_method_type: payout_data .payout_method_data .as_ref() .map(api_enums::PaymentMethodType::foreign_from), card_network: None, }; Ok(dsl_inputs::BackendInput { mandate, metadata, payment, payment_method, }) } #[cfg(feature = "v2")] pub fn make_dsl_input( payments_dsl_input: &routing::PaymentsDslInput<'_>, ) -> RoutingResult<dsl_inputs::BackendInput> { let mandate_data = dsl_inputs::MandateData { mandate_acceptance_type: payments_dsl_input.setup_mandate.as_ref().and_then( |mandate_data| { mandate_data .customer_acceptance .as_ref() .map(|customer_accept| match customer_accept.acceptance_type { hyperswitch_domain_models::mandates::AcceptanceType::Online => { euclid_enums::MandateAcceptanceType::Online } hyperswitch_domain_models::mandates::AcceptanceType::Offline => { euclid_enums::MandateAcceptanceType::Offline } }) }, ), mandate_type: payments_dsl_input .setup_mandate .as_ref() .and_then(|mandate_data| { mandate_data .mandate_type .clone() .map(|mandate_type| match mandate_type { hyperswitch_domain_models::mandates::MandateDataType::SingleUse(_) => { euclid_enums::MandateType::SingleUse } hyperswitch_domain_models::mandates::MandateDataType::MultiUse(_) => { euclid_enums::MandateType::MultiUse } }) }), payment_type: Some( if payments_dsl_input .recurring_details .as_ref() .is_some_and(|data| { matches!( data, api_models::mandates::RecurringDetails::ProcessorPaymentToken(_) ) }) { euclid_enums::PaymentType::PptMandate } else { payments_dsl_input.setup_mandate.map_or_else( || euclid_enums::PaymentType::NonMandate, |_| euclid_enums::PaymentType::SetupMandate, ) }, ), }; let payment_method_input = dsl_inputs::PaymentMethodInput { payment_method: Some(payments_dsl_input.payment_attempt.payment_method_type), payment_method_type: Some(payments_dsl_input.payment_attempt.payment_method_subtype), card_network: payments_dsl_input .payment_method_data .as_ref() .and_then(|pm_data| match pm_data { domain::PaymentMethodData::Card(card) => card.card_network.clone(), _ => None, }), }; let payment_input = dsl_inputs::PaymentInput { amount: payments_dsl_input .payment_attempt .amount_details .get_net_amount(), card_bin: payments_dsl_input.payment_method_data.as_ref().and_then( |pm_data| match pm_data { domain::PaymentMethodData::Card(card) => Some(card.card_number.get_card_isin()), _ => None, }, ), currency: payments_dsl_input.currency, authentication_type: Some(payments_dsl_input.payment_attempt.authentication_type), capture_method: Some(payments_dsl_input.payment_intent.capture_method), business_country: None, billing_country: payments_dsl_input .address .get_payment_method_billing() .and_then(|billing_address| billing_address.address.as_ref()) .and_then(|address_details| address_details.country) .map(api_enums::Country::from_alpha2), business_label: None, setup_future_usage: Some(payments_dsl_input.payment_intent.setup_future_usage), }; let metadata = payments_dsl_input .payment_intent .metadata .clone() .map(|value| value.parse_value("routing_parameters")) .transpose() .change_context(errors::RoutingError::MetadataParsingError) .attach_printable("Unable to parse routing_parameters from metadata of payment_intent") .unwrap_or(None); Ok(dsl_inputs::BackendInput { metadata, payment: payment_input, payment_method: payment_method_input, mandate: mandate_data, }) } #[cfg(feature = "v1")] pub fn make_dsl_input( payments_dsl_input: &routing::PaymentsDslInput<'_>, ) -> RoutingResult<dsl_inputs::BackendInput> { let mandate_data = dsl_inputs::MandateData { mandate_acceptance_type: payments_dsl_input.setup_mandate.as_ref().and_then( |mandate_data| { mandate_data .customer_acceptance .as_ref() .map(|cat| match cat.acceptance_type { hyperswitch_domain_models::mandates::AcceptanceType::Online => { euclid_enums::MandateAcceptanceType::Online } hyperswitch_domain_models::mandates::AcceptanceType::Offline => { euclid_enums::MandateAcceptanceType::Offline } }) }, ), mandate_type: payments_dsl_input .setup_mandate .as_ref() .and_then(|mandate_data| { mandate_data.mandate_type.clone().map(|mt| match mt { hyperswitch_domain_models::mandates::MandateDataType::SingleUse(_) => { euclid_enums::MandateType::SingleUse } hyperswitch_domain_models::mandates::MandateDataType::MultiUse(_) => { euclid_enums::MandateType::MultiUse } }) }), payment_type: Some( if payments_dsl_input .recurring_details .as_ref() .is_some_and(|data| { matches!( data, api_models::mandates::RecurringDetails::ProcessorPaymentToken(_) ) }) { euclid_enums::PaymentType::PptMandate } else { payments_dsl_input.setup_mandate.map_or_else( || euclid_enums::PaymentType::NonMandate, |_| euclid_enums::PaymentType::SetupMandate, ) }, ), }; let payment_method_input = dsl_inputs::PaymentMethodInput { payment_method: payments_dsl_input.payment_attempt.payment_method, payment_method_type: payments_dsl_input.payment_attempt.payment_method_type, card_network: payments_dsl_input .payment_method_data .as_ref() .and_then(|pm_data| match pm_data { domain::PaymentMethodData::Card(card) => card.card_network.clone(), _ => None, }), }; let payment_input = dsl_inputs::PaymentInput { amount: payments_dsl_input.payment_attempt.get_total_amount(), card_bin: payments_dsl_input.payment_method_data.as_ref().and_then( |pm_data| match pm_data { domain::PaymentMethodData::Card(card) => { Some(card.card_number.peek().chars().take(6).collect()) } _ => None, }, ), currency: payments_dsl_input.currency, authentication_type: payments_dsl_input.payment_attempt.authentication_type, capture_method: payments_dsl_input .payment_attempt .capture_method .and_then(|cm| cm.foreign_into()), business_country: payments_dsl_input .payment_intent .business_country .map(api_enums::Country::from_alpha2), billing_country: payments_dsl_input .address .get_payment_method_billing() .and_then(|bic| bic.address.as_ref()) .and_then(|add| add.country) .map(api_enums::Country::from_alpha2), business_label: payments_dsl_input.payment_intent.business_label.clone(), setup_future_usage: payments_dsl_input.payment_intent.setup_future_usage, }; let metadata = payments_dsl_input .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); Ok(dsl_inputs::BackendInput { metadata, payment: payment_input, payment_method: payment_method_input, mandate: mandate_data, }) } pub async fn perform_static_routing_v1( state: &SessionState, merchant_id: &common_utils::id_type::MerchantId, algorithm_id: Option<&common_utils::id_type::RoutingId>, business_profile: &domain::Profile, transaction_data: &routing::TransactionData<'_>, ) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> { let algorithm_id = if let Some(id) = algorithm_id { id } else { #[cfg(feature = "v1")] let fallback_config = routing::helpers::get_merchant_default_config( &*state.clone().store, business_profile.get_id().get_string_repr(), &api_enums::TransactionType::from(transaction_data), ) .await .change_context(errors::RoutingError::FallbackConfigFetchFailed)?; #[cfg(feature = "v2")] let fallback_config = admin::ProfileWrapper::new(business_profile.clone()) .get_default_fallback_list_of_connector_under_profile() .change_context(errors::RoutingError::FallbackConfigFetchFailed)?; return Ok(fallback_config); }; let cached_algorithm = ensure_algorithm_cached_v1( state, merchant_id, algorithm_id, business_profile.get_id(), &api_enums::TransactionType::from(transaction_data), ) .await?; Ok(match cached_algorithm.as_ref() { CachedAlgorithm::Single(conn) => vec![(**conn).clone()], CachedAlgorithm::Priority(plist) => plist.clone(), CachedAlgorithm::VolumeSplit(splits) => perform_volume_split(splits.to_vec()) .change_context(errors::RoutingError::ConnectorSelectionFailed)?, CachedAlgorithm::Advanced(interpreter) => { let backend_input = match transaction_data { routing::TransactionData::Payment(payment_data) => make_dsl_input(payment_data)?, #[cfg(feature = "payouts")] routing::TransactionData::Payout(payout_data) => { make_dsl_input_for_payouts(payout_data)? } }; execute_dsl_and_get_connector_v1(backend_input, interpreter)? } }) } async fn ensure_algorithm_cached_v1( state: &SessionState, merchant_id: &common_utils::id_type::MerchantId, algorithm_id: &common_utils::id_type::RoutingId, profile_id: &common_utils::id_type::ProfileId, transaction_type: &api_enums::TransactionType, ) -> RoutingResult<Arc<CachedAlgorithm>> { let key = { match transaction_type { common_enums::TransactionType::Payment => { format!( "routing_config_{}_{}", merchant_id.get_string_repr(), profile_id.get_string_repr(), ) } #[cfg(feature = "payouts")] common_enums::TransactionType::Payout => { format!( "routing_config_po_{}_{}", merchant_id.get_string_repr(), profile_id.get_string_repr() ) } } }; let cached_algorithm = ROUTING_CACHE .get_val::<Arc<CachedAlgorithm>>(CacheKey { key: key.clone(), prefix: state.tenant.redis_key_prefix.clone(), }) .await; let algorithm = if let Some(algo) = cached_algorithm { algo } else { refresh_routing_cache_v1(state, key.clone(), algorithm_id, profile_id).await? }; Ok(algorithm) } pub fn perform_straight_through_routing( algorithm: &routing_types::StraightThroughAlgorithm, creds_identifier: Option<&str>, ) -> RoutingResult<(Vec<routing_types::RoutableConnectorChoice>, bool)> { Ok(match algorithm { routing_types::StraightThroughAlgorithm::Single(conn) => { (vec![(**conn).clone()], creds_identifier.is_none()) } routing_types::StraightThroughAlgorithm::Priority(conns) => (conns.clone(), true), routing_types::StraightThroughAlgorithm::VolumeSplit(splits) => ( perform_volume_split(splits.to_vec()) .change_context(errors::RoutingError::ConnectorSelectionFailed) .attach_printable( "Volume Split connector selection error in straight through routing", )?, true, ), }) } pub fn perform_routing_for_single_straight_through_algorithm( algorithm: &routing_types::StraightThroughAlgorithm, ) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> { Ok(match algorithm { routing_types::StraightThroughAlgorithm::Single(connector) => vec![(**connector).clone()], routing_types::StraightThroughAlgorithm::Priority(_) | routing_types::StraightThroughAlgorithm::VolumeSplit(_) => { Err(errors::RoutingError::DslIncorrectSelectionAlgorithm) .attach_printable("Unsupported algorithm received as a result of static routing")? } }) } fn execute_dsl_and_get_connector_v1( backend_input: dsl_inputs::BackendInput, interpreter: &backend::VirInterpreterBackend<ConnectorSelection>, ) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> { let routing_output: routing_types::RoutingAlgorithm = interpreter .execute(backend_input) .map(|out| out.connector_selection.foreign_into()) .change_context(errors::RoutingError::DslExecutionError)?; Ok(match routing_output { routing_types::RoutingAlgorithm::Priority(plist) => plist, routing_types::RoutingAlgorithm::VolumeSplit(splits) => perform_volume_split(splits) .change_context(errors::RoutingError::DslFinalConnectorSelectionFailed)?, _ => Err(errors::RoutingError::DslIncorrectSelectionAlgorithm) .attach_printable("Unsupported algorithm received as a result of static routing")?, }) } pub async fn refresh_routing_cache_v1( state: &SessionState, key: String, algorithm_id: &common_utils::id_type::RoutingId, profile_id: &common_utils::id_type::ProfileId, ) -> RoutingResult<Arc<CachedAlgorithm>> { let algorithm = { let algorithm = state .store .find_routing_algorithm_by_profile_id_algorithm_id(profile_id, algorithm_id) .await .change_context(errors::RoutingError::DslMissingInDb)?; let algorithm: routing_types::RoutingAlgorithm = algorithm .algorithm_data .parse_value("RoutingAlgorithm") .change_context(errors::RoutingError::DslParsingError)?; algorithm }; let cached_algorithm = match algorithm { routing_types::RoutingAlgorithm::Single(conn) => CachedAlgorithm::Single(conn), routing_types::RoutingAlgorithm::Priority(plist) => CachedAlgorithm::Priority(plist), routing_types::RoutingAlgorithm::VolumeSplit(splits) => { CachedAlgorithm::VolumeSplit(splits) } routing_types::RoutingAlgorithm::Advanced(program) => { let interpreter = backend::VirInterpreterBackend::with_program(program) .change_context(errors::RoutingError::DslBackendInitError) .attach_printable("Error initializing DSL interpreter backend")?; CachedAlgorithm::Advanced(interpreter) } }; let arc_cached_algorithm = Arc::new(cached_algorithm); ROUTING_CACHE .push( CacheKey { key, prefix: state.tenant.redis_key_prefix.clone(), }, arc_cached_algorithm.clone(), ) .await; Ok(arc_cached_algorithm) } #[cfg(all(feature = "v1", feature = "dynamic_routing"))] pub fn perform_dynamic_routing_volume_split( splits: Vec<api_models::routing::RoutingVolumeSplit>, rng_seed: Option<&str>, ) -> RoutingResult<api_models::routing::RoutingVolumeSplit> { let weights: Vec<u8> = splits.iter().map(|sp| sp.split).collect(); let weighted_index = distributions::WeightedIndex::new(weights) .change_context(errors::RoutingError::VolumeSplitFailed) .attach_printable("Error creating weighted distribution for volume split")?; let idx = if let Some(seed) = rng_seed { let mut hasher = hash_map::DefaultHasher::new(); seed.hash(&mut hasher); let hash = hasher.finish(); let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(hash); weighted_index.sample(&mut rng) } else { let mut rng = rand::thread_rng(); weighted_index.sample(&mut rng) }; let routing_choice = *splits .get(idx) .ok_or(errors::RoutingError::VolumeSplitFailed) .attach_printable("Volume split index lookup failed")?; Ok(routing_choice) } pub fn perform_volume_split( mut splits: Vec<routing_types::ConnectorVolumeSplit>, ) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> { let weights: Vec<u8> = splits.iter().map(|sp| sp.split).collect(); let weighted_index = distributions::WeightedIndex::new(weights) .change_context(errors::RoutingError::VolumeSplitFailed) .attach_printable("Error creating weighted distribution for volume split")?; let mut rng = rand::thread_rng(); let idx = weighted_index.sample(&mut rng); splits .get(idx) .ok_or(errors::RoutingError::VolumeSplitFailed) .attach_printable("Volume split index lookup failed")?; // Panic Safety: We have performed a `get(idx)` operation just above which will // ensure that the index is always present, else throw an error. let removed = splits.remove(idx); splits.insert(0, removed); Ok(splits.into_iter().map(|sp| sp.connector).collect()) } // #[cfg(feature = "v1")] pub async fn get_merchant_cgraph( state: &SessionState, key_store: &domain::MerchantKeyStore, profile_id: &common_utils::id_type::ProfileId, transaction_type: &api_enums::TransactionType, ) -> RoutingResult<Arc<hyperswitch_constraint_graph::ConstraintGraph<euclid_dir::DirValue>>> { let merchant_id = &key_store.merchant_id; let key = { match transaction_type { api_enums::TransactionType::Payment => { format!( "cgraph_{}_{}", merchant_id.get_string_repr(), profile_id.get_string_repr() ) } #[cfg(feature = "payouts")] api_enums::TransactionType::Payout => { format!( "cgraph_po_{}_{}", merchant_id.get_string_repr(), profile_id.get_string_repr() ) } } }; let cached_cgraph = CGRAPH_CACHE .get_val::<Arc<hyperswitch_constraint_graph::ConstraintGraph<euclid_dir::DirValue>>>( CacheKey { key: key.clone(), prefix: state.tenant.redis_key_prefix.clone(), }, ) .await; let cgraph = if let Some(graph) = cached_cgraph { graph } else { refresh_cgraph_cache(state, key_store, key.clone(), profile_id, transaction_type).await? }; Ok(cgraph) } // #[cfg(feature = "v1")] pub async fn refresh_cgraph_cache( state: &SessionState, key_store: &domain::MerchantKeyStore, key: String, profile_id: &common_utils::id_type::ProfileId, transaction_type: &api_enums::TransactionType, ) -> RoutingResult<Arc<hyperswitch_constraint_graph::ConstraintGraph<euclid_dir::DirValue>>> { let mut merchant_connector_accounts = state .store .find_merchant_connector_account_by_merchant_id_and_disabled_list( &state.into(), &key_store.merchant_id, false, key_store, ) .await .change_context(errors::RoutingError::KgraphCacheRefreshFailed)?; match transaction_type { api_enums::TransactionType::Payment => { merchant_connector_accounts.retain(|mca| { mca.connector_type != storage_enums::ConnectorType::PaymentVas && mca.connector_type != storage_enums::ConnectorType::PaymentMethodAuth && mca.connector_type != storage_enums::ConnectorType::PayoutProcessor && mca.connector_type != storage_enums::ConnectorType::AuthenticationProcessor }); } #[cfg(feature = "payouts")] api_enums::TransactionType::Payout => { merchant_connector_accounts .retain(|mca| mca.connector_type == storage_enums::ConnectorType::PayoutProcessor); } }; let connector_type = match transaction_type { api_enums::TransactionType::Payment => common_enums::ConnectorType::PaymentProcessor, #[cfg(feature = "payouts")] api_enums::TransactionType::Payout => common_enums::ConnectorType::PayoutProcessor, }; let merchant_connector_accounts = merchant_connector_accounts .filter_based_on_profile_and_connector_type(profile_id, connector_type); let api_mcas = merchant_connector_accounts .into_iter() .map(admin_api::MerchantConnectorResponse::foreign_try_from) .collect::<Result<Vec<_>, _>>() .change_context(errors::RoutingError::KgraphCacheRefreshFailed)?; let connector_configs = state .conf .pm_filters .0 .clone() .into_iter() .filter(|(key, _)| key != "default") .map(|(key, value)| { let key = api_enums::RoutableConnectors::from_str(&key) .map_err(|_| errors::RoutingError::InvalidConnectorName(key))?; Ok((key, value.foreign_into())) }) .collect::<Result<HashMap<_, _>, errors::RoutingError>>()?; let default_configs = state .conf .pm_filters .0 .get("default") .cloned() .map(ForeignFrom::foreign_from); let config_pm_filters = CountryCurrencyFilter { connector_configs, default_configs, }; let cgraph = Arc::new( mca_graph::make_mca_graph(api_mcas, &config_pm_filters) .change_context(errors::RoutingError::KgraphCacheRefreshFailed) .attach_printable("when construction cgraph")?, ); CGRAPH_CACHE .push( CacheKey { key, prefix: state.tenant.redis_key_prefix.clone(), }, Arc::clone(&cgraph), ) .await; Ok(cgraph) } #[allow(clippy::too_many_arguments)] pub async fn perform_cgraph_filtering( state: &SessionState, key_store: &domain::MerchantKeyStore, chosen: Vec<routing_types::RoutableConnectorChoice>, backend_input: dsl_inputs::BackendInput, eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>, profile_id: &common_utils::id_type::ProfileId, transaction_type: &api_enums::TransactionType, ) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> { let context = euclid_graph::AnalysisContext::from_dir_values( backend_input .into_context() .change_context(errors::RoutingError::KgraphAnalysisError)?, ); let cached_cgraph = get_merchant_cgraph(state, key_store, profile_id, transaction_type).await?; let mut final_selection = Vec::<routing_types::RoutableConnectorChoice>::new(); for choice in chosen { let routable_connector = choice.connector; let euclid_choice: ast::ConnectorChoice = choice.clone().foreign_into(); let dir_val = euclid_choice .into_dir_value() .change_context(errors::RoutingError::KgraphAnalysisError)?; let cgraph_eligible = cached_cgraph .check_value_validity( dir_val, &context, &mut hyperswitch_constraint_graph::Memoization::new(), &mut hyperswitch_constraint_graph::CycleCheck::new(), None, ) .change_context(errors::RoutingError::KgraphAnalysisError)?; let filter_eligible = eligible_connectors.map_or(true, |list| list.contains(&routable_connector)); if cgraph_eligible && filter_eligible { final_selection.push(choice); } } Ok(final_selection) } pub async fn perform_eligibility_analysis( state: &SessionState, key_store: &domain::MerchantKeyStore, chosen: Vec<routing_types::RoutableConnectorChoice>, transaction_data: &routing::TransactionData<'_>, eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>, profile_id: &common_utils::id_type::ProfileId, ) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> { let backend_input = match transaction_data { routing::TransactionData::Payment(payment_data) => make_dsl_input(payment_data)?, #[cfg(feature = "payouts")] routing::TransactionData::Payout(payout_data) => make_dsl_input_for_payouts(payout_data)?, }; perform_cgraph_filtering( state, key_store, chosen, backend_input, eligible_connectors, profile_id, &api_enums::TransactionType::from(transaction_data), ) .await } pub async fn perform_fallback_routing( state: &SessionState, key_store: &domain::MerchantKeyStore, transaction_data: &routing::TransactionData<'_>, eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>, business_profile: &domain::Profile, ) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> { #[cfg(feature = "v1")] let fallback_config = routing::helpers::get_merchant_default_config( &*state.store, match transaction_data { routing::TransactionData::Payment(payment_data) => payment_data .payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::RoutingError::ProfileIdMissing)? .get_string_repr(), #[cfg(feature = "payouts")] routing::TransactionData::Payout(payout_data) => { payout_data.payout_attempt.profile_id.get_string_repr() } }, &api_enums::TransactionType::from(transaction_data), ) .await .change_context(errors::RoutingError::FallbackConfigFetchFailed)?; #[cfg(feature = "v2")] let fallback_config = admin::ProfileWrapper::new(business_profile.clone()) .get_default_fallback_list_of_connector_under_profile() .change_context(errors::RoutingError::FallbackConfigFetchFailed)?; let backend_input = match transaction_data { routing::TransactionData::Payment(payment_data) => make_dsl_input(payment_data)?, #[cfg(feature = "payouts")] routing::TransactionData::Payout(payout_data) => make_dsl_input_for_payouts(payout_data)?, }; perform_cgraph_filtering( state, key_store, fallback_config, backend_input, eligible_connectors, business_profile.get_id(), &api_enums::TransactionType::from(transaction_data), ) .await } pub async fn perform_eligibility_analysis_with_fallback( state: &SessionState, key_store: &domain::MerchantKeyStore, chosen: Vec<routing_types::RoutableConnectorChoice>, transaction_data: &routing::TransactionData<'_>, eligible_connectors: Option<Vec<api_enums::RoutableConnectors>>, business_profile: &domain::Profile, ) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> { let mut final_selection = perform_eligibility_analysis( state, key_store, chosen, transaction_data, eligible_connectors.as_ref(), business_profile.get_id(), ) .await?; let fallback_selection = perform_fallback_routing( state, key_store, transaction_data, eligible_connectors.as_ref(), business_profile, ) .await; final_selection.append( &mut fallback_selection .unwrap_or_default() .iter() .filter(|&routable_connector_choice| { !final_selection.contains(routable_connector_choice) }) .cloned() .collect::<Vec<_>>(), ); let final_selected_connectors = final_selection .iter() .map(|item| item.connector) .collect::<Vec<_>>(); logger::debug!(final_selected_connectors_for_routing=?final_selected_connectors, "List of final selected connectors for routing"); Ok(final_selection) } #[cfg(feature = "v2")] pub async fn perform_session_flow_routing<'a>( state: &'a SessionState, key_store: &'a domain::MerchantKeyStore, session_input: SessionFlowRoutingInput<'_>, business_profile: &domain::Profile, transaction_type: &api_enums::TransactionType, ) -> RoutingResult<FxHashMap<api_enums::PaymentMethodType, Vec<routing_types::SessionRoutingChoice>>> { let mut pm_type_map: FxHashMap<api_enums::PaymentMethodType, FxHashMap<String, api::GetToken>> = FxHashMap::default(); let profile_id = business_profile.get_id().clone(); let routing_algorithm = MerchantAccountRoutingAlgorithm::V1(business_profile.routing_algorithm_id.clone()); let payment_method_input = dsl_inputs::PaymentMethodInput { payment_method: None, payment_method_type: None, card_network: None, }; let payment_input = dsl_inputs::PaymentInput { amount: session_input .payment_intent .amount_details .calculate_net_amount(), currency: session_input.payment_intent.amount_details.currency, authentication_type: session_input.payment_intent.authentication_type, card_bin: None, capture_method: Option::<euclid_enums::CaptureMethod>::foreign_from( session_input.payment_intent.capture_method, ), // business_country not available in payment_intent anymore business_country: None, billing_country: session_input .country .map(storage_enums::Country::from_alpha2), // business_label not available in payment_intent anymore business_label: None, setup_future_usage: Some(session_input.payment_intent.setup_future_usage), }; let metadata = session_input .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 mut backend_input = dsl_inputs::BackendInput { metadata, payment: payment_input, payment_method: payment_method_input, mandate: dsl_inputs::MandateData { mandate_acceptance_type: None, mandate_type: None, payment_type: None, }, }; for connector_data in session_input.chosen.iter() { pm_type_map .entry(connector_data.payment_method_sub_type) .or_default() .insert( connector_data.connector.connector_name.to_string(), connector_data.connector.get_token.clone(), ); } let mut result: FxHashMap< api_enums::PaymentMethodType, Vec<routing_types::SessionRoutingChoice>, > = FxHashMap::default(); for (pm_type, allowed_connectors) in pm_type_map { let euclid_pmt: euclid_enums::PaymentMethodType = pm_type; let euclid_pm: euclid_enums::PaymentMethod = euclid_pmt.into(); backend_input.payment_method.payment_method = Some(euclid_pm); backend_input.payment_method.payment_method_type = Some(euclid_pmt); let session_pm_input = SessionRoutingPmTypeInput { routing_algorithm: &routing_algorithm, backend_input: backend_input.clone(), allowed_connectors, profile_id: &profile_id, }; let routable_connector_choice_option = perform_session_routing_for_pm_type( state, key_store, &session_pm_input, transaction_type, business_profile, ) .await?; if let Some(routable_connector_choice) = routable_connector_choice_option { let mut session_routing_choice: Vec<routing_types::SessionRoutingChoice> = Vec::new(); for selection in routable_connector_choice { let connector_name = selection.connector.to_string(); if let Some(get_token) = session_pm_input.allowed_connectors.get(&connector_name) { let connector_data = api::ConnectorData::get_connector_by_name( &state.clone().conf.connectors, &connector_name, get_token.clone(), selection.merchant_connector_id, ) .change_context(errors::RoutingError::InvalidConnectorName(connector_name))?; session_routing_choice.push(routing_types::SessionRoutingChoice { connector: connector_data, payment_method_type: pm_type, }); } } if !session_routing_choice.is_empty() { result.insert(pm_type, session_routing_choice); } } } Ok(result) } #[cfg(feature = "v1")] pub async fn perform_session_flow_routing( session_input: SessionFlowRoutingInput<'_>, business_profile: &domain::Profile, transaction_type: &api_enums::TransactionType, ) -> RoutingResult<FxHashMap<api_enums::PaymentMethodType, Vec<routing_types::SessionRoutingChoice>>> { let mut pm_type_map: FxHashMap<api_enums::PaymentMethodType, FxHashMap<String, api::GetToken>> = FxHashMap::default(); let profile_id = session_input .payment_intent .profile_id .clone() .get_required_value("profile_id") .change_context(errors::RoutingError::ProfileIdMissing)?; let routing_algorithm: MerchantAccountRoutingAlgorithm = { business_profile .routing_algorithm .clone() .map(|val| val.parse_value("MerchantAccountRoutingAlgorithm")) .transpose() .change_context(errors::RoutingError::InvalidRoutingAlgorithmStructure)? .unwrap_or_default() }; let payment_method_input = dsl_inputs::PaymentMethodInput { payment_method: None, payment_method_type: None, card_network: None, }; let payment_input = dsl_inputs::PaymentInput { amount: session_input.payment_attempt.get_total_amount(), currency: session_input .payment_intent .currency .get_required_value("Currency") .change_context(errors::RoutingError::DslMissingRequiredField { field_name: "currency".to_string(), })?, authentication_type: session_input.payment_attempt.authentication_type, card_bin: None, capture_method: session_input .payment_attempt .capture_method .and_then(Option::<euclid_enums::CaptureMethod>::foreign_from), business_country: session_input .payment_intent .business_country .map(api_enums::Country::from_alpha2), billing_country: session_input .country .map(storage_enums::Country::from_alpha2), business_label: session_input.payment_intent.business_label.clone(), setup_future_usage: session_input.payment_intent.setup_future_usage, }; let metadata = session_input .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 mut backend_input = dsl_inputs::BackendInput { metadata, payment: payment_input, payment_method: payment_method_input, mandate: dsl_inputs::MandateData { mandate_acceptance_type: None, mandate_type: None, payment_type: None, }, }; for connector_data in session_input.chosen.iter() { pm_type_map .entry(connector_data.payment_method_sub_type) .or_default() .insert( connector_data.connector.connector_name.to_string(), connector_data.connector.get_token.clone(), ); } let mut result: FxHashMap< api_enums::PaymentMethodType, Vec<routing_types::SessionRoutingChoice>, > = FxHashMap::default(); for (pm_type, allowed_connectors) in pm_type_map { let euclid_pmt: euclid_enums::PaymentMethodType = pm_type; let euclid_pm: euclid_enums::PaymentMethod = euclid_pmt.into(); backend_input.payment_method.payment_method = Some(euclid_pm); backend_input.payment_method.payment_method_type = Some(euclid_pmt); let session_pm_input = SessionRoutingPmTypeInput { state: session_input.state, key_store: session_input.key_store, attempt_id: session_input.payment_attempt.get_id(), routing_algorithm: &routing_algorithm, backend_input: backend_input.clone(), allowed_connectors, profile_id: &profile_id, }; let routable_connector_choice_option = perform_session_routing_for_pm_type( &session_pm_input, transaction_type, business_profile, ) .await?; if let Some(routable_connector_choice) = routable_connector_choice_option { let mut session_routing_choice: Vec<routing_types::SessionRoutingChoice> = Vec::new(); for selection in routable_connector_choice { let connector_name = selection.connector.to_string(); if let Some(get_token) = session_pm_input.allowed_connectors.get(&connector_name) { let connector_data = api::ConnectorData::get_connector_by_name( &session_pm_input.state.clone().conf.connectors, &connector_name, get_token.clone(), selection.merchant_connector_id, ) .change_context(errors::RoutingError::InvalidConnectorName(connector_name))?; session_routing_choice.push(routing_types::SessionRoutingChoice { connector: connector_data, payment_method_type: pm_type, }); } } if !session_routing_choice.is_empty() { result.insert(pm_type, session_routing_choice); } } } Ok(result) } #[cfg(feature = "v1")] async fn perform_session_routing_for_pm_type( session_pm_input: &SessionRoutingPmTypeInput<'_>, transaction_type: &api_enums::TransactionType, _business_profile: &domain::Profile, ) -> RoutingResult<Option<Vec<api_models::routing::RoutableConnectorChoice>>> { let merchant_id = &session_pm_input.key_store.merchant_id; let algorithm_id = match session_pm_input.routing_algorithm { MerchantAccountRoutingAlgorithm::V1(algorithm_ref) => &algorithm_ref.algorithm_id, }; let chosen_connectors = if let Some(ref algorithm_id) = algorithm_id { let cached_algorithm = ensure_algorithm_cached_v1( &session_pm_input.state.clone(), merchant_id, algorithm_id, session_pm_input.profile_id, transaction_type, ) .await?; match cached_algorithm.as_ref() { CachedAlgorithm::Single(conn) => vec![(**conn).clone()], CachedAlgorithm::Priority(plist) => plist.clone(), CachedAlgorithm::VolumeSplit(splits) => perform_volume_split(splits.to_vec()) .change_context(errors::RoutingError::ConnectorSelectionFailed)?, CachedAlgorithm::Advanced(interpreter) => execute_dsl_and_get_connector_v1( session_pm_input.backend_input.clone(), interpreter, )?, } } else { routing::helpers::get_merchant_default_config( &*session_pm_input.state.clone().store, session_pm_input.profile_id.get_string_repr(), transaction_type, ) .await .change_context(errors::RoutingError::FallbackConfigFetchFailed)? }; let mut final_selection = perform_cgraph_filtering( &session_pm_input.state.clone(), session_pm_input.key_store, chosen_connectors, session_pm_input.backend_input.clone(), None, session_pm_input.profile_id, transaction_type, ) .await?; if final_selection.is_empty() { let fallback = routing::helpers::get_merchant_default_config( &*session_pm_input.state.clone().store, session_pm_input.profile_id.get_string_repr(), transaction_type, ) .await .change_context(errors::RoutingError::FallbackConfigFetchFailed)?; final_selection = perform_cgraph_filtering( &session_pm_input.state.clone(), session_pm_input.key_store, fallback, session_pm_input.backend_input.clone(), None, session_pm_input.profile_id, transaction_type, ) .await?; } if final_selection.is_empty() { Ok(None) } else { Ok(Some(final_selection)) } } #[cfg(feature = "v2")] async fn get_chosen_connectors<'a>( state: &'a SessionState, key_store: &'a domain::MerchantKeyStore, session_pm_input: &SessionRoutingPmTypeInput<'_>, transaction_type: &api_enums::TransactionType, profile_wrapper: &admin::ProfileWrapper, ) -> RoutingResult<Vec<api_models::routing::RoutableConnectorChoice>> { let merchant_id = &key_store.merchant_id; let MerchantAccountRoutingAlgorithm::V1(algorithm_id) = session_pm_input.routing_algorithm; let chosen_connectors = if let Some(ref algorithm_id) = algorithm_id { let cached_algorithm = ensure_algorithm_cached_v1( state, merchant_id, algorithm_id, session_pm_input.profile_id, transaction_type, ) .await?; match cached_algorithm.as_ref() { CachedAlgorithm::Single(conn) => vec![(**conn).clone()], CachedAlgorithm::Priority(plist) => plist.clone(), CachedAlgorithm::VolumeSplit(splits) => perform_volume_split(splits.to_vec()) .change_context(errors::RoutingError::ConnectorSelectionFailed)?, CachedAlgorithm::Advanced(interpreter) => execute_dsl_and_get_connector_v1( session_pm_input.backend_input.clone(), interpreter, )?, } } else { profile_wrapper .get_default_fallback_list_of_connector_under_profile() .change_context(errors::RoutingError::FallbackConfigFetchFailed)? }; Ok(chosen_connectors) } #[cfg(feature = "v2")] async fn perform_session_routing_for_pm_type<'a>( state: &'a SessionState, key_store: &'a domain::MerchantKeyStore, session_pm_input: &SessionRoutingPmTypeInput<'_>, transaction_type: &api_enums::TransactionType, business_profile: &domain::Profile, ) -> RoutingResult<Option<Vec<api_models::routing::RoutableConnectorChoice>>> { let profile_wrapper = admin::ProfileWrapper::new(business_profile.clone()); let chosen_connectors = get_chosen_connectors( state, key_store, session_pm_input, transaction_type, &profile_wrapper, ) .await?; let mut final_selection = perform_cgraph_filtering( state, key_store, chosen_connectors, session_pm_input.backend_input.clone(), None, session_pm_input.profile_id, transaction_type, ) .await?; if final_selection.is_empty() { let fallback = profile_wrapper .get_default_fallback_list_of_connector_under_profile() .change_context(errors::RoutingError::FallbackConfigFetchFailed)?; final_selection = perform_cgraph_filtering( state, key_store, fallback, session_pm_input.backend_input.clone(), None, session_pm_input.profile_id, transaction_type, ) .await?; } if final_selection.is_empty() { Ok(None) } else { Ok(Some(final_selection)) } } #[cfg(feature = "v2")] 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!() } #[cfg(feature = "v1")] 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) } #[cfg(all(feature = "v1", feature = "dynamic_routing"))] 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) } /// success based dynamic routing #[cfg(all(feature = "v1", feature = "dynamic_routing"))] #[instrument(skip_all)] 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) } } #[cfg(all(feature = "v1", feature = "dynamic_routing"))] 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) } }
13,866
1,602
hyperswitch
crates/router/src/core/payments/transformers.rs
.rs
use std::{fmt::Debug, marker::PhantomData, str::FromStr}; use api_models::payments::{ Address, ConnectorMandateReferenceId, CustomerDetails, CustomerDetailsResponse, FrmMessage, RequestSurchargeDetails, }; use common_enums::{Currency, RequestIncrementalAuthorization}; use common_utils::{ consts::X_HS_LATENCY, fp_utils, pii, types::{ self as common_utils_type, AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector, }, }; use diesel_models::{ ephemeral_key, payment_attempt::ConnectorMandateReferenceId as DieselConnectorMandateReferenceId, }; use error_stack::{report, ResultExt}; #[cfg(feature = "v2")] use hyperswitch_domain_models::ApiModelToDieselModelConvertor; use hyperswitch_domain_models::{payments::payment_intent::CustomerData, router_request_types}; #[cfg(feature = "v2")] use masking::PeekInterface; use masking::{ExposeInterface, Maskable, Secret}; use router_env::{instrument, tracing}; use super::{flows::Feature, types::AuthenticationData, OperationSessionGetters, PaymentData}; use crate::{ configs::settings::ConnectorRequestReferenceIdConfig, core::{ errors::{self, RouterResponse, RouterResult}, payments::{self, helpers}, utils as core_utils, }, headers::X_PAYMENT_CONFIRM_SOURCE, routes::{metrics, SessionState}, services::{self, RedirectForm}, types::{ self, api::{self, ConnectorTransactionId}, domain, storage::{self, enums}, transformers::{ForeignFrom, ForeignInto, ForeignTryFrom}, MultipleCaptureRequestData, }, utils::{OptionExt, ValueExt}, }; #[cfg(feature = "v2")] pub async fn construct_router_data_to_update_calculated_tax<'a, F, T>( state: &'a SessionState, payment_data: PaymentData<F>, connector_id: &str, merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, customer: &'a Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, ) -> RouterResult<types::RouterData<F, T, types::PaymentsResponseData>> where T: TryFrom<PaymentAdditionalData<'a, F>>, types::RouterData<F, T, types::PaymentsResponseData>: Feature<F, T>, F: Clone, error_stack::Report<errors::ApiErrorResponse>: From<<T as TryFrom<PaymentAdditionalData<'a, F>>>::Error>, { todo!() } #[cfg(feature = "v1")] pub async fn construct_router_data_to_update_calculated_tax<'a, F, T>( state: &'a SessionState, payment_data: PaymentData<F>, connector_id: &str, merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, customer: &'a Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, ) -> RouterResult<types::RouterData<F, T, types::PaymentsResponseData>> where T: TryFrom<PaymentAdditionalData<'a, F>>, types::RouterData<F, T, types::PaymentsResponseData>: Feature<F, T>, F: Clone, error_stack::Report<errors::ApiErrorResponse>: From<<T as TryFrom<PaymentAdditionalData<'a, F>>>::Error>, { fp_utils::when(merchant_connector_account.is_disabled(), || { Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled) })?; let test_mode = merchant_connector_account.is_test_mode_on(); let auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while parsing value for ConnectorAuthType")?; let additional_data = PaymentAdditionalData { router_base_url: state.base_url.clone(), connector_name: connector_id.to_string(), payment_data: payment_data.clone(), state, customer_data: customer, }; let connector_mandate_request_reference_id = payment_data .payment_attempt .connector_mandate_detail .as_ref() .and_then(|detail| detail.get_connector_mandate_request_reference_id()); let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_account.get_id().clone(), customer_id: None, connector: connector_id.to_owned(), payment_id: payment_data .payment_attempt .payment_id .get_string_repr() .to_owned(), tenant_id: state.tenant.tenant_id.clone(), attempt_id: payment_data.payment_attempt.get_id().to_owned(), status: payment_data.payment_attempt.status, payment_method: diesel_models::enums::PaymentMethod::default(), connector_auth_type: auth_type, description: None, address: payment_data.address.clone(), auth_type: payment_data .payment_attempt .authentication_type .unwrap_or_default(), connector_meta_data: None, connector_wallets_details: None, request: T::try_from(additional_data)?, response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()), amount_captured: None, minor_amount_captured: None, access_token: None, session_token: None, reference_id: None, payment_method_status: None, payment_method_token: None, connector_customer: None, recurring_mandate_payment_data: None, connector_request_reference_id: core_utils::get_connector_request_reference_id( &state.conf, merchant_account.get_id(), &payment_data.payment_attempt, ), preprocessing_id: None, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, test_mode, payment_method_balance: None, connector_api_version: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id, authentication_id: None, psd2_sca_exemption_type: None, }; Ok(router_data) } #[cfg(feature = "v2")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn construct_payment_router_data_for_authorize<'a>( state: &'a SessionState, payment_data: hyperswitch_domain_models::payments::PaymentConfirmData<api::Authorize>, connector_id: &str, merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, customer: &'a Option<domain::Customer>, merchant_connector_account: &domain::MerchantConnectorAccount, _merchant_recipient_data: Option<types::MerchantRecipientData>, header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>, ) -> RouterResult<types::PaymentsAuthorizeRouterData> { use masking::ExposeOptionInterface; fp_utils::when(merchant_connector_account.is_disabled(), || { Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled) })?; let auth_type = merchant_connector_account .get_connector_account_details() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while parsing value for ConnectorAuthType")?; // TODO: Take Globalid and convert to connector reference id let customer_id = customer .to_owned() .map(|customer| common_utils::id_type::CustomerId::try_from(customer.id.clone())) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Invalid global customer generated, not able to convert to reference id", )?; let connector_customer_id = payment_data.get_connector_customer_id(customer.as_ref(), merchant_connector_account); let payment_method = payment_data.payment_attempt.payment_method_type; let router_base_url = &state.base_url; let attempt = &payment_data.payment_attempt; let complete_authorize_url = Some(helpers::create_complete_authorize_url( router_base_url, attempt, connector_id, None, )); let webhook_url = Some(helpers::create_webhook_url( router_base_url, &attempt.merchant_id, merchant_connector_account.get_id().get_string_repr(), )); let router_return_url = payment_data .payment_intent .create_finish_redirection_url(router_base_url, &merchant_account.publishable_key) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to construct finish redirection url")? .to_string(); let connector_request_reference_id = payment_data .payment_intent .merchant_reference_id .map(|id| id.get_string_repr().to_owned()) .unwrap_or(payment_data.payment_attempt.id.get_string_repr().to_owned()); let email = customer .as_ref() .and_then(|customer| customer.email.clone()) .map(pii::Email::from); let browser_info = payment_data .payment_attempt .browser_info .clone() .map(types::BrowserInformation::from); // TODO: few fields are repeated in both routerdata and request let request = types::PaymentsAuthorizeData { payment_method_data: payment_data .payment_method_data .get_required_value("payment_method_data")?, setup_future_usage: Some(payment_data.payment_intent.setup_future_usage), mandate_id: payment_data.mandate_data.clone(), off_session: None, setup_mandate_details: None, confirm: true, statement_descriptor_suffix: None, statement_descriptor: None, capture_method: Some(payment_data.payment_intent.capture_method), amount: payment_data .payment_attempt .amount_details .get_net_amount() .get_amount_as_i64(), minor_amount: payment_data.payment_attempt.amount_details.get_net_amount(), order_tax_amount: None, currency: payment_data.payment_intent.amount_details.currency, browser_info, email, customer_name: None, payment_experience: None, order_details: None, order_category: None, session_token: None, enrolled_for_3ds: true, related_transaction_id: None, payment_method_type: Some(payment_data.payment_attempt.payment_method_subtype), router_return_url: Some(router_return_url), webhook_url, complete_authorize_url, customer_id: None, surcharge_details: None, request_extended_authorization: None, request_incremental_authorization: matches!( payment_data .payment_intent .request_incremental_authorization, RequestIncrementalAuthorization::True | RequestIncrementalAuthorization::Default ), metadata: payment_data.payment_intent.metadata.expose_option(), authentication_data: None, customer_acceptance: None, split_payments: None, merchant_order_reference_id: None, integrity_object: None, shipping_cost: payment_data.payment_intent.amount_details.shipping_cost, additional_payment_method_data: None, merchant_account_id: None, merchant_config_currency: None, }; let connector_mandate_request_reference_id = payment_data .payment_attempt .connector_token_details .as_ref() .and_then(|detail| detail.get_connector_token_request_reference_id()); // TODO: evaluate the fields in router data, if they are required or not let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_account.get_id().clone(), tenant_id: state.tenant.tenant_id.clone(), // TODO: evaluate why we need customer id at the connector level. We already have connector customer id. customer_id, connector: connector_id.to_owned(), // TODO: evaluate why we need payment id at the connector level. We already have connector reference id payment_id: payment_data .payment_attempt .payment_id .get_string_repr() .to_owned(), // TODO: evaluate why we need attempt id at the connector level. We already have connector reference id attempt_id: payment_data .payment_attempt .get_id() .get_string_repr() .to_owned(), status: payment_data.payment_attempt.status, payment_method, connector_auth_type: auth_type, description: payment_data .payment_intent .description .as_ref() .map(|description| description.get_string_repr()) .map(ToOwned::to_owned), // TODO: Create unified address address: payment_data.payment_address.clone(), auth_type: payment_data.payment_attempt.authentication_type, connector_meta_data: None, connector_wallets_details: None, request, response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()), amount_captured: None, minor_amount_captured: None, access_token: None, session_token: None, reference_id: None, payment_method_status: None, payment_method_token: None, connector_customer: connector_customer_id, recurring_mandate_payment_data: None, // TODO: This has to be generated as the reference id based on the connector configuration // Some connectros might not accept accept the global id. This has to be done when generating the reference id connector_request_reference_id, preprocessing_id: payment_data.payment_attempt.preprocessing_step_id, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, // TODO: take this based on the env test_mode: Some(true), payment_method_balance: None, connector_api_version: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload, connector_mandate_request_reference_id, authentication_id: None, psd2_sca_exemption_type: None, }; Ok(router_data) } #[cfg(feature = "v2")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn construct_payment_router_data_for_capture<'a>( state: &'a SessionState, payment_data: hyperswitch_domain_models::payments::PaymentCaptureData<api::Capture>, connector_id: &str, merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, customer: &'a Option<domain::Customer>, merchant_connector_account: &domain::MerchantConnectorAccount, _merchant_recipient_data: Option<types::MerchantRecipientData>, header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>, ) -> RouterResult<types::PaymentsCaptureRouterData> { use masking::ExposeOptionInterface; fp_utils::when(merchant_connector_account.is_disabled(), || { Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled) })?; let auth_type = merchant_connector_account .get_connector_account_details() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while parsing value for ConnectorAuthType")?; let customer_id = customer .to_owned() .map(|customer| common_utils::id_type::CustomerId::try_from(customer.id.clone())) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Invalid global customer generated, not able to convert to reference id", )?; let payment_method = payment_data.payment_attempt.payment_method_type; let connector_request_reference_id = payment_data .payment_intent .merchant_reference_id .map(|id| id.get_string_repr().to_owned()) .unwrap_or(payment_data.payment_attempt.id.get_string_repr().to_owned()); let connector_mandate_request_reference_id = payment_data .payment_attempt .connector_token_details .as_ref() .and_then(|detail| detail.get_connector_token_request_reference_id()); let connector = api::ConnectorData::get_connector_by_name( &state.conf.connectors, connector_id, api::GetToken::Connector, payment_data.payment_attempt.merchant_connector_id.clone(), )?; let amount_to_capture = payment_data .payment_attempt .amount_details .get_amount_to_capture() .unwrap_or(payment_data.payment_attempt.amount_details.get_net_amount()); let amount = payment_data.payment_attempt.amount_details.get_net_amount(); let request = types::PaymentsCaptureData { capture_method: Some(payment_data.payment_intent.capture_method), amount_to_capture: amount_to_capture.get_amount_as_i64(), // This should be removed once we start moving to connector module minor_amount_to_capture: amount_to_capture, currency: payment_data.payment_intent.amount_details.currency, connector_transaction_id: connector .connector .connector_transaction_id(payment_data.payment_attempt.clone())? .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?, payment_amount: amount.get_amount_as_i64(), // This should be removed once we start moving to connector module minor_payment_amount: amount, connector_meta: payment_data .payment_attempt .connector_metadata .clone() .expose_option(), // TODO: add multiple capture data multiple_capture_data: None, // TODO: why do we need browser info during capture? browser_info: None, metadata: payment_data.payment_intent.metadata.expose_option(), integrity_object: None, split_payments: None, webhook_url: None, }; // TODO: evaluate the fields in router data, if they are required or not let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_account.get_id().clone(), // TODO: evaluate why we need customer id at the connector level. We already have connector customer id. customer_id, connector: connector_id.to_owned(), tenant_id: state.tenant.tenant_id.clone(), // TODO: evaluate why we need payment id at the connector level. We already have connector reference id payment_id: payment_data .payment_attempt .payment_id .get_string_repr() .to_owned(), // TODO: evaluate why we need attempt id at the connector level. We already have connector reference id attempt_id: payment_data .payment_attempt .get_id() .get_string_repr() .to_owned(), status: payment_data.payment_attempt.status, payment_method, connector_auth_type: auth_type, description: payment_data .payment_intent .description .as_ref() .map(|description| description.get_string_repr()) .map(ToOwned::to_owned), // TODO: Create unified address address: hyperswitch_domain_models::payment_address::PaymentAddress::default(), auth_type: payment_data.payment_attempt.authentication_type, connector_meta_data: None, connector_wallets_details: None, request, response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()), amount_captured: None, minor_amount_captured: None, access_token: None, session_token: None, reference_id: None, payment_method_status: None, payment_method_token: None, connector_customer: None, recurring_mandate_payment_data: None, // TODO: This has to be generated as the reference id based on the connector configuration // Some connectros might not accept accept the global id. This has to be done when generating the reference id connector_request_reference_id, preprocessing_id: payment_data.payment_attempt.preprocessing_step_id, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, // TODO: take this based on the env test_mode: Some(true), payment_method_balance: None, connector_api_version: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload, connector_mandate_request_reference_id, psd2_sca_exemption_type: None, authentication_id: None, }; Ok(router_data) } #[cfg(feature = "v2")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn construct_router_data_for_psync<'a>( state: &'a SessionState, payment_data: hyperswitch_domain_models::payments::PaymentStatusData<api::PSync>, connector_id: &str, merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, customer: &'a Option<domain::Customer>, merchant_connector_account: &domain::MerchantConnectorAccount, _merchant_recipient_data: Option<types::MerchantRecipientData>, header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>, ) -> RouterResult<types::PaymentsSyncRouterData> { use masking::ExposeOptionInterface; fp_utils::when(merchant_connector_account.is_disabled(), || { Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled) })?; // TODO: Take Globalid / CustomerReferenceId and convert to connector reference id let customer_id = None; let payment_intent = payment_data.payment_intent; let auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while parsing value for ConnectorAuthType")?; let attempt = &payment_data .payment_attempt .get_required_value("attempt") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Payment Attempt is not available in payment data")?; let connector_request_reference_id = payment_intent .merchant_reference_id .map(|id| id.get_string_repr().to_owned()) .unwrap_or(attempt.id.get_string_repr().to_owned()); let request = types::PaymentsSyncData { amount: attempt.amount_details.get_net_amount(), integrity_object: None, mandate_id: None, connector_transaction_id: match attempt.get_connector_payment_id() { Some(connector_txn_id) => { types::ResponseId::ConnectorTransactionId(connector_txn_id.to_owned()) } None => types::ResponseId::NoResponseId, }, encoded_data: attempt.encoded_data.clone().expose_option(), capture_method: Some(payment_intent.capture_method), connector_meta: attempt.connector_metadata.clone().expose_option(), sync_type: types::SyncRequestType::SinglePaymentSync, payment_method_type: Some(attempt.payment_method_subtype), currency: payment_intent.amount_details.currency, // TODO: Get the charges object from feature metadata split_payments: None, payment_experience: None, }; // TODO: evaluate the fields in router data, if they are required or not let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_account.get_id().clone(), // TODO: evaluate why we need customer id at the connector level. We already have connector customer id. customer_id, tenant_id: state.tenant.tenant_id.clone(), connector: connector_id.to_owned(), // TODO: evaluate why we need payment id at the connector level. We already have connector reference id payment_id: payment_intent.id.get_string_repr().to_owned(), // TODO: evaluate why we need attempt id at the connector level. We already have connector reference id attempt_id: attempt.get_id().get_string_repr().to_owned(), status: attempt.status, payment_method: attempt.payment_method_type, connector_auth_type: auth_type, description: payment_intent .description .as_ref() .map(|description| description.get_string_repr()) .map(ToOwned::to_owned), // TODO: Create unified address address: hyperswitch_domain_models::payment_address::PaymentAddress::default(), auth_type: attempt.authentication_type, connector_meta_data: None, connector_wallets_details: None, request, response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()), amount_captured: None, minor_amount_captured: None, access_token: None, session_token: None, reference_id: None, payment_method_status: None, payment_method_token: None, connector_customer: None, recurring_mandate_payment_data: None, // TODO: This has to be generated as the reference id based on the connector configuration // Some connectros might not accept accept the global id. This has to be done when generating the reference id connector_request_reference_id, preprocessing_id: attempt.preprocessing_step_id.clone(), #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, // TODO: take this based on the env test_mode: Some(true), payment_method_balance: None, connector_api_version: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload, connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, }; Ok(router_data) } #[cfg(feature = "v2")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn construct_payment_router_data_for_sdk_session<'a>( state: &'a SessionState, payment_data: hyperswitch_domain_models::payments::PaymentIntentData<api::Session>, connector_id: &str, merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, customer: &'a Option<domain::Customer>, merchant_connector_account: &domain::MerchantConnectorAccount, _merchant_recipient_data: Option<types::MerchantRecipientData>, header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>, ) -> RouterResult<types::PaymentsSessionRouterData> { fp_utils::when(merchant_connector_account.is_disabled(), || { Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled) })?; let auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while parsing value for ConnectorAuthType")?; // TODO: Take Globalid and convert to connector reference id let customer_id = customer .to_owned() .map(|customer| common_utils::id_type::CustomerId::try_from(customer.id.clone())) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Invalid global customer generated, not able to convert to reference id", )?; let email = customer .as_ref() .and_then(|customer| customer.email.clone()) .map(pii::Email::from); let order_details = payment_data .payment_intent .order_details .clone() .map(|order_details| { order_details .into_iter() .map(|order_detail| order_detail.expose()) .collect() }); let required_amount_type = StringMajorUnitForConnector; let apple_pay_amount = required_amount_type .convert( payment_data.payment_intent.amount_details.order_amount, payment_data.payment_intent.amount_details.currency, ) .change_context(errors::ApiErrorResponse::PreconditionFailed { message: "Failed to convert amount to string major unit for applePay".to_string(), })?; let apple_pay_recurring_details = payment_data .payment_intent .feature_metadata .and_then(|feature_metadata| feature_metadata.apple_pay_recurring_details) .map(|apple_pay_recurring_details| { ForeignInto::foreign_into((apple_pay_recurring_details, apple_pay_amount)) }); // TODO: few fields are repeated in both routerdata and request let request = types::PaymentsSessionData { amount: payment_data .payment_intent .amount_details .order_amount .get_amount_as_i64(), currency: payment_data.payment_intent.amount_details.currency, country: payment_data .payment_intent .billing_address .and_then(|billing_address| { billing_address .get_inner() .address .as_ref() .and_then(|address| address.country) }), // TODO: populate surcharge here surcharge_details: None, order_details, email, minor_amount: payment_data.payment_intent.amount_details.order_amount, apple_pay_recurring_details, }; // TODO: evaluate the fields in router data, if they are required or not let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_account.get_id().clone(), // TODO: evaluate why we need customer id at the connector level. We already have connector customer id. customer_id, connector: connector_id.to_owned(), tenant_id: state.tenant.tenant_id.clone(), // TODO: evaluate why we need payment id at the connector level. We already have connector reference id payment_id: payment_data.payment_intent.id.get_string_repr().to_owned(), // TODO: evaluate why we need attempt id at the connector level. We already have connector reference id attempt_id: "".to_string(), status: enums::AttemptStatus::Started, payment_method: enums::PaymentMethod::Wallet, connector_auth_type: auth_type, description: payment_data .payment_intent .description .as_ref() .map(|description| description.get_string_repr()) .map(ToOwned::to_owned), // TODO: Create unified address address: hyperswitch_domain_models::payment_address::PaymentAddress::default(), auth_type: payment_data .payment_intent .authentication_type .unwrap_or_default(), connector_meta_data: merchant_connector_account.get_metadata(), connector_wallets_details: None, request, response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()), amount_captured: None, minor_amount_captured: None, access_token: None, session_token: None, reference_id: None, payment_method_status: None, payment_method_token: None, connector_customer: None, recurring_mandate_payment_data: None, // TODO: This has to be generated as the reference id based on the connector configuration // Some connectros might not accept accept the global id. This has to be done when generating the reference id connector_request_reference_id: "".to_string(), preprocessing_id: None, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, // TODO: take this based on the env test_mode: Some(true), payment_method_balance: None, connector_api_version: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload, connector_mandate_request_reference_id: None, psd2_sca_exemption_type: None, authentication_id: None, }; Ok(router_data) } #[cfg(feature = "v2")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn construct_payment_router_data_for_setup_mandate<'a>( state: &'a SessionState, payment_data: hyperswitch_domain_models::payments::PaymentConfirmData<api::SetupMandate>, connector_id: &str, merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, customer: &'a Option<domain::Customer>, merchant_connector_account: &domain::MerchantConnectorAccount, _merchant_recipient_data: Option<types::MerchantRecipientData>, header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>, ) -> RouterResult<types::SetupMandateRouterData> { fp_utils::when(merchant_connector_account.is_disabled(), || { Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled) })?; let auth_type = merchant_connector_account .get_connector_account_details() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while parsing value for ConnectorAuthType")?; // TODO: Take Globalid and convert to connector reference id let customer_id = customer .to_owned() .map(|customer| common_utils::id_type::CustomerId::try_from(customer.id.clone())) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Invalid global customer generated, not able to convert to reference id", )?; let connector_customer_id = customer.as_ref().and_then(|customer| { customer .get_connector_customer_id(&merchant_connector_account.get_id()) .map(String::from) }); let payment_method = payment_data.payment_attempt.payment_method_type; let router_base_url = &state.base_url; let attempt = &payment_data.payment_attempt; let complete_authorize_url = Some(helpers::create_complete_authorize_url( router_base_url, attempt, connector_id, None, )); let webhook_url = Some(helpers::create_webhook_url( router_base_url, &attempt.merchant_id, merchant_connector_account.get_id().get_string_repr(), )); let router_return_url = payment_data .payment_intent .create_finish_redirection_url(router_base_url, &merchant_account.publishable_key) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to construct finish redirection url")? .to_string(); let connector_request_reference_id = payment_data .payment_intent .merchant_reference_id .map(|id| id.get_string_repr().to_owned()) .unwrap_or(payment_data.payment_attempt.id.get_string_repr().to_owned()); let email = customer .as_ref() .and_then(|customer| customer.email.clone()) .map(pii::Email::from); let browser_info = payment_data .payment_attempt .browser_info .clone() .map(types::BrowserInformation::from); // TODO: few fields are repeated in both routerdata and request let request = types::SetupMandateRequestData { currency: payment_data.payment_intent.amount_details.currency, payment_method_data: payment_data .payment_method_data .get_required_value("payment_method_data")?, amount: Some( payment_data .payment_attempt .amount_details .get_net_amount() .get_amount_as_i64(), ), confirm: true, statement_descriptor_suffix: None, customer_acceptance: None, mandate_id: None, setup_future_usage: Some(payment_data.payment_intent.setup_future_usage), off_session: None, setup_mandate_details: None, router_return_url: Some(router_return_url.clone()), webhook_url, browser_info, email, customer_name: None, return_url: Some(router_return_url), payment_method_type: Some(payment_data.payment_attempt.payment_method_subtype), request_incremental_authorization: matches!( payment_data .payment_intent .request_incremental_authorization, RequestIncrementalAuthorization::True | RequestIncrementalAuthorization::Default ), metadata: payment_data.payment_intent.metadata, minor_amount: Some(payment_data.payment_attempt.amount_details.get_net_amount()), shipping_cost: payment_data.payment_intent.amount_details.shipping_cost, capture_method: Some(payment_data.payment_intent.capture_method), complete_authorize_url, }; let connector_mandate_request_reference_id = payment_data .payment_attempt .connector_token_details .as_ref() .and_then(|detail| detail.get_connector_token_request_reference_id()); // TODO: evaluate the fields in router data, if they are required or not let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_account.get_id().clone(), tenant_id: state.tenant.tenant_id.clone(), // TODO: evaluate why we need customer id at the connector level. We already have connector customer id. customer_id, connector: connector_id.to_owned(), // TODO: evaluate why we need payment id at the connector level. We already have connector reference id payment_id: payment_data .payment_attempt .payment_id .get_string_repr() .to_owned(), // TODO: evaluate why we need attempt id at the connector level. We already have connector reference id attempt_id: payment_data .payment_attempt .get_id() .get_string_repr() .to_owned(), status: payment_data.payment_attempt.status, payment_method, connector_auth_type: auth_type, description: payment_data .payment_intent .description .as_ref() .map(|description| description.get_string_repr()) .map(ToOwned::to_owned), // TODO: Create unified address address: payment_data.payment_address.clone(), auth_type: payment_data.payment_attempt.authentication_type, connector_meta_data: None, connector_wallets_details: None, request, response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()), amount_captured: None, minor_amount_captured: None, access_token: None, session_token: None, reference_id: None, payment_method_status: None, payment_method_token: None, connector_customer: connector_customer_id, recurring_mandate_payment_data: None, // TODO: This has to be generated as the reference id based on the connector configuration // Some connectros might not accept accept the global id. This has to be done when generating the reference id connector_request_reference_id, preprocessing_id: payment_data.payment_attempt.preprocessing_step_id, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, // TODO: take this based on the env test_mode: Some(true), payment_method_balance: None, connector_api_version: None, connector_http_status_code: None, external_latency: None, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload, connector_mandate_request_reference_id, authentication_id: None, psd2_sca_exemption_type: None, }; Ok(router_data) } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn construct_payment_router_data<'a, F, T>( state: &'a SessionState, payment_data: PaymentData<F>, connector_id: &str, merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, customer: &'a Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, merchant_recipient_data: Option<types::MerchantRecipientData>, header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>, ) -> RouterResult<types::RouterData<F, T, types::PaymentsResponseData>> where T: TryFrom<PaymentAdditionalData<'a, F>>, types::RouterData<F, T, types::PaymentsResponseData>: Feature<F, T>, F: Clone, error_stack::Report<errors::ApiErrorResponse>: From<<T as TryFrom<PaymentAdditionalData<'a, F>>>::Error>, { let (payment_method, router_data); fp_utils::when(merchant_connector_account.is_disabled(), || { Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled) })?; let test_mode = merchant_connector_account.is_test_mode_on(); let auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while parsing value for ConnectorAuthType")?; payment_method = payment_data .payment_attempt .payment_method .or(payment_data.payment_attempt.payment_method) .get_required_value("payment_method_type")?; let resource_id = match payment_data .payment_attempt .get_connector_payment_id() .map(ToString::to_string) { Some(id) => types::ResponseId::ConnectorTransactionId(id), None => types::ResponseId::NoResponseId, }; // [#44]: why should response be filled during request let response = Ok(types::PaymentsResponseData::TransactionResponse { resource_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, }); let additional_data = PaymentAdditionalData { router_base_url: state.base_url.clone(), connector_name: connector_id.to_string(), payment_data: payment_data.clone(), state, customer_data: customer, }; let customer_id = customer.to_owned().map(|customer| customer.customer_id); let supported_connector = &state .conf .multiple_api_version_supported_connectors .supported_connectors; let connector_enum = api_models::enums::Connector::from_str(connector_id) .change_context(errors::ConnectorError::InvalidConnectorName) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "connector", }) .attach_printable_lazy(|| format!("unable to parse connector name {connector_id:?}"))?; let connector_api_version = if supported_connector.contains(&connector_enum) { state .store .find_config_by_key(&format!("connector_api_version_{connector_id}")) .await .map(|value| value.config) .ok() } else { None }; let apple_pay_flow = payments::decide_apple_pay_flow( state, payment_data.payment_attempt.payment_method_type, Some(merchant_connector_account), ); let unified_address = if let Some(payment_method_info) = payment_data.payment_method_info.clone() { let payment_method_billing = payment_method_info .payment_method_billing_address .map(|decrypted_data| decrypted_data.into_inner().expose()) .map(|decrypted_value| decrypted_value.parse_value("payment_method_billing_address")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to parse payment_method_billing_address")?; payment_data .address .clone() .unify_with_payment_data_billing(payment_method_billing) } else { payment_data.address }; let connector_mandate_request_reference_id = payment_data .payment_attempt .connector_mandate_detail .as_ref() .and_then(|detail| detail.get_connector_mandate_request_reference_id()); crate::logger::debug!("unified address details {:?}", unified_address); router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_account.get_id().clone(), customer_id, tenant_id: state.tenant.tenant_id.clone(), connector: connector_id.to_owned(), payment_id: payment_data .payment_attempt .payment_id .get_string_repr() .to_owned(), attempt_id: payment_data.payment_attempt.attempt_id.clone(), status: payment_data.payment_attempt.status, payment_method, connector_auth_type: auth_type, description: payment_data.payment_intent.description.clone(), address: unified_address, auth_type: payment_data .payment_attempt .authentication_type .unwrap_or_default(), connector_meta_data: merchant_connector_account.get_metadata(), connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), request: T::try_from(additional_data)?, response, amount_captured: payment_data .payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()), minor_amount_captured: payment_data.payment_intent.amount_captured, access_token: None, session_token: None, reference_id: None, payment_method_status: payment_data.payment_method_info.map(|info| info.status), payment_method_token: payment_data .pm_token .map(|token| types::PaymentMethodToken::Token(Secret::new(token))), connector_customer: payment_data.connector_customer_id, recurring_mandate_payment_data: payment_data.recurring_mandate_payment_data, connector_request_reference_id: core_utils::get_connector_request_reference_id( &state.conf, merchant_account.get_id(), &payment_data.payment_attempt, ), preprocessing_id: payment_data.payment_attempt.preprocessing_step_id, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, test_mode, payment_method_balance: None, connector_api_version, connector_http_status_code: None, external_latency: None, apple_pay_flow, frm_metadata: None, refund_id: None, dispute_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: merchant_recipient_data.map(|data| { api_models::admin::AdditionalMerchantData::foreign_from( types::AdditionalMerchantData::OpenBankingRecipientData(data), ) }), header_payload, connector_mandate_request_reference_id, authentication_id: None, psd2_sca_exemption_type: payment_data.payment_intent.psd2_sca_exemption_type, }; Ok(router_data) } pub trait ToResponse<F, D, Op> where Self: Sized, Op: Debug, D: OperationSessionGetters<F>, { #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] fn generate_response( data: D, customer: Option<domain::Customer>, auth_flow: services::AuthFlow, base_url: &str, operation: Op, connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig, connector_http_status_code: Option<u16>, external_latency: Option<u128>, is_latency_header_enabled: Option<bool>, ) -> RouterResponse<Self>; #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] fn generate_response( data: D, customer: Option<domain::Customer>, base_url: &str, operation: Op, connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig, connector_http_status_code: Option<u16>, external_latency: Option<u128>, is_latency_header_enabled: Option<bool>, merchant_account: &domain::MerchantAccount, ) -> RouterResponse<Self>; } /// Generate a response from the given Data. This should be implemented on a payment data object pub trait GenerateResponse<Response> where Self: Sized, { #[cfg(feature = "v2")] fn generate_response( self, state: &SessionState, connector_http_status_code: Option<u16>, external_latency: Option<u128>, is_latency_header_enabled: Option<bool>, merchant_account: &domain::MerchantAccount, profile: &domain::Profile, ) -> RouterResponse<Response>; } #[cfg(feature = "v2")] impl<F> GenerateResponse<api_models::payments::PaymentsCaptureResponse> for hyperswitch_domain_models::payments::PaymentCaptureData<F> where F: Clone, { fn generate_response( self, state: &SessionState, connector_http_status_code: Option<u16>, external_latency: Option<u128>, is_latency_header_enabled: Option<bool>, merchant_account: &domain::MerchantAccount, profile: &domain::Profile, ) -> RouterResponse<api_models::payments::PaymentsCaptureResponse> { let payment_intent = &self.payment_intent; let payment_attempt = &self.payment_attempt; let amount = api_models::payments::PaymentAmountDetailsResponse::foreign_from(( &payment_intent.amount_details, &payment_attempt.amount_details, )); let response = api_models::payments::PaymentsCaptureResponse { id: payment_intent.id.clone(), amount, status: payment_intent.status, }; Ok(services::ApplicationResponse::JsonWithHeaders(( response, vec![], ))) } } #[cfg(feature = "v1")] impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentsResponse where F: Clone, Op: Debug, D: OperationSessionGetters<F>, { #[allow(clippy::too_many_arguments)] fn generate_response( payment_data: D, customer: Option<domain::Customer>, auth_flow: services::AuthFlow, base_url: &str, operation: Op, connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig, connector_http_status_code: Option<u16>, external_latency: Option<u128>, is_latency_header_enabled: Option<bool>, ) -> RouterResponse<Self> { let captures = payment_data .get_multiple_capture_data() .and_then(|multiple_capture_data| { multiple_capture_data .expand_captures .and_then(|should_expand| { should_expand.then_some( multiple_capture_data .get_all_captures() .into_iter() .cloned() .collect(), ) }) }); payments_to_payments_response( payment_data, captures, customer, auth_flow, base_url, &operation, connector_request_reference_id_config, connector_http_status_code, external_latency, is_latency_header_enabled, ) } } #[cfg(feature = "v1")] impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentsSessionResponse where F: Clone, Op: Debug, D: OperationSessionGetters<F>, { #[allow(clippy::too_many_arguments)] fn generate_response( payment_data: D, _customer: Option<domain::Customer>, _auth_flow: services::AuthFlow, _base_url: &str, _operation: Op, _connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig, _connector_http_status_code: Option<u16>, _external_latency: Option<u128>, _is_latency_header_enabled: Option<bool>, ) -> RouterResponse<Self> { Ok(services::ApplicationResponse::JsonWithHeaders(( Self { session_token: payment_data.get_sessions_token(), payment_id: payment_data.get_payment_attempt().payment_id.clone(), client_secret: payment_data .get_payment_intent() .client_secret .clone() .get_required_value("client_secret")? .into(), }, vec![], ))) } } #[cfg(feature = "v2")] impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentsSessionResponse where F: Clone, Op: Debug, D: OperationSessionGetters<F>, { #[allow(clippy::too_many_arguments)] fn generate_response( payment_data: D, _customer: Option<domain::Customer>, _base_url: &str, _operation: Op, _connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig, _connector_http_status_code: Option<u16>, _external_latency: Option<u128>, _is_latency_header_enabled: Option<bool>, _merchant_account: &domain::MerchantAccount, ) -> RouterResponse<Self> { Ok(services::ApplicationResponse::JsonWithHeaders(( Self { session_token: payment_data.get_sessions_token(), payment_id: payment_data.get_payment_intent().id.clone(), }, vec![], ))) } } #[cfg(feature = "v1")] impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentsDynamicTaxCalculationResponse where F: Clone, Op: Debug, D: OperationSessionGetters<F>, { #[allow(clippy::too_many_arguments)] fn generate_response( payment_data: D, _customer: Option<domain::Customer>, _auth_flow: services::AuthFlow, _base_url: &str, _operation: Op, _connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig, _connector_http_status_code: Option<u16>, _external_latency: Option<u128>, _is_latency_header_enabled: Option<bool>, ) -> RouterResponse<Self> { let mut amount = payment_data.get_payment_intent().amount; let shipping_cost = payment_data.get_payment_intent().shipping_cost; if let Some(shipping_cost) = shipping_cost { amount = amount + shipping_cost; } let order_tax_amount = payment_data .get_payment_intent() .tax_details .clone() .and_then(|tax| { tax.payment_method_type .map(|a| a.order_tax_amount) .or_else(|| tax.default.map(|a| a.order_tax_amount)) }); if let Some(tax_amount) = order_tax_amount { amount = amount + tax_amount; } let currency = payment_data .get_payment_attempt() .currency .get_required_value("currency")?; Ok(services::ApplicationResponse::JsonWithHeaders(( Self { net_amount: amount, payment_id: payment_data.get_payment_attempt().payment_id.clone(), order_tax_amount, shipping_cost, display_amount: api_models::payments::DisplayAmountOnSdk::foreign_try_from(( amount, shipping_cost, order_tax_amount, currency, ))?, }, vec![], ))) } } #[cfg(feature = "v2")] impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentsIntentResponse where F: Clone, Op: Debug, D: OperationSessionGetters<F>, { #[allow(clippy::too_many_arguments)] fn generate_response( payment_data: D, _customer: Option<domain::Customer>, _base_url: &str, operation: Op, _connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig, _connector_http_status_code: Option<u16>, _external_latency: Option<u128>, _is_latency_header_enabled: Option<bool>, _merchant_account: &domain::MerchantAccount, ) -> RouterResponse<Self> { let payment_intent = payment_data.get_payment_intent(); Ok(services::ApplicationResponse::JsonWithHeaders(( Self { id: payment_intent.id.clone(), profile_id: payment_intent.profile_id.clone(), status: payment_intent.status, amount_details: api_models::payments::AmountDetailsResponse::foreign_from( payment_intent.amount_details.clone(), ), client_secret: payment_intent.client_secret.clone(), merchant_reference_id: payment_intent.merchant_reference_id.clone(), routing_algorithm_id: payment_intent.routing_algorithm_id.clone(), capture_method: payment_intent.capture_method, authentication_type: payment_intent.authentication_type, billing: payment_intent .billing_address .clone() .map(|billing| billing.into_inner()) .map(From::from), shipping: payment_intent .shipping_address .clone() .map(|shipping| shipping.into_inner()) .map(From::from), customer_id: payment_intent.customer_id.clone(), customer_present: payment_intent.customer_present.clone(), description: payment_intent.description.clone(), return_url: payment_intent.return_url.clone(), setup_future_usage: payment_intent.setup_future_usage, apply_mit_exemption: payment_intent.apply_mit_exemption.clone(), statement_descriptor: payment_intent.statement_descriptor.clone(), order_details: payment_intent.order_details.clone().map(|order_details| { order_details .into_iter() .map(|order_detail| order_detail.expose().convert_back()) .collect() }), allowed_payment_method_types: payment_intent.allowed_payment_method_types.clone(), metadata: payment_intent.metadata.clone(), connector_metadata: payment_intent.connector_metadata.clone(), feature_metadata: payment_intent .feature_metadata .clone() .map(|feature_metadata| feature_metadata.convert_back()), payment_link_enabled: payment_intent.enable_payment_link.clone(), payment_link_config: payment_intent .payment_link_config .clone() .map(ForeignFrom::foreign_from), request_incremental_authorization: payment_intent.request_incremental_authorization, expires_on: payment_intent.session_expiry, frm_metadata: payment_intent.frm_metadata.clone(), request_external_three_ds_authentication: payment_intent .request_external_three_ds_authentication .clone(), }, vec![], ))) } } #[cfg(feature = "v2")] impl<F> GenerateResponse<api_models::payments::PaymentsResponse> for hyperswitch_domain_models::payments::PaymentConfirmData<F> where F: Clone, { fn generate_response( self, state: &SessionState, connector_http_status_code: Option<u16>, external_latency: Option<u128>, is_latency_header_enabled: Option<bool>, merchant_account: &domain::MerchantAccount, profile: &domain::Profile, ) -> RouterResponse<api_models::payments::PaymentsResponse> { let payment_intent = self.payment_intent; let payment_attempt = self.payment_attempt; let amount = api_models::payments::PaymentAmountDetailsResponse::foreign_from(( &payment_intent.amount_details, &payment_attempt.amount_details, )); let connector = payment_attempt .connector .clone() .get_required_value("connector") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Connector is none when constructing response")?; let merchant_connector_id = payment_attempt .merchant_connector_id .clone() .get_required_value("merchant_connector_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Merchant connector id is none when constructing response")?; let error = payment_attempt .error .as_ref() .map(api_models::payments::ErrorDetails::foreign_from); let payment_address = self.payment_address; let payment_method_data = Some(api_models::payments::PaymentMethodDataResponseWithBilling { payment_method_data: None, billing: payment_address .get_request_payment_method_billing() .cloned() .map(From::from), }); // TODO: Add support for other next actions, currently only supporting redirect to url let redirect_to_url = payment_intent.create_start_redirection_url( &state.base_url, merchant_account.publishable_key.clone(), )?; let next_action = payment_attempt .redirection_data .as_ref() .map(|_| api_models::payments::NextActionData::RedirectToUrl { redirect_to_url }); let connector_token_details = payment_attempt .connector_token_details .and_then(Option::<api_models::payments::ConnectorTokenDetails>::foreign_from); let return_url = payment_intent .return_url .clone() .or(profile.return_url.clone()); let response = api_models::payments::PaymentsResponse { id: payment_intent.id.clone(), status: payment_intent.status, amount, customer_id: payment_intent.customer_id.clone(), connector: Some(connector), client_secret: payment_intent.client_secret.clone(), created: payment_intent.created_at, payment_method_data, payment_method_type: Some(payment_attempt.payment_method_type), payment_method_subtype: Some(payment_attempt.payment_method_subtype), next_action, connector_transaction_id: payment_attempt.connector_payment_id.clone(), connector_reference_id: None, connector_token_details, merchant_connector_id: Some(merchant_connector_id), browser_info: None, error, return_url, authentication_type: payment_intent.authentication_type, authentication_type_applied: Some(payment_attempt.authentication_type), payment_method_id: payment_attempt.payment_method_id, attempts: None, billing: None, //TODO: add this shipping: None, //TODO: add this }; Ok(services::ApplicationResponse::JsonWithHeaders(( response, vec![], ))) } } #[cfg(feature = "v2")] impl<F> GenerateResponse<api_models::payments::PaymentsResponse> for hyperswitch_domain_models::payments::PaymentStatusData<F> where F: Clone, { fn generate_response( self, state: &SessionState, connector_http_status_code: Option<u16>, external_latency: Option<u128>, is_latency_header_enabled: Option<bool>, merchant_account: &domain::MerchantAccount, profile: &domain::Profile, ) -> RouterResponse<api_models::payments::PaymentsResponse> { let payment_intent = self.payment_intent; let optional_payment_attempt = self.payment_attempt.as_ref(); let amount = api_models::payments::PaymentAmountDetailsResponse::foreign_from(( &payment_intent.amount_details, optional_payment_attempt.map(|payment_attempt| &payment_attempt.amount_details), )); let connector = optional_payment_attempt.and_then(|payment_attempt| payment_attempt.connector.clone()); let merchant_connector_id = optional_payment_attempt .and_then(|payment_attempt| payment_attempt.merchant_connector_id.clone()); let error = optional_payment_attempt .and_then(|payment_attempt| payment_attempt.error.clone()) .as_ref() .map(api_models::payments::ErrorDetails::foreign_from); let attempts = self.attempts.as_ref().map(|attempts| { attempts .iter() .map(api_models::payments::PaymentAttemptResponse::foreign_from) .collect() }); let payment_method_data = Some(api_models::payments::PaymentMethodDataResponseWithBilling { payment_method_data: None, billing: self .payment_address .get_request_payment_method_billing() .cloned() .map(From::from), }); let connector_token_details = self .payment_attempt .as_ref() .and_then(|attempt| attempt.connector_token_details.clone()) .and_then(Option::<api_models::payments::ConnectorTokenDetails>::foreign_from); let return_url = payment_intent.return_url.or(profile.return_url.clone()); let response = api_models::payments::PaymentsResponse { id: payment_intent.id.clone(), status: payment_intent.status, amount, customer_id: payment_intent.customer_id.clone(), connector, billing: self .payment_address .get_payment_billing() .cloned() .map(From::from), shipping: self.payment_address.get_shipping().cloned().map(From::from), client_secret: payment_intent.client_secret.clone(), created: payment_intent.created_at, payment_method_data, payment_method_type: self .payment_attempt .as_ref() .map(|attempt| attempt.payment_method_type), payment_method_subtype: self .payment_attempt .as_ref() .map(|attempt| attempt.payment_method_subtype), connector_transaction_id: self .payment_attempt .as_ref() .and_then(|attempt| attempt.connector_payment_id.clone()), connector_reference_id: None, merchant_connector_id, browser_info: None, connector_token_details, payment_method_id: self .payment_attempt .as_ref() .and_then(|attempt| attempt.payment_method_id.clone()), error, authentication_type_applied: self .payment_attempt .as_ref() .and_then(|attempt| attempt.authentication_applied), authentication_type: payment_intent.authentication_type, next_action: None, attempts, return_url, }; Ok(services::ApplicationResponse::JsonWithHeaders(( response, vec![], ))) } } #[cfg(feature = "v2")] impl<F> GenerateResponse<api_models::payments::PaymentAttemptResponse> for hyperswitch_domain_models::payments::PaymentAttemptRecordData<F> where F: Clone, { fn generate_response( self, _state: &SessionState, _connector_http_status_code: Option<u16>, _external_latency: Option<u128>, _is_latency_header_enabled: Option<bool>, _merchant_account: &domain::MerchantAccount, _profile: &domain::Profile, ) -> RouterResponse<api_models::payments::PaymentAttemptResponse> { let payment_attempt = self.payment_attempt; let response = api_models::payments::PaymentAttemptResponse::foreign_from(&payment_attempt); Ok(services::ApplicationResponse::JsonWithHeaders(( response, vec![], ))) } } #[cfg(feature = "v1")] impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentsPostSessionTokensResponse where F: Clone, Op: Debug, D: OperationSessionGetters<F>, { fn generate_response( payment_data: D, _customer: Option<domain::Customer>, _auth_flow: services::AuthFlow, _base_url: &str, _operation: Op, _connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig, _connector_http_status_code: Option<u16>, _external_latency: Option<u128>, _is_latency_header_enabled: Option<bool>, ) -> RouterResponse<Self> { let papal_sdk_next_action = paypal_sdk_next_steps_check(payment_data.get_payment_attempt().clone())?; let next_action = papal_sdk_next_action.map(|paypal_next_action_data| { api_models::payments::NextActionData::InvokeSdkClient { next_action_data: paypal_next_action_data, } }); Ok(services::ApplicationResponse::JsonWithHeaders(( Self { payment_id: payment_data.get_payment_intent().payment_id.clone(), next_action, status: payment_data.get_payment_intent().status, }, vec![], ))) } } impl ForeignTryFrom<(MinorUnit, Option<MinorUnit>, Option<MinorUnit>, Currency)> for api_models::payments::DisplayAmountOnSdk { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from( (net_amount, shipping_cost, order_tax_amount, currency): ( MinorUnit, Option<MinorUnit>, Option<MinorUnit>, Currency, ), ) -> Result<Self, Self::Error> { let major_unit_convertor = StringMajorUnitForConnector; let sdk_net_amount = major_unit_convertor .convert(net_amount, currency) .change_context(errors::ApiErrorResponse::PreconditionFailed { message: "Failed to convert net_amount to base unit".to_string(), }) .attach_printable("Failed to convert net_amount to string major unit")?; let sdk_shipping_cost = shipping_cost .map(|cost| { major_unit_convertor .convert(cost, currency) .change_context(errors::ApiErrorResponse::PreconditionFailed { message: "Failed to convert shipping_cost to base unit".to_string(), }) .attach_printable("Failed to convert shipping_cost to string major unit") }) .transpose()?; let sdk_order_tax_amount = order_tax_amount .map(|cost| { major_unit_convertor .convert(cost, currency) .change_context(errors::ApiErrorResponse::PreconditionFailed { message: "Failed to convert order_tax_amount to base unit".to_string(), }) .attach_printable("Failed to convert order_tax_amount to string major unit") }) .transpose()?; Ok(Self { net_amount: sdk_net_amount, shipping_cost: sdk_shipping_cost, order_tax_amount: sdk_order_tax_amount, }) } } #[cfg(feature = "v1")] impl<F, Op, D> ToResponse<F, D, Op> for api::VerifyResponse where F: Clone, Op: Debug, D: OperationSessionGetters<F>, { #[cfg(all(feature = "v2", feature = "customer_v2"))] #[allow(clippy::too_many_arguments)] fn generate_response( _data: D, _customer: Option<domain::Customer>, _auth_flow: services::AuthFlow, _base_url: &str, _operation: Op, _connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig, _connector_http_status_code: Option<u16>, _external_latency: Option<u128>, _is_latency_header_enabled: Option<bool>, ) -> RouterResponse<Self> { todo!() } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[allow(clippy::too_many_arguments)] fn generate_response( payment_data: D, customer: Option<domain::Customer>, _auth_flow: services::AuthFlow, _base_url: &str, _operation: Op, _connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig, _connector_http_status_code: Option<u16>, _external_latency: Option<u128>, _is_latency_header_enabled: Option<bool>, ) -> RouterResponse<Self> { let additional_payment_method_data: Option<api_models::payments::AdditionalPaymentData> = payment_data .get_payment_attempt() .payment_method_data .clone() .map(|data| data.parse_value("payment_method_data")) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "payment_method_data", })?; let payment_method_data_response = additional_payment_method_data.map(api::PaymentMethodDataResponse::from); Ok(services::ApplicationResponse::JsonWithHeaders(( Self { verify_id: Some(payment_data.get_payment_intent().payment_id.clone()), merchant_id: Some(payment_data.get_payment_intent().merchant_id.clone()), client_secret: payment_data .get_payment_intent() .client_secret .clone() .map(Secret::new), customer_id: customer.as_ref().map(|x| x.customer_id.clone()), email: customer .as_ref() .and_then(|cus| cus.email.as_ref().map(|s| s.to_owned())), name: customer .as_ref() .and_then(|cus| cus.name.as_ref().map(|s| s.to_owned())), phone: customer .as_ref() .and_then(|cus| cus.phone.as_ref().map(|s| s.to_owned())), mandate_id: payment_data .get_mandate_id() .and_then(|mandate_ids| mandate_ids.mandate_id.clone()), payment_method: payment_data.get_payment_attempt().payment_method, payment_method_data: payment_method_data_response, payment_token: payment_data.get_token().map(ToString::to_string), error_code: payment_data.get_payment_attempt().clone().error_code, error_message: payment_data.get_payment_attempt().clone().error_message, }, vec![], ))) } } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[instrument(skip_all)] // try to use router data here so that already validated things , we don't want to repeat the validations. // Add internal value not found and external value not found so that we can give 500 / Internal server error for internal value not found #[allow(clippy::too_many_arguments)] pub fn payments_to_payments_response<Op, F: Clone, D>( _payment_data: D, _captures: Option<Vec<storage::Capture>>, _customer: Option<domain::Customer>, _auth_flow: services::AuthFlow, _base_url: &str, _operation: &Op, _connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig, _connector_http_status_code: Option<u16>, _external_latency: Option<u128>, _is_latency_header_enabled: Option<bool>, ) -> RouterResponse<api_models::payments::PaymentsResponse> where Op: Debug, D: OperationSessionGetters<F>, { todo!() } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all)] // try to use router data here so that already validated things , we don't want to repeat the validations. // Add internal value not found and external value not found so that we can give 500 / Internal server error for internal value not found #[allow(clippy::too_many_arguments)] pub fn payments_to_payments_response<Op, F: Clone, D>( payment_data: D, captures: Option<Vec<storage::Capture>>, customer: Option<domain::Customer>, _auth_flow: services::AuthFlow, base_url: &str, operation: &Op, connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig, connector_http_status_code: Option<u16>, external_latency: Option<u128>, _is_latency_header_enabled: Option<bool>, ) -> RouterResponse<api::PaymentsResponse> where Op: Debug, D: OperationSessionGetters<F>, { use std::ops::Not; let payment_attempt = payment_data.get_payment_attempt().clone(); let payment_intent = payment_data.get_payment_intent().clone(); let payment_link_data = payment_data.get_payment_link_data(); let currency = payment_attempt .currency .as_ref() .get_required_value("currency")?; let amount = currency .to_currency_base_unit( payment_attempt .net_amount .get_total_amount() .get_amount_as_i64(), ) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "amount", })?; let mandate_id = payment_attempt.mandate_id.clone(); let refunds_response = payment_data.get_refunds().is_empty().not().then(|| { payment_data .get_refunds() .into_iter() .map(ForeignInto::foreign_into) .collect() }); let disputes_response = payment_data.get_disputes().is_empty().not().then(|| { payment_data .get_disputes() .into_iter() .map(ForeignInto::foreign_into) .collect() }); let incremental_authorizations_response = payment_data.get_authorizations().is_empty().not().then(|| { payment_data .get_authorizations() .into_iter() .map(ForeignInto::foreign_into) .collect() }); let external_authentication_details = payment_data .get_authentication() .map(ForeignInto::foreign_into); let attempts_response = payment_data.get_attempts().map(|attempts| { attempts .into_iter() .map(ForeignInto::foreign_into) .collect() }); let captures_response = captures.map(|captures| { captures .into_iter() .map(ForeignInto::foreign_into) .collect() }); let merchant_id = payment_attempt.merchant_id.to_owned(); let payment_method_type = payment_attempt .payment_method_type .as_ref() .map(ToString::to_string) .unwrap_or("".to_owned()); let payment_method = payment_attempt .payment_method .as_ref() .map(ToString::to_string) .unwrap_or("".to_owned()); let additional_payment_method_data: Option<api_models::payments::AdditionalPaymentData> = payment_attempt .payment_method_data .clone() .and_then(|data| match data { serde_json::Value::Null => None, // This is to handle the case when the payment_method_data is null _ => Some(data.parse_value("AdditionalPaymentData")), }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse the AdditionalPaymentData from payment_attempt.payment_method_data")?; let surcharge_details = payment_attempt .net_amount .get_surcharge_amount() .map(|surcharge_amount| RequestSurchargeDetails { surcharge_amount, tax_amount: payment_attempt.net_amount.get_tax_on_surcharge(), }); let merchant_decision = payment_intent.merchant_decision.to_owned(); let frm_message = payment_data.get_frm_message().map(FrmMessage::foreign_from); let payment_method_data = additional_payment_method_data.map(api::PaymentMethodDataResponse::from); let payment_method_data_response = (payment_method_data.is_some() || payment_data .get_address() .get_request_payment_method_billing() .is_some()) .then_some(api_models::payments::PaymentMethodDataResponseWithBilling { payment_method_data, billing: payment_data .get_address() .get_request_payment_method_billing() .cloned() .map(From::from), }); let mut headers = connector_http_status_code .map(|status_code| { vec![( "connector_http_status_code".to_string(), Maskable::new_normal(status_code.to_string()), )] }) .unwrap_or_default(); if let Some(payment_confirm_source) = payment_intent.payment_confirm_source { headers.push(( X_PAYMENT_CONFIRM_SOURCE.to_string(), Maskable::new_normal(payment_confirm_source.to_string()), )) } // For the case when we don't have Customer data directly stored in Payment intent let customer_table_response: Option<CustomerDetailsResponse> = customer.as_ref().map(ForeignInto::foreign_into); // If we have customer data in Payment Intent and if the customer is not deleted, We are populating the Retrieve response from the // same. If the customer is deleted then we use the customer table to populate customer details let customer_details_response = if let Some(customer_details_raw) = payment_intent.customer_details.clone() { let customer_details_encrypted = serde_json::from_value::<CustomerData>(customer_details_raw.into_inner().expose()); if let Ok(customer_details_encrypted_data) = customer_details_encrypted { Some(CustomerDetailsResponse { id: customer_table_response .as_ref() .and_then(|customer_data| customer_data.id.clone()), name: customer_table_response .as_ref() .and_then(|customer_data| customer_data.name.clone()) .or(customer_details_encrypted_data .name .or(customer.as_ref().and_then(|customer| { customer.name.as_ref().map(|name| name.clone().into_inner()) }))), email: customer_table_response .as_ref() .and_then(|customer_data| customer_data.email.clone()) .or(customer_details_encrypted_data.email.or(customer .as_ref() .and_then(|customer| customer.email.clone().map(pii::Email::from)))), phone: customer_table_response .as_ref() .and_then(|customer_data| customer_data.phone.clone()) .or(customer_details_encrypted_data .phone .or(customer.as_ref().and_then(|customer| { customer .phone .as_ref() .map(|phone| phone.clone().into_inner()) }))), phone_country_code: customer_table_response .as_ref() .and_then(|customer_data| customer_data.phone_country_code.clone()) .or(customer_details_encrypted_data .phone_country_code .or(customer .as_ref() .and_then(|customer| customer.phone_country_code.clone()))), }) } else { customer_table_response } } else { customer_table_response }; headers.extend( external_latency .map(|latency| { vec![( X_HS_LATENCY.to_string(), Maskable::new_normal(latency.to_string()), )] }) .unwrap_or_default(), ); let output = if payments::is_start_pay(&operation) && payment_attempt.authentication_data.is_some() { let redirection_data = payment_attempt .authentication_data .clone() .get_required_value("redirection_data")?; let form: RedirectForm = serde_json::from_value(redirection_data) .map_err(|_| errors::ApiErrorResponse::InternalServerError)?; services::ApplicationResponse::Form(Box::new(services::RedirectionFormData { redirect_form: form, payment_method_data: payment_data.get_payment_method_data().cloned(), amount, currency: currency.to_string(), })) } else { let mut next_action_response = None; let bank_transfer_next_steps = bank_transfer_next_steps_check(payment_attempt.clone())?; let next_action_voucher = voucher_next_steps_check(payment_attempt.clone())?; let next_action_mobile_payment = mobile_payment_next_steps_check(&payment_attempt)?; let next_action_containing_qr_code_url = qr_code_next_steps_check(payment_attempt.clone())?; let papal_sdk_next_action = paypal_sdk_next_steps_check(payment_attempt.clone())?; let next_action_containing_fetch_qr_code_url = fetch_qr_code_url_next_steps_check(payment_attempt.clone())?; let next_action_containing_wait_screen = wait_screen_next_steps_check(payment_attempt.clone())?; let next_action_invoke_hidden_frame = next_action_invoke_hidden_frame(&payment_attempt)?; if payment_intent.status == enums::IntentStatus::RequiresCustomerAction || bank_transfer_next_steps.is_some() || next_action_voucher.is_some() || next_action_containing_qr_code_url.is_some() || next_action_containing_wait_screen.is_some() || papal_sdk_next_action.is_some() || next_action_containing_fetch_qr_code_url.is_some() || payment_data.get_authentication().is_some() { next_action_response = bank_transfer_next_steps .map(|bank_transfer| { api_models::payments::NextActionData::DisplayBankTransferInformation { bank_transfer_steps_and_charges_details: bank_transfer, } }) .or(next_action_voucher.map(|voucher_data| { api_models::payments::NextActionData::DisplayVoucherInformation { voucher_details: voucher_data, } })) .or(next_action_mobile_payment.map(|mobile_payment_data| { api_models::payments::NextActionData::CollectOtp { consent_data_required: mobile_payment_data.consent_data_required, } })) .or(next_action_containing_qr_code_url.map(|qr_code_data| { api_models::payments::NextActionData::foreign_from(qr_code_data) })) .or(next_action_containing_fetch_qr_code_url.map(|fetch_qr_code_data| { api_models::payments::NextActionData::FetchQrCodeInformation { qr_code_fetch_url: fetch_qr_code_data.qr_code_fetch_url } })) .or(papal_sdk_next_action.map(|paypal_next_action_data| { api_models::payments::NextActionData::InvokeSdkClient{ next_action_data: paypal_next_action_data } })) .or(next_action_containing_wait_screen.map(|wait_screen_data| { api_models::payments::NextActionData::WaitScreenInformation { display_from_timestamp: wait_screen_data.display_from_timestamp, display_to_timestamp: wait_screen_data.display_to_timestamp, } })) .or(payment_attempt.authentication_data.as_ref().map(|_| { api_models::payments::NextActionData::RedirectToUrl { redirect_to_url: helpers::create_startpay_url( base_url, &payment_attempt, &payment_intent, ), } })) .or(match payment_data.get_authentication().as_ref(){ Some(authentication) => { if payment_intent.status == common_enums::IntentStatus::RequiresCustomerAction && authentication.cavv.is_none() && authentication.is_separate_authn_required(){ // if preAuthn and separate authentication needed. let poll_config = payment_data.get_poll_config().unwrap_or_default(); let request_poll_id = core_utils::get_external_authentication_request_poll_id(&payment_intent.payment_id); let payment_connector_name = payment_attempt.connector .as_ref() .get_required_value("connector")?; Some(api_models::payments::NextActionData::ThreeDsInvoke { three_ds_data: api_models::payments::ThreeDsData { three_ds_authentication_url: helpers::create_authentication_url(base_url, &payment_attempt), three_ds_authorize_url: helpers::create_authorize_url( base_url, &payment_attempt, payment_connector_name, ), three_ds_method_details: authentication.three_ds_method_url.as_ref().zip(authentication.three_ds_method_data.as_ref()).map(|(three_ds_method_url,three_ds_method_data )|{ api_models::payments::ThreeDsMethodData::AcsThreeDsMethodData { three_ds_method_data_submission: true, three_ds_method_data: Some(three_ds_method_data.clone()), three_ds_method_url: Some(three_ds_method_url.to_owned()), } }).unwrap_or(api_models::payments::ThreeDsMethodData::AcsThreeDsMethodData { three_ds_method_data_submission: false, three_ds_method_data: None, three_ds_method_url: None, }), poll_config: api_models::payments::PollConfigResponse {poll_id: request_poll_id, delay_in_secs: poll_config.delay_in_secs, frequency: poll_config.frequency}, message_version: authentication.message_version.as_ref() .map(|version| version.to_string()), directory_server_id: authentication.directory_server_id.clone(), }, }) }else{ None } }, None => None }) .or(match next_action_invoke_hidden_frame{ Some(threeds_invoke_data) => Some(construct_connector_invoke_hidden_frame( threeds_invoke_data, )?), None => None }); }; // next action check for third party sdk session (for ex: Apple pay through trustpay has third party sdk session response) if third_party_sdk_session_next_action(&payment_attempt, operation) { next_action_response = Some( api_models::payments::NextActionData::ThirdPartySdkSessionToken { session_token: payment_data.get_sessions_token().first().cloned(), }, ) } let routed_through = payment_attempt.connector.clone(); let connector_label = routed_through.as_ref().and_then(|connector_name| { core_utils::get_connector_label( payment_intent.business_country, payment_intent.business_label.as_ref(), payment_attempt.business_sub_label.as_ref(), connector_name, ) }); let mandate_data = payment_data.get_setup_mandate().map(|d| api::MandateData { customer_acceptance: d .customer_acceptance .clone() .map(|d| api::CustomerAcceptance { acceptance_type: match d.acceptance_type { hyperswitch_domain_models::mandates::AcceptanceType::Online => { api::AcceptanceType::Online } hyperswitch_domain_models::mandates::AcceptanceType::Offline => { api::AcceptanceType::Offline } }, accepted_at: d.accepted_at, online: d.online.map(|d| api::OnlineMandate { ip_address: d.ip_address, user_agent: d.user_agent, }), }), mandate_type: d.mandate_type.clone().map(|d| match d { hyperswitch_domain_models::mandates::MandateDataType::MultiUse(Some(i)) => { api::MandateType::MultiUse(Some(api::MandateAmountData { amount: i.amount, currency: i.currency, start_date: i.start_date, end_date: i.end_date, metadata: i.metadata, })) } hyperswitch_domain_models::mandates::MandateDataType::SingleUse(i) => { api::MandateType::SingleUse(api::payments::MandateAmountData { amount: i.amount, currency: i.currency, start_date: i.start_date, end_date: i.end_date, metadata: i.metadata, }) } hyperswitch_domain_models::mandates::MandateDataType::MultiUse(None) => { api::MandateType::MultiUse(None) } }), update_mandate_id: d.update_mandate_id.clone(), }); let order_tax_amount = payment_data .get_payment_attempt() .net_amount .get_order_tax_amount() .or_else(|| { payment_data .get_payment_intent() .tax_details .clone() .and_then(|tax| { tax.payment_method_type .map(|a| a.order_tax_amount) .or_else(|| tax.default.map(|a| a.order_tax_amount)) }) }); let connector_mandate_id = payment_data.get_mandate_id().and_then(|mandate| { mandate .mandate_reference_id .as_ref() .and_then(|mandate_ref| match mandate_ref { api_models::payments::MandateReferenceId::ConnectorMandateId( connector_mandate_reference_id, ) => connector_mandate_reference_id.get_connector_mandate_id(), _ => None, }) }); let connector_transaction_id = payment_attempt .get_connector_payment_id() .map(ToString::to_string); let payments_response = api::PaymentsResponse { payment_id: payment_intent.payment_id, merchant_id: payment_intent.merchant_id, status: payment_intent.status, amount: payment_attempt.net_amount.get_order_amount(), net_amount: payment_attempt.get_total_amount(), amount_capturable: payment_attempt.amount_capturable, amount_received: payment_intent.amount_captured, connector: routed_through, client_secret: payment_intent.client_secret.map(Secret::new), created: Some(payment_intent.created_at), currency: currency.to_string(), customer_id: customer.as_ref().map(|cus| cus.clone().customer_id), customer: customer_details_response, description: payment_intent.description, refunds: refunds_response, disputes: disputes_response, attempts: attempts_response, captures: captures_response, mandate_id, mandate_data, setup_future_usage: payment_intent.setup_future_usage, off_session: payment_intent.off_session, capture_on: None, capture_method: payment_attempt.capture_method, payment_method: payment_attempt.payment_method, payment_method_data: payment_method_data_response, payment_token: payment_attempt.payment_token, shipping: payment_data .get_address() .get_shipping() .cloned() .map(From::from), billing: payment_data .get_address() .get_payment_billing() .cloned() .map(From::from), order_details: payment_intent.order_details, email: customer .as_ref() .and_then(|cus| cus.email.as_ref().map(|s| s.to_owned())), name: customer .as_ref() .and_then(|cus| cus.name.as_ref().map(|s| s.to_owned())), phone: customer .as_ref() .and_then(|cus| cus.phone.as_ref().map(|s| s.to_owned())), return_url: payment_intent.return_url, authentication_type: payment_attempt.authentication_type, statement_descriptor_name: payment_intent.statement_descriptor_name, statement_descriptor_suffix: payment_intent.statement_descriptor_suffix, next_action: next_action_response, cancellation_reason: payment_attempt.cancellation_reason, error_code: payment_attempt.error_code, error_message: payment_attempt .error_reason .or(payment_attempt.error_message), unified_code: payment_attempt.unified_code, unified_message: payment_attempt.unified_message, payment_experience: payment_attempt.payment_experience, payment_method_type: payment_attempt.payment_method_type, connector_label, business_country: payment_intent.business_country, business_label: payment_intent.business_label, business_sub_label: payment_attempt.business_sub_label, allowed_payment_method_types: payment_intent.allowed_payment_method_types, ephemeral_key: payment_data .get_ephemeral_key() .map(ForeignFrom::foreign_from), manual_retry_allowed: helpers::is_manual_retry_allowed( &payment_intent.status, &payment_attempt.status, connector_request_reference_id_config, &merchant_id, ), connector_transaction_id, frm_message, metadata: payment_intent.metadata, connector_metadata: payment_intent.connector_metadata, feature_metadata: payment_intent.feature_metadata, reference_id: payment_attempt.connector_response_reference_id, payment_link: payment_link_data, profile_id: payment_intent.profile_id, surcharge_details, attempt_count: payment_intent.attempt_count, merchant_decision, merchant_connector_id: payment_attempt.merchant_connector_id, incremental_authorization_allowed: payment_intent.incremental_authorization_allowed, authorization_count: payment_intent.authorization_count, incremental_authorizations: incremental_authorizations_response, external_authentication_details, external_3ds_authentication_attempted: payment_attempt .external_three_ds_authentication_attempted, expires_on: payment_intent.session_expiry, fingerprint: payment_intent.fingerprint_id, browser_info: payment_attempt.browser_info, payment_method_id: payment_attempt.payment_method_id, payment_method_status: payment_data .get_payment_method_info() .map(|info| info.status), updated: Some(payment_intent.modified_at), split_payments: payment_attempt.charges, frm_metadata: payment_intent.frm_metadata, merchant_order_reference_id: payment_intent.merchant_order_reference_id, order_tax_amount, connector_mandate_id, shipping_cost: payment_intent.shipping_cost, capture_before: payment_attempt.capture_before, extended_authorization_applied: payment_attempt.extended_authorization_applied, card_discovery: payment_attempt.card_discovery, force_3ds_challenge: payment_intent.force_3ds_challenge, force_3ds_challenge_trigger: payment_intent.force_3ds_challenge_trigger, issuer_error_code: payment_attempt.issuer_error_code, issuer_error_message: payment_attempt.issuer_error_message, }; services::ApplicationResponse::JsonWithHeaders((payments_response, headers)) }; metrics::PAYMENT_OPS_COUNT.add( 1, router_env::metric_attributes!( ("operation", format!("{:?}", operation)), ("merchant", merchant_id.clone()), ("payment_method_type", payment_method_type), ("payment_method", payment_method), ), ); Ok(output) } #[cfg(feature = "v1")] pub fn third_party_sdk_session_next_action<Op>( payment_attempt: &storage::PaymentAttempt, operation: &Op, ) -> bool where Op: Debug, { // If the operation is confirm, we will send session token response in next action if format!("{operation:?}").eq("PaymentConfirm") { let condition1 = payment_attempt .connector .as_ref() .map(|connector| { matches!(connector.as_str(), "trustpay") || matches!(connector.as_str(), "payme") }) .and_then(|is_connector_supports_third_party_sdk| { if is_connector_supports_third_party_sdk { payment_attempt .payment_method .map(|pm| matches!(pm, diesel_models::enums::PaymentMethod::Wallet)) } else { Some(false) } }) .unwrap_or(false); // This condition to be triggered for open banking connectors, third party SDK session token will be provided let condition2 = payment_attempt .connector .as_ref() .map(|connector| matches!(connector.as_str(), "plaid")) .and_then(|is_connector_supports_third_party_sdk| { if is_connector_supports_third_party_sdk { payment_attempt .payment_method .map(|pm| matches!(pm, diesel_models::enums::PaymentMethod::OpenBanking)) .and_then(|first_match| { payment_attempt .payment_method_type .map(|pmt| { matches!( pmt, diesel_models::enums::PaymentMethodType::OpenBankingPIS ) }) .map(|second_match| first_match && second_match) }) } else { Some(false) } }) .unwrap_or(false); condition1 || condition2 } else { false } } pub fn qr_code_next_steps_check( payment_attempt: storage::PaymentAttempt, ) -> RouterResult<Option<api_models::payments::QrCodeInformation>> { let qr_code_steps: Option<Result<api_models::payments::QrCodeInformation, _>> = payment_attempt .connector_metadata .map(|metadata| metadata.parse_value("QrCodeInformation")); let qr_code_instructions = qr_code_steps.transpose().ok().flatten(); Ok(qr_code_instructions) } pub fn paypal_sdk_next_steps_check( payment_attempt: storage::PaymentAttempt, ) -> RouterResult<Option<api_models::payments::SdkNextActionData>> { let paypal_connector_metadata: Option<Result<api_models::payments::SdkNextActionData, _>> = payment_attempt.connector_metadata.map(|metadata| { metadata.parse_value("SdkNextActionData").map_err(|_| { crate::logger::warn!( "SdkNextActionData parsing failed for paypal_connector_metadata" ) }) }); let paypal_next_steps = paypal_connector_metadata.transpose().ok().flatten(); Ok(paypal_next_steps) } pub fn fetch_qr_code_url_next_steps_check( payment_attempt: storage::PaymentAttempt, ) -> RouterResult<Option<api_models::payments::FetchQrCodeInformation>> { let qr_code_steps: Option<Result<api_models::payments::FetchQrCodeInformation, _>> = payment_attempt .connector_metadata .map(|metadata| metadata.parse_value("FetchQrCodeInformation")); let qr_code_fetch_url = qr_code_steps.transpose().ok().flatten(); Ok(qr_code_fetch_url) } pub fn wait_screen_next_steps_check( payment_attempt: storage::PaymentAttempt, ) -> RouterResult<Option<api_models::payments::WaitScreenInstructions>> { let display_info_with_timer_steps: Option< Result<api_models::payments::WaitScreenInstructions, _>, > = payment_attempt .connector_metadata .map(|metadata| metadata.parse_value("WaitScreenInstructions")); let display_info_with_timer_instructions = display_info_with_timer_steps.transpose().ok().flatten(); Ok(display_info_with_timer_instructions) } pub fn next_action_invoke_hidden_frame( payment_attempt: &storage::PaymentAttempt, ) -> RouterResult<Option<api_models::payments::PaymentsConnectorThreeDsInvokeData>> { let connector_three_ds_invoke_data: Option< Result<api_models::payments::PaymentsConnectorThreeDsInvokeData, _>, > = payment_attempt .connector_metadata .clone() .map(|metadata| metadata.parse_value("PaymentsConnectorThreeDsInvokeData")); let three_ds_invoke_data = connector_three_ds_invoke_data.transpose().ok().flatten(); Ok(three_ds_invoke_data) } pub fn construct_connector_invoke_hidden_frame( connector_three_ds_invoke_data: api_models::payments::PaymentsConnectorThreeDsInvokeData, ) -> RouterResult<api_models::payments::NextActionData> { let iframe_data = api_models::payments::IframeData::ThreedsInvokeAndCompleteAutorize { three_ds_method_data_submission: connector_three_ds_invoke_data .three_ds_method_data_submission, three_ds_method_data: Some(connector_three_ds_invoke_data.three_ds_method_data), three_ds_method_url: connector_three_ds_invoke_data.three_ds_method_url, directory_server_id: connector_three_ds_invoke_data.directory_server_id, message_version: connector_three_ds_invoke_data.message_version, }; Ok(api_models::payments::NextActionData::InvokeHiddenIframe { iframe_data }) } #[cfg(feature = "v1")] impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::PaymentsResponse { fn foreign_from((pi, pa): (storage::PaymentIntent, storage::PaymentAttempt)) -> Self { let connector_transaction_id = pa.get_connector_payment_id().map(ToString::to_string); Self { payment_id: pi.payment_id, merchant_id: pi.merchant_id, status: pi.status, amount: pi.amount, amount_capturable: pa.amount_capturable, client_secret: pi.client_secret.map(|s| s.into()), created: Some(pi.created_at), currency: pi.currency.map(|c| c.to_string()).unwrap_or_default(), description: pi.description, metadata: pi.metadata, order_details: pi.order_details, customer_id: pi.customer_id.clone(), connector: pa.connector, payment_method: pa.payment_method, payment_method_type: pa.payment_method_type, business_label: pi.business_label, business_country: pi.business_country, business_sub_label: pa.business_sub_label, setup_future_usage: pi.setup_future_usage, capture_method: pa.capture_method, authentication_type: pa.authentication_type, connector_transaction_id, attempt_count: pi.attempt_count, profile_id: pi.profile_id, merchant_connector_id: pa.merchant_connector_id, payment_method_data: pa.payment_method_data.and_then(|data| { match data.parse_value("PaymentMethodDataResponseWithBilling") { Ok(parsed_data) => Some(parsed_data), Err(e) => { router_env::logger::error!("Failed to parse 'PaymentMethodDataResponseWithBilling' from payment method data. Error: {e:?}"); None } } }), merchant_order_reference_id: pi.merchant_order_reference_id, customer: pi.customer_details.and_then(|customer_details| match customer_details.into_inner().expose().parse_value::<CustomerData>("CustomerData"){ Ok(parsed_data) => Some( CustomerDetailsResponse { id: pi.customer_id, name: parsed_data.name, phone: parsed_data.phone, email: parsed_data.email, phone_country_code:parsed_data.phone_country_code }), Err(e) => { router_env::logger::error!("Failed to parse 'CustomerDetailsResponse' from payment method data. Error: {e:?}"); None } } ), billing: pi.billing_details.and_then(|billing_details| match billing_details.into_inner().expose().parse_value::<Address>("Address") { Ok(parsed_data) => Some(parsed_data), Err(e) => { router_env::logger::error!("Failed to parse 'BillingAddress' from payment method data. Error: {e:?}"); None } } ), shipping: pi.shipping_details.and_then(|shipping_details| match shipping_details.into_inner().expose().parse_value::<Address>("Address") { Ok(parsed_data) => Some(parsed_data), Err(e) => { router_env::logger::error!("Failed to parse 'ShippingAddress' from payment method data. Error: {e:?}"); None } } ), // TODO: fill in details based on requirement net_amount: pa.net_amount.get_total_amount(), amount_received: None, refunds: None, disputes: None, attempts: None, captures: None, mandate_id: None, mandate_data: None, off_session: None, capture_on: None, payment_token: None, email: None, name: None, phone: None, return_url: None, statement_descriptor_name: None, statement_descriptor_suffix: None, next_action: None, cancellation_reason: None, error_code: None, error_message: None, unified_code: None, unified_message: None, payment_experience: None, connector_label: None, allowed_payment_method_types: None, ephemeral_key: None, manual_retry_allowed: None, frm_message: None, connector_metadata: None, feature_metadata: None, reference_id: None, payment_link: None, surcharge_details: None, merchant_decision: None, incremental_authorization_allowed: None, authorization_count: None, incremental_authorizations: None, external_authentication_details: None, external_3ds_authentication_attempted: None, expires_on: None, fingerprint: None, browser_info: None, payment_method_id: None, payment_method_status: None, updated: None, split_payments: None, frm_metadata: None, capture_before: pa.capture_before, extended_authorization_applied: pa.extended_authorization_applied, order_tax_amount: None, connector_mandate_id:None, shipping_cost: None, card_discovery: pa.card_discovery, force_3ds_challenge: pi.force_3ds_challenge, force_3ds_challenge_trigger: pi.force_3ds_challenge_trigger, issuer_error_code: pa.issuer_error_code, issuer_error_message: pa.issuer_error_message, } } } #[cfg(feature = "v2")] impl ForeignFrom<(storage::PaymentIntent, Option<storage::PaymentAttempt>)> for api_models::payments::PaymentsListResponseItem { fn foreign_from((pi, pa): (storage::PaymentIntent, Option<storage::PaymentAttempt>)) -> Self { Self { id: pi.id, merchant_id: pi.merchant_id, profile_id: pi.profile_id, customer_id: pi.customer_id, payment_method_id: pa.as_ref().and_then(|p| p.payment_method_id.clone()), status: pi.status, amount: api_models::payments::PaymentAmountDetailsResponse::foreign_from(( &pi.amount_details, pa.as_ref().map(|p| &p.amount_details), )), created: pi.created_at, payment_method_type: pa.as_ref().and_then(|p| p.payment_method_type.into()), payment_method_subtype: pa.as_ref().and_then(|p| p.payment_method_subtype.into()), connector: pa.as_ref().and_then(|p| p.connector.clone()), merchant_connector_id: pa.as_ref().and_then(|p| p.merchant_connector_id.clone()), customer: None, merchant_reference_id: pi.merchant_reference_id, connector_payment_id: pa.as_ref().and_then(|p| p.connector_payment_id.clone()), connector_response_reference_id: pa .as_ref() .and_then(|p| p.connector_response_reference_id.clone()), metadata: pi.metadata, description: pi.description.map(|val| val.get_string_repr().to_string()), authentication_type: pi.authentication_type, capture_method: Some(pi.capture_method), setup_future_usage: Some(pi.setup_future_usage), attempt_count: pi.attempt_count, error: pa .as_ref() .and_then(|p| p.error.as_ref()) .map(api_models::payments::ErrorDetails::foreign_from), cancellation_reason: pa.as_ref().and_then(|p| p.cancellation_reason.clone()), order_details: None, return_url: pi.return_url, statement_descriptor: pi.statement_descriptor, allowed_payment_method_types: pi.allowed_payment_method_types, authorization_count: pi.authorization_count, modified_at: pa.as_ref().map(|p| p.modified_at), } } } #[cfg(feature = "v1")] impl ForeignFrom<ephemeral_key::EphemeralKey> for api::ephemeral_key::EphemeralKeyCreateResponse { fn foreign_from(from: ephemeral_key::EphemeralKey) -> Self { Self { customer_id: from.customer_id, created_at: from.created_at, expires: from.expires, secret: from.secret, } } } #[cfg(feature = "v1")] pub fn bank_transfer_next_steps_check( payment_attempt: storage::PaymentAttempt, ) -> RouterResult<Option<api_models::payments::BankTransferNextStepsData>> { let bank_transfer_next_step = if let Some(diesel_models::enums::PaymentMethod::BankTransfer) = payment_attempt.payment_method { if payment_attempt.payment_method_type != Some(diesel_models::enums::PaymentMethodType::Pix) { let bank_transfer_next_steps: Option<api_models::payments::BankTransferNextStepsData> = payment_attempt .connector_metadata .map(|metadata| { metadata .parse_value("NextStepsRequirements") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to parse the Value to NextRequirements struct", ) }) .transpose()?; bank_transfer_next_steps } else { None } } else { None }; Ok(bank_transfer_next_step) } #[cfg(feature = "v1")] pub fn voucher_next_steps_check( payment_attempt: storage::PaymentAttempt, ) -> RouterResult<Option<api_models::payments::VoucherNextStepData>> { let voucher_next_step = if let Some(diesel_models::enums::PaymentMethod::Voucher) = payment_attempt.payment_method { let voucher_next_steps: Option<api_models::payments::VoucherNextStepData> = payment_attempt .connector_metadata .map(|metadata| { metadata .parse_value("NextStepsRequirements") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse the Value to NextRequirements struct") }) .transpose()?; voucher_next_steps } else { None }; Ok(voucher_next_step) } #[cfg(feature = "v1")] pub fn mobile_payment_next_steps_check( payment_attempt: &storage::PaymentAttempt, ) -> RouterResult<Option<api_models::payments::MobilePaymentNextStepData>> { let mobile_payment_next_step = if let Some(diesel_models::enums::PaymentMethod::MobilePayment) = payment_attempt.payment_method { let mobile_paymebnt_next_steps: Option<api_models::payments::MobilePaymentNextStepData> = payment_attempt .connector_metadata .clone() .map(|metadata| { metadata .parse_value("MobilePaymentNextStepData") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse the Value to NextRequirements struct") }) .transpose()?; mobile_paymebnt_next_steps } else { None }; Ok(mobile_payment_next_step) } impl ForeignFrom<api_models::payments::QrCodeInformation> for api_models::payments::NextActionData { fn foreign_from(qr_info: api_models::payments::QrCodeInformation) -> Self { match qr_info { api_models::payments::QrCodeInformation::QrCodeUrl { image_data_url, qr_code_url, display_to_timestamp, } => Self::QrCodeInformation { image_data_url: Some(image_data_url), qr_code_url: Some(qr_code_url), display_to_timestamp, border_color: None, display_text: None, }, api_models::payments::QrCodeInformation::QrDataUrl { image_data_url, display_to_timestamp, } => Self::QrCodeInformation { image_data_url: Some(image_data_url), display_to_timestamp, qr_code_url: None, border_color: None, display_text: None, }, api_models::payments::QrCodeInformation::QrCodeImageUrl { qr_code_url, display_to_timestamp, } => Self::QrCodeInformation { qr_code_url: Some(qr_code_url), image_data_url: None, display_to_timestamp, border_color: None, display_text: None, }, api_models::payments::QrCodeInformation::QrColorDataUrl { color_image_data_url, display_to_timestamp, border_color, display_text, } => Self::QrCodeInformation { qr_code_url: None, image_data_url: Some(color_image_data_url), display_to_timestamp, border_color, display_text, }, } } } #[derive(Clone)] pub struct PaymentAdditionalData<'a, F> where F: Clone, { router_base_url: String, connector_name: String, payment_data: PaymentData<F>, state: &'a SessionState, customer_data: &'a Option<domain::Customer>, } #[cfg(all(feature = "v2", feature = "customer_v2"))] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthorizeData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(_additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { todo!() } } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthorizeData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data.clone(); let router_base_url = &additional_data.router_base_url; let connector_name = &additional_data.connector_name; let attempt = &payment_data.payment_attempt; let browser_info: Option<types::BrowserInformation> = attempt .browser_info .clone() .map(|b| b.parse_value("BrowserInformation")) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "browser_info", })?; let order_category = additional_data .payment_data .payment_intent .connector_metadata .clone() .map(|cm| { cm.parse_value::<api_models::payments::ConnectorMetadata>("ConnectorMetadata") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed parsing ConnectorMetadata") }) .transpose()? .and_then(|cm| cm.noon.and_then(|noon| noon.order_category)); let braintree_metadata = additional_data .payment_data .payment_intent .connector_metadata .clone() .map(|cm| { cm.parse_value::<api_models::payments::ConnectorMetadata>("ConnectorMetadata") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed parsing ConnectorMetadata") }) .transpose()? .and_then(|cm| cm.braintree); let merchant_account_id = braintree_metadata .as_ref() .and_then(|braintree| braintree.merchant_account_id.clone()); let merchant_config_currency = braintree_metadata.and_then(|braintree| braintree.merchant_config_currency); let order_details = additional_data .payment_data .payment_intent .order_details .map(|order_details| { order_details .iter() .map(|data| { data.to_owned() .parse_value("OrderDetailsWithAmount") .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "OrderDetailsWithAmount", }) .attach_printable("Unable to parse OrderDetailsWithAmount") }) .collect::<Result<Vec<_>, _>>() }) .transpose()?; let complete_authorize_url = Some(helpers::create_complete_authorize_url( router_base_url, attempt, connector_name, payment_data.creds_identifier.as_deref(), )); let merchant_connector_account_id_or_connector_name = payment_data .payment_attempt .merchant_connector_id .as_ref() .map(|mca_id| mca_id.get_string_repr()) .unwrap_or(connector_name); let webhook_url = Some(helpers::create_webhook_url( router_base_url, &attempt.merchant_id, merchant_connector_account_id_or_connector_name, )); let router_return_url = Some(helpers::create_redirect_url( router_base_url, attempt, connector_name, payment_data.creds_identifier.as_deref(), )); let additional_payment_method_data: Option<api_models::payments::AdditionalPaymentData> = payment_data.payment_attempt .payment_method_data .as_ref().map(|data| data.clone().parse_value("AdditionalPaymentData")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse AdditionalPaymentData from payment_data.payment_attempt.payment_method_data")?; let payment_method_data = payment_data.payment_method_data.or_else(|| { if payment_data.mandate_id.is_some() { Some(domain::PaymentMethodData::MandatePayment) } else { None } }); let amount = payment_data.payment_attempt.get_total_amount(); let customer_name = additional_data .customer_data .as_ref() .and_then(|customer_data| { customer_data .name .as_ref() .map(|customer| customer.clone().into_inner()) }); let customer_id = additional_data .customer_data .as_ref() .map(|data| data.customer_id.clone()); let split_payments = payment_data.payment_intent.split_payments.clone(); let merchant_order_reference_id = payment_data .payment_intent .merchant_order_reference_id .clone(); let shipping_cost = payment_data.payment_intent.shipping_cost; Ok(Self { payment_method_data: (payment_method_data.get_required_value("payment_method_data")?), setup_future_usage: payment_data.payment_intent.setup_future_usage, mandate_id: payment_data.mandate_id.clone(), off_session: payment_data.mandate_id.as_ref().map(|_| true), setup_mandate_details: payment_data.setup_mandate.clone(), confirm: payment_data.payment_attempt.confirm, statement_descriptor_suffix: payment_data.payment_intent.statement_descriptor_suffix, statement_descriptor: payment_data.payment_intent.statement_descriptor_name, capture_method: payment_data.payment_attempt.capture_method, amount: amount.get_amount_as_i64(), order_tax_amount: payment_data .payment_attempt .net_amount .get_order_tax_amount(), minor_amount: amount, currency: payment_data.currency, browser_info, email: payment_data.email, customer_name, payment_experience: payment_data.payment_attempt.payment_experience, order_details, order_category, session_token: None, enrolled_for_3ds: true, related_transaction_id: None, payment_method_type: payment_data.payment_attempt.payment_method_type, router_return_url, webhook_url, complete_authorize_url, customer_id, surcharge_details: payment_data.surcharge_details, request_incremental_authorization: matches!( payment_data .payment_intent .request_incremental_authorization, Some(RequestIncrementalAuthorization::True) | Some(RequestIncrementalAuthorization::Default) ), metadata: additional_data.payment_data.payment_intent.metadata, authentication_data: payment_data .authentication .as_ref() .map(AuthenticationData::foreign_try_from) .transpose()?, customer_acceptance: payment_data.customer_acceptance, request_extended_authorization: attempt.request_extended_authorization, split_payments, merchant_order_reference_id, integrity_object: None, additional_payment_method_data, shipping_cost, merchant_account_id, merchant_config_currency, }) } } #[cfg(feature = "v2")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSyncData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { todo!() } } #[cfg(feature = "v1")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSyncData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; let capture_method = payment_data.get_capture_method(); let amount = payment_data.payment_attempt.get_total_amount(); let payment_method_type = payment_data .payment_attempt .get_payment_method_type() .to_owned(); Ok(Self { amount, integrity_object: None, mandate_id: payment_data.mandate_id.clone(), connector_transaction_id: match payment_data.payment_attempt.get_connector_payment_id() { Some(connector_txn_id) => { types::ResponseId::ConnectorTransactionId(connector_txn_id.to_owned()) } None => types::ResponseId::NoResponseId, }, encoded_data: payment_data.payment_attempt.encoded_data, capture_method, connector_meta: payment_data.payment_attempt.connector_metadata, sync_type: match payment_data.multiple_capture_data { Some(multiple_capture_data) => types::SyncRequestType::MultipleCaptureSync( multiple_capture_data.get_pending_connector_capture_ids(), ), None => types::SyncRequestType::SinglePaymentSync, }, payment_method_type, currency: payment_data.currency, split_payments: payment_data.payment_intent.split_payments, payment_experience: payment_data.payment_attempt.payment_experience, }) } } impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsIncrementalAuthorizationData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; let connector = api::ConnectorData::get_connector_by_name( &additional_data.state.conf.connectors, &additional_data.connector_name, api::GetToken::Connector, payment_data.payment_attempt.merchant_connector_id.clone(), )?; let total_amount = payment_data .incremental_authorization_details .clone() .map(|details| details.total_amount) .ok_or( report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing incremental_authorization_details in payment_data"), )?; let additional_amount = payment_data .incremental_authorization_details .clone() .map(|details| details.additional_amount) .ok_or( report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("missing incremental_authorization_details in payment_data"), )?; Ok(Self { total_amount: total_amount.get_amount_as_i64(), additional_amount: additional_amount.get_amount_as_i64(), reason: payment_data .incremental_authorization_details .and_then(|details| details.reason), currency: payment_data.currency, connector_transaction_id: connector .connector .connector_transaction_id(payment_data.payment_attempt.clone())? .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?, }) } } #[cfg(feature = "v2")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCaptureData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { use masking::ExposeOptionInterface; let payment_data = additional_data.payment_data; let connector = api::ConnectorData::get_connector_by_name( &additional_data.state.conf.connectors, &additional_data.connector_name, api::GetToken::Connector, payment_data.payment_attempt.merchant_connector_id.clone(), )?; let amount_to_capture = payment_data .payment_attempt .amount_details .get_amount_to_capture() .unwrap_or(payment_data.payment_attempt.get_total_amount()); let amount = payment_data.payment_attempt.get_total_amount(); Ok(Self { capture_method: Some(payment_data.payment_intent.capture_method), amount_to_capture: amount_to_capture.get_amount_as_i64(), // This should be removed once we start moving to connector module minor_amount_to_capture: amount_to_capture, currency: payment_data.currency, connector_transaction_id: connector .connector .connector_transaction_id(payment_data.payment_attempt.clone())? .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?, payment_amount: amount.get_amount_as_i64(), // This should be removed once we start moving to connector module minor_payment_amount: amount, connector_meta: payment_data .payment_attempt .connector_metadata .expose_option(), // TODO: add multiple capture data multiple_capture_data: None, // TODO: why do we need browser info during capture? browser_info: None, metadata: payment_data.payment_intent.metadata.expose_option(), integrity_object: None, split_payments: None, webhook_url: None, }) } } #[cfg(feature = "v1")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCaptureData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; let connector = api::ConnectorData::get_connector_by_name( &additional_data.state.conf.connectors, &additional_data.connector_name, api::GetToken::Connector, payment_data.payment_attempt.merchant_connector_id.clone(), )?; let amount_to_capture = payment_data .payment_attempt .amount_to_capture .unwrap_or(payment_data.payment_attempt.get_total_amount()); let browser_info: Option<types::BrowserInformation> = payment_data .payment_attempt .browser_info .clone() .map(|b| b.parse_value("BrowserInformation")) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "browser_info", })?; let amount = payment_data.payment_attempt.get_total_amount(); let router_base_url = &additional_data.router_base_url; let attempt = &payment_data.payment_attempt; let merchant_connector_account_id = payment_data .payment_attempt .merchant_connector_id .as_ref() .map(|mca_id| mca_id.get_string_repr()) .ok_or(errors::ApiErrorResponse::MerchantAccountNotFound)?; let webhook_url: Option<_> = Some(helpers::create_webhook_url( router_base_url, &attempt.merchant_id, merchant_connector_account_id, )); Ok(Self { capture_method: payment_data.get_capture_method(), amount_to_capture: amount_to_capture.get_amount_as_i64(), // This should be removed once we start moving to connector module minor_amount_to_capture: amount_to_capture, currency: payment_data.currency, connector_transaction_id: connector .connector .connector_transaction_id(payment_data.payment_attempt.clone())? .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?, payment_amount: amount.get_amount_as_i64(), // This should be removed once we start moving to connector module minor_payment_amount: amount, connector_meta: payment_data.payment_attempt.connector_metadata, multiple_capture_data: match payment_data.multiple_capture_data { Some(multiple_capture_data) => Some(MultipleCaptureRequestData { capture_sequence: multiple_capture_data.get_captures_count()?, capture_reference: multiple_capture_data .get_latest_capture() .capture_id .clone(), }), None => None, }, browser_info, metadata: payment_data.payment_intent.metadata, integrity_object: None, split_payments: payment_data.payment_intent.split_payments, webhook_url, }) } } #[cfg(feature = "v2")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCancelData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { todo!() } } #[cfg(feature = "v1")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCancelData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; let connector = api::ConnectorData::get_connector_by_name( &additional_data.state.conf.connectors, &additional_data.connector_name, api::GetToken::Connector, payment_data.payment_attempt.merchant_connector_id.clone(), )?; let browser_info: Option<types::BrowserInformation> = payment_data .payment_attempt .browser_info .clone() .map(|b| b.parse_value("BrowserInformation")) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "browser_info", })?; let amount = payment_data.payment_attempt.get_total_amount(); let router_base_url = &additional_data.router_base_url; let attempt = &payment_data.payment_attempt; let merchant_connector_account_id = payment_data .payment_attempt .merchant_connector_id .as_ref() .map(|mca_id| mca_id.get_string_repr()) .ok_or(errors::ApiErrorResponse::MerchantAccountNotFound)?; let webhook_url: Option<_> = Some(helpers::create_webhook_url( router_base_url, &attempt.merchant_id, merchant_connector_account_id, )); let capture_method = payment_data.payment_attempt.capture_method; Ok(Self { amount: Some(amount.get_amount_as_i64()), // This should be removed once we start moving to connector module minor_amount: Some(amount), currency: Some(payment_data.currency), connector_transaction_id: connector .connector .connector_transaction_id(payment_data.payment_attempt.clone())? .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?, cancellation_reason: payment_data.payment_attempt.cancellation_reason, connector_meta: payment_data.payment_attempt.connector_metadata, browser_info, metadata: payment_data.payment_intent.metadata, webhook_url, capture_method, }) } } impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsApproveData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; let amount = payment_data.payment_attempt.get_total_amount(); Ok(Self { amount: Some(amount.get_amount_as_i64()), //need to change after we move to connector module currency: Some(payment_data.currency), }) } } #[cfg(feature = "v2")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SdkPaymentsSessionUpdateData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { todo!() } } #[cfg(feature = "v1")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SdkPaymentsSessionUpdateData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; let order_tax_amount = payment_data .payment_intent .tax_details .clone() .and_then(|tax| tax.payment_method_type.map(|pmt| pmt.order_tax_amount)) .ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "order_tax_amount", })?; let surcharge_amount = payment_data .surcharge_details .as_ref() .map(|surcharge_details| surcharge_details.get_total_surcharge_amount()) .unwrap_or_default(); let shipping_cost = payment_data .payment_intent .shipping_cost .unwrap_or_default(); // net_amount here would include amount, order_tax_amount, surcharge_amount and shipping_cost let net_amount = payment_data.payment_intent.amount + order_tax_amount + shipping_cost + surcharge_amount; Ok(Self { amount: net_amount, order_tax_amount, currency: payment_data.currency, order_amount: payment_data.payment_intent.amount, session_id: payment_data.session_id, shipping_cost: payment_data.payment_intent.shipping_cost, }) } } #[cfg(feature = "v2")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPostSessionTokensData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { todo!() } } #[cfg(feature = "v1")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPostSessionTokensData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data.clone(); let surcharge_amount = payment_data .surcharge_details .as_ref() .map(|surcharge_details| surcharge_details.get_total_surcharge_amount()) .unwrap_or_default(); let shipping_cost = payment_data .payment_intent .shipping_cost .unwrap_or_default(); // amount here would include amount, surcharge_amount and shipping_cost let amount = payment_data.payment_intent.amount + shipping_cost + surcharge_amount; let merchant_order_reference_id = payment_data .payment_intent .merchant_order_reference_id .clone(); let router_base_url = &additional_data.router_base_url; let connector_name = &additional_data.connector_name; let attempt = &payment_data.payment_attempt; let router_return_url = Some(helpers::create_redirect_url( router_base_url, attempt, connector_name, payment_data.creds_identifier.as_deref(), )); Ok(Self { amount, //need to change after we move to connector module order_amount: payment_data.payment_intent.amount, currency: payment_data.currency, merchant_order_reference_id, capture_method: payment_data.payment_attempt.capture_method, shipping_cost: payment_data.payment_intent.shipping_cost, setup_future_usage: payment_data.payment_intent.setup_future_usage, router_return_url, }) } } impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsRejectData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; let amount = payment_data.payment_attempt.get_total_amount(); Ok(Self { amount: Some(amount.get_amount_as_i64()), //need to change after we move to connector module currency: Some(payment_data.currency), }) } } #[cfg(feature = "v2")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSessionData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data.clone(); let order_details = additional_data .payment_data .payment_intent .order_details .map(|order_details| { order_details .iter() .map(|data| data.to_owned().expose()) .collect() }); let surcharge_amount = payment_data .surcharge_details .as_ref() .map(|surcharge_details| surcharge_details.get_total_surcharge_amount()) .unwrap_or_default(); let amount = payment_data.payment_intent.amount_details.order_amount; let shipping_cost = payment_data .payment_intent .amount_details .shipping_cost .unwrap_or_default(); // net_amount here would include amount, surcharge_amount and shipping_cost let net_amount = amount + surcharge_amount + shipping_cost; let required_amount_type = StringMajorUnitForConnector; let apple_pay_amount = required_amount_type .convert(net_amount, payment_data.currency) .change_context(errors::ApiErrorResponse::PreconditionFailed { message: "Failed to convert amount to string major unit for applePay".to_string(), })?; let apple_pay_recurring_details = payment_data .payment_intent .feature_metadata .and_then(|feature_metadata| feature_metadata.apple_pay_recurring_details) .map(|apple_pay_recurring_details| { ForeignInto::foreign_into((apple_pay_recurring_details, apple_pay_amount)) }); Ok(Self { amount: amount.get_amount_as_i64(), //need to change once we move to connector module minor_amount: amount, currency: payment_data.currency, country: payment_data.address.get_payment_method_billing().and_then( |billing_address| { billing_address .address .as_ref() .and_then(|address| address.country) }, ), order_details, surcharge_details: payment_data.surcharge_details, email: payment_data.email, apple_pay_recurring_details, }) } } #[cfg(feature = "v1")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSessionData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data.clone(); let order_details = additional_data .payment_data .payment_intent .order_details .map(|order_details| { order_details .iter() .map(|data| { data.to_owned() .parse_value("OrderDetailsWithAmount") .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "OrderDetailsWithAmount", }) .attach_printable("Unable to parse OrderDetailsWithAmount") }) .collect::<Result<Vec<_>, _>>() }) .transpose()?; let surcharge_amount = payment_data .surcharge_details .as_ref() .map(|surcharge_details| surcharge_details.get_total_surcharge_amount()) .unwrap_or_default(); let amount = payment_data.payment_intent.amount; let shipping_cost = payment_data .payment_intent .shipping_cost .unwrap_or_default(); // net_amount here would include amount, surcharge_amount and shipping_cost let net_amount = amount + surcharge_amount + shipping_cost; let required_amount_type = StringMajorUnitForConnector; let apple_pay_amount = required_amount_type .convert(net_amount, payment_data.currency) .change_context(errors::ApiErrorResponse::PreconditionFailed { message: "Failed to convert amount to string major unit for applePay".to_string(), })?; let apple_pay_recurring_details = payment_data .payment_intent .feature_metadata .map(|feature_metadata| { feature_metadata .parse_value::<diesel_models::types::FeatureMetadata>("FeatureMetadata") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed parsing FeatureMetadata") }) .transpose()? .and_then(|feature_metadata| feature_metadata.apple_pay_recurring_details) .map(|apple_pay_recurring_details| { ForeignFrom::foreign_from((apple_pay_recurring_details, apple_pay_amount)) }); Ok(Self { amount: net_amount.get_amount_as_i64(), //need to change once we move to connector module minor_amount: amount, currency: payment_data.currency, country: payment_data.address.get_payment_method_billing().and_then( |billing_address| { billing_address .address .as_ref() .and_then(|address| address.country) }, ), order_details, email: payment_data.email, surcharge_details: payment_data.surcharge_details, apple_pay_recurring_details, }) } } impl ForeignFrom<( diesel_models::types::ApplePayRecurringDetails, StringMajorUnit, )> for api_models::payments::ApplePayRecurringPaymentRequest { fn foreign_from( (apple_pay_recurring_details, net_amount): ( diesel_models::types::ApplePayRecurringDetails, StringMajorUnit, ), ) -> Self { Self { payment_description: apple_pay_recurring_details.payment_description, regular_billing: api_models::payments::ApplePayRegularBillingRequest { amount: net_amount, label: apple_pay_recurring_details.regular_billing.label, payment_timing: api_models::payments::ApplePayPaymentTiming::Recurring, recurring_payment_start_date: apple_pay_recurring_details .regular_billing .recurring_payment_start_date, recurring_payment_end_date: apple_pay_recurring_details .regular_billing .recurring_payment_end_date, recurring_payment_interval_unit: apple_pay_recurring_details .regular_billing .recurring_payment_interval_unit .map(ForeignFrom::foreign_from), recurring_payment_interval_count: apple_pay_recurring_details .regular_billing .recurring_payment_interval_count, }, billing_agreement: apple_pay_recurring_details.billing_agreement, management_u_r_l: apple_pay_recurring_details.management_url, } } } impl ForeignFrom<diesel_models::types::ApplePayRecurringDetails> for api_models::payments::ApplePayRecurringDetails { fn foreign_from( apple_pay_recurring_details: diesel_models::types::ApplePayRecurringDetails, ) -> Self { Self { payment_description: apple_pay_recurring_details.payment_description, regular_billing: ForeignFrom::foreign_from(apple_pay_recurring_details.regular_billing), billing_agreement: apple_pay_recurring_details.billing_agreement, management_url: apple_pay_recurring_details.management_url, } } } impl ForeignFrom<diesel_models::types::ApplePayRegularBillingDetails> for api_models::payments::ApplePayRegularBillingDetails { fn foreign_from( apple_pay_regular_billing: diesel_models::types::ApplePayRegularBillingDetails, ) -> Self { Self { label: apple_pay_regular_billing.label, recurring_payment_start_date: apple_pay_regular_billing.recurring_payment_start_date, recurring_payment_end_date: apple_pay_regular_billing.recurring_payment_end_date, recurring_payment_interval_unit: apple_pay_regular_billing .recurring_payment_interval_unit .map(ForeignFrom::foreign_from), recurring_payment_interval_count: apple_pay_regular_billing .recurring_payment_interval_count, } } } impl ForeignFrom<diesel_models::types::RecurringPaymentIntervalUnit> for api_models::payments::RecurringPaymentIntervalUnit { fn foreign_from( apple_pay_recurring_payment_interval_unit: diesel_models::types::RecurringPaymentIntervalUnit, ) -> Self { match apple_pay_recurring_payment_interval_unit { diesel_models::types::RecurringPaymentIntervalUnit::Day => Self::Day, diesel_models::types::RecurringPaymentIntervalUnit::Month => Self::Month, diesel_models::types::RecurringPaymentIntervalUnit::Year => Self::Year, diesel_models::types::RecurringPaymentIntervalUnit::Hour => Self::Hour, diesel_models::types::RecurringPaymentIntervalUnit::Minute => Self::Minute, } } } #[cfg(feature = "v1")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequestData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; let router_base_url = &additional_data.router_base_url; let connector_name = &additional_data.connector_name; let attempt = &payment_data.payment_attempt; let router_return_url = Some(helpers::create_redirect_url( router_base_url, attempt, connector_name, payment_data.creds_identifier.as_deref(), )); let browser_info: Option<types::BrowserInformation> = attempt .browser_info .clone() .map(|b| b.parse_value("BrowserInformation")) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "browser_info", })?; let customer_name = additional_data .customer_data .as_ref() .and_then(|customer_data| { customer_data .name .as_ref() .map(|customer| customer.clone().into_inner()) }); let amount = payment_data.payment_attempt.get_total_amount(); let merchant_connector_account_id_or_connector_name = payment_data .payment_attempt .merchant_connector_id .as_ref() .map(|mca_id| mca_id.get_string_repr()) .unwrap_or(connector_name); let webhook_url = Some(helpers::create_webhook_url( router_base_url, &attempt.merchant_id, merchant_connector_account_id_or_connector_name, )); let complete_authorize_url = Some(helpers::create_complete_authorize_url( router_base_url, attempt, connector_name, payment_data.creds_identifier.as_deref(), )); Ok(Self { currency: payment_data.currency, confirm: true, amount: Some(amount.get_amount_as_i64()), //need to change once we move to connector module minor_amount: Some(amount), payment_method_data: (payment_data .payment_method_data .get_required_value("payment_method_data")?), statement_descriptor_suffix: payment_data.payment_intent.statement_descriptor_suffix, setup_future_usage: payment_data.payment_intent.setup_future_usage, off_session: payment_data.mandate_id.as_ref().map(|_| true), mandate_id: payment_data.mandate_id.clone(), setup_mandate_details: payment_data.setup_mandate, customer_acceptance: payment_data.customer_acceptance, router_return_url, email: payment_data.email, customer_name, return_url: payment_data.payment_intent.return_url, browser_info, payment_method_type: attempt.payment_method_type, request_incremental_authorization: matches!( payment_data .payment_intent .request_incremental_authorization, Some(RequestIncrementalAuthorization::True) | Some(RequestIncrementalAuthorization::Default) ), metadata: payment_data.payment_intent.metadata.clone().map(Into::into), shipping_cost: payment_data.payment_intent.shipping_cost, webhook_url, complete_authorize_url, capture_method: payment_data.payment_attempt.capture_method, }) } } #[cfg(feature = "v2")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequestData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { todo!() } } impl ForeignTryFrom<types::CaptureSyncResponse> for storage::CaptureUpdate { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from( capture_sync_response: types::CaptureSyncResponse, ) -> Result<Self, Self::Error> { match capture_sync_response { types::CaptureSyncResponse::Success { resource_id, status, connector_response_reference_id, .. } => { let (connector_capture_id, processor_capture_data) = match resource_id { types::ResponseId::EncodedData(_) | types::ResponseId::NoResponseId => { (None, None) } types::ResponseId::ConnectorTransactionId(id) => { let (txn_id, txn_data) = common_utils_type::ConnectorTransactionId::form_id_and_data(id); (Some(txn_id), txn_data) } }; Ok(Self::ResponseUpdate { status: enums::CaptureStatus::foreign_try_from(status)?, connector_capture_id, connector_response_reference_id, processor_capture_data, }) } types::CaptureSyncResponse::Error { code, message, reason, status_code, .. } => Ok(Self::ErrorUpdate { status: match status_code { 500..=511 => enums::CaptureStatus::Pending, _ => enums::CaptureStatus::Failed, }, error_code: Some(code), error_message: Some(message), error_reason: reason, }), } } } #[cfg(feature = "v1")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::CompleteAuthorizeData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; let router_base_url = &additional_data.router_base_url; let connector_name = &additional_data.connector_name; let attempt = &payment_data.payment_attempt; let browser_info: Option<types::BrowserInformation> = payment_data .payment_attempt .browser_info .clone() .map(|b| b.parse_value("BrowserInformation")) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "browser_info", })?; let redirect_response = payment_data.redirect_response.map(|redirect| { types::CompleteAuthorizeRedirectResponse { params: redirect.param, payload: redirect.json_payload, } }); let amount = payment_data.payment_attempt.get_total_amount(); let complete_authorize_url = Some(helpers::create_complete_authorize_url( router_base_url, attempt, connector_name, payment_data.creds_identifier.as_deref(), )); let braintree_metadata = payment_data .payment_intent .connector_metadata .clone() .map(|cm| { cm.parse_value::<api_models::payments::ConnectorMetadata>("ConnectorMetadata") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed parsing ConnectorMetadata") }) .transpose()? .and_then(|cm| cm.braintree); let merchant_account_id = braintree_metadata .as_ref() .and_then(|braintree| braintree.merchant_account_id.clone()); let merchant_config_currency = braintree_metadata.and_then(|braintree| braintree.merchant_config_currency); Ok(Self { setup_future_usage: payment_data.payment_intent.setup_future_usage, mandate_id: payment_data.mandate_id.clone(), off_session: payment_data.mandate_id.as_ref().map(|_| true), setup_mandate_details: payment_data.setup_mandate.clone(), confirm: payment_data.payment_attempt.confirm, statement_descriptor_suffix: payment_data.payment_intent.statement_descriptor_suffix, capture_method: payment_data.payment_attempt.capture_method, amount: amount.get_amount_as_i64(), // need to change once we move to connector module minor_amount: amount, currency: payment_data.currency, browser_info, email: payment_data.email, payment_method_data: payment_data.payment_method_data, connector_transaction_id: payment_data .payment_attempt .get_connector_payment_id() .map(ToString::to_string), redirect_response, connector_meta: payment_data.payment_attempt.connector_metadata, complete_authorize_url, metadata: payment_data.payment_intent.metadata, customer_acceptance: payment_data.customer_acceptance, merchant_account_id, merchant_config_currency, threeds_method_comp_ind: payment_data.threeds_method_comp_ind, }) } } #[cfg(feature = "v2")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::CompleteAuthorizeData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { todo!() } } #[cfg(feature = "v2")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPreProcessingData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { todo!() } } #[cfg(feature = "v1")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPreProcessingData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; let payment_method_data = payment_data.payment_method_data; let router_base_url = &additional_data.router_base_url; let attempt = &payment_data.payment_attempt; let connector_name = &additional_data.connector_name; let order_details = payment_data .payment_intent .order_details .map(|order_details| { order_details .iter() .map(|data| { data.to_owned() .parse_value("OrderDetailsWithAmount") .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "OrderDetailsWithAmount", }) .attach_printable("Unable to parse OrderDetailsWithAmount") }) .collect::<Result<Vec<_>, _>>() }) .transpose()?; let merchant_connector_account_id_or_connector_name = payment_data .payment_attempt .merchant_connector_id .as_ref() .map(|mca_id| mca_id.get_string_repr()) .unwrap_or(connector_name); let webhook_url = Some(helpers::create_webhook_url( router_base_url, &attempt.merchant_id, merchant_connector_account_id_or_connector_name, )); let router_return_url = Some(helpers::create_redirect_url( router_base_url, attempt, connector_name, payment_data.creds_identifier.as_deref(), )); let complete_authorize_url = Some(helpers::create_complete_authorize_url( router_base_url, attempt, connector_name, payment_data.creds_identifier.as_deref(), )); let browser_info: Option<types::BrowserInformation> = payment_data .payment_attempt .browser_info .clone() .map(|b| b.parse_value("BrowserInformation")) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "browser_info", })?; let amount = payment_data.payment_attempt.get_total_amount(); Ok(Self { payment_method_data, email: payment_data.email, currency: Some(payment_data.currency), amount: Some(amount.get_amount_as_i64()), // need to change this once we move to connector module minor_amount: Some(amount), payment_method_type: payment_data.payment_attempt.payment_method_type, setup_mandate_details: payment_data.setup_mandate, capture_method: payment_data.payment_attempt.capture_method, order_details, router_return_url, webhook_url, complete_authorize_url, browser_info, surcharge_details: payment_data.surcharge_details, connector_transaction_id: payment_data .payment_attempt .get_connector_payment_id() .map(ToString::to_string), redirect_response: None, mandate_id: payment_data.mandate_id, related_transaction_id: None, enrolled_for_3ds: true, split_payments: payment_data.payment_intent.split_payments, metadata: payment_data.payment_intent.metadata.map(Secret::new), }) } } impl ForeignFrom<payments::FraudCheck> for FrmMessage { fn foreign_from(fraud_check: payments::FraudCheck) -> Self { Self { frm_name: fraud_check.frm_name, frm_transaction_id: fraud_check.frm_transaction_id, frm_transaction_type: Some(fraud_check.frm_transaction_type.to_string()), frm_status: Some(fraud_check.frm_status.to_string()), frm_score: fraud_check.frm_score, frm_reason: fraud_check.frm_reason, frm_error: fraud_check.frm_error, } } } impl ForeignFrom<CustomerDetails> for router_request_types::CustomerDetails { fn foreign_from(customer: CustomerDetails) -> Self { Self { customer_id: Some(customer.id), name: customer.name, email: customer.email, phone: customer.phone, phone_country_code: customer.phone_country_code, } } } /// The response amount details in the confirm intent response will have the combined fields from /// intent amount details and attempt amount details. #[cfg(feature = "v2")] impl ForeignFrom<( &hyperswitch_domain_models::payments::AmountDetails, &hyperswitch_domain_models::payments::payment_attempt::AttemptAmountDetails, )> for api_models::payments::PaymentAmountDetailsResponse { fn foreign_from( (intent_amount_details, attempt_amount_details): ( &hyperswitch_domain_models::payments::AmountDetails, &hyperswitch_domain_models::payments::payment_attempt::AttemptAmountDetails, ), ) -> Self { Self { order_amount: intent_amount_details.order_amount, currency: intent_amount_details.currency, shipping_cost: attempt_amount_details.get_shipping_cost(), order_tax_amount: attempt_amount_details.get_order_tax_amount(), external_tax_calculation: intent_amount_details.skip_external_tax_calculation, surcharge_calculation: intent_amount_details.skip_surcharge_calculation, surcharge_amount: attempt_amount_details.get_surcharge_amount(), tax_on_surcharge: attempt_amount_details.get_tax_on_surcharge(), net_amount: attempt_amount_details.get_net_amount(), amount_to_capture: attempt_amount_details.get_amount_to_capture(), amount_capturable: attempt_amount_details.get_amount_capturable(), amount_captured: intent_amount_details.amount_captured, } } } /// The response amount details in the confirm intent response will have the combined fields from /// intent amount details and attempt amount details. #[cfg(feature = "v2")] impl ForeignFrom<( &hyperswitch_domain_models::payments::AmountDetails, Option<&hyperswitch_domain_models::payments::payment_attempt::AttemptAmountDetails>, )> for api_models::payments::PaymentAmountDetailsResponse { fn foreign_from( (intent_amount_details, attempt_amount_details): ( &hyperswitch_domain_models::payments::AmountDetails, Option<&hyperswitch_domain_models::payments::payment_attempt::AttemptAmountDetails>, ), ) -> Self { Self { order_amount: intent_amount_details.order_amount, currency: intent_amount_details.currency, shipping_cost: attempt_amount_details .and_then(|attempt_amount| attempt_amount.get_shipping_cost()) .or(intent_amount_details.shipping_cost), order_tax_amount: attempt_amount_details .and_then(|attempt_amount| attempt_amount.get_order_tax_amount()) .or(intent_amount_details .tax_details .as_ref() .and_then(|tax_details| tax_details.get_default_tax_amount())), external_tax_calculation: intent_amount_details.skip_external_tax_calculation, surcharge_calculation: intent_amount_details.skip_surcharge_calculation, surcharge_amount: attempt_amount_details .and_then(|attempt| attempt.get_surcharge_amount()) .or(intent_amount_details.surcharge_amount), tax_on_surcharge: attempt_amount_details .and_then(|attempt| attempt.get_tax_on_surcharge()) .or(intent_amount_details.tax_on_surcharge), net_amount: attempt_amount_details .map(|attempt| attempt.get_net_amount()) .unwrap_or(intent_amount_details.calculate_net_amount()), amount_to_capture: attempt_amount_details .and_then(|attempt| attempt.get_amount_to_capture()), amount_capturable: attempt_amount_details .map(|attempt| attempt.get_amount_capturable()) .unwrap_or(MinorUnit::zero()), amount_captured: intent_amount_details.amount_captured, } } } #[cfg(feature = "v2")] impl ForeignFrom<&hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt> for api_models::payments::PaymentAttemptResponse { fn foreign_from( attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, ) -> Self { Self { id: attempt.get_id().to_owned(), status: attempt.status, amount: api_models::payments::PaymentAttemptAmountDetails::foreign_from( &attempt.amount_details, ), connector: attempt.connector.clone(), error: attempt .error .as_ref() .map(api_models::payments::ErrorDetails::foreign_from), authentication_type: attempt.authentication_type, created_at: attempt.created_at, modified_at: attempt.modified_at, cancellation_reason: attempt.cancellation_reason.clone(), payment_token: attempt.payment_token.clone(), connector_metadata: attempt.connector_metadata.clone(), payment_experience: attempt.payment_experience, payment_method_type: attempt.payment_method_type, connector_reference_id: attempt.connector_response_reference_id.clone(), payment_method_subtype: attempt.get_payment_method_type(), connector_payment_id: attempt .get_connector_payment_id() .map(|str| common_utils::types::ConnectorTransactionId::from(str.to_owned())), payment_method_id: attempt.payment_method_id.clone(), client_source: attempt.client_source.clone(), client_version: attempt.client_version.clone(), feature_metadata: attempt .feature_metadata .as_ref() .map(api_models::payments::PaymentAttemptFeatureMetadata::foreign_from), } } } #[cfg(feature = "v2")] impl ForeignFrom<&hyperswitch_domain_models::payments::payment_attempt::AttemptAmountDetails> for api_models::payments::PaymentAttemptAmountDetails { fn foreign_from( amount: &hyperswitch_domain_models::payments::payment_attempt::AttemptAmountDetails, ) -> Self { Self { net_amount: amount.get_net_amount(), amount_to_capture: amount.get_amount_to_capture(), surcharge_amount: amount.get_surcharge_amount(), tax_on_surcharge: amount.get_tax_on_surcharge(), amount_capturable: amount.get_amount_capturable(), shipping_cost: amount.get_shipping_cost(), order_tax_amount: amount.get_order_tax_amount(), } } } #[cfg(feature = "v2")] impl ForeignFrom<&hyperswitch_domain_models::payments::payment_attempt::ErrorDetails> for api_models::payments::ErrorDetails { fn foreign_from( error_details: &hyperswitch_domain_models::payments::payment_attempt::ErrorDetails, ) -> Self { Self { code: error_details.code.to_owned(), message: error_details.message.to_owned(), unified_code: error_details.unified_code.clone(), unified_message: error_details.unified_message.clone(), network_advice_code: error_details.network_advice_code.clone(), network_decline_code: error_details.network_decline_code.clone(), network_error_message: error_details.network_error_message.clone(), } } } #[cfg(feature = "v2")] impl ForeignFrom< &hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptFeatureMetadata, > for api_models::payments::PaymentAttemptFeatureMetadata { fn foreign_from( feature_metadata: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptFeatureMetadata, ) -> Self { let revenue_recovery = feature_metadata.revenue_recovery.as_ref().map(|recovery| { api_models::payments::PaymentAttemptRevenueRecoveryData { attempt_triggered_by: recovery.attempt_triggered_by, } }); Self { revenue_recovery } } } #[cfg(feature = "v2")] impl ForeignFrom<hyperswitch_domain_models::payments::AmountDetails> for api_models::payments::AmountDetailsResponse { fn foreign_from(amount_details: hyperswitch_domain_models::payments::AmountDetails) -> Self { Self { order_amount: amount_details.order_amount, currency: amount_details.currency, shipping_cost: amount_details.shipping_cost, order_tax_amount: amount_details.tax_details.and_then(|tax_details| { tax_details.default.map(|default| default.order_tax_amount) }), external_tax_calculation: amount_details.skip_external_tax_calculation, surcharge_calculation: amount_details.skip_surcharge_calculation, surcharge_amount: amount_details.surcharge_amount, tax_on_surcharge: amount_details.tax_on_surcharge, } } } #[cfg(feature = "v2")] impl ForeignFrom<api_models::admin::PaymentLinkConfigRequest> for diesel_models::PaymentLinkConfigRequestForPayments { fn foreign_from(config: api_models::admin::PaymentLinkConfigRequest) -> Self { Self { theme: config.theme, logo: config.logo, seller_name: config.seller_name, sdk_layout: config.sdk_layout, display_sdk_only: config.display_sdk_only, enabled_saved_payment_method: config.enabled_saved_payment_method, hide_card_nickname_field: config.hide_card_nickname_field, show_card_form_by_default: config.show_card_form_by_default, details_layout: config.details_layout, transaction_details: config.transaction_details.map(|transaction_details| { transaction_details .iter() .map(|details| { diesel_models::PaymentLinkTransactionDetails::foreign_from(details.clone()) }) .collect() }), background_image: config.background_image.map(|background_image| { diesel_models::business_profile::PaymentLinkBackgroundImageConfig::foreign_from( background_image.clone(), ) }), payment_button_text: config.payment_button_text, custom_message_for_card_terms: config.custom_message_for_card_terms, payment_button_colour: config.payment_button_colour, skip_status_screen: config.skip_status_screen, background_colour: config.background_colour, payment_button_text_colour: config.payment_button_text_colour, sdk_ui_rules: config.sdk_ui_rules, payment_link_ui_rules: config.payment_link_ui_rules, enable_button_only_on_form_ready: config.enable_button_only_on_form_ready, } } } #[cfg(feature = "v2")] impl ForeignFrom<api_models::admin::PaymentLinkTransactionDetails> for diesel_models::PaymentLinkTransactionDetails { fn foreign_from(from: api_models::admin::PaymentLinkTransactionDetails) -> Self { Self { key: from.key, value: from.value, ui_configuration: from .ui_configuration .map(diesel_models::TransactionDetailsUiConfiguration::foreign_from), } } } #[cfg(feature = "v2")] impl ForeignFrom<api_models::admin::TransactionDetailsUiConfiguration> for diesel_models::TransactionDetailsUiConfiguration { fn foreign_from(from: api_models::admin::TransactionDetailsUiConfiguration) -> Self { Self { position: from.position, is_key_bold: from.is_key_bold, is_value_bold: from.is_value_bold, } } } #[cfg(feature = "v2")] impl ForeignFrom<diesel_models::PaymentLinkConfigRequestForPayments> for api_models::admin::PaymentLinkConfigRequest { fn foreign_from(config: diesel_models::PaymentLinkConfigRequestForPayments) -> Self { Self { theme: config.theme, logo: config.logo, seller_name: config.seller_name, sdk_layout: config.sdk_layout, display_sdk_only: config.display_sdk_only, enabled_saved_payment_method: config.enabled_saved_payment_method, hide_card_nickname_field: config.hide_card_nickname_field, show_card_form_by_default: config.show_card_form_by_default, details_layout: config.details_layout, transaction_details: config.transaction_details.map(|transaction_details| { transaction_details .iter() .map(|details| { api_models::admin::PaymentLinkTransactionDetails::foreign_from( details.clone(), ) }) .collect() }), background_image: config.background_image.map(|background_image| { api_models::admin::PaymentLinkBackgroundImageConfig::foreign_from( background_image.clone(), ) }), payment_button_text: config.payment_button_text, custom_message_for_card_terms: config.custom_message_for_card_terms, payment_button_colour: config.payment_button_colour, skip_status_screen: config.skip_status_screen, background_colour: config.background_colour, payment_button_text_colour: config.payment_button_text_colour, sdk_ui_rules: config.sdk_ui_rules, payment_link_ui_rules: config.payment_link_ui_rules, enable_button_only_on_form_ready: config.enable_button_only_on_form_ready, } } } #[cfg(feature = "v2")] impl ForeignFrom<diesel_models::PaymentLinkTransactionDetails> for api_models::admin::PaymentLinkTransactionDetails { fn foreign_from(from: diesel_models::PaymentLinkTransactionDetails) -> Self { Self { key: from.key, value: from.value, ui_configuration: from .ui_configuration .map(api_models::admin::TransactionDetailsUiConfiguration::foreign_from), } } } #[cfg(feature = "v2")] impl ForeignFrom<diesel_models::TransactionDetailsUiConfiguration> for api_models::admin::TransactionDetailsUiConfiguration { fn foreign_from(from: diesel_models::TransactionDetailsUiConfiguration) -> Self { Self { position: from.position, is_key_bold: from.is_key_bold, is_value_bold: from.is_value_bold, } } } impl ForeignFrom<DieselConnectorMandateReferenceId> for ConnectorMandateReferenceId { fn foreign_from(value: DieselConnectorMandateReferenceId) -> Self { Self::new( value.connector_mandate_id, value.payment_method_id, None, value.mandate_metadata, value.connector_mandate_request_reference_id, ) } } impl ForeignFrom<ConnectorMandateReferenceId> for DieselConnectorMandateReferenceId { fn foreign_from(value: ConnectorMandateReferenceId) -> Self { Self { connector_mandate_id: value.get_connector_mandate_id(), payment_method_id: value.get_payment_method_id(), mandate_metadata: value.get_mandate_metadata(), connector_mandate_request_reference_id: value .get_connector_mandate_request_reference_id(), } } } #[cfg(feature = "v2")] impl ForeignFrom<diesel_models::ConnectorTokenDetails> for Option<api_models::payments::ConnectorTokenDetails> { fn foreign_from(value: diesel_models::ConnectorTokenDetails) -> Self { let connector_token_request_reference_id = value.connector_token_request_reference_id.clone(); value.connector_mandate_id.clone().map(|mandate_id| { api_models::payments::ConnectorTokenDetails { token: mandate_id, connector_token_request_reference_id, } }) } } impl ForeignFrom<(Self, Option<&api_models::payments::AdditionalPaymentData>)> for Option<enums::PaymentMethodType> { fn foreign_from(req: (Self, Option<&api_models::payments::AdditionalPaymentData>)) -> Self { let (payment_method_type, additional_pm_data) = req; additional_pm_data .and_then(|pm_data| { if let api_models::payments::AdditionalPaymentData::Card(card_info) = pm_data { card_info.card_type.as_ref().and_then(|card_type_str| { api_models::enums::PaymentMethodType::from_str(&card_type_str.to_lowercase()).map_err(|err| { crate::logger::error!( "Err - {:?}\nInvalid card_type value found in BIN DB - {:?}", err, card_type_str, ); }).ok() }) } else { None } }) .map_or(payment_method_type, |card_type_in_bin_store| { if let Some(card_type_in_req) = payment_method_type { if card_type_in_req != card_type_in_bin_store { crate::logger::info!( "Mismatch in card_type\nAPI request - {}; BIN lookup - {}\nOverriding with {}", card_type_in_req, card_type_in_bin_store, card_type_in_bin_store, ); } } Some(card_type_in_bin_store) }) } }
37,520
1,603
hyperswitch
crates/router/src/core/payments/flows.rs
.rs
pub mod approve_flow; pub mod authorize_flow; pub mod cancel_flow; pub mod capture_flow; pub mod complete_authorize_flow; pub mod incremental_authorization_flow; pub mod post_session_tokens_flow; pub mod psync_flow; pub mod reject_flow; pub mod session_flow; pub mod session_update_flow; pub mod setup_mandate_flow; use async_trait::async_trait; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] use hyperswitch_domain_models::router_flow_types::{ BillingConnectorPaymentsSync, RecoveryRecordBack, }; use hyperswitch_domain_models::{ mandates::CustomerAcceptance, router_flow_types::{ Authenticate, AuthenticationConfirmation, PostAuthenticate, PreAuthenticate, }, router_request_types::PaymentsCaptureData, }; use hyperswitch_interfaces::api::{ payouts::Payouts, UasAuthentication, UasAuthenticationConfirmation, UasPostAuthentication, UasPreAuthentication, UnifiedAuthenticationService, }; #[cfg(feature = "frm")] use crate::types::fraud_check as frm_types; use crate::{ connector, core::{ errors::{ApiErrorResponse, ConnectorError, CustomResult, RouterResult}, payments::{self, helpers}, }, logger, routes::SessionState, services, types as router_types, types::{self, api, api::enums as api_enums, domain}, }; #[async_trait] #[allow(clippy::too_many_arguments)] pub trait ConstructFlowSpecificData<F, Req, Res> { #[cfg(feature = "v1")] async fn construct_router_data<'a>( &self, state: &SessionState, connector_id: &str, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, merchant_recipient_data: Option<types::MerchantRecipientData>, header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>, ) -> RouterResult<types::RouterData<F, Req, Res>>; #[cfg(feature = "v2")] async fn construct_router_data<'a>( &self, _state: &SessionState, _connector_id: &str, _merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _merchant_connector_account: &domain::MerchantConnectorAccount, _merchant_recipient_data: Option<types::MerchantRecipientData>, _header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>, ) -> RouterResult<types::RouterData<F, Req, Res>>; async fn get_merchant_recipient_data<'a>( &self, state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, merchant_connector_account: &helpers::MerchantConnectorAccountType, connector: &api::ConnectorData, ) -> RouterResult<Option<types::MerchantRecipientData>>; } #[allow(clippy::too_many_arguments)] #[async_trait] 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)) } } macro_rules! default_imp_for_complete_authorize { ($($path:ident::$connector:ident),*) => { $( impl api::PaymentsCompleteAuthorize for $path::$connector {} impl services::ConnectorIntegration< api::CompleteAuthorize, types::CompleteAuthorizeData, types::PaymentsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PaymentsCompleteAuthorize for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration< api::CompleteAuthorize, types::CompleteAuthorizeData, types::PaymentsResponseData, > for connector::DummyConnector<T> { } default_imp_for_complete_authorize!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, connector::Wise, connector::Wellsfargopayout ); macro_rules! default_imp_for_webhook_source_verification { ($($path:ident::$connector:ident),*) => { $( impl api::ConnectorVerifyWebhookSource for $path::$connector {} impl services::ConnectorIntegration< api::VerifyWebhookSource, types::VerifyWebhookSourceRequestData, types::VerifyWebhookSourceResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "dummy_connector")] impl<const T: u8> api::ConnectorVerifyWebhookSource for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration< api::VerifyWebhookSource, types::VerifyWebhookSourceRequestData, types::VerifyWebhookSourceResponseData, > for connector::DummyConnector<T> { } default_imp_for_webhook_source_verification!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise ); macro_rules! default_imp_for_create_customer { ($($path:ident::$connector:ident),*) => { $( impl api::ConnectorCustomer for $path::$connector {} impl services::ConnectorIntegration< api::CreateConnectorCustomer, types::ConnectorCustomerData, types::PaymentsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "dummy_connector")] impl<const T: u8> api::ConnectorCustomer for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration< api::CreateConnectorCustomer, types::ConnectorCustomerData, types::PaymentsResponseData, > for connector::DummyConnector<T> { } default_imp_for_create_customer!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise ); macro_rules! default_imp_for_connector_redirect_response { ($($path:ident::$connector:ident),*) => { $( impl services::ConnectorRedirectResponse for $path::$connector { fn get_flow_type( &self, _query_params: &str, _json_payload: Option<serde_json::Value>, _action: services::PaymentAction ) -> CustomResult<payments::CallConnectorAction, ConnectorError> { Ok(payments::CallConnectorAction::Trigger) } } )* }; } #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorRedirectResponse for connector::DummyConnector<T> { fn get_flow_type( &self, _query_params: &str, _json_payload: Option<serde_json::Value>, _action: services::PaymentAction, ) -> CustomResult<payments::CallConnectorAction, ConnectorError> { Ok(payments::CallConnectorAction::Trigger) } } default_imp_for_connector_redirect_response!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise ); macro_rules! default_imp_for_connector_request_id { ($($path:ident::$connector:ident),*) => { $( impl api::ConnectorTransactionId for $path::$connector {} )* }; } #[cfg(feature = "dummy_connector")] impl<const T: u8> api::ConnectorTransactionId for connector::DummyConnector<T> {} default_imp_for_connector_request_id!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise ); macro_rules! default_imp_for_accept_dispute { ($($path:ident::$connector:ident),*) => { $( impl api::Dispute for $path::$connector {} impl api::AcceptDispute for $path::$connector {} impl services::ConnectorIntegration< api::Accept, types::AcceptDisputeRequestData, types::AcceptDisputeResponse, > for $path::$connector {} )* }; } #[cfg(feature = "dummy_connector")] impl<const T: u8> api::Dispute for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> api::AcceptDispute for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration< api::Accept, types::AcceptDisputeRequestData, types::AcceptDisputeResponse, > for connector::DummyConnector<T> { } default_imp_for_accept_dispute!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise ); macro_rules! default_imp_for_file_upload { ($($path:ident::$connector:ident),*) => { $( impl api::FileUpload for $path::$connector {} impl api::UploadFile for $path::$connector {} impl services::ConnectorIntegration< api::Upload, types::UploadFileRequestData, types::UploadFileResponse, > for $path::$connector {} impl api::RetrieveFile for $path::$connector {} impl services::ConnectorIntegration< api::Retrieve, types::RetrieveFileRequestData, types::RetrieveFileResponse, > for $path::$connector {} )* }; } #[cfg(feature = "dummy_connector")] impl<const T: u8> api::FileUpload for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> api::UploadFile for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration< api::Upload, types::UploadFileRequestData, types::UploadFileResponse, > for connector::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> api::RetrieveFile for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration< api::Retrieve, types::RetrieveFileRequestData, types::RetrieveFileResponse, > for connector::DummyConnector<T> { } default_imp_for_file_upload!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise ); macro_rules! default_imp_for_submit_evidence { ($($path:ident::$connector:ident),*) => { $( impl api::SubmitEvidence for $path::$connector {} impl services::ConnectorIntegration< api::Evidence, types::SubmitEvidenceRequestData, types::SubmitEvidenceResponse, > for $path::$connector {} )* }; } #[cfg(feature = "dummy_connector")] impl<const T: u8> api::SubmitEvidence for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration< api::Evidence, types::SubmitEvidenceRequestData, types::SubmitEvidenceResponse, > for connector::DummyConnector<T> { } default_imp_for_submit_evidence!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise ); macro_rules! default_imp_for_defend_dispute { ($($path:ident::$connector:ident),*) => { $( impl api::DefendDispute for $path::$connector {} impl services::ConnectorIntegration< api::Defend, types::DefendDisputeRequestData, types::DefendDisputeResponse, > for $path::$connector {} )* }; } #[cfg(feature = "dummy_connector")] impl<const T: u8> api::DefendDispute for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration< api::Defend, types::DefendDisputeRequestData, types::DefendDisputeResponse, > for connector::DummyConnector<T> { } default_imp_for_defend_dispute!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise ); macro_rules! default_imp_for_pre_processing_steps{ ($($path:ident::$connector:ident),*)=> { $( impl api::PaymentsPreProcessing for $path::$connector {} impl services::ConnectorIntegration< api::PreProcessing, types::PaymentsPreProcessingData, types::PaymentsResponseData, > for $path::$connector {} )* }; } macro_rules! default_imp_for_post_processing_steps{ ($($path:ident::$connector:ident),*)=> { $( impl api::PaymentsPostProcessing for $path::$connector {} impl services::ConnectorIntegration< api::PostProcessing, types::PaymentsPostProcessingData, types::PaymentsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PaymentsPreProcessing for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration< api::PreProcessing, types::PaymentsPreProcessingData, types::PaymentsResponseData, > for connector::DummyConnector<T> { } default_imp_for_pre_processing_steps!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise ); #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PaymentsPostProcessing for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration< api::PostProcessing, types::PaymentsPostProcessingData, types::PaymentsResponseData, > for connector::DummyConnector<T> { } default_imp_for_post_processing_steps!( connector::Adyenplatform, connector::Nmi, connector::Stripe, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Payone, connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise ); macro_rules! default_imp_for_payouts { ($($path:ident::$connector:ident),*) => { $( impl Payouts for $path::$connector {} )* }; } #[cfg(feature = "dummy_connector")] impl<const T: u8> Payouts for connector::DummyConnector<T> {} default_imp_for_payouts!( connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout ); #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_create { ($($path:ident::$connector:ident),*) => { $( impl api::PayoutCreate for $path::$connector {} impl services::ConnectorIntegration< api::PoCreate, types::PayoutsData, types::PayoutsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PayoutCreate for connector::DummyConnector<T> {} #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::PayoutsResponseData> for connector::DummyConnector<T> { } #[cfg(feature = "payouts")] default_imp_for_payouts_create!( connector::Adyenplatform, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout ); #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_retrieve { ($($path:ident::$connector:ident),*) => { $( impl api::PayoutSync for $path::$connector {} impl services::ConnectorIntegration< api::PoSync, types::PayoutsData, types::PayoutsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PayoutSync for connector::DummyConnector<T> {} #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration<api::PoSync, types::PayoutsData, types::PayoutsResponseData> for connector::DummyConnector<T> { } #[cfg(feature = "payouts")] default_imp_for_payouts_retrieve!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise ); #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_eligibility { ($($path:ident::$connector:ident),*) => { $( impl api::PayoutEligibility for $path::$connector {} impl services::ConnectorIntegration< api::PoEligibility, types::PayoutsData, types::PayoutsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PayoutEligibility for connector::DummyConnector<T> {} #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration< api::PoEligibility, types::PayoutsData, types::PayoutsResponseData, > for connector::DummyConnector<T> { } #[cfg(feature = "payouts")] default_imp_for_payouts_eligibility!( connector::Adyenplatform, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout ); #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_fulfill { ($($path:ident::$connector:ident),*) => { $( impl api::PayoutFulfill for $path::$connector {} impl services::ConnectorIntegration< api::PoFulfill, types::PayoutsData, types::PayoutsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PayoutFulfill for connector::DummyConnector<T> {} #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResponseData> for connector::DummyConnector<T> { } #[cfg(feature = "payouts")] default_imp_for_payouts_fulfill!( connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout ); #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_cancel { ($($path:ident::$connector:ident),*) => { $( impl api::PayoutCancel for $path::$connector {} impl services::ConnectorIntegration< api::PoCancel, types::PayoutsData, types::PayoutsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PayoutCancel for connector::DummyConnector<T> {} #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::PayoutsResponseData> for connector::DummyConnector<T> { } #[cfg(feature = "payouts")] default_imp_for_payouts_cancel!( connector::Adyenplatform, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout ); #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_quote { ($($path:ident::$connector:ident),*) => { $( impl api::PayoutQuote for $path::$connector {} impl services::ConnectorIntegration< api::PoQuote, types::PayoutsData, types::PayoutsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PayoutQuote for connector::DummyConnector<T> {} #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration<api::PoQuote, types::PayoutsData, types::PayoutsResponseData> for connector::DummyConnector<T> { } #[cfg(feature = "payouts")] default_imp_for_payouts_quote!( connector::Adyenplatform, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout ); #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_recipient { ($($path:ident::$connector:ident),*) => { $( impl api::PayoutRecipient for $path::$connector {} impl services::ConnectorIntegration< api::PoRecipient, types::PayoutsData, types::PayoutsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PayoutRecipient for connector::DummyConnector<T> {} #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration<api::PoRecipient, types::PayoutsData, types::PayoutsResponseData> for connector::DummyConnector<T> { } #[cfg(feature = "payouts")] default_imp_for_payouts_recipient!( connector::Adyenplatform, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout ); #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_recipient_account { ($($path:ident::$connector:ident),*) => { $( impl api::PayoutRecipientAccount for $path::$connector {} impl services::ConnectorIntegration< api::PoRecipientAccount, types::PayoutsData, types::PayoutsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PayoutRecipientAccount for connector::DummyConnector<T> {} #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration< api::PoRecipientAccount, types::PayoutsData, types::PayoutsResponseData, > for connector::DummyConnector<T> { } #[cfg(feature = "payouts")] default_imp_for_payouts_recipient_account!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise ); macro_rules! default_imp_for_approve { ($($path:ident::$connector:ident),*) => { $( impl api::PaymentApprove for $path::$connector {} impl services::ConnectorIntegration< api::Approve, types::PaymentsApproveData, types::PaymentsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PaymentApprove for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration< api::Approve, types::PaymentsApproveData, types::PaymentsResponseData, > for connector::DummyConnector<T> { } default_imp_for_approve!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise ); macro_rules! default_imp_for_reject { ($($path:ident::$connector:ident),*) => { $( impl api::PaymentReject for $path::$connector {} impl services::ConnectorIntegration< api::Reject, types::PaymentsRejectData, types::PaymentsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PaymentReject for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration< api::Reject, types::PaymentsRejectData, types::PaymentsResponseData, > for connector::DummyConnector<T> { } default_imp_for_reject!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise ); #[cfg(feature = "frm")] macro_rules! default_imp_for_fraud_check { ($($path:ident::$connector:ident),*) => { $( impl api::FraudCheck for $path::$connector {} )* }; } #[cfg(feature = "dummy_connector")] impl<const T: u8> api::FraudCheck for connector::DummyConnector<T> {} #[cfg(feature = "frm")] default_imp_for_fraud_check!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Nmi, connector::Netcetera, connector::Payone, connector::Plaid, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise ); #[cfg(feature = "frm")] macro_rules! default_imp_for_frm_sale { ($($path:ident::$connector:ident),*) => { $( impl api::FraudCheckSale for $path::$connector {} impl services::ConnectorIntegration< api::Sale, frm_types::FraudCheckSaleData, frm_types::FraudCheckResponseData, > for $path::$connector {} )* }; } #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> api::FraudCheckSale for connector::DummyConnector<T> {} #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> services::ConnectorIntegration< api::Sale, frm_types::FraudCheckSaleData, frm_types::FraudCheckResponseData, > for connector::DummyConnector<T> { } #[cfg(feature = "frm")] default_imp_for_frm_sale!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise ); #[cfg(feature = "frm")] macro_rules! default_imp_for_frm_checkout { ($($path:ident::$connector:ident),*) => { $( impl api::FraudCheckCheckout for $path::$connector {} impl services::ConnectorIntegration< api::Checkout, frm_types::FraudCheckCheckoutData, frm_types::FraudCheckResponseData, > for $path::$connector {} )* }; } #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> api::FraudCheckCheckout for connector::DummyConnector<T> {} #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> services::ConnectorIntegration< api::Checkout, frm_types::FraudCheckCheckoutData, frm_types::FraudCheckResponseData, > for connector::DummyConnector<T> { } #[cfg(feature = "frm")] default_imp_for_frm_checkout!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise ); #[cfg(feature = "frm")] macro_rules! default_imp_for_frm_transaction { ($($path:ident::$connector:ident),*) => { $( impl api::FraudCheckTransaction for $path::$connector {} impl services::ConnectorIntegration< api::Transaction, frm_types::FraudCheckTransactionData, frm_types::FraudCheckResponseData, > for $path::$connector {} )* }; } #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> api::FraudCheckTransaction for connector::DummyConnector<T> {} #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> services::ConnectorIntegration< api::Transaction, frm_types::FraudCheckTransactionData, frm_types::FraudCheckResponseData, > for connector::DummyConnector<T> { } #[cfg(feature = "frm")] default_imp_for_frm_transaction!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise ); #[cfg(feature = "frm")] macro_rules! default_imp_for_frm_fulfillment { ($($path:ident::$connector:ident),*) => { $( impl api::FraudCheckFulfillment for $path::$connector {} impl services::ConnectorIntegration< api::Fulfillment, frm_types::FraudCheckFulfillmentData, frm_types::FraudCheckResponseData, > for $path::$connector {} )* }; } #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> api::FraudCheckFulfillment for connector::DummyConnector<T> {} #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> services::ConnectorIntegration< api::Fulfillment, frm_types::FraudCheckFulfillmentData, frm_types::FraudCheckResponseData, > for connector::DummyConnector<T> { } #[cfg(feature = "frm")] default_imp_for_frm_fulfillment!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise ); #[cfg(feature = "frm")] macro_rules! default_imp_for_frm_record_return { ($($path:ident::$connector:ident),*) => { $( impl api::FraudCheckRecordReturn for $path::$connector {} impl services::ConnectorIntegration< api::RecordReturn, frm_types::FraudCheckRecordReturnData, frm_types::FraudCheckResponseData, > for $path::$connector {} )* }; } #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> api::FraudCheckRecordReturn for connector::DummyConnector<T> {} #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> services::ConnectorIntegration< api::RecordReturn, frm_types::FraudCheckRecordReturnData, frm_types::FraudCheckResponseData, > for connector::DummyConnector<T> { } #[cfg(feature = "frm")] default_imp_for_frm_record_return!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise ); macro_rules! default_imp_for_incremental_authorization { ($($path:ident::$connector:ident),*) => { $( impl api::PaymentIncrementalAuthorization for $path::$connector {} impl services::ConnectorIntegration< api::IncrementalAuthorization, types::PaymentsIncrementalAuthorizationData, types::PaymentsResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PaymentIncrementalAuthorization for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration< api::IncrementalAuthorization, types::PaymentsIncrementalAuthorizationData, types::PaymentsResponseData, > for connector::DummyConnector<T> { } default_imp_for_incremental_authorization!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise ); macro_rules! default_imp_for_revoking_mandates { ($($path:ident::$connector:ident),*) => { $( impl api::ConnectorMandateRevoke for $path::$connector {} impl services::ConnectorIntegration< api::MandateRevoke, types::MandateRevokeRequestData, types::MandateRevokeResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "dummy_connector")] impl<const T: u8> api::ConnectorMandateRevoke for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration< api::MandateRevoke, types::MandateRevokeRequestData, types::MandateRevokeResponseData, > for connector::DummyConnector<T> { } default_imp_for_revoking_mandates!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, connector::Wise ); macro_rules! default_imp_for_connector_authentication { ($($path:ident::$connector:ident),*) => { $( impl api::ExternalAuthentication for $path::$connector {} impl api::ConnectorAuthentication for $path::$connector {} impl api::ConnectorPreAuthentication for $path::$connector {} impl api::ConnectorPreAuthenticationVersionCall for $path::$connector {} impl api::ConnectorPostAuthentication for $path::$connector {} impl services::ConnectorIntegration< api::Authentication, types::authentication::ConnectorAuthenticationRequestData, types::authentication::AuthenticationResponseData, > for $path::$connector {} impl services::ConnectorIntegration< api::PreAuthentication, types::authentication::PreAuthNRequestData, types::authentication::AuthenticationResponseData, > for $path::$connector {} impl services::ConnectorIntegration< api::PreAuthenticationVersionCall, types::authentication::PreAuthNRequestData, types::authentication::AuthenticationResponseData, > for $path::$connector {} impl services::ConnectorIntegration< api::PostAuthentication, types::authentication::ConnectorPostAuthenticationRequestData, types::authentication::AuthenticationResponseData, > for $path::$connector {} )* }; } #[cfg(feature = "dummy_connector")] impl<const T: u8> api::ExternalAuthentication for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> api::ConnectorPreAuthentication for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> api::ConnectorPreAuthenticationVersionCall for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> api::ConnectorAuthentication for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> api::ConnectorPostAuthentication for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration< api::Authentication, types::authentication::ConnectorAuthenticationRequestData, types::authentication::AuthenticationResponseData, > for connector::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration< api::PreAuthentication, types::authentication::PreAuthNRequestData, types::authentication::AuthenticationResponseData, > for connector::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration< api::PreAuthenticationVersionCall, types::authentication::PreAuthNRequestData, types::authentication::AuthenticationResponseData, > for connector::DummyConnector<T> { } #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration< api::PostAuthentication, types::authentication::ConnectorPostAuthenticationRequestData, types::authentication::AuthenticationResponseData, > for connector::DummyConnector<T> { } default_imp_for_connector_authentication!( connector::Adyenplatform, connector::Ebanx, connector::Nmi, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Stripe, connector::Wellsfargopayout, connector::Wise ); macro_rules! default_imp_for_authorize_session_token { ($($path:ident::$connector:ident),*) => { $( impl api::PaymentAuthorizeSessionToken for $path::$connector {} impl services::ConnectorIntegration< api::AuthorizeSessionToken, types::AuthorizeSessionTokenData, types::PaymentsResponseData > for $path::$connector {} )* }; } #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PaymentAuthorizeSessionToken for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration< api::AuthorizeSessionToken, types::AuthorizeSessionTokenData, types::PaymentsResponseData, > for connector::DummyConnector<T> { } default_imp_for_authorize_session_token!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise ); macro_rules! default_imp_for_calculate_tax { ($($path:ident::$connector:ident),*) => { $( impl api::TaxCalculation for $path::$connector {} impl services::ConnectorIntegration< api::CalculateTax, types::PaymentsTaxCalculationData, types::TaxCalculationResponseData > for $path::$connector {} )* }; } #[cfg(feature = "dummy_connector")] impl<const T: u8> api::TaxCalculation for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration< api::CalculateTax, types::PaymentsTaxCalculationData, types::TaxCalculationResponseData, > for connector::DummyConnector<T> { } default_imp_for_calculate_tax!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise ); macro_rules! default_imp_for_session_update { ($($path:ident::$connector:ident),*) => { $( impl api::PaymentSessionUpdate for $path::$connector {} impl services::ConnectorIntegration< api::SdkSessionUpdate, types::SdkPaymentsSessionUpdateData, types::PaymentsResponseData > for $path::$connector {} )* }; } #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PaymentSessionUpdate for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration< api::SdkSessionUpdate, types::SdkPaymentsSessionUpdateData, types::PaymentsResponseData, > for connector::DummyConnector<T> { } default_imp_for_session_update!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise ); macro_rules! default_imp_for_post_session_tokens { ($($path:ident::$connector:ident),*) => { $( impl api::PaymentPostSessionTokens for $path::$connector {} impl services::ConnectorIntegration< api::PostSessionTokens, types::PaymentsPostSessionTokensData, types::PaymentsResponseData > for $path::$connector {} )* }; } #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PaymentPostSessionTokens for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration< api::PostSessionTokens, types::PaymentsPostSessionTokensData, types::PaymentsResponseData, > for connector::DummyConnector<T> { } default_imp_for_post_session_tokens!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise ); macro_rules! default_imp_for_uas_pre_authentication { ($($path:ident::$connector:ident),*) => { $( impl UnifiedAuthenticationService for $path::$connector {} impl UasPreAuthentication for $path::$connector {} impl services::ConnectorIntegration< PreAuthenticate, types::UasPreAuthenticationRequestData, types::UasAuthenticationResponseData > for $path::$connector {} )* }; } #[cfg(feature = "dummy_connector")] impl<const T: u8> UasPreAuthentication for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> UnifiedAuthenticationService for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration< PreAuthenticate, types::UasPreAuthenticationRequestData, types::UasAuthenticationResponseData, > for connector::DummyConnector<T> { } default_imp_for_uas_pre_authentication!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise ); macro_rules! default_imp_for_uas_post_authentication { ($($path:ident::$connector:ident),*) => { $( impl UasPostAuthentication for $path::$connector {} impl services::ConnectorIntegration< PostAuthenticate, types::UasPostAuthenticationRequestData, types::UasAuthenticationResponseData > for $path::$connector {} )* }; } #[cfg(feature = "dummy_connector")] impl<const T: u8> UasPostAuthentication for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration< PostAuthenticate, types::UasPostAuthenticationRequestData, types::UasAuthenticationResponseData, > for connector::DummyConnector<T> { } default_imp_for_uas_post_authentication!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise ); macro_rules! default_imp_for_uas_authentication_confirmation { ($($path:ident::$connector:ident),*) => { $( impl UasAuthenticationConfirmation for $path::$connector {} impl services::ConnectorIntegration< AuthenticationConfirmation, types::UasConfirmationRequestData, types::UasAuthenticationResponseData > for $path::$connector {} )* }; } default_imp_for_uas_authentication_confirmation!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise ); #[cfg(feature = "dummy_connector")] impl<const T: u8> UasAuthenticationConfirmation for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration< AuthenticationConfirmation, types::UasConfirmationRequestData, types::UasAuthenticationResponseData, > for connector::DummyConnector<T> { } macro_rules! default_imp_for_uas_authentication { ($($path:ident::$connector:ident),*) => { $( impl UasAuthentication for $path::$connector {} impl services::ConnectorIntegration< Authenticate, types::UasAuthenticationRequestData, types::UasAuthenticationResponseData > for $path::$connector {} )* }; } #[cfg(feature = "dummy_connector")] impl<const T: u8> UasAuthentication for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration< Authenticate, types::UasAuthenticationRequestData, types::UasAuthenticationResponseData, > for connector::DummyConnector<T> { } default_imp_for_uas_authentication!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise ); /// Determines whether a capture API call should be made for a payment attempt /// This function evaluates whether an authorized payment should proceed with a capture API call /// based on various payment parameters. It's primarily used in two-step (auth + capture) payment flows for CaptureMethod SequentialAutomatic /// pub fn should_initiate_capture_flow( connector_name: &router_types::Connector, customer_acceptance: Option<CustomerAcceptance>, capture_method: Option<api_enums::CaptureMethod>, setup_future_usage: Option<api_enums::FutureUsage>, status: common_enums::AttemptStatus, ) -> bool { match status { common_enums::AttemptStatus::Authorized => { if let Some(api_enums::CaptureMethod::SequentialAutomatic) = capture_method { match connector_name { router_types::Connector::Paybox => { // Check CIT conditions for Paybox setup_future_usage == Some(api_enums::FutureUsage::OffSession) && customer_acceptance.is_some() } _ => false, } } else { false } } _ => false, } } /// Executes a capture request by building a connector-specific request and deciding /// the appropriate flow to send it to the payment connector. pub async fn call_capture_request( mut capture_router_data: types::RouterData< api::Capture, PaymentsCaptureData, types::PaymentsResponseData, >, state: &SessionState, connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, business_profile: &domain::Profile, header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<types::RouterData<api::Capture, PaymentsCaptureData, types::PaymentsResponseData>> { // Build capture-specific connector request let (connector_request, _should_continue_further) = capture_router_data .build_flow_specific_connector_request(state, connector, call_connector_action.clone()) .await?; // Execute capture flow capture_router_data .decide_flows( state, connector, call_connector_action, connector_request, business_profile, header_payload.clone(), ) .await } /// Processes the response from the capture flow and determines the final status and the response. fn handle_post_capture_response( authorize_router_data_response: types::PaymentsResponseData, post_capture_router_data: Result< types::RouterData<api::Capture, PaymentsCaptureData, types::PaymentsResponseData>, error_stack::Report<ApiErrorResponse>, >, ) -> RouterResult<(common_enums::AttemptStatus, types::PaymentsResponseData)> { match post_capture_router_data { Err(err) => { logger::error!( "Capture flow encountered an error: {:?}. Proceeding without updating.", err ); Ok(( common_enums::AttemptStatus::Authorized, authorize_router_data_response, )) } Ok(post_capture_router_data) => { match ( &post_capture_router_data.response, post_capture_router_data.status, ) { (Ok(post_capture_resp), common_enums::AttemptStatus::Charged) => Ok(( common_enums::AttemptStatus::Charged, types::PaymentsResponseData::merge_transaction_responses( &authorize_router_data_response, post_capture_resp, )?, )), _ => { logger::error!( "Error in post capture_router_data response: {:?}, Current Status: {:?}. Proceeding without updating.", post_capture_router_data.response, post_capture_router_data.status, ); Ok(( common_enums::AttemptStatus::Authorized, authorize_router_data_response, )) } } } } } macro_rules! default_imp_for_revenue_recovery { ($($path:ident::$connector:ident),*) => { $( impl api::RevenueRecovery for $path::$connector {} )* }; } #[cfg(feature = "dummy_connector")] impl<const T: u8> api::RevenueRecovery for connector::DummyConnector<T> {} default_imp_for_revenue_recovery! { connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] macro_rules! default_imp_for_billing_connector_payment_sync { ($($path:ident::$connector:ident),*) => { $( impl api::BillingConnectorPaymentsSyncIntegration for $path::$connector {} impl services::ConnectorIntegration< BillingConnectorPaymentsSync, types::BillingConnectorPaymentsSyncRequest, types::BillingConnectorPaymentsSyncResponse, > for $path::$connector {} )* }; } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] #[cfg(feature = "dummy_connector")] impl<const T: u8> api::BillingConnectorPaymentsSyncIntegration for connector::DummyConnector<T> {} #[cfg(all(feature = "v2", feature = "revenue_recovery"))] #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration< BillingConnectorPaymentsSync, types::BillingConnectorPaymentsSyncRequest, types::BillingConnectorPaymentsSyncResponse, > for connector::DummyConnector<T> { } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] default_imp_for_billing_connector_payment_sync!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise ); #[cfg(all(feature = "v2", feature = "revenue_recovery"))] macro_rules! default_imp_for_revenue_recovery_record_back { ($($path:ident::$connector:ident),*) => { $( impl api::RevenueRecoveryRecordBack for $path::$connector {} impl services::ConnectorIntegration< RecoveryRecordBack, types::RevenueRecoveryRecordBackRequest, types::RevenueRecoveryRecordBackResponse, > for $path::$connector {} )* }; } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] #[cfg(feature = "dummy_connector")] impl<const T: u8> api::RevenueRecoveryRecordBack for connector::DummyConnector<T> {} #[cfg(all(feature = "v2", feature = "revenue_recovery"))] #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorIntegration< RecoveryRecordBack, types::RevenueRecoveryRecordBackRequest, types::RevenueRecoveryRecordBackResponse, > for connector::DummyConnector<T> { } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] default_imp_for_revenue_recovery_record_back!( connector::Adyenplatform, connector::Ebanx, connector::Gpayments, connector::Netcetera, connector::Nmi, connector::Payone, connector::Plaid, connector::Riskified, connector::Signifyd, connector::Stripe, connector::Threedsecureio, connector::Wellsfargopayout, connector::Wise );
14,132
1,604
hyperswitch
crates/router/src/core/payments/customers.rs
.rs
use common_utils::pii; use masking::ExposeOptionInterface; use router_env::{instrument, tracing}; use crate::{ core::{ errors::{ConnectorErrorExt, RouterResult}, payments, }, logger, routes::{metrics, SessionState}, services, types::{self, api, domain, storage}, }; #[instrument(skip_all)] pub async fn create_connector_customer<F: Clone, T: Clone>( state: &SessionState, connector: &api::ConnectorData, router_data: &types::RouterData<F, T, types::PaymentsResponseData>, customer_request_data: types::ConnectorCustomerData, ) -> RouterResult<Option<String>> { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::CreateConnectorCustomer, types::ConnectorCustomerData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); let customer_response_data: Result<types::PaymentsResponseData, types::ErrorResponse> = Err(types::ErrorResponse::default()); let customer_router_data = payments::helpers::router_data_type_conversion::< _, api::CreateConnectorCustomer, _, _, _, _, >( router_data.clone(), customer_request_data, customer_response_data, ); let resp = services::execute_connector_processing_step( state, connector_integration, &customer_router_data, payments::CallConnectorAction::Trigger, None, ) .await .to_payment_failed_response()?; metrics::CONNECTOR_CUSTOMER_CREATE.add( 1, router_env::metric_attributes!(("connector", connector.connector_name.to_string())), ); let connector_customer_id = match resp.response { Ok(response) => match response { types::PaymentsResponseData::ConnectorCustomerResponse { connector_customer_id, } => Some(connector_customer_id), _ => None, }, Err(err) => { logger::error!(create_connector_customer_error=?err); None } }; Ok(connector_customer_id) } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] pub fn should_call_connector_create_customer<'a>( state: &SessionState, connector: &api::ConnectorData, customer: &'a Option<domain::Customer>, connector_label: &str, ) -> (bool, Option<&'a str>) { // Check if create customer is required for the connector let connector_needs_customer = state .conf .connector_customer .connector_list .contains(&connector.connector_name); if connector_needs_customer { let connector_customer_details = customer .as_ref() .and_then(|customer| customer.get_connector_customer_id(connector_label)); let should_call_connector = connector_customer_details.is_none(); (should_call_connector, connector_customer_details) } else { (false, None) } } #[cfg(all(feature = "v2", feature = "customer_v2"))] pub fn should_call_connector_create_customer<'a>( state: &SessionState, connector: &api::ConnectorData, customer: &'a Option<domain::Customer>, merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId, ) -> (bool, Option<&'a str>) { // Check if create customer is required for the connector let connector_needs_customer = state .conf .connector_customer .connector_list .contains(&connector.connector_name); if connector_needs_customer { let connector_customer_details = customer .as_ref() .and_then(|customer| customer.get_connector_customer_id(merchant_connector_id)); let should_call_connector = connector_customer_details.is_none(); (should_call_connector, connector_customer_details) } else { (false, None) } } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument] pub async fn update_connector_customer_in_customers( connector_label: &str, customer: Option<&domain::Customer>, connector_customer_id: Option<String>, ) -> Option<storage::CustomerUpdate> { let mut connector_customer_map = customer .and_then(|customer| customer.connector_customer.clone().expose_option()) .and_then(|connector_customer| connector_customer.as_object().cloned()) .unwrap_or_default(); let updated_connector_customer_map = connector_customer_id.map(|connector_customer_id| { let connector_customer_value = serde_json::Value::String(connector_customer_id); connector_customer_map.insert(connector_label.to_string(), connector_customer_value); connector_customer_map }); updated_connector_customer_map .map(serde_json::Value::Object) .map( |connector_customer_value| storage::CustomerUpdate::ConnectorCustomer { connector_customer: Some(pii::SecretSerdeValue::new(connector_customer_value)), }, ) } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[instrument] pub async fn update_connector_customer_in_customers( merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, customer: Option<&domain::Customer>, connector_customer_id: Option<String>, ) -> Option<storage::CustomerUpdate> { connector_customer_id.map(|connector_customer_id| { let mut connector_customer_map = customer .and_then(|customer| customer.connector_customer.clone()) .unwrap_or_default(); connector_customer_map.insert(merchant_connector_id, connector_customer_id); storage::CustomerUpdate::ConnectorCustomer { connector_customer: Some(connector_customer_map), } }) }
1,208
1,605