From e5cf6698da9bccc803c338c94441b107d68c66f8 Mon Sep 17 00:00:00 2001 From: Nithin N <57832822+Nithin1506200@users.noreply.github.com> Date: Fri, 16 May 2025 19:20:04 +0530 Subject: [PATCH] refactor(connector): stripe migration from router to hyperswitch_connectors (#8007) --- .../hyperswitch_connectors/src/connectors.rs | 3 +- .../src/connectors}/stripe.rs | 1578 ++++++++-------- .../src/connectors}/stripe/transformers.rs | 1603 ++++++++--------- .../stripe/transformers/connect.rs | 82 +- .../hyperswitch_connectors/src/constants.rs | 1 + .../src/default_implementations.rs | 33 + .../src/default_implementations_v2.rs | 25 + crates/hyperswitch_connectors/src/types.rs | 28 +- crates/hyperswitch_connectors/src/utils.rs | 117 +- crates/router/src/connector.rs | 9 +- crates/router/src/connector/utils.rs | 75 +- crates/router/src/core/payments.rs | 17 - crates/router/src/core/payments/flows.rs | 768 -------- crates/router/src/macros.rs | 2 +- crates/router/src/types.rs | 15 +- 15 files changed, 1738 insertions(+), 2618 deletions(-) rename crates/{router/src/connector => hyperswitch_connectors/src/connectors}/stripe.rs (58%) rename crates/{router/src/connector => hyperswitch_connectors/src/connectors}/stripe/transformers.rs (74%) rename crates/{router/src/connector => hyperswitch_connectors/src/connectors}/stripe/transformers/connect.rs (86%) diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs index 0dcd327c13..283c6a9a3a 100644 --- a/crates/hyperswitch_connectors/src/connectors.rs +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -79,6 +79,7 @@ pub mod shift4; pub mod signifyd; pub mod square; pub mod stax; +pub mod stripe; pub mod stripebilling; pub mod taxjar; pub mod threedsecureio; @@ -116,7 +117,7 @@ pub use self::{ payone::Payone, paypal::Paypal, paystack::Paystack, payu::Payu, placetopay::Placetopay, plaid::Plaid, powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, recurly::Recurly, redsys::Redsys, riskified::Riskified, shift4::Shift4, signifyd::Signifyd, - square::Square, stax::Stax, stripebilling::Stripebilling, taxjar::Taxjar, + square::Square, stax::Stax, stripe::Stripe, stripebilling::Stripebilling, taxjar::Taxjar, threedsecureio::Threedsecureio, thunes::Thunes, trustpay::Trustpay, tsys::Tsys, unified_authentication_service::UnifiedAuthenticationService, vgs::Vgs, volt::Volt, wellsfargo::Wellsfargo, wellsfargopayout::Wellsfargopayout, wise::Wise, worldline::Worldline, diff --git a/crates/router/src/connector/stripe.rs b/crates/hyperswitch_connectors/src/connectors/stripe.rs similarity index 58% rename from crates/router/src/connector/stripe.rs rename to crates/hyperswitch_connectors/src/connectors/stripe.rs index 0fcddc5c34..be1777bac4 100644 --- a/crates/router/src/connector/stripe.rs +++ b/crates/hyperswitch_connectors/src/connectors/stripe.rs @@ -2,43 +2,91 @@ pub mod transformers; use std::collections::HashMap; +use api_models::webhooks::IncomingWebhookEvent; +use common_enums::{ + CallConnectorAction, CaptureMethod, PaymentAction, PaymentChargeType, PaymentMethodType, + PaymentResourceUpdateStatus, StripeChargeType, +}; use common_utils::{ - request::RequestContent, + crypto, + errors::CustomResult, + ext_traits::{ByteSliceExt as _, BytesExt, OptionExt as _}, + request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, }; -use diesel_models::enums; use error_stack::ResultExt; -use hyperswitch_domain_models::router_request_types::SplitRefundsRequest; -use masking::PeekInterface; +use hyperswitch_domain_models::{ + payment_method_data::PaymentMethodData, + router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, + router_flow_types::{ + AccessTokenAuth, Authorize, Capture, CreateConnectorCustomer, Evidence, Execute, PSync, + PaymentMethodToken, RSync, Retrieve, Session, SetupMandate, UpdateMetadata, Upload, Void, + }, + router_request_types::{ + AccessTokenRequestData, ConnectorCustomerData, PaymentMethodTokenizationData, + PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, + PaymentsSyncData, PaymentsUpdateMetadataData, RefundsData, RetrieveFileRequestData, + SetupMandateRequestData, SplitRefundsRequest, SubmitEvidenceRequestData, + UploadFileRequestData, + }, + router_response_types::{ + PaymentsResponseData, RefundsResponseData, RetrieveFileResponse, SubmitEvidenceResponse, + UploadFileResponse, + }, + types::{ + ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData, + PaymentsCaptureRouterData, PaymentsSyncRouterData, PaymentsUpdateMetadataRouterData, + RefundsRouterData, TokenizationRouterData, + }, +}; +#[cfg(feature = "payouts")] +use hyperswitch_domain_models::{ + router_flow_types::{PoCancel, PoCreate, PoFulfill, PoRecipient, PoRecipientAccount}, + types::{PayoutsData, PayoutsResponseData, PayoutsRouterData}, +}; +#[cfg(feature = "payouts")] +use hyperswitch_interfaces::types::{ + PayoutCancelType, PayoutCreateType, PayoutFulfillType, PayoutRecipientAccountType, + PayoutRecipientType, +}; +use hyperswitch_interfaces::{ + api::{ + self, + disputes::SubmitEvidence, + files::{FilePurpose, FileUpload, RetrieveFile, UploadFile}, + ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse, + ConnectorSpecifications, ConnectorValidation, + }, + configs::Connectors, + consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}, + disputes::DisputePayload, + errors::ConnectorError, + events::connector_api_logs::ConnectorEvent, + types::{ + ConnectorCustomerType, PaymentsAuthorizeType, PaymentsCaptureType, PaymentsSyncType, + PaymentsUpdateMetadataType, PaymentsVoidType, RefundExecuteType, RefundSyncType, Response, + RetrieveFileType, SubmitEvidenceType, TokenizationType, UploadFileType, + }, + webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, +}; +use masking::{Mask as _, Maskable, PeekInterface}; use router_env::{instrument, tracing}; use stripe::auth_headers; use self::transformers as stripe; -use super::utils::{self as connector_utils, PaymentMethodDataType, RefundsRequestData}; #[cfg(feature = "payouts")] -use super::utils::{PayoutsData, RouterData}; +use crate::utils::{PayoutsData as OtherPayoutsData, RouterData as OtherRouterData}; use crate::{ - configs::settings, - consts, - core::{ - errors::{self, CustomResult}, - payments, - }, - events::connector_api_logs::ConnectorEvent, - headers, - services::{ - self, - request::{self, Mask}, - ConnectorSpecifications, ConnectorValidation, - }, + constants::headers::{AUTHORIZATION, CONTENT_TYPE, STRIPE_COMPATIBLE_CONNECT_ACCOUNT}, types::{ - self, - api::{self, ConnectorCommon, ConnectorCommonExt}, - domain, + ResponseRouterData, RetrieveFileRouterData, SubmitEvidenceRouterData, UploadFileRouterData, + }, + utils::{ + self, get_authorise_integrity_object, get_capture_integrity_object, + get_refund_integrity_object, get_sync_integrity_object, PaymentMethodDataType, + RefundsRequestData as OtherRefundsRequestData, }, - utils::{crypto, ByteSliceExt, BytesExt, OptionExt}, }; - #[derive(Clone)] pub struct Stripe { amount_converter: &'static (dyn AmountConvertor + Sync), @@ -54,15 +102,15 @@ impl Stripe { impl ConnectorCommonExt for Stripe where - Self: services::ConnectorIntegration, + Self: ConnectorIntegration, { fn build_headers( &self, - req: &types::RouterData, - _connectors: &settings::Connectors, - ) -> CustomResult)>, errors::ConnectorError> { + req: &RouterData, + _connectors: &Connectors, + ) -> CustomResult)>, ConnectorError> { let mut header = vec![( - headers::CONTENT_TYPE.to_string(), + CONTENT_TYPE.to_string(), Self::common_get_content_type(self).to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; @@ -80,20 +128,20 @@ impl ConnectorCommon for Stripe { "application/x-www-form-urlencoded" } - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { // &self.base_url connectors.stripe.base_url.as_ref() } fn get_auth_header( &self, - auth_type: &types::ConnectorAuthType, - ) -> CustomResult)>, errors::ConnectorError> { + auth_type: &ConnectorAuthType, + ) -> CustomResult)>, ConnectorError> { let auth = stripe::StripeAuthType::try_from(auth_type) - .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + .change_context(ConnectorError::FailedToObtainAuthType)?; Ok(vec![ ( - headers::AUTHORIZATION.to_string(), + AUTHORIZATION.to_string(), format!("Bearer {}", auth.api_key.peek()).into_masked(), ), ( @@ -106,25 +154,27 @@ impl ConnectorCommon for Stripe { #[cfg(feature = "payouts")] fn build_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult { + ) -> CustomResult { + use hyperswitch_interfaces::consts::NO_ERROR_CODE; + let response: stripe::StripeConnectErrorResponse = res .response .parse_struct("StripeConnectErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); - Ok(types::ErrorResponse { + Ok(ErrorResponse { status_code: res.status_code, code: response .error .code .clone() - .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: response .error .code - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: response.error.message, attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), @@ -138,26 +188,26 @@ impl ConnectorCommon for Stripe { impl ConnectorValidation for Stripe { fn validate_connector_against_payment_request( &self, - capture_method: Option, - _payment_method: enums::PaymentMethod, - _pmt: Option, - ) -> CustomResult<(), errors::ConnectorError> { + capture_method: Option, + _payment_method: common_enums::PaymentMethod, + _pmt: Option, + ) -> CustomResult<(), ConnectorError> { let capture_method = capture_method.unwrap_or_default(); match capture_method { - enums::CaptureMethod::SequentialAutomatic - | enums::CaptureMethod::Automatic - | enums::CaptureMethod::Manual => Ok(()), - enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( - connector_utils::construct_not_supported_error_report(capture_method, self.id()), + CaptureMethod::SequentialAutomatic + | CaptureMethod::Automatic + | CaptureMethod::Manual => Ok(()), + CaptureMethod::ManualMultiple | CaptureMethod::Scheduled => Err( + utils::construct_not_supported_error_report(capture_method, self.id()), ), } } fn validate_mandate_payment( &self, - pm_type: Option, - pm_data: domain::payments::PaymentMethodData, - ) -> CustomResult<(), errors::ConnectorError> { + pm_type: Option, + pm_data: PaymentMethodData, + ) -> CustomResult<(), ConnectorError> { let mandate_supported_pmd = std::collections::HashSet::from([ PaymentMethodDataType::Card, PaymentMethodDataType::ApplePay, @@ -170,7 +220,7 @@ impl ConnectorValidation for Stripe { PaymentMethodDataType::Ideal, PaymentMethodDataType::BancontactCard, ]); - connector_utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id()) + utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id()) } } @@ -184,43 +234,27 @@ impl api::PaymentCapture for Stripe {} impl api::PaymentSession for Stripe {} impl api::ConnectorAccessToken for Stripe {} -impl - services::ConnectorIntegration< - api::AccessTokenAuth, - types::AccessTokenRequestData, - types::AccessToken, - > for Stripe -{ +impl ConnectorIntegration for Stripe { // Not Implemented (R) } -impl - services::ConnectorIntegration< - api::Session, - types::PaymentsSessionData, - types::PaymentsResponseData, - > for Stripe -{ +impl ConnectorIntegration for Stripe { // Not Implemented (R) } impl api::ConnectorCustomer for Stripe {} -impl - services::ConnectorIntegration< - api::CreateConnectorCustomer, - types::ConnectorCustomerData, - types::PaymentsResponseData, - > for Stripe +impl ConnectorIntegration + for Stripe { fn get_headers( &self, - req: &types::ConnectorCustomerRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult)>, errors::ConnectorError> { + req: &ConnectorCustomerRouterData, + _connectors: &Connectors, + ) -> CustomResult)>, ConnectorError> { let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - types::ConnectorCustomerType::get_content_type(self) + CONTENT_TYPE.to_string(), + ConnectorCustomerType::get_content_type(self) .to_string() .into(), )]; @@ -235,37 +269,33 @@ impl fn get_url( &self, - _req: &types::ConnectorCustomerRouterData, - connectors: &settings::Connectors, - ) -> CustomResult { + _req: &ConnectorCustomerRouterData, + connectors: &Connectors, + ) -> CustomResult { Ok(format!("{}{}", self.base_url(connectors), "v1/customers")) } fn get_request_body( &self, - req: &types::ConnectorCustomerRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult { + req: &ConnectorCustomerRouterData, + _connectors: &Connectors, + ) -> CustomResult { let connector_req = stripe::CustomerRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - req: &types::ConnectorCustomerRouterData, - connectors: &settings::Connectors, - ) -> CustomResult, errors::ConnectorError> { + req: &ConnectorCustomerRouterData, + connectors: &Connectors, + ) -> CustomResult, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::ConnectorCustomerType::get_url( - self, req, connectors, - )?) + RequestBuilder::new() + .method(Method::Post) + .url(&ConnectorCustomerType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::ConnectorCustomerType::get_headers( - self, req, connectors, - )?) - .set_body(types::ConnectorCustomerType::get_request_body( + .headers(ConnectorCustomerType::get_headers(self, req, connectors)?) + .set_body(ConnectorCustomerType::get_request_body( self, req, connectors, )?) .build(), @@ -274,53 +304,53 @@ impl fn handle_response( &self, - data: &types::ConnectorCustomerRouterData, + data: &ConnectorCustomerRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult + res: Response, + ) -> CustomResult where - types::PaymentsResponseData: Clone, + PaymentsResponseData: Clone, { let response: stripe::StripeCustomerResponse = res .response .parse_struct("StripeCustomerResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) - .change_context(errors::ConnectorError::ResponseHandlingFailed) + .change_context(ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult { + ) -> CustomResult { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(types::ErrorResponse { + Ok(ErrorResponse { status_code: res.status_code, code: response .error .code .clone() - .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: response .error .code - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error @@ -342,23 +372,17 @@ impl impl api::PaymentToken for Stripe {} -impl - services::ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Stripe +impl ConnectorIntegration + for Stripe { fn get_headers( &self, - req: &types::TokenizationRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult)>, errors::ConnectorError> { + req: &TokenizationRouterData, + _connectors: &Connectors, + ) -> CustomResult)>, ConnectorError> { let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - types::TokenizationType::get_content_type(self) - .to_string() - .into(), + CONTENT_TYPE.to_string(), + TokenizationType::get_content_type(self).to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); @@ -371,88 +395,86 @@ impl fn get_url( &self, - _req: &types::TokenizationRouterData, - connectors: &settings::Connectors, - ) -> CustomResult { + _req: &TokenizationRouterData, + connectors: &Connectors, + ) -> CustomResult { Ok(format!("{}{}", self.base_url(connectors), "v1/tokens")) } fn get_request_body( &self, - req: &types::TokenizationRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult { + req: &TokenizationRouterData, + _connectors: &Connectors, + ) -> CustomResult { let connector_req = stripe::TokenRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - req: &types::TokenizationRouterData, - connectors: &settings::Connectors, - ) -> CustomResult, errors::ConnectorError> { + req: &TokenizationRouterData, + connectors: &Connectors, + ) -> CustomResult, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::TokenizationType::get_url(self, req, connectors)?) + RequestBuilder::new() + .method(Method::Post) + .url(&TokenizationType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::TokenizationType::get_headers(self, req, connectors)?) - .set_body(types::TokenizationType::get_request_body( - self, req, connectors, - )?) + .headers(TokenizationType::get_headers(self, req, connectors)?) + .set_body(TokenizationType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, - data: &types::TokenizationRouterData, + data: &TokenizationRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult + res: Response, + ) -> CustomResult where - types::PaymentsResponseData: Clone, + PaymentsResponseData: Clone, { let response: stripe::StripeTokenResponse = res .response .parse_struct("StripeTokenResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) - .change_context(errors::ConnectorError::ResponseHandlingFailed) + .change_context(ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult { + ) -> CustomResult { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(types::ErrorResponse { + Ok(ErrorResponse { status_code: res.status_code, code: response .error .code .clone() - .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: response .error .code - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error @@ -474,20 +496,14 @@ impl impl api::MandateSetup for Stripe {} -impl - services::ConnectorIntegration< - api::Capture, - types::PaymentsCaptureData, - types::PaymentsResponseData, - > for Stripe -{ +impl ConnectorIntegration for Stripe { fn get_headers( &self, - req: &types::PaymentsCaptureRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult)>, errors::ConnectorError> { + req: &PaymentsCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult)>, ConnectorError> { let mut header = vec![( - headers::CONTENT_TYPE.to_string(), + CONTENT_TYPE.to_string(), Self::common_get_content_type(self).to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; @@ -501,10 +517,9 @@ impl fn get_url( &self, - req: &types::PaymentsCaptureRouterData, - - connectors: &settings::Connectors, - ) -> CustomResult { + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult { let id = req.request.connector_transaction_id.as_str(); Ok(format!( @@ -517,10 +532,10 @@ impl fn get_request_body( &self, - req: &types::PaymentsCaptureRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult { - let amount = connector_utils::convert_amount( + req: &PaymentsCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult { + let amount = utils::convert_amount( self.amount_converter, req.request.minor_amount_to_capture, req.request.currency, @@ -531,18 +546,16 @@ impl fn build_request( &self, - req: &types::PaymentsCaptureRouterData, - connectors: &settings::Connectors, - ) -> CustomResult, errors::ConnectorError> { + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PaymentsCaptureType::get_headers( - self, req, connectors, - )?) - .set_body(types::PaymentsCaptureType::get_request_body( + .headers(PaymentsCaptureType::get_headers(self, req, connectors)?) + .set_body(PaymentsCaptureType::get_request_body( self, req, connectors, )?) .build(), @@ -551,20 +564,20 @@ impl fn handle_response( &self, - data: &types::PaymentsCaptureRouterData, + data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult + res: Response, + ) -> CustomResult where - types::PaymentsCaptureData: Clone, - types::PaymentsResponseData: Clone, + PaymentsCaptureData: Clone, + PaymentsResponseData: Clone, { let response: stripe::PaymentIntentResponse = res .response .parse_struct("PaymentIntentResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; - let response_integrity_object = connector_utils::get_capture_integrity_object( + let response_integrity_object = get_capture_integrity_object( self.amount_converter, response.amount_received, response.currency.clone(), @@ -573,12 +586,12 @@ impl event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - let new_router_data = types::RouterData::try_from(types::ResponseRouterData { + let new_router_data = RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) - .change_context(errors::ConnectorError::ResponseHandlingFailed); + .change_context(ConnectorError::ResponseHandlingFailed); new_router_data.map(|mut router_data| { router_data.request.integrity_object = Some(response_integrity_object); @@ -588,28 +601,28 @@ impl fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult { + ) -> CustomResult { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(types::ErrorResponse { + Ok(ErrorResponse { status_code: res.status_code, code: response .error .code .clone() - .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: response .error .code - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error @@ -629,20 +642,15 @@ impl } } -impl - services::ConnectorIntegration - for Stripe -{ +impl ConnectorIntegration for Stripe { fn get_headers( &self, - req: &types::PaymentsSyncRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult)>, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + _connectors: &Connectors, + ) -> CustomResult)>, ConnectorError> { let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - types::PaymentsSyncType::get_content_type(self) - .to_string() - .into(), + CONTENT_TYPE.to_string(), + PaymentsSyncType::get_content_type(self).to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); @@ -666,9 +674,9 @@ impl fn get_url( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult { + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult { let id = req.request.connector_transaction_id.clone(); match id.get_connector_transaction_id() { @@ -685,33 +693,33 @@ impl x, "?expand[0]=latest_charge" //updated payment_id(if present) reside inside latest_charge field )), - x => x.change_context(errors::ConnectorError::MissingConnectorTransactionID), + x => x.change_context(ConnectorError::MissingConnectorTransactionID), } } fn build_request( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Get) - .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) + RequestBuilder::new() + .method(Method::Get) + .url(&PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) + .headers(PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, - data: &types::PaymentsSyncRouterData, + data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult + res: Response, + ) -> CustomResult where - types::PaymentsResponseData: Clone, + PaymentsResponseData: Clone, { let id = data.request.connector_transaction_id.clone(); match id.get_connector_transaction_id() { @@ -719,12 +727,12 @@ impl let response: stripe::SetupIntentResponse = res .response .parse_struct("SetupIntentSyncResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -734,9 +742,9 @@ impl let response: stripe::PaymentIntentSyncResponse = res .response .parse_struct("PaymentIntentSyncResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; - let response_integrity_object = connector_utils::get_sync_integrity_object( + let response_integrity_object = get_sync_integrity_object( self.amount_converter, response.amount, response.currency.clone(), @@ -745,7 +753,7 @@ impl event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - let new_router_data = types::RouterData::try_from(types::ResponseRouterData { + let new_router_data = RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -755,35 +763,33 @@ impl router_data }) } - Err(err) => { - Err(err).change_context(errors::ConnectorError::MissingConnectorTransactionID) - } + Err(err) => Err(err).change_context(ConnectorError::MissingConnectorTransactionID), } } fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult { + ) -> CustomResult { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(types::ErrorResponse { + Ok(ErrorResponse { status_code: res.status_code, code: response .error .code .clone() - .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: response .error .code - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error @@ -804,21 +810,15 @@ impl } #[async_trait::async_trait] -impl - services::ConnectorIntegration< - api::Authorize, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, - > for Stripe -{ +impl ConnectorIntegration for Stripe { fn get_headers( &self, - req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult)>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult)>, ConnectorError> { let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - types::PaymentsAuthorizeType::get_content_type(self) + CONTENT_TYPE.to_string(), + PaymentsAuthorizeType::get_content_type(self) .to_string() .into(), )]; @@ -830,10 +830,10 @@ impl )) = &req.request.split_payments { if stripe_split_payment.charge_type - == api::enums::PaymentChargeType::Stripe(api::enums::StripeChargeType::Direct) + == PaymentChargeType::Stripe(StripeChargeType::Direct) { let mut customer_account_header = vec![( - headers::STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(), + STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(), stripe_split_payment .transfer_account_id .clone() @@ -851,9 +851,9 @@ impl fn get_url( &self, - _req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult { + _req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult { Ok(format!( "{}{}", self.base_url(connectors), @@ -863,10 +863,10 @@ impl fn get_request_body( &self, - req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult { - let amount = connector_utils::convert_amount( + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult { + let amount = utils::convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, @@ -878,20 +878,16 @@ impl fn build_request( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsAuthorizeType::get_url( - self, req, connectors, - )?) + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PaymentsAuthorizeType::get_headers( - self, req, connectors, - )?) - .set_body(types::PaymentsAuthorizeType::get_request_body( + .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?) + .set_body(PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), @@ -900,16 +896,16 @@ impl fn handle_response( &self, - data: &types::PaymentsAuthorizeRouterData, + data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult { + res: Response, + ) -> CustomResult { let response: stripe::PaymentIntentResponse = res .response .parse_struct("PaymentIntentResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; - let response_integrity_object = connector_utils::get_authorise_integrity_object( + let response_integrity_object = get_authorise_integrity_object( self.amount_converter, response.amount, response.currency.clone(), @@ -918,12 +914,12 @@ impl event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - let new_router_data = types::RouterData::try_from(types::ResponseRouterData { + let new_router_data = RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) - .change_context(errors::ConnectorError::ResponseHandlingFailed); + .change_context(ConnectorError::ResponseHandlingFailed); new_router_data.map(|mut router_data| { router_data.request.integrity_object = Some(response_integrity_object); @@ -933,26 +929,26 @@ impl fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult { + ) -> CustomResult { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(types::ErrorResponse { + Ok(ErrorResponse { status_code: res.status_code, code: response .error .code .clone() - .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: response .error .code - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error @@ -972,22 +968,14 @@ impl } } -impl - services::ConnectorIntegration< - api::UpdateMetadata, - types::PaymentsUpdateMetadataData, - types::PaymentsResponseData, - > for Stripe +impl ConnectorIntegration + for Stripe { fn get_headers( &self, - req: &types::RouterData< - api::UpdateMetadata, - types::PaymentsUpdateMetadataData, - types::PaymentsResponseData, - >, - connectors: &settings::Connectors, - ) -> CustomResult)>, errors::ConnectorError> { + req: &RouterData, + connectors: &Connectors, + ) -> CustomResult)>, ConnectorError> { self.build_headers(req, connectors) } @@ -997,9 +985,9 @@ impl fn get_url( &self, - req: &types::PaymentsUpdateMetadataRouterData, - connectors: &settings::Connectors, - ) -> CustomResult { + req: &PaymentsUpdateMetadataRouterData, + connectors: &Connectors, + ) -> CustomResult { let payment_id = &req.request.connector_transaction_id; Ok(format!( "{}v1/payment_intents/{}", @@ -1010,28 +998,26 @@ impl fn get_request_body( &self, - req: &types::PaymentsUpdateMetadataRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult { + req: &PaymentsUpdateMetadataRouterData, + _connectors: &Connectors, + ) -> CustomResult { let connector_req = stripe::UpdateMetadataRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - req: &types::PaymentsUpdateMetadataRouterData, - connectors: &settings::Connectors, - ) -> CustomResult, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsUpdateMetadataType::get_url( - self, req, connectors, - )?) + req: &PaymentsUpdateMetadataRouterData, + connectors: &Connectors, + ) -> CustomResult, ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsUpdateMetadataType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PaymentsUpdateMetadataType::get_headers( + .headers(PaymentsUpdateMetadataType::get_headers( self, req, connectors, )?) - .set_body(types::PaymentsUpdateMetadataType::get_request_body( + .set_body(PaymentsUpdateMetadataType::get_request_body( self, req, connectors, )?) .build(); @@ -1040,49 +1026,41 @@ impl fn handle_response( &self, - data: &types::PaymentsUpdateMetadataRouterData, + data: &PaymentsUpdateMetadataRouterData, _event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult { + res: Response, + ) -> CustomResult { router_env::logger::debug!("skipped parsing of the response"); // If 200 status code, then metadata was updated successfully. let status = if res.status_code == 200 { - enums::PaymentResourceUpdateStatus::Success + PaymentResourceUpdateStatus::Success } else { - enums::PaymentResourceUpdateStatus::Failure + PaymentResourceUpdateStatus::Failure }; - Ok(types::PaymentsUpdateMetadataRouterData { - response: Ok(types::PaymentsResponseData::PaymentResourceUpdateResponse { status }), + Ok(PaymentsUpdateMetadataRouterData { + response: Ok(PaymentsResponseData::PaymentResourceUpdateResponse { status }), ..data.clone() }) } fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult { + ) -> CustomResult { self.build_error_response(res, event_builder) } } -impl - services::ConnectorIntegration< - api::Void, - types::PaymentsCancelData, - types::PaymentsResponseData, - > for Stripe -{ +impl ConnectorIntegration for Stripe { fn get_headers( &self, - req: &types::PaymentsCancelRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult)>, errors::ConnectorError> { + req: &PaymentsCancelRouterData, + _connectors: &Connectors, + ) -> CustomResult)>, ConnectorError> { let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - types::PaymentsVoidType::get_content_type(self) - .to_string() - .into(), + CONTENT_TYPE.to_string(), + PaymentsVoidType::get_content_type(self).to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); @@ -1095,9 +1073,9 @@ impl fn get_url( &self, - req: &types::PaymentsCancelRouterData, - connectors: &settings::Connectors, - ) -> CustomResult { + req: &PaymentsCancelRouterData, + connectors: &Connectors, + ) -> CustomResult { let payment_id = &req.request.connector_transaction_id; Ok(format!( "{}v1/payment_intents/{}/cancel", @@ -1108,76 +1086,74 @@ impl fn get_request_body( &self, - req: &types::PaymentsCancelRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult { + req: &PaymentsCancelRouterData, + _connectors: &Connectors, + ) -> CustomResult { let connector_req = stripe::CancelRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - req: &types::PaymentsCancelRouterData, - connectors: &settings::Connectors, - ) -> CustomResult, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) + req: &PaymentsCancelRouterData, + connectors: &Connectors, + ) -> CustomResult, ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsVoidType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) - .set_body(types::PaymentsVoidType::get_request_body( - self, req, connectors, - )?) + .headers(PaymentsVoidType::get_headers(self, req, connectors)?) + .set_body(PaymentsVoidType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) } fn handle_response( &self, - data: &types::PaymentsCancelRouterData, + data: &PaymentsCancelRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult { + res: Response, + ) -> CustomResult { let response: stripe::PaymentIntentResponse = res .response .parse_struct("PaymentIntentResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) - .change_context(errors::ConnectorError::ResponseHandlingFailed) + .change_context(ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult { + ) -> CustomResult { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(types::ErrorResponse { + Ok(ErrorResponse { status_code: res.status_code, code: response .error .code .clone() - .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: response .error .code - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error @@ -1197,29 +1173,15 @@ impl } } -type Verify = dyn services::ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, ->; -impl - services::ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for Stripe -{ +type Verify = dyn ConnectorIntegration; +impl ConnectorIntegration for Stripe { fn get_headers( &self, - req: &types::RouterData< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - >, - _connectors: &settings::Connectors, - ) -> CustomResult)>, errors::ConnectorError> { + req: &RouterData, + _connectors: &Connectors, + ) -> CustomResult)>, ConnectorError> { let mut header = vec![( - headers::CONTENT_TYPE.to_string(), + CONTENT_TYPE.to_string(), Verify::get_content_type(self).to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; @@ -1233,13 +1195,9 @@ impl fn get_url( &self, - _req: &types::RouterData< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - >, - connectors: &settings::Connectors, - ) -> CustomResult { + _req: &RouterData, + connectors: &Connectors, + ) -> CustomResult { Ok(format!( "{}{}", self.base_url(connectors), @@ -1249,29 +1207,21 @@ impl fn get_request_body( &self, - req: &types::RouterData< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - >, - _connectors: &settings::Connectors, - ) -> CustomResult { + req: &RouterData, + _connectors: &Connectors, + ) -> CustomResult { let connector_req = stripe::SetupIntentRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - req: &types::RouterData< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - >, - connectors: &settings::Connectors, - ) -> CustomResult, errors::ConnectorError> { + req: &RouterData, + connectors: &Connectors, + ) -> CustomResult, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) + RequestBuilder::new() + .method(Method::Post) .url(&Verify::get_url(self, req, connectors)?) .attach_default_headers() .headers(Verify::get_headers(self, req, connectors)?) @@ -1282,66 +1232,58 @@ impl fn handle_response( &self, - data: &types::RouterData< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - >, + data: &RouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, + res: Response, ) -> CustomResult< - types::RouterData< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - >, - errors::ConnectorError, + RouterData, + ConnectorError, > where - api::SetupMandate: Clone, - types::SetupMandateRequestData: Clone, - types::PaymentsResponseData: Clone, + SetupMandate: Clone, + SetupMandateRequestData: Clone, + PaymentsResponseData: Clone, { let response: stripe::SetupIntentResponse = res .response .parse_struct("SetupIntentResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) - .change_context(errors::ConnectorError::ResponseHandlingFailed) + .change_context(ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult { + ) -> CustomResult { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(types::ErrorResponse { + Ok(ErrorResponse { status_code: res.status_code, code: response .error .code .clone() - .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: response .error .code - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error @@ -1365,19 +1307,15 @@ impl api::Refund for Stripe {} impl api::RefundExecute for Stripe {} impl api::RefundSync for Stripe {} -impl services::ConnectorIntegration - for Stripe -{ +impl ConnectorIntegration for Stripe { fn get_headers( &self, - req: &types::RefundsRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult)>, errors::ConnectorError> { + req: &RefundsRouterData, + _connectors: &Connectors, + ) -> CustomResult)>, ConnectorError> { let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - types::RefundExecuteType::get_content_type(self) - .to_string() - .into(), + CONTENT_TYPE.to_string(), + RefundExecuteType::get_content_type(self).to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); @@ -1386,10 +1324,10 @@ impl services::ConnectorIntegration { - if stripe_charge == &api::enums::StripeChargeType::Direct { + PaymentChargeType::Stripe(stripe_charge) => { + if stripe_charge == &StripeChargeType::Direct { let mut customer_account_header = vec![( - headers::STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(), + STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(), stripe_split_refund .transfer_account_id .clone() @@ -1409,18 +1347,18 @@ impl services::ConnectorIntegration, - connectors: &settings::Connectors, - ) -> CustomResult { + _req: &RefundsRouterData, + connectors: &Connectors, + ) -> CustomResult { Ok(format!("{}{}", self.base_url(connectors), "v1/refunds")) } fn get_request_body( &self, - req: &types::RefundsRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult { - let refund_amount = connector_utils::convert_amount( + req: &RefundsRouterData, + _connectors: &Connectors, + ) -> CustomResult { + let refund_amount = utils::convert_amount( self.amount_converter, req.request.minor_refund_amount, req.request.currency, @@ -1439,19 +1377,15 @@ impl services::ConnectorIntegration, - connectors: &settings::Connectors, - ) -> CustomResult, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::RefundExecuteType::get_url(self, req, connectors)?) + req: &RefundsRouterData, + connectors: &Connectors, + ) -> CustomResult, ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::RefundExecuteType::get_headers( - self, req, connectors, - )?) - .set_body(types::RefundExecuteType::get_request_body( - self, req, connectors, - )?) + .headers(RefundExecuteType::get_headers(self, req, connectors)?) + .set_body(RefundExecuteType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) } @@ -1459,16 +1393,16 @@ impl services::ConnectorIntegration, + data: &RefundsRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult, errors::ConnectorError> { + res: Response, + ) -> CustomResult, ConnectorError> { let response: stripe::RefundResponse = res.response .parse_struct("Stripe RefundResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; - let response_integrity_object = connector_utils::get_refund_integrity_object( + let response_integrity_object = get_refund_integrity_object( self.amount_converter, response.amount, response.currency.clone(), @@ -1477,7 +1411,7 @@ impl services::ConnectorIntegration, - ) -> CustomResult { + ) -> CustomResult { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(types::ErrorResponse { + Ok(ErrorResponse { status_code: res.status_code, code: response .error .code .clone() - .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: response .error .code - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error @@ -1534,19 +1468,15 @@ impl services::ConnectorIntegration - for Stripe -{ +impl ConnectorIntegration for Stripe { fn get_headers( &self, - req: &types::RouterData, - _connectors: &settings::Connectors, - ) -> CustomResult)>, errors::ConnectorError> { + req: &RouterData, + _connectors: &Connectors, + ) -> CustomResult)>, ConnectorError> { let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - types::RefundSyncType::get_content_type(self) - .to_string() - .into(), + CONTENT_TYPE.to_string(), + RefundSyncType::get_content_type(self).to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); @@ -1569,24 +1499,24 @@ impl services::ConnectorIntegration, - connectors: &settings::Connectors, - ) -> CustomResult { + req: &RefundsRouterData, + connectors: &Connectors, + ) -> CustomResult { let id = req.request.get_connector_refund_id()?; Ok(format!("{}v1/refunds/{}", self.base_url(connectors), id)) } fn build_request( &self, - req: &types::RefundsRouterData, - connectors: &settings::Connectors, - ) -> CustomResult, errors::ConnectorError> { + req: &RefundsRouterData, + connectors: &Connectors, + ) -> CustomResult, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::RefundSyncType::get_url(self, req, connectors)?) + RequestBuilder::new() + .method(Method::Post) + .url(&RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::RefundSyncType::get_headers(self, req, connectors)?) + .headers(RefundSyncType::get_headers(self, req, connectors)?) .build(), )) } @@ -1594,19 +1524,16 @@ impl services::ConnectorIntegration, + data: &RefundsRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult< - types::RouterData, - errors::ConnectorError, - > { + res: Response, + ) -> CustomResult, ConnectorError> { let response: stripe::RefundResponse = res.response .parse_struct("Stripe RefundResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; - let response_integrity_object = connector_utils::get_refund_integrity_object( + let response_integrity_object = get_refund_integrity_object( self.amount_converter, response.amount, response.currency.clone(), @@ -1615,7 +1542,7 @@ impl services::ConnectorIntegration, - ) -> CustomResult { + ) -> CustomResult { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(types::ErrorResponse { + Ok(ErrorResponse { status_code: res.status_code, code: response .error .code .clone() - .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: response .error .code - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error @@ -1672,27 +1599,27 @@ impl services::ConnectorIntegration CustomResult<(), errors::ConnectorError> { + ) -> CustomResult<(), ConnectorError> { match purpose { - api::FilePurpose::DisputeEvidence => { + FilePurpose::DisputeEvidence => { let supported_file_types = ["image/jpeg", "image/png", "application/pdf"]; // 5 Megabytes (MB) if file_size > 5000000 { - Err(errors::ConnectorError::FileValidationFailed { + Err(ConnectorError::FileValidationFailed { reason: "file_size exceeded the max file size of 5MB".to_owned(), })? } if !supported_file_types.contains(&file_type.to_string().as_str()) { - Err(errors::ConnectorError::FileValidationFailed { + Err(ConnectorError::FileValidationFailed { reason: "file_type does not match JPEG, JPG, PNG, or PDF format".to_owned(), })? } @@ -1702,22 +1629,12 @@ impl api::FileUpload for Stripe { } } -impl - services::ConnectorIntegration< - api::Upload, - types::UploadFileRequestData, - types::UploadFileResponse, - > for Stripe -{ +impl ConnectorIntegration for Stripe { fn get_headers( &self, - req: &types::RouterData< - api::Upload, - types::UploadFileRequestData, - types::UploadFileResponse, - >, - _connectors: &settings::Connectors, - ) -> CustomResult)>, errors::ConnectorError> { + req: &RouterData, + _connectors: &Connectors, + ) -> CustomResult)>, ConnectorError> { self.get_auth_header(&req.connector_auth_type) } @@ -1727,9 +1644,9 @@ impl fn get_url( &self, - _req: &types::UploadFileRouterData, - connectors: &settings::Connectors, - ) -> CustomResult { + _req: &UploadFileRouterData, + connectors: &Connectors, + ) -> CustomResult { Ok(format!( "{}{}", connectors.stripe.base_url_file_upload, "v1/files" @@ -1738,27 +1655,25 @@ impl fn get_request_body( &self, - req: &types::UploadFileRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult { + req: &UploadFileRouterData, + _connectors: &Connectors, + ) -> CustomResult { let connector_req = transformers::construct_file_upload_request(req.clone())?; Ok(RequestContent::FormData(connector_req)) } fn build_request( &self, - req: &types::UploadFileRouterData, - connectors: &settings::Connectors, - ) -> CustomResult, errors::ConnectorError> { + req: &UploadFileRouterData, + connectors: &Connectors, + ) -> CustomResult, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::UploadFileType::get_url(self, req, connectors)?) + RequestBuilder::new() + .method(Method::Post) + .url(&UploadFileType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::UploadFileType::get_headers(self, req, connectors)?) - .set_body(types::UploadFileType::get_request_body( - self, req, connectors, - )?) + .headers(UploadFileType::get_headers(self, req, connectors)?) + .set_body(UploadFileType::get_request_body(self, req, connectors)?) .build(), )) } @@ -1766,21 +1681,19 @@ impl #[instrument(skip_all)] fn handle_response( &self, - data: &types::UploadFileRouterData, + data: &UploadFileRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult< - types::RouterData, - errors::ConnectorError, - > { + res: Response, + ) -> CustomResult, ConnectorError> + { let response: stripe::FileUploadResponse = res .response .parse_struct("Stripe FileUploadResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(types::UploadFileRouterData { - response: Ok(types::UploadFileResponse { + Ok(UploadFileRouterData { + response: Ok(UploadFileResponse { provider_file_id: response.file_id, }), ..data.clone() @@ -1789,28 +1702,28 @@ impl fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult { + ) -> CustomResult { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(types::ErrorResponse { + Ok(ErrorResponse { status_code: res.status_code, code: response .error .code .clone() - .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: response .error .code - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error @@ -1830,32 +1743,22 @@ impl } } -impl api::RetrieveFile for Stripe {} +impl RetrieveFile for Stripe {} -impl - services::ConnectorIntegration< - api::Retrieve, - types::RetrieveFileRequestData, - types::RetrieveFileResponse, - > for Stripe -{ +impl ConnectorIntegration for Stripe { fn get_headers( &self, - req: &types::RouterData< - api::Retrieve, - types::RetrieveFileRequestData, - types::RetrieveFileResponse, - >, - _connectors: &settings::Connectors, - ) -> CustomResult)>, errors::ConnectorError> { + req: &RouterData, + _connectors: &Connectors, + ) -> CustomResult)>, ConnectorError> { self.get_auth_header(&req.connector_auth_type) } fn get_url( &self, - req: &types::RetrieveFileRouterData, - connectors: &settings::Connectors, - ) -> CustomResult { + req: &RetrieveFileRouterData, + connectors: &Connectors, + ) -> CustomResult { Ok(format!( "{}v1/files/{}/contents", connectors.stripe.base_url_file_upload, req.request.provider_file_id @@ -1864,15 +1767,15 @@ impl fn build_request( &self, - req: &types::RetrieveFileRouterData, - connectors: &settings::Connectors, - ) -> CustomResult, errors::ConnectorError> { + req: &RetrieveFileRouterData, + connectors: &Connectors, + ) -> CustomResult, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Get) - .url(&types::RetrieveFileType::get_url(self, req, connectors)?) + RequestBuilder::new() + .method(Method::Get) + .url(&RetrieveFileType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::RetrieveFileType::get_headers(self, req, connectors)?) + .headers(RetrieveFileType::get_headers(self, req, connectors)?) .build(), )) } @@ -1880,24 +1783,17 @@ impl #[instrument(skip_all)] fn handle_response( &self, - data: &types::RetrieveFileRouterData, + data: &RetrieveFileRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult< - types::RouterData< - api::Retrieve, - types::RetrieveFileRequestData, - types::RetrieveFileResponse, - >, - errors::ConnectorError, - > { + res: Response, + ) -> CustomResult { let response = res.response; event_builder.map(|event| event.set_response_body(&serde_json::json!({"connector_response_type": "file", "status_code": res.status_code}))); router_env::logger::info!(connector_response_type=?"file"); - Ok(types::RetrieveFileRouterData { - response: Ok(types::RetrieveFileResponse { + Ok(RetrieveFileRouterData { + response: Ok(RetrieveFileResponse { file_data: response.to_vec(), }), ..data.clone() @@ -1906,28 +1802,28 @@ impl fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult { + ) -> CustomResult { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(types::ErrorResponse { + Ok(ErrorResponse { status_code: res.status_code, code: response .error .code .clone() - .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: response .error .code - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error @@ -1947,23 +1843,17 @@ impl } } -impl api::SubmitEvidence for Stripe {} +impl SubmitEvidence for Stripe {} -impl - services::ConnectorIntegration< - api::Evidence, - types::SubmitEvidenceRequestData, - types::SubmitEvidenceResponse, - > for Stripe -{ +impl ConnectorIntegration for Stripe { fn get_headers( &self, - req: &types::SubmitEvidenceRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult)>, errors::ConnectorError> { + req: &SubmitEvidenceRouterData, + _connectors: &Connectors, + ) -> CustomResult)>, ConnectorError> { let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - types::SubmitEvidenceType::get_content_type(self) + CONTENT_TYPE.to_string(), + SubmitEvidenceType::get_content_type(self) .to_string() .into(), )]; @@ -1978,9 +1868,9 @@ impl fn get_url( &self, - req: &types::SubmitEvidenceRouterData, - connectors: &settings::Connectors, - ) -> CustomResult { + req: &SubmitEvidenceRouterData, + connectors: &Connectors, + ) -> CustomResult { Ok(format!( "{}{}{}", self.base_url(connectors), @@ -1991,28 +1881,24 @@ impl fn get_request_body( &self, - req: &types::SubmitEvidenceRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult { + req: &SubmitEvidenceRouterData, + _connectors: &Connectors, + ) -> CustomResult { let connector_req = stripe::Evidence::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - req: &types::SubmitEvidenceRouterData, - connectors: &settings::Connectors, - ) -> CustomResult, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::SubmitEvidenceType::get_url(self, req, connectors)?) + req: &SubmitEvidenceRouterData, + connectors: &Connectors, + ) -> CustomResult, ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&SubmitEvidenceType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::SubmitEvidenceType::get_headers( - self, req, connectors, - )?) - .set_body(types::SubmitEvidenceType::get_request_body( - self, req, connectors, - )?) + .headers(SubmitEvidenceType::get_headers(self, req, connectors)?) + .set_body(SubmitEvidenceType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) } @@ -2020,18 +1906,18 @@ impl #[instrument(skip_all)] fn handle_response( &self, - data: &types::SubmitEvidenceRouterData, + data: &SubmitEvidenceRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult { + res: Response, + ) -> CustomResult { let response: stripe::DisputeObj = res .response .parse_struct("Stripe DisputeObj") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(types::SubmitEvidenceRouterData { - response: Ok(types::SubmitEvidenceResponse { + Ok(SubmitEvidenceRouterData { + response: Ok(SubmitEvidenceResponse { dispute_status: api_models::enums::DisputeStatus::DisputeChallenged, connector_status: Some(response.status), }), @@ -2041,28 +1927,28 @@ impl fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult { + ) -> CustomResult { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(types::ErrorResponse { + Ok(ErrorResponse { status_code: res.status_code, code: response .error .code .clone() - .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: response .error .code - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error @@ -2084,16 +1970,16 @@ impl fn get_signature_elements_from_header( headers: &actix_web::http::header::HeaderMap, -) -> CustomResult>, errors::ConnectorError> { +) -> CustomResult>, ConnectorError> { let security_header = headers .get("Stripe-Signature") .map(|header_value| { header_value .to_str() .map(String::from) - .map_err(|_| errors::ConnectorError::WebhookSignatureNotFound) + .map_err(|_| ConnectorError::WebhookSignatureNotFound) }) - .ok_or(errors::ConnectorError::WebhookSignatureNotFound)??; + .ok_or(ConnectorError::WebhookSignatureNotFound)??; let props = security_header.split(',').collect::>(); let mut security_header_kvs: HashMap> = HashMap::with_capacity(props.len()); @@ -2101,7 +1987,7 @@ fn get_signature_elements_from_header( for prop_str in &props { let (prop_key, prop_value) = prop_str .split_once('=') - .ok_or(errors::ConnectorError::WebhookSourceVerificationFailed)?; + .ok_or(ConnectorError::WebhookSourceVerificationFailed)?; security_header_kvs.insert(prop_key.to_string(), prop_value.bytes().collect()); } @@ -2110,39 +1996,39 @@ fn get_signature_elements_from_header( } #[async_trait::async_trait] -impl api::IncomingWebhook for Stripe { +impl IncomingWebhook for Stripe { fn get_webhook_source_verification_algorithm( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult, errors::ConnectorError> { + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult, ConnectorError> { Ok(Box::new(crypto::HmacSha256)) } fn get_webhook_source_verification_signature( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, - ) -> CustomResult, errors::ConnectorError> { + ) -> CustomResult, ConnectorError> { let mut security_header_kvs = get_signature_elements_from_header(request.headers)?; let signature = security_header_kvs .remove("v1") - .ok_or(errors::ConnectorError::WebhookSignatureNotFound)?; + .ok_or(ConnectorError::WebhookSignatureNotFound)?; - hex::decode(signature).change_context(errors::ConnectorError::WebhookSignatureNotFound) + hex::decode(signature).change_context(ConnectorError::WebhookSignatureNotFound) } fn get_webhook_source_verification_message( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, - ) -> CustomResult, errors::ConnectorError> { + ) -> CustomResult, ConnectorError> { let mut security_header_kvs = get_signature_elements_from_header(request.headers)?; let timestamp = security_header_kvs .remove("t") - .ok_or(errors::ConnectorError::WebhookSignatureNotFound)?; + .ok_or(ConnectorError::WebhookSignatureNotFound)?; Ok(format!( "{}.{}", @@ -2154,12 +2040,12 @@ impl api::IncomingWebhook for Stripe { fn get_webhook_object_reference_id( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult { + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult { let details: stripe::WebhookEvent = request .body .parse_struct("WebhookEvent") - .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; + .change_context(ConnectorError::WebhookReferenceIdNotFound)?; Ok(match details.event_data.event_object.object { stripe::WebhookEventObjectType::PaymentIntent => { @@ -2199,7 +2085,7 @@ impl api::IncomingWebhook for Stripe { .event_data .event_object .payment_intent - .ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?, + .ok_or(ConnectorError::WebhookReferenceIdNotFound)?, ), ), } @@ -2211,7 +2097,7 @@ impl api::IncomingWebhook for Stripe { .event_data .event_object .payment_intent - .ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?, + .ok_or(ConnectorError::WebhookReferenceIdNotFound)?, ), ) } @@ -2265,25 +2151,25 @@ impl api::IncomingWebhook for Stripe { fn get_webhook_event_type( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult { + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult { let details: stripe::WebhookEventTypeBody = request .body .parse_struct("WebhookEventTypeBody") - .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; + .change_context(ConnectorError::WebhookReferenceIdNotFound)?; Ok(match details.event_type { stripe::WebhookEventType::PaymentIntentFailed => { - api::IncomingWebhookEvent::PaymentIntentFailure + IncomingWebhookEvent::PaymentIntentFailure } stripe::WebhookEventType::PaymentIntentSucceed => { - api::IncomingWebhookEvent::PaymentIntentSuccess + IncomingWebhookEvent::PaymentIntentSuccess } stripe::WebhookEventType::PaymentIntentCanceled => { - api::IncomingWebhookEvent::PaymentIntentCancelled + IncomingWebhookEvent::PaymentIntentCancelled } stripe::WebhookEventType::PaymentIntentAmountCapturableUpdated => { - api::IncomingWebhookEvent::PaymentIntentAuthorizationSuccess + IncomingWebhookEvent::PaymentIntentAuthorizationSuccess } stripe::WebhookEventType::ChargeSucceeded => { if let Some(stripe::WebhookPaymentMethodDetails { @@ -2292,9 +2178,9 @@ impl api::IncomingWebhook for Stripe { | stripe::WebhookPaymentMethodType::MultibancoBankTransfers, }) = details.event_data.event_object.payment_method_details { - api::IncomingWebhookEvent::PaymentIntentSuccess + IncomingWebhookEvent::PaymentIntentSuccess } else { - api::IncomingWebhookEvent::EventNotSupported + IncomingWebhookEvent::EventNotSupported } } stripe::WebhookEventType::ChargeRefundUpdated => details @@ -2302,35 +2188,31 @@ impl api::IncomingWebhook for Stripe { .event_object .status .map(|status| match status { - stripe::WebhookEventStatus::Succeeded => { - api::IncomingWebhookEvent::RefundSuccess - } - stripe::WebhookEventStatus::Failed => api::IncomingWebhookEvent::RefundFailure, - _ => api::IncomingWebhookEvent::EventNotSupported, + stripe::WebhookEventStatus::Succeeded => IncomingWebhookEvent::RefundSuccess, + stripe::WebhookEventStatus::Failed => IncomingWebhookEvent::RefundFailure, + _ => IncomingWebhookEvent::EventNotSupported, }) - .unwrap_or(api::IncomingWebhookEvent::EventNotSupported), - stripe::WebhookEventType::SourceChargeable => { - api::IncomingWebhookEvent::SourceChargeable - } - stripe::WebhookEventType::DisputeCreated => api::IncomingWebhookEvent::DisputeOpened, - stripe::WebhookEventType::DisputeClosed => api::IncomingWebhookEvent::DisputeCancelled, + .unwrap_or(IncomingWebhookEvent::EventNotSupported), + stripe::WebhookEventType::SourceChargeable => IncomingWebhookEvent::SourceChargeable, + stripe::WebhookEventType::DisputeCreated => IncomingWebhookEvent::DisputeOpened, + stripe::WebhookEventType::DisputeClosed => IncomingWebhookEvent::DisputeCancelled, stripe::WebhookEventType::DisputeUpdated => details .event_data .event_object .status .map(Into::into) - .unwrap_or(api::IncomingWebhookEvent::EventNotSupported), + .unwrap_or(IncomingWebhookEvent::EventNotSupported), stripe::WebhookEventType::PaymentIntentPartiallyFunded => { - api::IncomingWebhookEvent::PaymentIntentPartiallyFunded + IncomingWebhookEvent::PaymentIntentPartiallyFunded } stripe::WebhookEventType::PaymentIntentRequiresAction => { - api::IncomingWebhookEvent::PaymentActionRequired + IncomingWebhookEvent::PaymentActionRequired } stripe::WebhookEventType::ChargeDisputeFundsWithdrawn => { - api::IncomingWebhookEvent::DisputeLost + IncomingWebhookEvent::DisputeLost } stripe::WebhookEventType::ChargeDisputeFundsReinstated => { - api::IncomingWebhookEvent::DisputeWon + IncomingWebhookEvent::DisputeWon } stripe::WebhookEventType::Unknown | stripe::WebhookEventType::ChargeCaptured @@ -2342,37 +2224,37 @@ impl api::IncomingWebhook for Stripe { | stripe::WebhookEventType::PaymentIntentCreated | stripe::WebhookEventType::PaymentIntentProcessing | stripe::WebhookEventType::SourceTransactionCreated => { - api::IncomingWebhookEvent::EventNotSupported + IncomingWebhookEvent::EventNotSupported } }) } fn get_webhook_resource_object( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult, errors::ConnectorError> { + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult, ConnectorError> { let details: stripe::WebhookEvent = request .body .parse_struct("WebhookEvent") - .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + .change_context(ConnectorError::WebhookBodyDecodingFailed)?; Ok(Box::new(details.event_data.event_object)) } fn get_dispute_details( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult { + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult { let details: stripe::WebhookEvent = request .body .parse_struct("WebhookEvent") - .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; - Ok(api::disputes::DisputePayload { + .change_context(ConnectorError::WebhookBodyDecodingFailed)?; + Ok(DisputePayload { amount: details .event_data .event_object .amount .get_required_value("amount") - .change_context(errors::ConnectorError::MissingRequiredField { + .change_context(ConnectorError::MissingRequiredField { field_name: "amount", })? .to_string(), @@ -2390,7 +2272,7 @@ impl api::IncomingWebhook for Stripe { .event_data .event_object .status - .ok_or(errors::ConnectorError::WebhookResourceObjectNotFound)? + .ok_or(ConnectorError::WebhookResourceObjectNotFound)? .to_string(), created_at: Some(details.event_data.event_object.created), updated_at: None, @@ -2398,18 +2280,18 @@ impl api::IncomingWebhook for Stripe { } } -impl services::ConnectorRedirectResponse for Stripe { +impl ConnectorRedirectResponse for Stripe { fn get_flow_type( &self, _query_params: &str, _json_payload: Option, - action: services::PaymentAction, - ) -> CustomResult { + action: PaymentAction, + ) -> CustomResult { match action { - services::PaymentAction::PSync - | services::PaymentAction::CompleteAuthorize - | services::PaymentAction::PaymentAuthenticateCompleteAuthorize => { - Ok(payments::CallConnectorAction::Trigger) + PaymentAction::PSync + | PaymentAction::CompleteAuthorize + | PaymentAction::PaymentAuthenticateCompleteAuthorize => { + Ok(CallConnectorAction::Trigger) } } } @@ -2428,18 +2310,16 @@ impl api::PayoutRecipient for Stripe {} impl api::PayoutRecipientAccount for Stripe {} #[cfg(feature = "payouts")] -impl services::ConnectorIntegration - for Stripe -{ +impl ConnectorIntegration for Stripe { fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, - req: &types::PayoutsRouterData, - connectors: &settings::Connectors, - ) -> CustomResult { + req: &PayoutsRouterData, + connectors: &Connectors, + ) -> CustomResult { let transfer_id = req.request.get_transfer_id()?; Ok(format!( "{}v1/transfers/{}/reversals", @@ -2449,34 +2329,32 @@ impl services::ConnectorIntegration, - _connectors: &settings::Connectors, - ) -> CustomResult)>, errors::ConnectorError> { + req: &PayoutsRouterData, + _connectors: &Connectors, + ) -> CustomResult)>, ConnectorError> { self.build_headers(req, _connectors) } fn get_request_body( &self, - req: &types::RouterData, - _connectors: &settings::Connectors, - ) -> CustomResult { + req: &RouterData, + _connectors: &Connectors, + ) -> CustomResult { let connector_req = stripe::StripeConnectReversalRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - req: &types::PayoutsRouterData, - connectors: &settings::Connectors, - ) -> CustomResult, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PayoutCancelType::get_url(self, req, connectors)?) + req: &PayoutsRouterData, + connectors: &Connectors, + ) -> CustomResult, ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&PayoutCancelType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PayoutCancelType::get_headers(self, req, connectors)?) - .set_body(types::PayoutCancelType::get_request_body( - self, req, connectors, - )?) + .headers(PayoutCancelType::get_headers(self, req, connectors)?) + .set_body(PayoutCancelType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) @@ -2484,16 +2362,16 @@ impl services::ConnectorIntegration, + data: &PayoutsRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult, errors::ConnectorError> { + res: Response, + ) -> CustomResult, ConnectorError> { let response: stripe::StripeConnectReversalResponse = res .response .parse_struct("StripeConnectReversalResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -2502,59 +2380,55 @@ impl services::ConnectorIntegration, - ) -> CustomResult { + ) -> CustomResult { self.build_error_response(res, event_builder) } } #[cfg(feature = "payouts")] -impl services::ConnectorIntegration - for Stripe -{ +impl ConnectorIntegration for Stripe { fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, - _req: &types::PayoutsRouterData, - connectors: &settings::Connectors, - ) -> CustomResult { + _req: &PayoutsRouterData, + connectors: &Connectors, + ) -> CustomResult { Ok(format!("{}v1/transfers", connectors.stripe.base_url)) } fn get_headers( &self, - req: &types::PayoutsRouterData, - connectors: &settings::Connectors, - ) -> CustomResult)>, errors::ConnectorError> { + req: &PayoutsRouterData, + connectors: &Connectors, + ) -> CustomResult)>, ConnectorError> { self.build_headers(req, connectors) } fn get_request_body( &self, - req: &types::PayoutsRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult { + req: &PayoutsRouterData, + _connectors: &Connectors, + ) -> CustomResult { let connector_req = stripe::StripeConnectPayoutCreateRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - req: &types::PayoutsRouterData, - connectors: &settings::Connectors, - ) -> CustomResult, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PayoutCreateType::get_url(self, req, connectors)?) + req: &PayoutsRouterData, + connectors: &Connectors, + ) -> CustomResult, ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&PayoutCreateType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PayoutCreateType::get_headers(self, req, connectors)?) - .set_body(types::PayoutCreateType::get_request_body( - self, req, connectors, - )?) + .headers(PayoutCreateType::get_headers(self, req, connectors)?) + .set_body(PayoutCreateType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) @@ -2562,16 +2436,16 @@ impl services::ConnectorIntegration, + data: &PayoutsRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult, errors::ConnectorError> { + res: Response, + ) -> CustomResult, ConnectorError> { let response: stripe::StripeConnectPayoutCreateResponse = res .response .parse_struct("StripeConnectPayoutCreateResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -2580,38 +2454,36 @@ impl services::ConnectorIntegration, - ) -> CustomResult { + ) -> CustomResult { self.build_error_response(res, event_builder) } } #[cfg(feature = "payouts")] -impl services::ConnectorIntegration - for Stripe -{ +impl ConnectorIntegration for Stripe { fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, - _req: &types::PayoutsRouterData, - connectors: &settings::Connectors, - ) -> CustomResult { + _req: &PayoutsRouterData, + connectors: &Connectors, + ) -> CustomResult { Ok(format!("{}v1/payouts", connectors.stripe.base_url,)) } fn get_headers( &self, - req: &types::PayoutsRouterData, - connectors: &settings::Connectors, - ) -> CustomResult)>, errors::ConnectorError> { + req: &PayoutsRouterData, + connectors: &Connectors, + ) -> CustomResult)>, ConnectorError> { let mut headers = self.build_headers(req, connectors)?; let customer_account = req.get_connector_customer_id()?; let mut customer_account_header = vec![( - headers::STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(), + STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(), customer_account.into_masked(), )]; headers.append(&mut customer_account_header); @@ -2620,28 +2492,24 @@ impl services::ConnectorIntegration, - _connectors: &settings::Connectors, - ) -> CustomResult { + req: &PayoutsRouterData, + _connectors: &Connectors, + ) -> CustomResult { let connector_req = stripe::StripeConnectPayoutFulfillRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - req: &types::PayoutsRouterData, - connectors: &settings::Connectors, - ) -> CustomResult, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PayoutFulfillType::get_url(self, req, connectors)?) + req: &PayoutsRouterData, + connectors: &Connectors, + ) -> CustomResult, ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&PayoutFulfillType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PayoutFulfillType::get_headers( - self, req, connectors, - )?) - .set_body(types::PayoutFulfillType::get_request_body( - self, req, connectors, - )?) + .headers(PayoutFulfillType::get_headers(self, req, connectors)?) + .set_body(PayoutFulfillType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) @@ -2649,16 +2517,16 @@ impl services::ConnectorIntegration, + data: &PayoutsRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult, errors::ConnectorError> { + res: Response, + ) -> CustomResult, ConnectorError> { let response: stripe::StripeConnectPayoutFulfillResponse = res .response .parse_struct("StripeConnectPayoutFulfillResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -2667,60 +2535,55 @@ impl services::ConnectorIntegration, - ) -> CustomResult { + ) -> CustomResult { self.build_error_response(res, event_builder) } } #[cfg(feature = "payouts")] -impl - services::ConnectorIntegration - for Stripe -{ +impl ConnectorIntegration for Stripe { fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, - _req: &types::PayoutsRouterData, - connectors: &settings::Connectors, - ) -> CustomResult { + _req: &PayoutsRouterData, + connectors: &Connectors, + ) -> CustomResult { Ok(format!("{}v1/accounts", connectors.stripe.base_url)) } fn get_headers( &self, - req: &types::PayoutsRouterData, - connectors: &settings::Connectors, - ) -> CustomResult)>, errors::ConnectorError> { + req: &PayoutsRouterData, + connectors: &Connectors, + ) -> CustomResult)>, ConnectorError> { self.build_headers(req, connectors) } fn get_request_body( &self, - req: &types::PayoutsRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult { + req: &PayoutsRouterData, + _connectors: &Connectors, + ) -> CustomResult { let connector_req = stripe::StripeConnectRecipientCreateRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - req: &types::PayoutsRouterData, - connectors: &settings::Connectors, - ) -> CustomResult, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PayoutRecipientType::get_url(self, req, connectors)?) + req: &PayoutsRouterData, + connectors: &Connectors, + ) -> CustomResult, ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&PayoutRecipientType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PayoutRecipientType::get_headers( - self, req, connectors, - )?) - .set_body(types::PayoutRecipientType::get_request_body( + .headers(PayoutRecipientType::get_headers(self, req, connectors)?) + .set_body(PayoutRecipientType::get_request_body( self, req, connectors, )?) .build(); @@ -2730,16 +2593,16 @@ impl fn handle_response( &self, - data: &types::PayoutsRouterData, + data: &PayoutsRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult, errors::ConnectorError> { + res: Response, + ) -> CustomResult, ConnectorError> { let response: stripe::StripeConnectRecipientCreateResponse = res .response .parse_struct("StripeConnectRecipientCreateResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -2748,30 +2611,24 @@ impl fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult { + ) -> CustomResult { self.build_error_response(res, event_builder) } } #[cfg(feature = "payouts")] -impl - services::ConnectorIntegration< - api::PoRecipientAccount, - types::PayoutsData, - types::PayoutsResponseData, - > for Stripe -{ +impl ConnectorIntegration for Stripe { fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, - req: &types::PayoutsRouterData, - connectors: &settings::Connectors, - ) -> CustomResult { + req: &PayoutsRouterData, + connectors: &Connectors, + ) -> CustomResult { let connector_customer_id = req.get_connector_customer_id()?; Ok(format!( "{}v1/accounts/{}/external_accounts", @@ -2781,36 +2638,34 @@ impl fn get_headers( &self, - req: &types::PayoutsRouterData, - connectors: &settings::Connectors, - ) -> CustomResult)>, errors::ConnectorError> { + req: &PayoutsRouterData, + connectors: &Connectors, + ) -> CustomResult)>, ConnectorError> { self.build_headers(req, connectors) } fn get_request_body( &self, - req: &types::PayoutsRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult { + req: &PayoutsRouterData, + _connectors: &Connectors, + ) -> CustomResult { let connector_req = stripe::StripeConnectRecipientAccountCreateRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - req: &types::PayoutsRouterData, - connectors: &settings::Connectors, - ) -> CustomResult, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PayoutRecipientAccountType::get_url( - self, req, connectors, - )?) + req: &PayoutsRouterData, + connectors: &Connectors, + ) -> CustomResult, ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&PayoutRecipientAccountType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PayoutRecipientAccountType::get_headers( + .headers(PayoutRecipientAccountType::get_headers( self, req, connectors, )?) - .set_body(types::PayoutRecipientAccountType::get_request_body( + .set_body(PayoutRecipientAccountType::get_request_body( self, req, connectors, )?) .build(); @@ -2820,17 +2675,16 @@ impl fn handle_response( &self, - data: &types::PayoutsRouterData, + data: &PayoutsRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult, errors::ConnectorError> - { + res: Response, + ) -> CustomResult, ConnectorError> { let response: stripe::StripeConnectRecipientAccountCreateResponse = res .response .parse_struct("StripeConnectRecipientAccountCreateResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -2839,9 +2693,9 @@ impl fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult { + ) -> CustomResult { self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs similarity index 74% rename from crates/router/src/connector/stripe/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs index ad2e1d7e85..da6ec76936 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs @@ -1,38 +1,66 @@ use std::{collections::HashMap, ops::Deref}; use api_models::{self, enums as api_enums, payments}; +use common_enums::{enums, AttemptStatus, PaymentChargeType, StripeChargeType}; use common_utils::{ + collect_missing_value_keys, errors::CustomResult, - ext_traits::{ByteSliceExt, Encode}, + ext_traits::{ByteSliceExt, Encode, OptionExt as _}, pii::{self, Email}, - request::RequestContent, + request::{Method, RequestContent}, types::MinorUnit, }; use error_stack::ResultExt; -use hyperswitch_domain_models::mandates::AcceptanceType; -use masking::{ExposeInterface, ExposeOptionInterface, Mask, PeekInterface, Secret}; +use hyperswitch_domain_models::{ + mandates::AcceptanceType, + payment_method_data::{ + self, BankRedirectData, Card, CardRedirectData, GiftCardData, GooglePayWalletData, + PayLaterData, PaymentMethodData, VoucherData, WalletData, + }, + router_data::{ + AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData, + PaymentMethodToken, RouterData, + }, + router_flow_types::{Execute, RSync}, + router_request_types::{ + BrowserInformation, ChargeRefundsOptions, DestinationChargeRefund, DirectChargeRefund, + ResponseId, SplitRefundsRequest, + }, + router_response_types::{ + MandateReference, PaymentsResponseData, PreprocessingResponseId, RedirectForm, + RefundsResponseData, + }, + types::{ + ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData, + PaymentsUpdateMetadataRouterData, RefundsRouterData, SetupMandateRouterData, + TokenizationRouterData, + }, +}; +use hyperswitch_interfaces::{consts, errors::ConnectorError}; +use masking::{ExposeInterface, ExposeOptionInterface, Mask, Maskable, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use serde_json::Value; use time::PrimitiveDateTime; use url::Url; + +use crate::{ + constants::headers::STRIPE_COMPATIBLE_CONNECT_ACCOUNT, + utils::{convert_uppercase, ApplePay, ApplePayDecrypt, RouterData as OtherRouterData}, +}; #[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}, + RefundsResponseRouterData, ResponseRouterData, SubmitEvidenceRouterData, + UploadFileRouterData, + }, + utils::{ + get_unimplemented_payment_method_error_message, is_payment_failure, is_refund_failure, + PaymentsAuthorizeRequestData, SplitPaymentData, }, - utils::OptionExt, }; - pub mod auth_headers { pub const STRIPE_API_VERSION: &str = "stripe-version"; pub const STRIPE_VERSION: &str = "2022-11-15"; @@ -42,15 +70,15 @@ pub struct StripeAuthType { pub(super) api_key: Secret, } -impl TryFrom<&types::ConnectorAuthType> for StripeAuthType { - type Error = error_stack::Report; - fn try_from(item: &types::ConnectorAuthType) -> Result { - if let types::ConnectorAuthType::HeaderKey { api_key } = item { +impl TryFrom<&ConnectorAuthType> for StripeAuthType { + type Error = error_stack::Report; + fn try_from(item: &ConnectorAuthType) -> Result { + if let ConnectorAuthType::HeaderKey { api_key } = item { Ok(Self { api_key: api_key.to_owned(), }) } else { - Err(errors::ConnectorError::FailedToObtainAuthType.into()) + Err(ConnectorError::FailedToObtainAuthType.into()) } } } @@ -414,7 +442,7 @@ pub struct SepaBankTransferData { #[serde( rename = "payment_method_options[customer_balance][bank_transfer][eu_bank_transfer][country]" )] - pub country: api_models::enums::CountryAlpha2, + pub country: enums::CountryAlpha2, } #[derive(Debug, Eq, PartialEq, Serialize)] @@ -664,7 +692,7 @@ pub enum StripeCreditTransferTypes { } impl TryFrom for StripePaymentMethodType { - type Error = error_stack::Report; + type Error = error_stack::Report; fn try_from(value: enums::PaymentMethodType) -> Result { match value { enums::PaymentMethodType::Credit => Ok(Self::Card), @@ -701,8 +729,8 @@ impl TryFrom for StripePaymentMethodType { | 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"), + | enums::PaymentMethodType::Oxxo => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), ) .into()), enums::PaymentMethodType::AliPayHk @@ -771,8 +799,8 @@ impl TryFrom for StripePaymentMethodType { | 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"), + | enums::PaymentMethodType::Mifinity => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), ) .into()), } @@ -880,87 +908,85 @@ impl From for api_models::webhooks::IncomingWebhookEvent { } } -impl TryFrom<&common_enums::enums::BankNames> for StripeBankNames { - type Error = errors::ConnectorError; - fn try_from(bank: &common_enums::enums::BankNames) -> Result { +impl TryFrom<&enums::BankNames> for StripeBankNames { + type Error = ConnectorError; + fn try_from(bank: &enums::BankNames) -> Result { 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 => { + enums::BankNames::AbnAmro => Self::AbnAmro, + enums::BankNames::ArzteUndApothekerBank => Self::ArzteUndApothekerBank, + enums::BankNames::AsnBank => Self::AsnBank, + enums::BankNames::AustrianAnadiBankAg => Self::AustrianAnadiBankAg, + enums::BankNames::BankAustria => Self::BankAustria, + enums::BankNames::BankhausCarlSpangler => Self::BankhausCarlSpangler, + 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 => { + enums::BankNames::BawagPskAg => Self::BawagPskAg, + enums::BankNames::BksBankAg => Self::BksBankAg, + enums::BankNames::BrullKallmusBankAg => Self::BrullKallmusBankAg, + enums::BankNames::BtvVierLanderBank => Self::BtvVierLanderBank, + enums::BankNames::Bunq => Self::Bunq, + enums::BankNames::CapitalBankGraweGruppeAg => Self::CapitalBankGraweGruppeAg, + enums::BankNames::Citi => Self::CitiHandlowy, + enums::BankNames::Dolomitenbank => Self::Dolomitenbank, + enums::BankNames::EasybankAg => Self::EasybankAg, + enums::BankNames::ErsteBankUndSparkassen => Self::ErsteBankUndSparkassen, + enums::BankNames::Handelsbanken => Self::Handelsbanken, + enums::BankNames::HypoAlpeadriabankInternationalAg => { Self::HypoAlpeadriabankInternationalAg } - common_enums::enums::BankNames::HypoNoeLbFurNiederosterreichUWien => { + enums::BankNames::HypoNoeLbFurNiederosterreichUWien => { Self::HypoNoeLbFurNiederosterreichUWien } - common_enums::enums::BankNames::HypoOberosterreichSalzburgSteiermark => { + enums::BankNames::HypoOberosterreichSalzburgSteiermark => { Self::HypoOberosterreichSalzburgSteiermark } - common_enums::enums::BankNames::HypoTirolBankAg => Self::HypoTirolBankAg, - common_enums::enums::BankNames::HypoVorarlbergBankAg => Self::HypoVorarlbergBankAg, - common_enums::enums::BankNames::HypoBankBurgenlandAktiengesellschaft => { + enums::BankNames::HypoTirolBankAg => Self::HypoTirolBankAg, + enums::BankNames::HypoVorarlbergBankAg => Self::HypoVorarlbergBankAg, + 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 => { + enums::BankNames::Ing => Self::Ing, + enums::BankNames::Knab => Self::Knab, + enums::BankNames::MarchfelderBank => Self::MarchfelderBank, + enums::BankNames::OberbankAg => Self::OberbankAg, + 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, + enums::BankNames::Rabobank => Self::Rabobank, + enums::BankNames::Regiobank => Self::Regiobank, + enums::BankNames::Revolut => Self::Revolut, + enums::BankNames::SnsBank => Self::SnsBank, + enums::BankNames::TriodosBank => Self::TriodosBank, + enums::BankNames::VanLanschot => Self::VanLanschot, + enums::BankNames::Moneyou => Self::Moneyou, + enums::BankNames::SchoellerbankAg => Self::SchoellerbankAg, + enums::BankNames::SpardaBankWien => Self::SpardaBankWien, + enums::BankNames::VolksbankGruppe => Self::VolksbankGruppe, + enums::BankNames::VolkskreditbankAg => Self::VolkskreditbankAg, + enums::BankNames::VrBankBraunau => Self::VrBankBraunau, + enums::BankNames::PlusBank => Self::PlusBank, + enums::BankNames::EtransferPocztowy24 => Self::EtransferPocztowy24, + enums::BankNames::BankiSpbdzielcze => Self::BankiSpbdzielcze, + enums::BankNames::BankNowyBfgSa => Self::BankNowyBfgSa, + enums::BankNames::GetinBank => Self::GetinBank, + enums::BankNames::Blik => Self::Blik, + enums::BankNames::NoblePay => Self::NoblePay, + enums::BankNames::IdeaBank => Self::IdeaBank, + enums::BankNames::EnveloBank => Self::EnveloBank, + enums::BankNames::NestPrzelew => Self::NestPrzelew, + enums::BankNames::MbankMtransfer => Self::MbankMtransfer, + enums::BankNames::Inteligo => Self::Inteligo, + enums::BankNames::PbacZIpko => Self::PbacZIpko, + enums::BankNames::BnpParibas => Self::BnpParibas, + enums::BankNames::BankPekaoSa => Self::BankPekaoSa, + enums::BankNames::VolkswagenBank => Self::VolkswagenBank, + enums::BankNames::AliorBank => Self::AliorBank, + enums::BankNames::Boz => Self::Boz, - _ => Err(errors::ConnectorError::NotImplemented( - connector_util::get_unimplemented_payment_method_error_message("stripe"), + _ => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), ))?, }) } @@ -969,7 +995,7 @@ impl TryFrom<&common_enums::enums::BankNames> for StripeBankNames { fn validate_shipping_address_against_payment_method( shipping_address: &Option, payment_method: Option<&StripePaymentMethodType>, -) -> Result<(), error_stack::Report> { +) -> Result<(), error_stack::Report> { match payment_method { Some(StripePaymentMethodType::AfterpayClearpay) => match shipping_address { Some(address) => { @@ -980,14 +1006,14 @@ fn validate_shipping_address_against_payment_method( ); if !missing_fields.is_empty() { - return Err(errors::ConnectorError::MissingRequiredFields { + return Err(ConnectorError::MissingRequiredFields { field_names: missing_fields, } .into()); } Ok(()) } - None => Err(errors::ConnectorError::MissingRequiredField { + None => Err(ConnectorError::MissingRequiredField { field_name: "shipping.address", } .into()), @@ -996,125 +1022,112 @@ fn validate_shipping_address_against_payment_method( } } -impl TryFrom<&domain::payments::PayLaterData> for StripePaymentMethodType { - type Error = errors::ConnectorError; - fn try_from(pay_later_data: &domain::payments::PayLaterData) -> Result { +impl TryFrom<&PayLaterData> for StripePaymentMethodType { + type Error = ConnectorError; + fn try_from(pay_later_data: &PayLaterData) -> Result { 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) - } + PayLaterData::KlarnaRedirect { .. } => Ok(Self::Klarna), + PayLaterData::AffirmRedirect {} => Ok(Self::Affirm), + 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 { - 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 { - type Error = errors::ConnectorError; - fn foreign_try_from(wallet_data: &domain::WalletData) -> Result { - 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"), + PayLaterData::KlarnaSdk { .. } + | PayLaterData::PayBrightRedirect {} + | PayLaterData::WalleyRedirect {} + | PayLaterData::AlmaRedirect {} + | PayLaterData::AtomeRedirect {} => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), )), } } } -impl From<&domain::BankDebitData> for StripePaymentMethodType { - fn from(bank_debit_data: &domain::BankDebitData) -> Self { +impl TryFrom<&BankRedirectData> for StripePaymentMethodType { + type Error = ConnectorError; + fn try_from(bank_redirect_data: &BankRedirectData) -> Result { + match bank_redirect_data { + BankRedirectData::Giropay { .. } => Ok(Self::Giropay), + BankRedirectData::Ideal { .. } => Ok(Self::Ideal), + BankRedirectData::Sofort { .. } => Ok(Self::Sofort), + BankRedirectData::BancontactCard { .. } => Ok(Self::Bancontact), + BankRedirectData::Przelewy24 { .. } => Ok(Self::Przelewy24), + BankRedirectData::Eps { .. } => Ok(Self::Eps), + BankRedirectData::Blik { .. } => Ok(Self::Blik), + BankRedirectData::OnlineBankingFpx { .. } => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), + )), + BankRedirectData::Bizum {} + | BankRedirectData::Interac { .. } + | BankRedirectData::Eft { .. } + | BankRedirectData::OnlineBankingCzechRepublic { .. } + | BankRedirectData::OnlineBankingFinland { .. } + | BankRedirectData::OnlineBankingPoland { .. } + | BankRedirectData::OnlineBankingSlovakia { .. } + | BankRedirectData::OnlineBankingThailand { .. } + | BankRedirectData::OpenBankingUk { .. } + | BankRedirectData::Trustly { .. } + | BankRedirectData::LocalBankRedirect {} => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), + )), + } + } +} + +fn get_stripe_payment_method_type_from_wallet_data( + wallet_data: &WalletData, +) -> Result, ConnectorError> { + match wallet_data { + WalletData::AliPayRedirect(_) => Ok(Some(StripePaymentMethodType::Alipay)), + WalletData::ApplePay(_) => Ok(None), + WalletData::GooglePay(_) => Ok(Some(StripePaymentMethodType::Card)), + WalletData::WeChatPayQr(_) => Ok(Some(StripePaymentMethodType::Wechatpay)), + WalletData::CashappQr(_) => Ok(Some(StripePaymentMethodType::Cashapp)), + WalletData::AmazonPayRedirect(_) => Ok(Some(StripePaymentMethodType::AmazonPay)), + WalletData::MobilePayRedirect(_) => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), + )), + WalletData::PaypalRedirect(_) + | WalletData::AliPayQr(_) + | WalletData::AliPayHkRedirect(_) + | WalletData::MomoRedirect(_) + | WalletData::KakaoPayRedirect(_) + | WalletData::GoPayRedirect(_) + | WalletData::GcashRedirect(_) + | WalletData::ApplePayRedirect(_) + | WalletData::ApplePayThirdPartySdk(_) + | WalletData::DanaRedirect {} + | WalletData::GooglePayRedirect(_) + | WalletData::GooglePayThirdPartySdk(_) + | WalletData::MbWayRedirect(_) + | WalletData::PaypalSdk(_) + | WalletData::Paze(_) + | WalletData::SamsungPay(_) + | WalletData::TwintRedirect {} + | WalletData::VippsRedirect {} + | WalletData::TouchNGoRedirect(_) + | WalletData::SwishQr(_) + | WalletData::WeChatPayRedirect(_) + | WalletData::Mifinity(_) => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), + )), + } +} + +impl From<&payment_method_data::BankDebitData> for StripePaymentMethodType { + fn from(bank_debit_data: &payment_method_data::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, + payment_method_data::BankDebitData::AchBankDebit { .. } => Self::Ach, + payment_method_data::BankDebitData::SepaBankDebit { .. } => Self::Sepa, + payment_method_data::BankDebitData::BecsBankDebit { .. } => Self::Becs, + payment_method_data::BankDebitData::BacsBankDebit { .. } => Self::Bacs, } } } fn get_bank_debit_data( - bank_debit_data: &domain::BankDebitData, + bank_debit_data: &payment_method_data::BankDebitData, ) -> (StripePaymentMethodType, BankDebitData) { match bank_debit_data { - domain::BankDebitData::AchBankDebit { + payment_method_data::BankDebitData::AchBankDebit { account_number, routing_number, .. @@ -1126,13 +1139,13 @@ fn get_bank_debit_data( }; (StripePaymentMethodType::Ach, ach_data) } - domain::BankDebitData::SepaBankDebit { iban, .. } => { + payment_method_data::BankDebitData::SepaBankDebit { iban, .. } => { let sepa_data: BankDebitData = BankDebitData::Sepa { iban: iban.to_owned(), }; (StripePaymentMethodType::Sepa, sepa_data) } - domain::BankDebitData::BecsBankDebit { + payment_method_data::BankDebitData::BecsBankDebit { account_number, bsb_number, .. @@ -1143,7 +1156,7 @@ fn get_bank_debit_data( }; (StripePaymentMethodType::Becs, becs_data) } - domain::BankDebitData::BacsBankDebit { + payment_method_data::BankDebitData::BacsBankDebit { account_number, sort_code, .. @@ -1158,9 +1171,9 @@ fn get_bank_debit_data( } fn create_stripe_payment_method( - payment_method_data: &domain::PaymentMethodData, + payment_method_data: &PaymentMethodData, auth_type: enums::AuthenticationType, - payment_method_token: Option, + payment_method_token: Option, is_customer_initiated_mandate_payment: Option, billing_address: StripeBillingAddress, ) -> Result< @@ -1169,10 +1182,10 @@ fn create_stripe_payment_method( Option, StripeBillingAddress, ), - error_stack::Report, + error_stack::Report, > { match payment_method_data { - domain::PaymentMethodData::Card(card_details) => { + PaymentMethodData::Card(card_details) => { let payment_method_auth_type = match auth_type { enums::AuthenticationType::ThreeDs => Auth3ds::Any, enums::AuthenticationType::NoThreeDs => Auth3ds::Automatic, @@ -1183,7 +1196,7 @@ fn create_stripe_payment_method( billing_address, )) } - domain::PaymentMethodData::PayLater(pay_later_data) => { + PaymentMethodData::PayLater(pay_later_data) => { let stripe_pm_type = StripePaymentMethodType::try_from(pay_later_data)?; Ok(( @@ -1194,7 +1207,7 @@ fn create_stripe_payment_method( billing_address, )) } - domain::PaymentMethodData::BankRedirect(bank_redirect_data) => { + 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()), @@ -1208,8 +1221,8 @@ fn create_stripe_payment_method( Ok((bank_redirect_data, Some(pm_type), billing_address)) } - domain::PaymentMethodData::Wallet(wallet_data) => { - let pm_type = ForeignTryFrom::foreign_try_from(wallet_data)?; + PaymentMethodData::Wallet(wallet_data) => { + let pm_type = get_stripe_payment_method_type_from_wallet_data(wallet_data)?; let wallet_specific_data = StripePaymentMethodData::try_from((wallet_data, payment_method_token))?; Ok(( @@ -1218,7 +1231,7 @@ fn create_stripe_payment_method( StripeBillingAddress::default(), )) } - domain::PaymentMethodData::BankDebit(bank_debit_data) => { + PaymentMethodData::BankDebit(bank_debit_data) => { let (pm_type, bank_debit_data) = get_bank_debit_data(bank_debit_data); let pm_data = StripePaymentMethodData::BankDebit(StripeBankDebitData { @@ -1227,155 +1240,149 @@ fn create_stripe_payment_method( 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(), + PaymentMethodData::BankTransfer(bank_transfer_data) => match bank_transfer_data.deref() { + payment_method_data::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, + }), )), - 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", + None, + StripeBillingAddress::default(), + )), + payment_method_data::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( + ConnectorError::MissingRequiredField { + field_name: "billing_address.email", }, )?, - })), - ), - Some(StripePaymentMethodType::CustomerBalance), - billing_address, + }, + )), + ), + None, + StripeBillingAddress::default(), + )), + payment_method_data::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( + ConnectorError::MissingRequiredField { + field_name: "billing_address.country", + }, + )?, + }), )), - 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, + Some(StripePaymentMethodType::CustomerBalance), + billing_address, + )), + payment_method_data::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, + }), )), - 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"), + Some(StripePaymentMethodType::CustomerBalance), + billing_address, + )), + payment_method_data::BankTransferData::Pix { .. } => Err( + ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message( + "stripe", + )) + .into(), + ), + payment_method_data::BankTransferData::Pse {} + | payment_method_data::BankTransferData::LocalBankTransfer { .. } + | payment_method_data::BankTransferData::InstantBankTransfer {} + | payment_method_data::BankTransferData::PermataBankTransfer { .. } + | payment_method_data::BankTransferData::BcaBankTransfer { .. } + | payment_method_data::BankTransferData::BniVaBankTransfer { .. } + | payment_method_data::BankTransferData::BriVaBankTransfer { .. } + | payment_method_data::BankTransferData::CimbVaBankTransfer { .. } + | payment_method_data::BankTransferData::DanamonVaBankTransfer { .. } + | payment_method_data::BankTransferData::MandiriVaBankTransfer { .. } => Err( + ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message( + "stripe", + )) + .into(), + ), + }, + PaymentMethodData::Crypto(_) => Err(ConnectorError::NotImplemented( + 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()) - } + PaymentMethodData::GiftCard(giftcard_data) => match giftcard_data.deref() { + GiftCardData::Givex(_) | GiftCardData::PaySafeCard {} => Err( + ConnectorError::NotImplemented(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()) - } + PaymentMethodData::CardRedirect(cardredirect_data) => match cardredirect_data { + CardRedirectData::Knet {} + | CardRedirectData::Benefit {} + | CardRedirectData::MomoAtm {} + | CardRedirectData::CardRedirect {} => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), + ) + .into()), }, - domain::PaymentMethodData::Reward => Err(errors::ConnectorError::NotImplemented( - connector_util::get_unimplemented_payment_method_error_message("stripe"), + PaymentMethodData::Reward => Err(ConnectorError::NotImplemented( + 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"), + PaymentMethodData::Voucher(voucher_data) => match voucher_data { + VoucherData::Boleto(_) | VoucherData::Oxxo => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), + ) + .into()), + VoucherData::Alfamart(_) + | VoucherData::Efecty + | VoucherData::PagoEfectivo + | VoucherData::RedCompra + | VoucherData::RedPagos + | VoucherData::Indomaret(_) + | VoucherData::SevenEleven(_) + | VoucherData::Lawson(_) + | VoucherData::MiniStop(_) + | VoucherData::FamilyMart(_) + | VoucherData::Seicomart(_) + | VoucherData::PayEasy(_) => Err(ConnectorError::NotImplemented( + 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()) - } + PaymentMethodData::Upi(_) + | PaymentMethodData::RealTimePayment(_) + | PaymentMethodData::MobilePayment(_) + | PaymentMethodData::MandatePayment + | PaymentMethodData::OpenBanking(_) + | PaymentMethodData::CardToken(_) + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => Err( + ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message( + "stripe", + )) + .into(), + ), } } @@ -1395,11 +1402,9 @@ fn get_stripe_card_network(card_network: common_enums::CardNetwork) -> Option for StripePaymentMethodData { - type Error = errors::ConnectorError; - fn try_from( - (card, payment_method_auth_type): (&domain::Card, Auth3ds), - ) -> Result { +impl TryFrom<(&Card, Auth3ds)> for StripePaymentMethodData { + type Error = ConnectorError; + fn try_from((card, payment_method_auth_type): (&Card, Auth3ds)) -> Result { Ok(Self::Card(StripeCardData { payment_method_data_type: StripePaymentMethodType::Card, payment_method_data_card_number: card.card_number.clone(), @@ -1415,18 +1420,15 @@ impl TryFrom<(&domain::Card, Auth3ds)> for StripePaymentMethodData { } } -impl TryFrom<(&domain::WalletData, Option)> for StripePaymentMethodData { - type Error = error_stack::Report; +impl TryFrom<(&WalletData, Option)> for StripePaymentMethodData { + type Error = error_stack::Report; fn try_from( - (wallet_data, payment_method_token): ( - &domain::WalletData, - Option, - ), + (wallet_data, payment_method_token): (&WalletData, Option), ) -> Result { match wallet_data { - domain::WalletData::ApplePay(applepay_data) => { + WalletData::ApplePay(applepay_data) => { let mut apple_pay_decrypt_data = - if let Some(types::PaymentMethodToken::ApplePayDecrypt(decrypt_data)) = + if let Some(PaymentMethodToken::ApplePayDecrypt(decrypt_data)) = payment_method_token { let expiry_year_4_digit = decrypt_data.get_four_digit_expiry_year()?; @@ -1463,87 +1465,84 @@ impl TryFrom<(&domain::WalletData, Option)> for Strip ), }))); }; - let pmd = apple_pay_decrypt_data - .ok_or(errors::ConnectorError::MissingApplePayTokenData)?; + let pmd = apple_pay_decrypt_data.ok_or(ConnectorError::MissingApplePayTokenData)?; Ok(pmd) } - domain::WalletData::WeChatPayQr(_) => Ok(Self::Wallet(StripeWallet::WechatpayPayment( + WalletData::WeChatPayQr(_) => Ok(Self::Wallet(StripeWallet::WechatpayPayment( WechatpayPayment { client: WechatClient::Web, payment_method_data_type: StripePaymentMethodType::Wechatpay, }, ))), - domain::WalletData::AliPayRedirect(_) => { + 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 { + WalletData::CashappQr(_) => Ok(Self::Wallet(StripeWallet::Cashapp(CashappPayment { + payment_method_data_type: StripePaymentMethodType::Cashapp, + }))), + 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"), + }, + ))), + WalletData::GooglePay(gpay_data) => Ok(Self::try_from(gpay_data)?), + WalletData::PaypalRedirect(_) | WalletData::MobilePayRedirect(_) => Err( + ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message( + "stripe", + )) + .into(), + ), + WalletData::AliPayQr(_) + | WalletData::AliPayHkRedirect(_) + | WalletData::MomoRedirect(_) + | WalletData::KakaoPayRedirect(_) + | WalletData::GoPayRedirect(_) + | WalletData::GcashRedirect(_) + | WalletData::ApplePayRedirect(_) + | WalletData::ApplePayThirdPartySdk(_) + | WalletData::DanaRedirect {} + | WalletData::GooglePayRedirect(_) + | WalletData::GooglePayThirdPartySdk(_) + | WalletData::MbWayRedirect(_) + | WalletData::PaypalSdk(_) + | WalletData::Paze(_) + | WalletData::SamsungPay(_) + | WalletData::TwintRedirect {} + | WalletData::VippsRedirect {} + | WalletData::TouchNGoRedirect(_) + | WalletData::SwishQr(_) + | WalletData::WeChatPayRedirect(_) + | WalletData::Mifinity(_) => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), ) .into()), } } } -impl TryFrom<&domain::BankRedirectData> for StripePaymentMethodData { - type Error = error_stack::Report; - fn try_from(bank_redirect_data: &domain::BankRedirectData) -> Result { +impl TryFrom<&BankRedirectData> for StripePaymentMethodData { + type Error = error_stack::Report; + fn try_from(bank_redirect_data: &BankRedirectData) -> Result { let payment_method_data_type = StripePaymentMethodType::try_from(bank_redirect_data)?; match bank_redirect_data { - domain::BankRedirectData::BancontactCard { .. } => Ok(Self::BankRedirect( + BankRedirectData::BancontactCard { .. } => Ok(Self::BankRedirect( StripeBankRedirectData::StripeBancontactCard(Box::new(StripeBancontactCard { payment_method_data_type, })), )), - domain::BankRedirectData::Blik { blik_code } => Ok(Self::BankRedirect( + 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 { + ConnectorError::MissingRequiredField { field_name: "blik_code", }, )?), })), )), - domain::BankRedirectData::Eps { bank_name, .. } => Ok(Self::BankRedirect( + BankRedirectData::Eps { bank_name, .. } => Ok(Self::BankRedirect( StripeBankRedirectData::StripeEps(Box::new(StripeEps { payment_method_data_type, bank_name: bank_name @@ -1551,12 +1550,12 @@ impl TryFrom<&domain::BankRedirectData> for StripePaymentMethodData { .transpose()?, })), )), - domain::BankRedirectData::Giropay { .. } => Ok(Self::BankRedirect( + BankRedirectData::Giropay { .. } => Ok(Self::BankRedirect( StripeBankRedirectData::StripeGiropay(Box::new(StripeGiropay { payment_method_data_type, })), )), - domain::BankRedirectData::Ideal { bank_name, .. } => { + BankRedirectData::Ideal { bank_name, .. } => { let bank_name = bank_name .map(|bank_name| StripeBankNames::try_from(&bank_name)) .transpose()?; @@ -1567,7 +1566,7 @@ impl TryFrom<&domain::BankRedirectData> for StripePaymentMethodData { }), ))) } - domain::BankRedirectData::Przelewy24 { bank_name, .. } => { + BankRedirectData::Przelewy24 { bank_name, .. } => { let bank_name = bank_name .map(|bank_name| StripeBankNames::try_from(&bank_name)) .transpose()?; @@ -1578,36 +1577,32 @@ impl TryFrom<&domain::BankRedirectData> for StripePaymentMethodData { })), )) } - 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::Sofort { .. } - | domain::BankRedirectData::Trustly { .. } - | domain::BankRedirectData::LocalBankRedirect {} => { - Err(errors::ConnectorError::NotImplemented( - connector_util::get_unimplemented_payment_method_error_message("stripe"), - ) - .into()) - } + BankRedirectData::OnlineBankingFpx { .. } => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), + ) + .into()), + BankRedirectData::Bizum {} + | BankRedirectData::Eft { .. } + | BankRedirectData::Interac { .. } + | BankRedirectData::OnlineBankingCzechRepublic { .. } + | BankRedirectData::OnlineBankingFinland { .. } + | BankRedirectData::OnlineBankingPoland { .. } + | BankRedirectData::OnlineBankingSlovakia { .. } + | BankRedirectData::OnlineBankingThailand { .. } + | BankRedirectData::OpenBankingUk { .. } + | BankRedirectData::Sofort { .. } + | BankRedirectData::Trustly { .. } + | BankRedirectData::LocalBankRedirect {} => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), + ) + .into()), } } } -impl TryFrom<&domain::GooglePayWalletData> for StripePaymentMethodData { - type Error = error_stack::Report; - fn try_from(gpay_data: &domain::GooglePayWalletData) -> Result { +impl TryFrom<&GooglePayWalletData> for StripePaymentMethodData { + type Error = error_stack::Report; + fn try_from(gpay_data: &GooglePayWalletData) -> Result { Ok(Self::Wallet(StripeWallet::GooglepayToken(GooglePayToken { token: Secret::new( gpay_data @@ -1615,7 +1610,7 @@ impl TryFrom<&domain::GooglePayWalletData> for StripePaymentMethodData { .token .as_bytes() .parse_struct::("StripeGpayToken") - .change_context(errors::ConnectorError::InvalidWalletToken { + .change_context(ConnectorError::InvalidWalletToken { wallet_name: "Google Pay".to_string(), })? .id, @@ -1625,11 +1620,9 @@ impl TryFrom<&domain::GooglePayWalletData> for StripePaymentMethodData { } } -impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntentRequest { - type Error = error_stack::Report; - fn try_from( - data: (&types::PaymentsAuthorizeRouterData, MinorUnit), - ) -> Result { +impl TryFrom<(&PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntentRequest { + type Error = error_stack::Report; + fn try_from(data: (&PaymentsAuthorizeRouterData, MinorUnit)) -> Result { let item = data.0; let amount = data.1; let order_id = item.connector_request_reference_id.clone(); @@ -1737,7 +1730,7 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntent }); let payment_data = match item.request.payment_method_data { - domain::payments::PaymentMethodData::CardDetailsForNetworkTransactionId( + PaymentMethodData::CardDetailsForNetworkTransactionId( ref card_details_for_network_transaction_id, ) => StripePaymentMethodData::Card(StripeCardData { payment_method_data_type: StripePaymentMethodType::Card, @@ -1759,29 +1752,27 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntent .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", - })? - } + PaymentMethodData::CardRedirect(_) + | PaymentMethodData::Wallet(_) + | PaymentMethodData::PayLater(_) + | PaymentMethodData::BankRedirect(_) + | PaymentMethodData::BankDebit(_) + | PaymentMethodData::BankTransfer(_) + | PaymentMethodData::Crypto(_) + | PaymentMethodData::MandatePayment + | PaymentMethodData::Reward + | PaymentMethodData::RealTimePayment(_) + | PaymentMethodData::MobilePayment(_) + | PaymentMethodData::Upi(_) + | PaymentMethodData::Voucher(_) + | PaymentMethodData::GiftCard(_) + | PaymentMethodData::OpenBanking(_) + | PaymentMethodData::CardToken(_) + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::Card(_) => Err(ConnectorError::NotSupported { + message: "Network tokenization for payment method".to_string(), + connector: "Stripe", + })?, }; ( @@ -1798,10 +1789,12 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntent &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 + Some( + PaymentsAuthorizeRequestData::is_customer_initiated_mandate_payment( + &item.request, + ), + ), + billing_address, )?; validate_shipping_address_against_payment_method( @@ -1821,26 +1814,26 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntent }; payment_data = match item.request.payment_method_data { - domain::PaymentMethodData::Wallet(domain::WalletData::ApplePay(_)) => { + PaymentMethodData::Wallet(WalletData::ApplePay(_)) => { let payment_method_token = item .payment_method_token .to_owned() .get_required_value("payment_token") - .change_context(errors::ConnectorError::InvalidWalletToken { + .change_context(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 { + PaymentMethodToken::Token(payment_method_token) => payment_method_token, + PaymentMethodToken::ApplePayDecrypt(_) => { + Err(ConnectorError::InvalidWalletToken { wallet_name: "Apple Pay".to_string(), })? } - types::PaymentMethodToken::PazeDecrypt(_) => { + PaymentMethodToken::PazeDecrypt(_) => { Err(crate::unimplemented_payment_method!("Paze", "Stripe"))? } - types::PaymentMethodToken::GooglePayDecrypt(_) => { + PaymentMethodToken::GooglePayDecrypt(_) => { Err(crate::unimplemented_payment_method!("Google Pay", "Stripe"))? } }; @@ -1863,25 +1856,23 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntent .customer_acceptance .as_ref() .map(|customer_acceptance| { - Ok::<_, error_stack::Report>( + Ok::<_, error_stack::Report>( 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", - }, - )?; + .change_context(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 { + ConnectorError::MissingRequiredField { field_name: "ip_address", }, )?, @@ -1937,22 +1928,18 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntent 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(), - ), - }) - } - } - } + PaymentChargeType::Stripe(charge_type) => match charge_type { + StripeChargeType::Direct => Some(IntentCharges { + application_fee_amount: stripe_split_payment.application_fees, + destination_account_id: None, + }), + 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) } @@ -1993,8 +1980,8 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntent } fn get_payment_method_type_for_saved_payment_method_payment( - item: &types::PaymentsAuthorizeRouterData, -) -> Result, error_stack::Report> { + item: &PaymentsAuthorizeRouterData, +) -> Result, error_stack::Report> { if item.payment_method == api_enums::PaymentMethod::Card { Ok(Some(StripePaymentMethodType::Card)) //stripe takes ["Card"] as default } else { @@ -2004,13 +1991,13 @@ fn get_payment_method_type_for_saved_payment_method_payment( Some(payment_method_type) => { StripePaymentMethodType::try_from(payment_method_type) } - None => Err(errors::ConnectorError::MissingRequiredField { + None => Err(ConnectorError::MissingRequiredField { field_name: "payment_method_type", } .into()), } } - None => Err(errors::ConnectorError::MissingRequiredField { + None => Err(ConnectorError::MissingRequiredField { field_name: "recurring_mandate_payment_data", } .into()), @@ -2025,8 +2012,8 @@ fn get_payment_method_type_for_saved_payment_method_payment( } } -impl From for StripeBrowserInformation { - fn from(item: types::BrowserInformation) -> Self { +impl From for StripeBrowserInformation { + fn from(item: BrowserInformation) -> Self { Self { ip_address: item.ip_address.map(|ip| Secret::new(ip.to_string())), user_agent: item.user_agent, @@ -2034,9 +2021,9 @@ impl From for StripeBrowserInformation { } } -impl TryFrom<&types::SetupMandateRouterData> for SetupIntentRequest { - type Error = error_stack::Report; - fn try_from(item: &types::SetupMandateRouterData) -> Result { +impl TryFrom<&SetupMandateRouterData> for SetupIntentRequest { + type Error = error_stack::Report; + fn try_from(item: &SetupMandateRouterData) -> Result { //Only cards supported for mandates let pm_type = StripePaymentMethodType::Card; let payment_data = StripePaymentMethodData::try_from((item, item.auth_type, pm_type))?; @@ -2068,12 +2055,12 @@ impl TryFrom<&types::SetupMandateRouterData> for SetupIntentRequest { } } -impl TryFrom<&types::TokenizationRouterData> for TokenRequest { - type Error = error_stack::Report; - fn try_from(item: &types::TokenizationRouterData) -> Result { +impl TryFrom<&TokenizationRouterData> for TokenRequest { + type Error = error_stack::Report; + fn try_from(item: &TokenizationRouterData) -> Result { // Card flow for tokenization is handled separately because of API contact difference let request_payment_data = match &item.request.payment_method_data { - domain::PaymentMethodData::Card(card_details) => { + 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(), @@ -2099,9 +2086,9 @@ impl TryFrom<&types::TokenizationRouterData> for TokenRequest { } } -impl TryFrom<&types::ConnectorCustomerRouterData> for CustomerRequest { - type Error = error_stack::Report; - fn try_from(item: &types::ConnectorCustomerRouterData) -> Result { +impl TryFrom<&ConnectorCustomerRouterData> for CustomerRequest { + type Error = error_stack::Report; + fn try_from(item: &ConnectorCustomerRouterData) -> Result { Ok(Self { description: item.request.description.to_owned(), email: item.request.email.to_owned(), @@ -2131,7 +2118,7 @@ pub enum StripePaymentStatus { Pending, } -impl From for enums::AttemptStatus { +impl From for AttemptStatus { fn from(item: StripePaymentStatus) -> Self { match item { StripePaymentStatus::Succeeded => Self::Charged, @@ -2336,7 +2323,7 @@ pub struct AdditionalPaymentMethodDetails { pub authentication_details: Option, } -impl From for types::AdditionalPaymentMethodConnectorResponse { +impl From for AdditionalPaymentMethodConnectorResponse { fn from(item: AdditionalPaymentMethodDetails) -> Self { Self::Card { authentication_data: item.authentication_details, @@ -2440,7 +2427,7 @@ pub struct SetupIntentResponse { fn extract_payment_method_connector_response_from_latest_charge( stripe_charge_enum: &StripeChargeEnum, -) -> Option { +) -> Option { if let StripeChargeEnum::ChargeObject(charge_object) = stripe_charge_enum { charge_object .payment_method_details @@ -2449,13 +2436,13 @@ fn extract_payment_method_connector_response_from_latest_charge( } else { None } - .map(types::AdditionalPaymentMethodConnectorResponse::from) - .map(types::ConnectorResponseData::with_additional_payment_method_data) + .map(AdditionalPaymentMethodConnectorResponse::from) + .map(ConnectorResponseData::with_additional_payment_method_data) } fn extract_payment_method_connector_response_from_latest_attempt( stripe_latest_attempt: &LatestAttempt, -) -> Option { +) -> Option { if let LatestAttempt::PaymentIntentAttempt(intent_attempt) = stripe_latest_attempt { intent_attempt .payment_method_details @@ -2464,26 +2451,23 @@ fn extract_payment_method_connector_response_from_latest_attempt( } else { None } - .map(types::AdditionalPaymentMethodConnectorResponse::from) - .map(types::ConnectorResponseData::with_additional_payment_method_data) + .map(AdditionalPaymentMethodConnectorResponse::from) + .map(ConnectorResponseData::with_additional_payment_method_data) } -impl - TryFrom> - for types::RouterData +impl TryFrom> + for RouterData where - T: connector_util::SplitPaymentData, + T: SplitPaymentData, { - type Error = error_stack::Report; + type Error = error_stack::Report; fn try_from( - item: types::ResponseRouterData, + item: ResponseRouterData, ) -> Result { 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)) - }); + .map(|redirection_url| RedirectForm::from((redirection_url, Method::Get))); let mandate_reference = item.response.payment_method.map(|payment_method_id| { // Implemented Save and re-use payment information for recurring charges @@ -2491,7 +2475,7 @@ where // 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 { + MandateReference { connector_mandate_id, payment_method_id, mandate_metadata: None, @@ -2517,14 +2501,14 @@ where let connector_metadata = get_connector_metadata(item.response.next_action.as_ref(), item.response.amount)?; - let status = enums::AttemptStatus::from(item.response.status); + let status = AttemptStatus::from(item.response.status); - let response = if connector_util::is_payment_failure(status) { - types::PaymentsResponseData::foreign_try_from(( + let response = if is_payment_failure(status) { + *get_stripe_payments_response_data( &item.response.last_payment_error, item.http_code, item.response.id.clone(), - )) + ) } else { let charges = item .response @@ -2536,8 +2520,8 @@ where }) .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()), + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(redirection_data), mandate_reference: Box::new(mandate_reference), connector_metadata, @@ -2575,7 +2559,7 @@ where pub fn get_connector_metadata( next_action: Option<&StripeNextActionResponse>, amount: MinorUnit, -) -> CustomResult, errors::ConnectorError> { +) -> CustomResult, ConnectorError> { let next_action_response = next_action .and_then(|next_action_response| match next_action_response { StripeNextActionResponse::DisplayBankTransferInstructions(response) => { @@ -2679,7 +2663,7 @@ pub fn get_connector_metadata( _ => None, }) .transpose() - .change_context(errors::ConnectorError::ResponseHandlingFailed)?; + .change_context(ConnectorError::ResponseHandlingFailed)?; Ok(next_action_response) } @@ -2722,27 +2706,19 @@ pub fn get_payment_method_id( } } -impl - TryFrom> - for types::RouterData +impl TryFrom> + for RouterData where - T: connector_util::SplitPaymentData, + T: SplitPaymentData, { - type Error = error_stack::Report; + type Error = error_stack::Report; fn try_from( - item: types::ResponseRouterData< - F, - PaymentIntentSyncResponse, - T, - types::PaymentsResponseData, - >, + item: ResponseRouterData, ) -> Result { 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)) - }); + .map(|redirection_url| RedirectForm::from((redirection_url, Method::Get))); let mandate_reference = item .response @@ -2755,7 +2731,7 @@ where let payment_method_id = get_payment_method_id(item.response.latest_charge.clone(), payment_method_id); - types::MandateReference { + MandateReference { connector_mandate_id: Some(payment_method_id.clone()), payment_method_id: Some(payment_method_id), mandate_metadata: None, @@ -2766,7 +2742,7 @@ where 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 status = AttemptStatus::from(item.response.status.to_owned()); let connector_response_data = item .response @@ -2774,12 +2750,12 @@ where .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(( + let response = if is_payment_failure(status) { + *get_stripe_payments_response_data( &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 @@ -2802,8 +2778,8 @@ where }) .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()), + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(redirection_data), mandate_reference: Box::new(mandate_reference), connector_metadata, @@ -2815,7 +2791,7 @@ where }; Ok(Self { - status: enums::AttemptStatus::from(item.response.status.to_owned()), + status: AttemptStatus::from(item.response.status.to_owned()), response, amount_captured: item .response @@ -2828,20 +2804,17 @@ where } } -impl - TryFrom> - for types::RouterData +impl TryFrom> + for RouterData { - type Error = error_stack::Report; + type Error = error_stack::Report; fn try_from( - item: types::ResponseRouterData, + item: ResponseRouterData, ) -> Result { 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)) - }); + .map(|redirection_url| RedirectForm::from((redirection_url, Method::Get))); let mandate_reference = item.response.payment_method.map(|payment_method_id| { // Implemented Save and re-use payment information for recurring charges @@ -2849,26 +2822,26 @@ impl // 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 { + 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 status = 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(( + let response = if is_payment_failure(status) { + *get_stripe_payments_response_data( &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 @@ -2882,8 +2855,8 @@ impl _ => None, }; - Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(redirection_data), mandate_reference: Box::new(mandate_reference), connector_metadata: None, @@ -2903,20 +2876,20 @@ impl } } -impl ForeignFrom> for Option { - fn foreign_from(latest_attempt: Option) -> 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, - } +pub fn stripe_opt_latest_attempt_to_opt_string( + latest_attempt: Option, +) -> Option { + 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, } } @@ -3119,10 +3092,10 @@ pub struct RefundRequest { pub meta_data: StripeMetadata, } -impl TryFrom<(&types::RefundsRouterData, MinorUnit)> for RefundRequest { - type Error = error_stack::Report; +impl TryFrom<(&RefundsRouterData, MinorUnit)> for RefundRequest { + type Error = error_stack::Report; fn try_from( - (item, refund_amount): (&types::RefundsRouterData, MinorUnit), + (item, refund_amount): (&RefundsRouterData, MinorUnit), ) -> Result { let payment_intent = item.request.connector_transaction_id.clone(); Ok(Self { @@ -3146,28 +3119,26 @@ pub struct ChargeRefundRequest { pub meta_data: StripeMetadata, } -impl TryFrom<&types::RefundsRouterData> for ChargeRefundRequest { - type Error = error_stack::Report; - fn try_from(item: &types::RefundsRouterData) -> Result { +impl TryFrom<&RefundsRouterData> for ChargeRefundRequest { + type Error = error_stack::Report; + fn try_from(item: &RefundsRouterData) -> Result { let amount = item.request.minor_refund_amount; match item.request.split_refunds.as_ref() { - None => Err(errors::ConnectorError::MissingRequiredField { + None => Err(ConnectorError::MissingRequiredField { field_name: "split_refunds", } .into()), Some(split_refunds) => match split_refunds { - types::SplitRefundsRequest::StripeSplitRefund(stripe_refund) => { + SplitRefundsRequest::StripeSplitRefund(stripe_refund) => { let (refund_application_fee, reverse_transfer) = match &stripe_refund.options { - types::ChargeRefundsOptions::Direct(types::DirectChargeRefund { + ChargeRefundsOptions::Direct(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)), + ChargeRefundsOptions::Destination(DestinationChargeRefund { + revert_platform_fee, + revert_transfer, + }) => (Some(*revert_platform_fee), Some(*revert_transfer)), }; Ok(Self { @@ -3181,7 +3152,7 @@ impl TryFrom<&types::RefundsRouterData> for ChargeRefundRequest { }, }) } - _ => Err(errors::ConnectorError::MissingRequiredField { + _ => Err(ConnectorError::MissingRequiredField { field_name: "stripe_split_refund", })?, }, @@ -3224,16 +3195,14 @@ pub struct RefundResponse { pub failure_reason: Option, } -impl TryFrom> - for types::RefundsRouterData -{ - type Error = error_stack::Report; +impl TryFrom> for RefundsRouterData { + type Error = error_stack::Report; fn try_from( - item: types::RefundsResponseRouterData, + item: RefundsResponseRouterData, ) -> Result { let refund_status = enums::RefundStatus::from(item.response.status); - let response = if connector_util::is_refund_failure(refund_status) { - Err(types::ErrorResponse { + let response = if is_refund_failure(refund_status) { + Err(hyperswitch_domain_models::router_data::ErrorResponse { code: consts::NO_ERROR_CODE.to_string(), message: item .response @@ -3249,7 +3218,7 @@ impl TryFrom> network_error_message: None, }) } else { - Ok(types::RefundsResponseData { + Ok(RefundsResponseData { connector_refund_id: item.response.id, refund_status, }) @@ -3262,16 +3231,14 @@ impl TryFrom> } } -impl TryFrom> - for types::RefundsRouterData -{ - type Error = error_stack::Report; +impl TryFrom> for RefundsRouterData { + type Error = error_stack::Report; fn try_from( - item: types::RefundsResponseRouterData, + item: RefundsResponseRouterData, ) -> Result { let refund_status = enums::RefundStatus::from(item.response.status); - let response = if connector_util::is_refund_failure(refund_status) { - Err(types::ErrorResponse { + let response = if is_refund_failure(refund_status) { + Err(hyperswitch_domain_models::router_data::ErrorResponse { code: consts::NO_ERROR_CODE.to_string(), message: item .response @@ -3287,7 +3254,7 @@ impl TryFrom> network_error_message: None, }) } else { - Ok(types::RefundsResponseData { + Ok(RefundsResponseData { connector_refund_id: item.response.id, refund_status, }) @@ -3380,9 +3347,9 @@ pub struct CancelRequest { cancellation_reason: Option, } -impl TryFrom<&types::PaymentsCancelRouterData> for CancelRequest { - type Error = error_stack::Report; - fn try_from(item: &types::PaymentsCancelRouterData) -> Result { +impl TryFrom<&PaymentsCancelRouterData> for CancelRequest { + type Error = error_stack::Report; + fn try_from(item: &PaymentsCancelRouterData) -> Result { Ok(Self { cancellation_reason: item.request.cancellation_reason.clone(), }) @@ -3395,9 +3362,9 @@ pub struct UpdateMetadataRequest { pub metadata: HashMap, } -impl TryFrom<&types::PaymentsUpdateMetadataRouterData> for UpdateMetadataRequest { - type Error = error_stack::Report; - fn try_from(item: &types::PaymentsUpdateMetadataRouterData) -> Result { +impl TryFrom<&PaymentsUpdateMetadataRouterData> for UpdateMetadataRequest { + type Error = error_stack::Report; + fn try_from(item: &PaymentsUpdateMetadataRouterData) -> Result { let metadata = format_metadata_for_request(item.request.metadata.clone()); Ok(Self { metadata }) } @@ -3484,7 +3451,7 @@ pub struct CaptureRequest { } impl TryFrom for CaptureRequest { - type Error = error_stack::Report; + type Error = error_stack::Report; fn try_from(capture_amount: MinorUnit) -> Result { Ok(Self { amount_to_capture: Some(capture_amount), @@ -3492,31 +3459,26 @@ impl TryFrom for CaptureRequest { } } -impl - TryFrom> - for types::RouterData +impl TryFrom> + for RouterData { - type Error = error_stack::Report; + type Error = error_stack::Report; fn try_from( - item: types::ResponseRouterData, + item: ResponseRouterData, ) -> Result { let connector_source_response = item.response.to_owned(); let connector_metadata = connector_source_response .encode_to_value() - .change_context(errors::ConnectorError::ResponseHandlingFailed)?; + .change_context(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 - } + AttemptStatus::Pending => AttemptStatus::AuthenticationPending, _ => connector_source_response.status.into(), }; Ok(Self { - response: Ok(types::PaymentsResponseData::PreProcessingResponse { - pre_processing_id: types::PreprocessingResponseId::PreProcessingId( - item.response.id, - ), + response: Ok(PaymentsResponseData::PreProcessingResponse { + pre_processing_id: PreprocessingResponseId::PreProcessingId(item.response.id), connector_metadata: Some(connector_metadata), session_token: None, connector_response_reference_id: None, @@ -3527,12 +3489,10 @@ impl } } -impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for ChargesRequest { - type Error = error_stack::Report; +impl TryFrom<(&PaymentsAuthorizeRouterData, MinorUnit)> for ChargesRequest { + type Error = error_stack::Report; - fn try_from( - data: (&types::PaymentsAuthorizeRouterData, MinorUnit), - ) -> Result { + fn try_from(data: (&PaymentsAuthorizeRouterData, MinorUnit)) -> Result { { let value = data.0; let amount = data.1; @@ -3552,21 +3512,21 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for ChargesReques } } -impl TryFrom> - for types::RouterData +impl TryFrom> + for RouterData { - type Error = error_stack::Report; + type Error = error_stack::Report; fn try_from( - item: types::ResponseRouterData, + item: ResponseRouterData, ) -> Result { 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 { + .change_context(ConnectorError::ResponseHandlingFailed)?; + let status = AttemptStatus::from(item.response.status); + let response = if is_payment_failure(status) { + Err(hyperswitch_domain_models::router_data::ErrorResponse { code: item .response .failure_code @@ -3585,8 +3545,8 @@ impl TryFrom TryFrom - TryFrom> - for types::RouterData +impl TryFrom> + for RouterData { - type Error = error_stack::Report; + type Error = error_stack::Report; fn try_from( - item: types::ResponseRouterData, + item: ResponseRouterData, ) -> Result { Ok(Self { - response: Ok(types::PaymentsResponseData::TokenizationResponse { + response: Ok(PaymentsResponseData::TokenizationResponse { token: item.response.id.expose(), }), ..item.data @@ -3622,16 +3581,15 @@ impl } } -impl - TryFrom> - for types::RouterData +impl TryFrom> + for RouterData { - type Error = error_stack::Report; + type Error = error_stack::Report; fn try_from( - item: types::ResponseRouterData, + item: ResponseRouterData, ) -> Result { Ok(Self { - response: Ok(types::PaymentsResponseData::ConnectorCustomerResponse { + response: Ok(PaymentsResponseData::ConnectorCustomerResponse { connector_customer_id: item.response.id, }), ..item.data @@ -3740,7 +3698,7 @@ pub struct WebhookEventObjectData { pub id: String, pub object: WebhookEventObjectType, pub amount: Option, - #[serde(default, deserialize_with = "connector_util::convert_uppercase")] + #[serde(default, deserialize_with = "convert_uppercase")] pub currency: enums::Currency, pub payment_intent: Option, pub client_secret: Option>, @@ -3847,113 +3805,116 @@ pub struct EvidenceDetails { impl TryFrom<( - &types::SetupMandateRouterData, + &SetupMandateRouterData, enums::AuthenticationType, StripePaymentMethodType, )> for StripePaymentMethodData { - type Error = error_stack::Report; + type Error = error_stack::Report; fn try_from( (item, auth_type, pm_type): ( - &types::SetupMandateRouterData, + &SetupMandateRouterData, enums::AuthenticationType, StripePaymentMethodType, ), ) -> Result { let pm_data = &item.request.payment_method_data; match pm_data { - domain::PaymentMethodData::Card(ref ccard) => { + 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 { + PaymentMethodData::PayLater(_) => Ok(Self::PayLater(StripePayLaterData { payment_method_data_type: pm_type, })), - domain::PaymentMethodData::BankRedirect(ref bank_redirect_data) => { + PaymentMethodData::BankRedirect(ref bank_redirect_data) => { Ok(Self::try_from(bank_redirect_data)?) } - domain::PaymentMethodData::Wallet(ref wallet_data) => { - Ok(Self::try_from((wallet_data, None))?) - } - domain::PaymentMethodData::BankDebit(bank_debit_data) => { + PaymentMethodData::Wallet(ref wallet_data) => Ok(Self::try_from((wallet_data, None))?), + 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() + 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( + payment_method_data::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, + }), + ))) + } + payment_method_data::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"), + ))), + ), + payment_method_data::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()?, + })), + )) + } + payment_method_data::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, + })), + )) + } + payment_method_data::BankTransferData::Pix { .. } + | payment_method_data::BankTransferData::Pse {} + | payment_method_data::BankTransferData::PermataBankTransfer { .. } + | payment_method_data::BankTransferData::BcaBankTransfer { .. } + | payment_method_data::BankTransferData::BniVaBankTransfer { .. } + | payment_method_data::BankTransferData::BriVaBankTransfer { .. } + | payment_method_data::BankTransferData::CimbVaBankTransfer { .. } + | payment_method_data::BankTransferData::DanamonVaBankTransfer { .. } + | payment_method_data::BankTransferData::LocalBankTransfer { .. } + | payment_method_data::BankTransferData::InstantBankTransfer {} + | payment_method_data::BankTransferData::MandiriVaBankTransfer { .. } => { + Err(ConnectorError::NotImplemented( + 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"), + PaymentMethodData::MandatePayment + | PaymentMethodData::Crypto(_) + | PaymentMethodData::Reward + | PaymentMethodData::RealTimePayment(_) + | PaymentMethodData::MobilePayment(_) + | PaymentMethodData::GiftCard(_) + | PaymentMethodData::Upi(_) + | PaymentMethodData::CardRedirect(_) + | PaymentMethodData::Voucher(_) + | PaymentMethodData::OpenBanking(_) + | PaymentMethodData::CardToken(_) + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { + Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), ))? } } @@ -3966,13 +3927,13 @@ pub struct StripeGpayToken { } pub fn get_bank_transfer_request_data( - req: &types::PaymentsAuthorizeRouterData, - bank_transfer_data: &domain::BankTransferData, + req: &PaymentsAuthorizeRouterData, + bank_transfer_data: &payment_method_data::BankTransferData, amount: MinorUnit, -) -> CustomResult { +) -> CustomResult { match bank_transfer_data { - domain::BankTransferData::AchBankTransfer { .. } - | domain::BankTransferData::MultibancoBankTransfer { .. } => { + payment_method_data::BankTransferData::AchBankTransfer { .. } + | payment_method_data::BankTransferData::MultibancoBankTransfer { .. } => { let req = ChargesRequest::try_from((req, amount))?; Ok(RequestContent::FormUrlEncoded(Box::new(req))) } @@ -3984,15 +3945,15 @@ pub fn get_bank_transfer_request_data( } pub fn construct_file_upload_request( - file_upload_router_data: types::UploadFileRouterData, -) -> CustomResult { + file_upload_router_data: UploadFileRouterData, +) -> CustomResult { 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)?; + .map_err(|_| ConnectorError::RequestEncodingFailed)?; multipart = multipart.part("file", file_data); Ok(multipart) } @@ -4060,7 +4021,7 @@ pub struct Evidence { fn mandatory_parameters_for_sepa_bank_debit_mandates( billing_details: &Option, is_customer_initiated_mandate_payment: Option, -) -> Result { +) -> Result { let billing_name = billing_details .clone() .and_then(|billing_data| billing_data.name.clone()); @@ -4070,17 +4031,13 @@ fn mandatory_parameters_for_sepa_bank_debit_mandates( .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", - })?, - ), + name: Some(billing_name.ok_or(ConnectorError::MissingRequiredField { + field_name: "billing_name", + })?), - email: Some( - billing_email.ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "billing_email", - })?, - ), + email: Some(billing_email.ok_or(ConnectorError::MissingRequiredField { + field_name: "billing_email", + })?), ..StripeBillingAddress::default() }), Some(false) | None => Ok(StripeBillingAddress { @@ -4091,9 +4048,9 @@ fn mandatory_parameters_for_sepa_bank_debit_mandates( } } -impl TryFrom<&types::SubmitEvidenceRouterData> for Evidence { - type Error = error_stack::Report; - fn try_from(item: &types::SubmitEvidenceRouterData) -> Result { +impl TryFrom<&SubmitEvidenceRouterData> for Evidence { + type Error = error_stack::Report; + fn try_from(item: &SubmitEvidenceRouterData) -> Result { let submit_evidence_request_data = item.request.clone(); Ok(Self { access_activity_log: submit_evidence_request_data.access_activity_log, @@ -4171,67 +4128,65 @@ fn get_transaction_metadata( meta_data } -impl ForeignTryFrom<(&Option, u16, String)> for types::PaymentsResponseData { - type Error = types::ErrorResponse; - fn foreign_try_from( - (response, http_code, response_id): (&Option, u16, String), - ) -> Result { - 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(), - ), - }; +fn get_stripe_payments_response_data( + response: &Option, + http_code: u16, + response_id: String, +) -> Box> { + 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: response - .as_ref() - .and_then(|res| res.network_advice_code.clone()), - network_decline_code: response - .as_ref() - .and_then(|res| res.network_decline_code.clone()), - network_error_message: response - .as_ref() - .and_then(|res| res.decline_code.clone().or(res.advice_code.clone())), - }) - } + Box::new(Err(hyperswitch_domain_models::router_data::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: response + .as_ref() + .and_then(|res| res.network_advice_code.clone()), + network_decline_code: response + .as_ref() + .and_then(|res| res.network_decline_code.clone()), + network_error_message: response + .as_ref() + .and_then(|res| res.decline_code.clone().or(res.advice_code.clone())), + })) } pub(super) fn transform_headers_for_connect_platform( - charge_type: api::enums::PaymentChargeType, + charge_type: PaymentChargeType, transfer_account_id: String, - header: &mut Vec<(String, services::request::Maskable)>, + header: &mut Vec<(String, Maskable)>, ) { - if let api::enums::PaymentChargeType::Stripe(api::enums::StripeChargeType::Direct) = charge_type - { + if let PaymentChargeType::Stripe(StripeChargeType::Direct) = charge_type { let mut customer_account_header = vec![( - headers::STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(), + STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(), transfer_account_id.into_masked(), )]; header.append(&mut customer_account_header); @@ -4243,7 +4198,7 @@ pub fn construct_charge_response( request: &T, ) -> Option where - T: connector_util::SplitPaymentData, + T: SplitPaymentData, { let charge_request = request.get_split_payment_data(); if let Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment( @@ -4269,15 +4224,13 @@ where #[cfg(test)] mod test_validate_shipping_address_against_payment_method { #![allow(clippy::unwrap_used)] - use api_models::enums::CountryAlpha2; + use common_enums::CountryAlpha2; + use hyperswitch_interfaces::errors::ConnectorError; use masking::Secret; - use crate::{ - connector::stripe::transformers::{ - validate_shipping_address_against_payment_method, StripePaymentMethodType, - StripeShippingAddress, - }, - core::errors, + use crate::connectors::stripe::transformers::{ + validate_shipping_address_against_payment_method, StripePaymentMethodType, + StripeShippingAddress, }; #[test] @@ -4403,8 +4356,8 @@ mod test_validate_shipping_address_against_payment_method { } } - fn get_missing_fields(connector_error: &errors::ConnectorError) -> Vec<&'static str> { - if let errors::ConnectorError::MissingRequiredFields { field_names } = connector_error { + fn get_missing_fields(connector_error: &ConnectorError) -> Vec<&'static str> { + if let ConnectorError::MissingRequiredFields { field_names } = connector_error { return field_names.to_vec(); } diff --git a/crates/router/src/connector/stripe/transformers/connect.rs b/crates/hyperswitch_connectors/src/connectors/stripe/transformers/connect.rs similarity index 86% rename from crates/router/src/connector/stripe/transformers/connect.rs rename to crates/hyperswitch_connectors/src/connectors/stripe/transformers/connect.rs index 9852338038..bb8d4509da 100644 --- a/crates/router/src/connector/stripe/transformers/connect.rs +++ b/crates/hyperswitch_connectors/src/connectors/stripe/transformers/connect.rs @@ -1,17 +1,17 @@ use api_models; -use common_utils::pii::Email; +use common_enums::{enums, Currency}; +use common_utils::{ext_traits::OptionExt as _, pii::Email}; use error_stack::ResultExt; +use hyperswitch_domain_models::types::{PayoutsResponseData, PayoutsRouterData}; +use hyperswitch_interfaces::errors; 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, + types::{PayoutIndividualDetailsExt as _, PayoutsResponseRouterData}, + utils::{CustomerDetails as _, PayoutsData as _, RouterData}, }; - type Error = error_stack::Report; #[derive(Clone, Debug, Deserialize, Serialize)] @@ -33,7 +33,7 @@ pub struct StripeConnectErrorResponse { #[derive(Clone, Debug, Serialize)] pub struct StripeConnectPayoutCreateRequest { amount: i64, - currency: enums::Currency, + currency: Currency, destination: String, transfer_group: String, } @@ -56,7 +56,7 @@ pub struct TransferReversals { #[derive(Clone, Debug, Serialize)] pub struct StripeConnectPayoutFulfillRequest { amount: i64, - currency: enums::Currency, + currency: Currency, } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -190,7 +190,7 @@ pub struct RecipientBankAccountRequest { #[serde(rename = "external_account[country]")] external_account_country: enums::CountryAlpha2, #[serde(rename = "external_account[currency]")] - external_account_currency: enums::Currency, + external_account_currency: Currency, #[serde(rename = "external_account[account_holder_name]")] external_account_account_holder_name: Secret, #[serde(rename = "external_account[account_number]")] @@ -207,9 +207,9 @@ pub struct StripeConnectRecipientAccountCreateResponse { } // Payouts create/transfer request transform -impl TryFrom<&types::PayoutsRouterData> for StripeConnectPayoutCreateRequest { +impl TryFrom<&PayoutsRouterData> for StripeConnectPayoutCreateRequest { type Error = Error; - fn try_from(item: &types::PayoutsRouterData) -> Result { + fn try_from(item: &PayoutsRouterData) -> Result { let request = item.request.to_owned(); let connector_customer_id = item.get_connector_customer_id()?; Ok(Self { @@ -222,17 +222,17 @@ impl TryFrom<&types::PayoutsRouterData> for StripeConnectPayoutCreateReque } // Payouts create response transform -impl TryFrom> - for types::PayoutsRouterData +impl TryFrom> + for PayoutsRouterData { type Error = Error; fn try_from( - item: types::PayoutsResponseRouterData, + item: PayoutsResponseRouterData, ) -> Result { let response: StripeConnectPayoutCreateResponse = item.response; Ok(Self { - response: Ok(types::PayoutsResponseData { + response: Ok(PayoutsResponseData { status: Some(enums::PayoutStatus::RequiresFulfillment), connector_payout_id: Some(response.id), payout_eligible: None, @@ -246,9 +246,9 @@ impl TryFrom TryFrom<&types::PayoutsRouterData> for StripeConnectPayoutFulfillRequest { +impl TryFrom<&PayoutsRouterData> for StripeConnectPayoutFulfillRequest { type Error = Error; - fn try_from(item: &types::PayoutsRouterData) -> Result { + fn try_from(item: &PayoutsRouterData) -> Result { let request = item.request.to_owned(); Ok(Self { amount: request.amount, @@ -258,17 +258,17 @@ impl TryFrom<&types::PayoutsRouterData> for StripeConnectPayoutFulfillRequ } // Payouts fulfill response transform -impl TryFrom> - for types::PayoutsRouterData +impl TryFrom> + for PayoutsRouterData { type Error = Error; fn try_from( - item: types::PayoutsResponseRouterData, + item: PayoutsResponseRouterData, ) -> Result { let response: StripeConnectPayoutFulfillResponse = item.response; Ok(Self { - response: Ok(types::PayoutsResponseData { + response: Ok(PayoutsResponseData { status: Some(enums::PayoutStatus::from(response.status)), connector_payout_id: Some(response.id), payout_eligible: None, @@ -282,9 +282,9 @@ impl TryFrom TryFrom<&types::PayoutsRouterData> for StripeConnectReversalRequest { +impl TryFrom<&PayoutsRouterData> for StripeConnectReversalRequest { type Error = Error; - fn try_from(item: &types::PayoutsRouterData) -> Result { + fn try_from(item: &PayoutsRouterData) -> Result { Ok(Self { amount: item.request.amount, }) @@ -292,15 +292,15 @@ impl TryFrom<&types::PayoutsRouterData> for StripeConnectReversalRequest { } // Payouts reversal response transform -impl TryFrom> - for types::PayoutsRouterData +impl TryFrom> + for PayoutsRouterData { type Error = Error; fn try_from( - item: types::PayoutsResponseRouterData, + item: PayoutsResponseRouterData, ) -> Result { Ok(Self { - response: Ok(types::PayoutsResponseData { + response: Ok(PayoutsResponseData { status: Some(enums::PayoutStatus::Cancelled), connector_payout_id: item.data.request.connector_payout_id.clone(), payout_eligible: None, @@ -314,12 +314,12 @@ impl TryFrom TryFrom<&types::PayoutsRouterData> for StripeConnectRecipientCreateRequest { +impl TryFrom<&PayoutsRouterData> for StripeConnectRecipientCreateRequest { type Error = Error; - fn try_from(item: &types::PayoutsRouterData) -> Result { + fn try_from(item: &PayoutsRouterData) -> Result { let request = item.request.to_owned(); let customer_details = request.get_customer_details()?; - let customer_email = customer_details.get_email()?; + let customer_email = customer_details.get_customer_email()?; let address = item.get_billing_address()?.clone(); let payout_vendor_details = request.get_vendor_details()?; let (vendor_details, individual_details) = ( @@ -366,16 +366,16 @@ impl TryFrom<&types::PayoutsRouterData> for StripeConnectRecipientCreateRe } // Recipient creation response transform -impl TryFrom> - for types::PayoutsRouterData +impl TryFrom> + for PayoutsRouterData { type Error = Error; fn try_from( - item: types::PayoutsResponseRouterData, + item: PayoutsResponseRouterData, ) -> Result { let response: StripeConnectRecipientCreateResponse = item.response; Ok(Self { - response: Ok(types::PayoutsResponseData { + response: Ok(PayoutsResponseData { status: Some(enums::PayoutStatus::RequiresVendorAccountCreation), connector_payout_id: Some(response.id), payout_eligible: None, @@ -389,13 +389,13 @@ impl TryFrom TryFrom<&types::PayoutsRouterData> for StripeConnectRecipientAccountCreateRequest { +impl TryFrom<&PayoutsRouterData> for StripeConnectRecipientAccountCreateRequest { type Error = Error; - fn try_from(item: &types::PayoutsRouterData) -> Result { + fn try_from(item: &PayoutsRouterData) -> Result { 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 customer_name = customer_details.get_customer_name()?; let payout_vendor_details = request.get_vendor_details()?; match payout_method_data { api_models::payouts::PayoutMethodData::Card(_) => { @@ -450,15 +450,15 @@ impl TryFrom<&types::PayoutsRouterData> for StripeConnectRecipientAccountC } // Recipient account's creation response -impl TryFrom> - for types::PayoutsRouterData +impl TryFrom> + for PayoutsRouterData { type Error = Error; fn try_from( - item: types::PayoutsResponseRouterData, + item: PayoutsResponseRouterData, ) -> Result { Ok(Self { - response: Ok(types::PayoutsResponseData { + response: Ok(PayoutsResponseData { status: Some(enums::PayoutStatus::RequiresCreation), connector_payout_id: item.data.request.connector_payout_id.clone(), payout_eligible: None, diff --git a/crates/hyperswitch_connectors/src/constants.rs b/crates/hyperswitch_connectors/src/constants.rs index 47ef0be4ec..faeb9e2c0a 100644 --- a/crates/hyperswitch_connectors/src/constants.rs +++ b/crates/hyperswitch_connectors/src/constants.rs @@ -27,6 +27,7 @@ pub(crate) mod headers { pub(crate) const X_API_KEY: &str = "X-Api-Key"; pub(crate) const CORRELATION_ID: &str = "Correlation-Id"; pub(crate) const WP_API_VERSION: &str = "WP-Api-Version"; + pub(crate) const STRIPE_COMPATIBLE_CONNECT_ACCOUNT: &str = "Stripe-Account"; pub(crate) const SOURCE: &str = "Source"; pub(crate) const USER_AGENT: &str = "User-Agent"; pub(crate) const KEY: &str = "key"; diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index cbca2a9808..e8013933d6 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -195,6 +195,7 @@ default_imp_for_authorize_session_token!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::UnifiedAuthenticationService, @@ -311,6 +312,7 @@ default_imp_for_calculate_tax!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Threedsecureio, connectors::Thunes, @@ -392,6 +394,7 @@ default_imp_for_session_update!( connectors::Riskified, connectors::Shift4, connectors::Signifyd, + connectors::Stripe, connectors::Stax, connectors::Square, connectors::Stripebilling, @@ -509,6 +512,7 @@ default_imp_for_post_session_tokens!( connectors::Signifyd, connectors::Square, connectors::Stax, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Mifinity, @@ -754,6 +758,7 @@ default_imp_for_complete_authorize!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -868,6 +873,7 @@ default_imp_for_incremental_authorization!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -1185,6 +1191,7 @@ default_imp_for_pre_processing_steps!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -1299,6 +1306,7 @@ default_imp_for_post_processing_steps!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -1416,6 +1424,7 @@ default_imp_for_approve!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -1533,6 +1542,7 @@ default_imp_for_reject!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -1649,6 +1659,7 @@ default_imp_for_webhook_source_verification!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -1765,6 +1776,7 @@ default_imp_for_accept_dispute!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -1995,6 +2007,7 @@ default_imp_for_defend_dispute!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -2451,6 +2464,7 @@ default_imp_for_payouts_retrieve!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -2567,6 +2581,7 @@ default_imp_for_payouts_eligibility!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -2909,6 +2924,7 @@ default_imp_for_payouts_quote!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -3259,6 +3275,7 @@ default_imp_for_frm_sale!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -3376,6 +3393,7 @@ default_imp_for_frm_checkout!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -3493,6 +3511,7 @@ default_imp_for_frm_transaction!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -3610,6 +3629,7 @@ default_imp_for_frm_fulfillment!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -3725,6 +3745,7 @@ default_imp_for_frm_record_return!( connectors::Recurly, connectors::Redsys, connectors::Shift4, + connectors::Stripe, connectors::Stax, connectors::Square, connectors::Stripebilling, @@ -3840,6 +3861,7 @@ default_imp_for_revoking_mandates!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -3953,6 +3975,7 @@ default_imp_for_uas_pre_authentication!( connectors::Riskified, connectors::Shift4, connectors::Signifyd, + connectors::Stripe, connectors::Stax, connectors::Square, connectors::Stripebilling, @@ -4067,6 +4090,7 @@ default_imp_for_uas_post_authentication!( connectors::Riskified, connectors::Shift4, connectors::Signifyd, + connectors::Stripe, connectors::Stax, connectors::Square, connectors::Stripebilling, @@ -4184,6 +4208,7 @@ default_imp_for_uas_authentication_confirmation!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -4290,6 +4315,7 @@ default_imp_for_connector_request_id!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -4399,6 +4425,7 @@ default_imp_for_fraud_check!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -4538,6 +4565,7 @@ default_imp_for_connector_authentication!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, @@ -4651,6 +4679,7 @@ default_imp_for_uas_authentication!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -4758,6 +4787,7 @@ default_imp_for_revenue_recovery! { connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -4875,6 +4905,7 @@ default_imp_for_billing_connector_payment_sync!( connectors::Riskified, connectors::Shift4, connectors::Signifyd, + connectors::Stripe, connectors::Stax, connectors::Square, connectors::Taxjar, @@ -4991,6 +5022,7 @@ default_imp_for_revenue_recovery_record_back!( connectors::Riskified, connectors::Shift4, connectors::Signifyd, + connectors::Stripe, connectors::Stax, connectors::Square, connectors::Taxjar, @@ -5109,6 +5141,7 @@ default_imp_for_billing_connector_invoice_sync!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Threedsecureio, connectors::Taxjar, diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index 3e5d37a44e..e6b0a24574 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -318,6 +318,7 @@ default_imp_for_new_connector_integration_payment!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -435,6 +436,7 @@ default_imp_for_new_connector_integration_refund!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -547,6 +549,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -664,6 +667,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -780,6 +784,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -897,6 +902,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -1024,6 +1030,7 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -1143,6 +1150,7 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -1262,6 +1270,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -1381,6 +1390,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -1500,6 +1510,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -1619,6 +1630,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -1738,6 +1750,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -1857,6 +1870,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -1976,6 +1990,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -2093,6 +2108,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -2212,6 +2228,7 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -2331,6 +2348,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -2450,6 +2468,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -2569,6 +2588,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -2688,6 +2708,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -2803,6 +2824,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -2890,6 +2912,7 @@ default_imp_for_new_connector_integration_frm!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Taxjar, connectors::Threedsecureio, @@ -3004,6 +3027,7 @@ default_imp_for_new_connector_integration_connector_authentication!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Taxjar, connectors::Threedsecureio, @@ -3110,6 +3134,7 @@ default_imp_for_new_connector_integration_revenue_recovery!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Taxjar, connectors::Threedsecureio, diff --git a/crates/hyperswitch_connectors/src/types.rs b/crates/hyperswitch_connectors/src/types.rs index a072317ea7..f6673e7dc4 100644 --- a/crates/hyperswitch_connectors/src/types.rs +++ b/crates/hyperswitch_connectors/src/types.rs @@ -9,7 +9,7 @@ use hyperswitch_domain_models::{ Authentication, PostAuthentication, PreAuthentication, PreAuthenticationVersionCall, }, Accept, AccessTokenAuth, Authorize, Capture, Defend, Evidence, PSync, PostProcessing, - PreProcessing, Session, Upload, Void, + PreProcessing, Retrieve, Session, Upload, Void, }, router_request_types::{ authentication::{ @@ -19,11 +19,12 @@ use hyperswitch_domain_models::{ AcceptDisputeRequestData, AccessTokenRequestData, DefendDisputeRequestData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsPostProcessingData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, RefundsData, - SubmitEvidenceRequestData, UploadFileRequestData, + RetrieveFileRequestData, SubmitEvidenceRequestData, UploadFileRequestData, }, router_response_types::{ AcceptDisputeResponse, AuthenticationResponseData, DefendDisputeResponse, - PaymentsResponseData, RefundsResponseData, SubmitEvidenceResponse, UploadFileResponse, + PaymentsResponseData, RefundsResponseData, RetrieveFileResponse, SubmitEvidenceResponse, + UploadFileResponse, }, }; #[cfg(feature = "frm")] @@ -141,3 +142,24 @@ pub(crate) type FrmRecordReturnType = #[cfg(feature = "frm")] pub(crate) type FrmSaleType = dyn ConnectorIntegration; + +pub(crate) type RetrieveFileRouterData = + RouterData; + +#[cfg(feature = "payouts")] +pub(crate) trait PayoutIndividualDetailsExt { + type Error; + fn get_external_account_account_holder_type(&self) -> Result; +} + +#[cfg(feature = "payouts")] +impl PayoutIndividualDetailsExt for api_models::payouts::PayoutIndividualDetails { + type Error = error_stack::Report; + fn get_external_account_account_holder_type(&self) -> Result { + self.external_account_account_holder_type + .clone() + .ok_or_else(crate::utils::missing_field_err( + "external_account_account_holder_type", + )) + } +} diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index fc9c45f539..c3c3a23baa 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -53,11 +53,12 @@ use hyperswitch_domain_models::{ RouterData as ConnectorRouterData, }, router_request_types::{ - AuthenticationData, BrowserInformation, CompleteAuthorizeData, ConnectorCustomerData, - MandateRevokeRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, - PaymentsCancelData, PaymentsCaptureData, PaymentsPostSessionTokensData, - PaymentsPreProcessingData, PaymentsSyncData, RefundsData, ResponseId, - SetupMandateRequestData, + AuthenticationData, AuthoriseIntegrityObject, BrowserInformation, CaptureIntegrityObject, + CompleteAuthorizeData, ConnectorCustomerData, MandateRevokeRequestData, + PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, + PaymentsCaptureData, PaymentsPostSessionTokensData, PaymentsPreProcessingData, + PaymentsSyncData, RefundIntegrityObject, RefundsData, ResponseId, SetupMandateRequestData, + SyncIntegrityObject, }, router_response_types::{CaptureSyncResponse, PaymentsResponseData}, types::{OrderDetailsWithAmount, SetupMandateRouterData}, @@ -2514,13 +2515,13 @@ macro_rules! get_formatted_date_time { #[macro_export] macro_rules! unimplemented_payment_method { ($payment_method:expr, $connector:expr) => { - errors::ConnectorError::NotImplemented(format!( + hyperswitch_interfaces::errors::ConnectorError::NotImplemented(format!( "{} through {}", $payment_method, $connector )) }; ($payment_method:expr, $flow:expr, $connector:expr) => { - errors::ConnectorError::NotImplemented(format!( + hyperswitch_interfaces::errors::ConnectorError::NotImplemented(format!( "{} {} through {}", $payment_method, $flow, $connector )) @@ -6328,3 +6329,105 @@ impl FraudCheckRecordReturnRequest for FraudCheckRecordReturnData { self.currency.ok_or_else(missing_field_err("currency")) } } + +pub trait SplitPaymentData { + fn get_split_payment_data(&self) -> Option; +} + +impl SplitPaymentData for PaymentsCaptureData { + fn get_split_payment_data(&self) -> Option { + None + } +} + +impl SplitPaymentData for PaymentsAuthorizeData { + fn get_split_payment_data(&self) -> Option { + self.split_payments.clone() + } +} + +impl SplitPaymentData for PaymentsSyncData { + fn get_split_payment_data(&self) -> Option { + self.split_payments.clone() + } +} + +impl SplitPaymentData for PaymentsCancelData { + fn get_split_payment_data(&self) -> Option { + None + } +} + +impl SplitPaymentData for SetupMandateRequestData { + fn get_split_payment_data(&self) -> Option { + None + } +} + +pub fn get_refund_integrity_object( + amount_convertor: &dyn AmountConvertor, + refund_amount: T, + currency: String, +) -> Result> { + let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str()) + .change_context(errors::ConnectorError::ParsingFailed)?; + + let refund_amount_in_minor_unit = + convert_back_amount_to_minor_units(amount_convertor, refund_amount, currency_enum)?; + + Ok(RefundIntegrityObject { + currency: currency_enum, + refund_amount: refund_amount_in_minor_unit, + }) +} + +pub fn get_capture_integrity_object( + amount_convertor: &dyn AmountConvertor, + capture_amount: Option, + currency: String, +) -> Result> { + let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str()) + .change_context(errors::ConnectorError::ParsingFailed)?; + + let capture_amount_in_minor_unit = capture_amount + .map(|amount| convert_back_amount_to_minor_units(amount_convertor, amount, currency_enum)) + .transpose()?; + + Ok(CaptureIntegrityObject { + capture_amount: capture_amount_in_minor_unit, + currency: currency_enum, + }) +} + +pub fn get_sync_integrity_object( + amount_convertor: &dyn AmountConvertor, + amount: T, + currency: String, +) -> Result> { + let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str()) + .change_context(errors::ConnectorError::ParsingFailed)?; + let amount_in_minor_unit = + convert_back_amount_to_minor_units(amount_convertor, amount, currency_enum)?; + + Ok(SyncIntegrityObject { + amount: Some(amount_in_minor_unit), + currency: Some(currency_enum), + }) +} + +pub fn get_authorise_integrity_object( + amount_convertor: &dyn AmountConvertor, + amount: T, + currency: String, +) -> Result> { + let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str()) + .change_context(errors::ConnectorError::ParsingFailed)?; + + let amount_in_minor_unit = + convert_back_amount_to_minor_units(amount_convertor, amount, currency_enum)?; + + Ok(AuthoriseIntegrityObject { + amount: amount_in_minor_unit, + currency: currency_enum, + }) +} diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index 26332d3f43..da49aaed74 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -1,6 +1,5 @@ #[cfg(feature = "dummy_connector")] pub mod dummyconnector; -pub mod stripe; pub mod utils; pub use hyperswitch_connectors::connectors::{ @@ -31,9 +30,10 @@ pub use hyperswitch_connectors::connectors::{ plaid::Plaid, powertranz, powertranz::Powertranz, prophetpay, prophetpay::Prophetpay, rapyd, rapyd::Rapyd, razorpay, razorpay::Razorpay, recurly, recurly::Recurly, redsys, redsys::Redsys, riskified, riskified::Riskified, shift4, shift4::Shift4, signifyd, signifyd::Signifyd, square, - square::Square, stax, stax::Stax, stripebilling, stripebilling::Stripebilling, taxjar, - taxjar::Taxjar, threedsecureio, threedsecureio::Threedsecureio, thunes, thunes::Thunes, - trustpay, trustpay::Trustpay, tsys, tsys::Tsys, unified_authentication_service, + square::Square, stax, stax::Stax, stripe, stripe::Stripe, stripebilling, + stripebilling::Stripebilling, taxjar, taxjar::Taxjar, threedsecureio, + threedsecureio::Threedsecureio, thunes, thunes::Thunes, trustpay, trustpay::Trustpay, tsys, + tsys::Tsys, unified_authentication_service, unified_authentication_service::UnifiedAuthenticationService, vgs, vgs::Vgs, volt, volt::Volt, wellsfargo, wellsfargo::Wellsfargo, wellsfargopayout, wellsfargopayout::Wellsfargopayout, wise, wise::Wise, worldline, worldline::Worldline, worldpay, worldpay::Worldpay, worldpayxml, @@ -42,4 +42,3 @@ pub use hyperswitch_connectors::connectors::{ #[cfg(feature = "dummy_connector")] pub use self::dummyconnector::DummyConnector; -pub use self::stripe::Stripe; diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index f06433c545..9a64dfdaa6 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -21,12 +21,7 @@ use common_utils::{ use diesel_models::{enums, types::OrderDetailsWithAmount}; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ - network_tokenization::NetworkTokenNumber, - payments::payment_attempt::PaymentAttempt, - router_request_types::{ - AuthoriseIntegrityObject, CaptureIntegrityObject, RefundIntegrityObject, - SyncIntegrityObject, - }, + network_tokenization::NetworkTokenNumber, payments::payment_attempt::PaymentAttempt, }; use masking::{Deserialize, ExposeInterface, Secret}; use once_cell::sync::Lazy; @@ -750,7 +745,6 @@ impl PaymentsCaptureRequestData for types::PaymentsCaptureData { self.capture_method.to_owned() } } - pub trait SplitPaymentData { fn get_split_payment_data(&self) -> Option; } @@ -2755,73 +2749,6 @@ pub fn convert_back_amount_to_minor_units( .change_context(errors::ConnectorError::AmountConversionFailed) } -pub fn get_authorise_integrity_object( - amount_convertor: &dyn AmountConvertor, - amount: T, - currency: String, -) -> Result> { - let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str()) - .change_context(errors::ConnectorError::ParsingFailed)?; - - let amount_in_minor_unit = - convert_back_amount_to_minor_units(amount_convertor, amount, currency_enum)?; - - Ok(AuthoriseIntegrityObject { - amount: amount_in_minor_unit, - currency: currency_enum, - }) -} - -pub fn get_sync_integrity_object( - amount_convertor: &dyn AmountConvertor, - amount: T, - currency: String, -) -> Result> { - let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str()) - .change_context(errors::ConnectorError::ParsingFailed)?; - let amount_in_minor_unit = - convert_back_amount_to_minor_units(amount_convertor, amount, currency_enum)?; - - Ok(SyncIntegrityObject { - amount: Some(amount_in_minor_unit), - currency: Some(currency_enum), - }) -} - -pub fn get_capture_integrity_object( - amount_convertor: &dyn AmountConvertor, - capture_amount: Option, - currency: String, -) -> Result> { - let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str()) - .change_context(errors::ConnectorError::ParsingFailed)?; - - let capture_amount_in_minor_unit = capture_amount - .map(|amount| convert_back_amount_to_minor_units(amount_convertor, amount, currency_enum)) - .transpose()?; - - Ok(CaptureIntegrityObject { - capture_amount: capture_amount_in_minor_unit, - currency: currency_enum, - }) -} - -pub fn get_refund_integrity_object( - amount_convertor: &dyn AmountConvertor, - refund_amount: T, - currency: String, -) -> Result> { - let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str()) - .change_context(errors::ConnectorError::ParsingFailed)?; - - let refund_amount_in_minor_unit = - convert_back_amount_to_minor_units(amount_convertor, refund_amount, currency_enum)?; - - Ok(RefundIntegrityObject { - currency: currency_enum, - refund_amount: refund_amount_in_minor_unit, - }) -} pub trait NetworkTokenData { fn get_card_issuer(&self) -> Result; fn get_expiry_year_4_digit(&self) -> Secret; diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index f5350e81d5..d166bc41a2 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -96,7 +96,6 @@ use crate::core::routing::helpers as routing_helpers; 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}, @@ -5503,22 +5502,6 @@ pub struct IncrementalAuthorizationDetails { pub authorization_id: Option, } -pub trait CustomerDetailsExt { - type Error; - fn get_name(&self) -> Result, Self::Error>; - fn get_email(&self) -> Result; -} - -impl CustomerDetailsExt for CustomerDetails { - type Error = error_stack::Report; - fn get_name(&self) -> Result, Self::Error> { - self.name.clone().ok_or_else(missing_field_err("name")) - } - fn get_email(&self) -> Result { - 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, diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index ff52833cd4..2e4864c80c 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -190,21 +190,6 @@ pub trait Feature { } } -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 api::PaymentsCompleteAuthorize for connector::DummyConnector {} #[cfg(feature = "dummy_connector")] @@ -217,22 +202,6 @@ impl { } -default_imp_for_complete_authorize!(connector::Stripe); -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 api::ConnectorVerifyWebhookSource for connector::DummyConnector {} #[cfg(feature = "dummy_connector")] @@ -244,22 +213,6 @@ impl > for connector::DummyConnector { } -default_imp_for_webhook_source_verification!(connector::Stripe); - -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 api::ConnectorCustomer for connector::DummyConnector {} @@ -273,25 +226,6 @@ impl { } -default_imp_for_create_customer!(); - -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, - _action: services::PaymentAction - ) -> CustomResult { - Ok(payments::CallConnectorAction::Trigger) - } - } - )* - }; -} - #[cfg(feature = "dummy_connector")] impl services::ConnectorRedirectResponse for connector::DummyConnector { fn get_flow_type( @@ -304,37 +238,9 @@ impl services::ConnectorRedirectResponse for connector::DummyConnec } } -default_imp_for_connector_redirect_response!(); - -macro_rules! default_imp_for_connector_request_id { - ($($path:ident::$connector:ident),*) => { - $( - impl api::ConnectorTransactionId for $path::$connector {} - )* - }; -} - #[cfg(feature = "dummy_connector")] impl api::ConnectorTransactionId for connector::DummyConnector {} -default_imp_for_connector_request_id!(connector::Stripe); - -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 api::Dispute for connector::DummyConnector {} #[cfg(feature = "dummy_connector")] @@ -349,32 +255,6 @@ impl { } -default_imp_for_accept_dispute!(connector::Stripe); - -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 api::FileUpload for connector::DummyConnector {} #[cfg(feature = "dummy_connector")] @@ -400,23 +280,6 @@ impl { } -default_imp_for_file_upload!(); - -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 api::SubmitEvidence for connector::DummyConnector {} #[cfg(feature = "dummy_connector")] @@ -429,23 +292,6 @@ impl { } -default_imp_for_submit_evidence!(); - -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 api::DefendDispute for connector::DummyConnector {} #[cfg(feature = "dummy_connector")] @@ -458,38 +304,6 @@ impl { } -default_imp_for_defend_dispute!(connector::Stripe); - -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 api::PaymentsPreProcessing for connector::DummyConnector {} #[cfg(feature = "dummy_connector")] @@ -502,8 +316,6 @@ impl { } -default_imp_for_pre_processing_steps!(connector::Stripe); - #[cfg(feature = "dummy_connector")] impl api::PaymentsPostProcessing for connector::DummyConnector {} #[cfg(feature = "dummy_connector")] @@ -516,37 +328,9 @@ impl { } -default_imp_for_post_processing_steps!(connector::Stripe); - -macro_rules! default_imp_for_payouts { - ($($path:ident::$connector:ident),*) => { - $( - impl Payouts for $path::$connector {} - )* - }; -} - #[cfg(feature = "dummy_connector")] impl Payouts for connector::DummyConnector {} -default_imp_for_payouts!(); - -#[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 api::PayoutCreate for connector::DummyConnector {} @@ -558,25 +342,6 @@ impl { } -#[cfg(feature = "payouts")] -default_imp_for_payouts_create!(); - -#[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 api::PayoutSync for connector::DummyConnector {} @@ -588,25 +353,6 @@ impl { } -#[cfg(feature = "payouts")] -default_imp_for_payouts_retrieve!(connector::Stripe); - -#[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 api::PayoutEligibility for connector::DummyConnector {} @@ -621,25 +367,6 @@ impl { } -#[cfg(feature = "payouts")] -default_imp_for_payouts_eligibility!(connector::Stripe); - -#[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 api::PayoutFulfill for connector::DummyConnector {} @@ -651,25 +378,6 @@ impl { } -#[cfg(feature = "payouts")] -default_imp_for_payouts_fulfill!(); - -#[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 api::PayoutCancel for connector::DummyConnector {} @@ -681,25 +389,6 @@ impl { } -#[cfg(feature = "payouts")] -default_imp_for_payouts_cancel!(); - -#[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 api::PayoutQuote for connector::DummyConnector {} @@ -711,25 +400,6 @@ impl { } -#[cfg(feature = "payouts")] -default_imp_for_payouts_quote!(connector::Stripe); - -#[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 api::PayoutRecipient for connector::DummyConnector {} @@ -741,25 +411,6 @@ impl { } -#[cfg(feature = "payouts")] -default_imp_for_payouts_recipient!(); - -#[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 api::PayoutRecipientAccount for connector::DummyConnector {} @@ -774,24 +425,6 @@ impl { } -#[cfg(feature = "payouts")] -default_imp_for_payouts_recipient_account!(); - -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 api::PaymentApprove for connector::DummyConnector {} #[cfg(feature = "dummy_connector")] @@ -804,23 +437,6 @@ impl { } -default_imp_for_approve!(connector::Stripe); - -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 api::PaymentReject for connector::DummyConnector {} #[cfg(feature = "dummy_connector")] @@ -833,39 +449,9 @@ impl { } -default_imp_for_reject!(connector::Stripe); - -#[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 api::FraudCheck for connector::DummyConnector {} -#[cfg(feature = "frm")] -default_imp_for_fraud_check!(connector::Stripe); - -#[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 api::FraudCheckSale for connector::DummyConnector {} #[cfg(all(feature = "frm", feature = "dummy_connector"))] @@ -878,25 +464,6 @@ impl { } -#[cfg(feature = "frm")] -default_imp_for_frm_sale!(connector::Stripe); - -#[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 api::FraudCheckCheckout for connector::DummyConnector {} #[cfg(all(feature = "frm", feature = "dummy_connector"))] @@ -909,25 +476,6 @@ impl { } -#[cfg(feature = "frm")] -default_imp_for_frm_checkout!(connector::Stripe); - -#[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 api::FraudCheckTransaction for connector::DummyConnector {} #[cfg(all(feature = "frm", feature = "dummy_connector"))] @@ -940,25 +488,6 @@ impl { } -#[cfg(feature = "frm")] -default_imp_for_frm_transaction!(connector::Stripe); - -#[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 api::FraudCheckFulfillment for connector::DummyConnector {} #[cfg(all(feature = "frm", feature = "dummy_connector"))] @@ -971,25 +500,6 @@ impl { } -#[cfg(feature = "frm")] -default_imp_for_frm_fulfillment!(connector::Stripe); - -#[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 api::FraudCheckRecordReturn for connector::DummyConnector {} #[cfg(all(feature = "frm", feature = "dummy_connector"))] @@ -1002,24 +512,6 @@ impl { } -#[cfg(feature = "frm")] -default_imp_for_frm_record_return!(connector::Stripe); - -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 api::PaymentIncrementalAuthorization for connector::DummyConnector {} #[cfg(feature = "dummy_connector")] @@ -1032,22 +524,6 @@ impl { } -default_imp_for_incremental_authorization!(connector::Stripe); - -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 api::ConnectorMandateRevoke for connector::DummyConnector {} #[cfg(feature = "dummy_connector")] @@ -1059,46 +535,6 @@ impl > for connector::DummyConnector { } -default_imp_for_revoking_mandates!(connector::Stripe); - -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 api::ExternalAuthentication for connector::DummyConnector {} @@ -1147,21 +583,7 @@ impl > for connector::DummyConnector { } -default_imp_for_connector_authentication!(connector::Stripe); -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 api::PaymentAuthorizeSessionToken for connector::DummyConnector {} #[cfg(feature = "dummy_connector")] @@ -1173,21 +595,7 @@ impl > for connector::DummyConnector { } -default_imp_for_authorize_session_token!(connector::Stripe); -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 api::TaxCalculation for connector::DummyConnector {} #[cfg(feature = "dummy_connector")] @@ -1200,21 +608,6 @@ impl { } -default_imp_for_calculate_tax!(connector::Stripe); - -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 api::PaymentSessionUpdate for connector::DummyConnector {} #[cfg(feature = "dummy_connector")] @@ -1227,21 +620,6 @@ impl { } -default_imp_for_session_update!(connector::Stripe); - -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 api::PaymentPostSessionTokens for connector::DummyConnector {} #[cfg(feature = "dummy_connector")] @@ -1254,21 +632,6 @@ impl { } -default_imp_for_post_session_tokens!(connector::Stripe); - -macro_rules! default_imp_for_update_metadata { - ($($path:ident::$connector:ident),*) => { - $( impl api::PaymentUpdateMetadata for $path::$connector {} - impl - services::ConnectorIntegration< - api::UpdateMetadata, - types::PaymentsUpdateMetadataData, - types::PaymentsResponseData - > for $path::$connector - {} - )* - }; -} #[cfg(feature = "dummy_connector")] impl api::PaymentUpdateMetadata for connector::DummyConnector {} #[cfg(feature = "dummy_connector")] @@ -1281,22 +644,6 @@ impl { } -default_imp_for_update_metadata!(); - -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 UasPreAuthentication for connector::DummyConnector {} #[cfg(feature = "dummy_connector")] @@ -1311,21 +658,6 @@ impl { } -default_imp_for_uas_pre_authentication!(connector::Stripe); - -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 UasPostAuthentication for connector::DummyConnector {} #[cfg(feature = "dummy_connector")] @@ -1338,24 +670,6 @@ impl { } -default_imp_for_uas_post_authentication!(connector::Stripe); - -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::Stripe); - #[cfg(feature = "dummy_connector")] impl UasAuthenticationConfirmation for connector::DummyConnector {} #[cfg(feature = "dummy_connector")] @@ -1368,20 +682,6 @@ impl { } -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 UasAuthentication for connector::DummyConnector {} #[cfg(feature = "dummy_connector")] @@ -1394,8 +694,6 @@ impl { } -default_imp_for_uas_authentication!(connector::Stripe); - /// 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 @@ -1506,38 +804,9 @@ fn handle_post_capture_response( } } -macro_rules! default_imp_for_revenue_recovery { - ($($path:ident::$connector:ident),*) => { - $( impl api::RevenueRecovery for $path::$connector {} - )* - }; -} - #[cfg(feature = "dummy_connector")] impl api::RevenueRecovery for connector::DummyConnector {} -default_imp_for_revenue_recovery! { - - connector::Stripe - - - -} - -#[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 api::BillingConnectorPaymentsSyncIntegration for connector::DummyConnector {} @@ -1552,24 +821,6 @@ impl { } -#[cfg(all(feature = "v2", feature = "revenue_recovery"))] -default_imp_for_billing_connector_payment_sync!(connector::Stripe); - -#[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 api::RevenueRecoveryRecordBack for connector::DummyConnector {} @@ -1583,24 +834,7 @@ impl > for connector::DummyConnector { } -#[cfg(all(feature = "v2", feature = "revenue_recovery"))] -default_imp_for_revenue_recovery_record_back!(connector::Stripe); -#[cfg(all(feature = "v2", feature = "revenue_recovery"))] -macro_rules! default_imp_for_billing_connector_invoice_sync { - ($($path:ident::$connector:ident),*) => { - $( - impl api::BillingConnectorInvoiceSyncIntegration for $path::$connector {} - impl - services::ConnectorIntegration< - BillingConnectorInvoiceSync, - types::BillingConnectorInvoiceSyncRequest, - types::BillingConnectorInvoiceSyncResponse, - > for $path::$connector - {} - )* - }; -} #[cfg(all(feature = "v2", feature = "revenue_recovery"))] #[cfg(feature = "dummy_connector")] impl api::BillingConnectorInvoiceSyncIntegration for connector::DummyConnector {} @@ -1614,5 +848,3 @@ impl > for connector::DummyConnector { } -#[cfg(all(feature = "v2", feature = "revenue_recovery"))] -default_imp_for_billing_connector_invoice_sync!(connector::Stripe); diff --git a/crates/router/src/macros.rs b/crates/router/src/macros.rs index c6de30c8d0..21c89342fb 100644 --- a/crates/router/src/macros.rs +++ b/crates/router/src/macros.rs @@ -1,4 +1,4 @@ -pub use common_utils::{collect_missing_value_keys, newtype}; +pub use common_utils::newtype; #[macro_export] macro_rules! get_payment_link_config_value_based_on_priority { diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 22a84c66d1..af5d983a48 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -115,10 +115,7 @@ pub use hyperswitch_interfaces::types::{ pub use crate::core::payments::CustomerDetails; #[cfg(feature = "payouts")] -use crate::{ - connector::utils::missing_field_err, - core::utils::IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_PAYOUTS_FLOW, -}; +use crate::core::utils::IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_PAYOUTS_FLOW; use crate::{ consts, core::{ @@ -252,16 +249,6 @@ pub trait PayoutIndividualDetailsExt { fn get_external_account_account_holder_type(&self) -> Result; } -#[cfg(feature = "payouts")] -impl PayoutIndividualDetailsExt for api_models::payouts::PayoutIndividualDetails { - type Error = error_stack::Report; - fn get_external_account_account_holder_type(&self) -> Result { - self.external_account_account_holder_type - .clone() - .ok_or_else(missing_field_err("external_account_account_holder_type")) - } -} - pub trait Capturable { fn get_captured_amount(&self, _payment_data: &PaymentData) -> Option where