Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
chore: introduce pre_authenticate flow in shift4 (#10861)
Hrithikesh4de5319869d5
diff --git a/config/development.toml b/config/development.tomlindex e39401c9a3..52e559afdd 100644--- a/config/development.toml+++ b/config/development.toml@@ -38,7 +38,7 @@ pool_size = 5connection_timeout = 10[preprocessing_flow_config]-authentication_bloated_connectors = "paypal,nmi,cybersource,barclaycard"+authentication_bloated_connectors = "paypal,nmi,cybersource,barclaycard,shift4"order_create_bloated_connectors = "trustpay,payme"[redis]diff --git a/crates/hyperswitch_connectors/src/connectors/shift4.rs b/crates/hyperswitch_connectors/src/connectors/shift4.rsindex b7bf72e4d4..dd8342f08d 100644--- a/crates/hyperswitch_connectors/src/connectors/shift4.rs+++ b/crates/hyperswitch_connectors/src/connectors/shift4.rs@@ -18,12 +18,13 @@ use hyperswitch_domain_models::{access_token_auth::AccessTokenAuth,payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},refunds::{Execute, RSync},- CompleteAuthorize, PreProcessing,+ CompleteAuthorize, PreAuthenticate, PreProcessing,},router_request_types::{AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData,- PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData,- PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData,+ PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData,+ PaymentsPreAuthenticateData, PaymentsPreProcessingData, PaymentsSessionData,+ PaymentsSyncData, RefundsData, SetupMandateRequestData,},router_response_types::{ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,@@ -31,8 +32,9 @@ use hyperswitch_domain_models::{},types::{PaymentsAuthorizeRouterData, PaymentsCaptureRouterData,- PaymentsCompleteAuthorizeRouterData, PaymentsPreProcessingRouterData,- PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,+ PaymentsCompleteAuthorizeRouterData, PaymentsPreAuthenticateRouterData,+ PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefundSyncRouterData,+ RefundsRouterData,},};use hyperswitch_interfaces::{@@ -53,7 +55,7 @@ use transformers::{self as shift4, Shift4PaymentsRequest, Shift4RefundRequest};use crate::{constants::headers,types::ResponseRouterData,- utils::{convert_amount, RefundsRequestData},+ utils::{convert_amount, PaymentsAuthorizeRequestData, RefundsRequestData},};#[derive(Clone)]@@ -156,6 +158,7 @@ impl ConnectorCommon for Shift4 {impl ConnectorValidation for Shift4 {}+impl api::PaymentsPreAuthenticate for Shift4 {}impl api::Payment for Shift4 {}impl api::PaymentVoid for Shift4 {}impl api::PaymentSync for Shift4 {}@@ -457,6 +460,113 @@ impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> fo//TODO: implement sessions flow}+impl ConnectorIntegration<PreAuthenticate, PaymentsPreAuthenticateData, PaymentsResponseData>+ for Shift4+{+ fn get_headers(+ &self,+ req: &PaymentsPreAuthenticateRouterData,+ _connectors: &Connectors,+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {+ let mut headers = vec![+ (+ headers::CONTENT_TYPE.to_string(),+ "application/x-www-form-urlencoded".to_string().into(),+ ),+ (+ ACCEPT.to_string(),+ self.common_get_content_type().to_string().into(),+ ),+ ];+ let mut api_key = self.get_auth_header(&req.connector_auth_type)?;+ headers.append(&mut api_key);+ Ok(headers)+ }++ fn get_content_type(&self) -> &'static str {+ self.common_get_content_type()+ }++ fn get_url(+ &self,+ _req: &PaymentsPreAuthenticateRouterData,+ connectors: &Connectors,+ ) -> CustomResult<String, errors::ConnectorError> {+ Ok(format!("{}3d-secure", self.base_url(connectors)))+ }++ fn get_request_body(+ &self,+ req: &PaymentsPreAuthenticateRouterData,+ _connectors: &Connectors,+ ) -> CustomResult<RequestContent, errors::ConnectorError> {+ let amount = convert_amount(+ self.amount_converter,+ req.request.minor_amount,+ req.request+ .currency+ .ok_or_else(|| errors::ConnectorError::MissingRequiredField {+ field_name: "currency",+ })?,+ )?;+ let connector_router_data = shift4::Shift4RouterData::try_from((amount, req))?;+ let connector_req = Shift4PaymentsRequest::try_from(&connector_router_data)?;+ Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))+ }++ fn build_request(+ &self,+ req: &PaymentsPreAuthenticateRouterData,+ connectors: &Connectors,+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {+ Ok(Some(+ RequestBuilder::new()+ .method(Method::Post)+ .url(&types::PaymentsPreAuthenticateType::get_url(+ self, req, connectors,+ )?)+ .attach_default_headers()+ .headers(types::PaymentsPreAuthenticateType::get_headers(+ self, req, connectors,+ )?)+ .set_body(types::PaymentsPreAuthenticateType::get_request_body(+ self, req, connectors,+ )?)+ .build(),+ ))+ }++ fn handle_response(+ &self,+ data: &PaymentsPreAuthenticateRouterData,+ event_builder: Option<&mut ConnectorEvent>,+ res: Response,+ ) -> CustomResult<PaymentsPreAuthenticateRouterData, errors::ConnectorError> {+ let response: shift4::Shift4ThreeDsResponse = res+ .response+ .parse_struct("Shift4ThreeDsResponse")+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;++ event_builder.map(|i| i.set_response_body(&response));+ router_env::logger::info!(connector_response=?response);++ PaymentsPreAuthenticateRouterData::try_from(ResponseRouterData {+ response,+ data: data.clone(),+ http_code: res.status_code,+ })+ .change_context(errors::ConnectorError::ResponseHandlingFailed)+ }++ fn get_error_response(+ &self,+ res: Response,+ event_builder: Option<&mut ConnectorEvent>,+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {+ self.build_error_response(res, event_builder)+ }+}+impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>for Shift4{@@ -977,6 +1087,17 @@ static SHIFT4_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 2] =[enums::EventClass::Payments, enums::EventClass::Refunds];impl ConnectorSpecifications for Shift4 {+ fn is_pre_authentication_flow_required(&self, current_flow: api::CurrentFlowInfo<'_>) -> bool {+ match current_flow {+ api::CurrentFlowInfo::Authorize {+ request_data,+ auth_type,+ } => auth_type.is_three_ds() && request_data.is_card(),+ // No alternate flow for complete authorize and SetupMandate+ api::CurrentFlowInfo::SetupMandate { .. }+ | api::CurrentFlowInfo::CompleteAuthorize { .. } => false,+ }+ }fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {Some(&SHIFT4_CONNECTOR_INFO)}diff --git a/crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs b/crates/hyperswitch_connectors/src/connectors/shift4/transformers.rsindex 10224bba25..aab80afe5f 100644--- a/crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs@@ -15,10 +15,13 @@ use hyperswitch_domain_models::{router_data::{ConnectorAuthType, RouterData},router_flow_types::refunds::{Execute, RSync},router_request_types::{- CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsPreProcessingData, ResponseId,+ CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsPreAuthenticateData,+ PaymentsPreProcessingData, ResponseId,},router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},- types::{PaymentsPreProcessingRouterData, RefundsRouterData},+ types::{+ PaymentsPreAuthenticateRouterData, PaymentsPreProcessingRouterData, RefundsRouterData,+ },};use hyperswitch_interfaces::errors;use masking::Secret;@@ -27,11 +30,13 @@ use url::Url;use crate::{types::{- PaymentsPreprocessingResponseRouterData, RefundsResponseRouterData, ResponseRouterData,+ PaymentsPreAuthenticateResponseRouterData, PaymentsPreprocessingResponseRouterData,+ RefundsResponseRouterData, ResponseRouterData,},utils::{self, to_connector_meta, PaymentsAuthorizeRequestData,- PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingRequestData, RouterData as _,+ PaymentsCompleteAuthorizeRequestData, PaymentsPreAuthenticateRequestData,+ PaymentsPreProcessingRequestData, RouterData as _,},};@@ -97,6 +102,46 @@ impl Shift4AuthorizePreprocessingCommon for PaymentsAuthorizeData {}}+impl Shift4AuthorizePreprocessingCommon for PaymentsPreAuthenticateData {+ fn get_email_optional(&self) -> Option<pii::Email> {+ self.email.clone()+ }++ fn get_complete_authorize_url(&self) -> Option<String> {+ self.complete_authorize_url.clone()+ }++ fn get_currency_required(+ &self,+ ) -> Result<enums::Currency, error_stack::Report<errors::ConnectorError>> {+ self.currency.ok_or(+ errors::ConnectorError::MissingRequiredField {+ field_name: "currency",+ }+ .into(),+ )+ }+ fn get_payment_method_data_required(+ &self,+ ) -> Result<PaymentMethodData, error_stack::Report<errors::ConnectorError>> {+ Ok(self.payment_method_data.clone())+ }++ fn is_automatic_capture(&self) -> Result<bool, Error> {+ self.is_auto_capture()+ }++ fn get_router_return_url(&self) -> Option<String> {+ self.router_return_url.clone()+ }++ fn get_metadata(+ &self,+ ) -> Result<Option<serde_json::Value>, error_stack::Report<errors::ConnectorError>> {+ Ok(None)+ }+}+impl Shift4AuthorizePreprocessingCommon for PaymentsPreProcessingData {fn get_email_optional(&self) -> Option<pii::Email> {self.email.clone()@@ -939,6 +984,47 @@ pub struct Shift4CardToken {pub id: Secret<String>,}+impl TryFrom<PaymentsPreAuthenticateResponseRouterData<Shift4ThreeDsResponse>>+ for PaymentsPreAuthenticateRouterData+{+ type Error = Error;+ fn try_from(+ item: PaymentsPreAuthenticateResponseRouterData<Shift4ThreeDsResponse>,+ ) -> Result<Self, Self::Error> {+ let redirection_data = item+ .response+ .redirect_url+ .map(|url| RedirectForm::from((url, Method::Get)));+ Ok(Self {+ status: if redirection_data.is_some() {+ enums::AttemptStatus::AuthenticationPending+ } else {+ enums::AttemptStatus::Pending+ },+ request: PaymentsPreAuthenticateData {+ enrolled_for_3ds: item.response.enrolled,+ ..item.data.request+ },+ response: Ok(PaymentsResponseData::TransactionResponse {+ resource_id: ResponseId::NoResponseId,+ redirection_data: Box::new(redirection_data),+ mandate_reference: Box::new(None),+ connector_metadata: Some(+ serde_json::to_value(Shift4CardToken {+ id: item.response.token.id,+ })+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?,+ ),+ network_txn_id: None,+ connector_response_reference_id: None,+ incremental_authorization_allowed: None,+ charges: None,+ }),+ ..item.data+ })+ }+}+impl TryFrom<PaymentsPreprocessingResponseRouterData<Shift4ThreeDsResponse>>for PaymentsPreProcessingRouterData{diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rsindex 37a38e7bfe..cbe8238482 100644--- a/crates/hyperswitch_connectors/src/default_implementations.rs+++ b/crates/hyperswitch_connectors/src/default_implementations.rs@@ -2049,7 +2049,6 @@ default_imp_for_pre_authenticate_steps!(connectors::Recurly,connectors::Riskified,connectors::Santander,- connectors::Shift4,connectors::Sift,connectors::Signifyd,connectors::Silverflow,diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rsindex 793cb53772..e9bd91fdea 100644--- a/crates/router/src/core/payments/flows/authorize_flow.rs+++ b/crates/router/src/core/payments/flows/authorize_flow.rs@@ -383,6 +383,8 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAuauthorize_router_data.request.related_transaction_id = related_transaction_id;}let should_continue_after_preauthenticate = match connector.connector_name {+ // connector specific handling to decide whether to continue with authorize or not should not be done here+ // this is just a temporary fix for Redsys and Shift4 connectorsapi_models::enums::Connector::Redsys => match &authorize_router_data.response {Ok(types::PaymentsResponseData::TransactionResponse {connector_metadata,@@ -399,6 +401,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu}_ => false,},+ api_models::enums::Connector::Shift4 => true,api_models::enums::Connector::Nuvei => true,_ => false,};