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
feat(ucs): Added IncrementalAuthorization Flow support for HS<>UCS tunnel (#10831)
Saptak Dutta5dd6fc7630d3
diff --git a/crates/external_services/src/grpc_client/unified_connector_service.rs b/crates/external_services/src/grpc_client/unified_connector_service.rsindex d5c3ea9470..de03c7a83e 100644--- a/crates/external_services/src/grpc_client/unified_connector_service.rs+++ b/crates/external_services/src/grpc_client/unified_connector_service.rs@@ -215,6 +215,37 @@ impl UnifiedConnectorServiceClient {})}+ /// Performs Incremental Authorization+ pub async fn incremental_authorization(+ &self,+ sdk_session_token_request: payments_grpc::PaymentServiceIncrementalAuthorizationRequest,+ connector_auth_metadata: ConnectorAuthMetadata,+ grpc_headers: GrpcHeadersUcs,+ ) -> UnifiedConnectorServiceResult<+ tonic::Response<payments_grpc::PaymentServiceIncrementalAuthorizationResponse>,+ > {+ let mut request = tonic::Request::new(sdk_session_token_request);++ let connector_name = connector_auth_metadata.connector_name.clone();+ let metadata =+ build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;+ *request.metadata_mut() = metadata;++ self.client+ .clone()+ .incremental_authorization(request)+ .await+ .change_context(UnifiedConnectorServiceError::IncrementalAuthorizationFailure)+ .inspect_err(|error| {+ logger::error!(+ grpc_error=?error,+ method="incremental_authorization",+ connector_name=?connector_name,+ "UCS incremental_authorization gRPC call failed"+ )+ })+ }+/// Performs Payment Granular Authorizepub async fn payment_authorize_granular(&self,diff --git a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rsindex 88463eb3b6..ec51932340 100644--- a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs+++ b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs@@ -153,6 +153,10 @@ pub enum UnifiedConnectorServiceError {/// Failed to perform Sdk Session Token from gRPC Server#[error("Failed to perform Sdk Session Token from gRPC Server")]SdkSessionTokenFailure,++ /// Failed to perform Incremental Authorization from gRPC Server+ #[error("Failed to perform Incremental Authorization from gRPC Server")]+ IncrementalAuthorizationFailure,}/// UCS Webhook transformation statusdiff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rsindex 98ef97aae3..86e9beac4f 100644--- a/crates/router/src/core/payments/flows/authorize_flow.rs+++ b/crates/router/src/core/payments/flows/authorize_flow.rs@@ -363,6 +363,9 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAupre_authenticate_router_data,connector,gateway_context,+ payments::CallConnectorAction::Trigger,+ None,+ None,)).await?;// Convert back to CompleteAuthorize router data while preserving preprocessing response datadiff --git a/crates/router/src/core/payments/flows/complete_authorize_flow.rs b/crates/router/src/core/payments/flows/complete_authorize_flow.rsindex 50e07c38da..e5fa7aa729 100644--- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs+++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs@@ -291,6 +291,9 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData>authenticate_router_data,connector,gateway_context,+ payments::CallConnectorAction::Trigger,+ None,+ None,)).await?;@@ -372,6 +375,9 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData>post_authenticate_router_data,connector,gateway_context,+ payments::CallConnectorAction::Trigger,+ None,+ None,)).await?;// Convert back to CompleteAuthorize router data while preserving preprocessing response datadiff --git a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs b/crates/router/src/core/payments/flows/incremental_authorization_flow.rsindex 49dd1cc9a3..a722c6eefe 100644--- a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs+++ b/crates/router/src/core/payments/flows/incremental_authorization_flow.rs@@ -1,4 +1,5 @@use async_trait::async_trait;+use hyperswitch_domain_models::router_data_v2::PaymentFlowData;use super::ConstructFlowSpecificData;use crate::{@@ -82,26 +83,18 @@ impl Feature<api::IncrementalAuthorization, types::PaymentsIncrementalAuthorizat_business_profile: &domain::Profile,_header_payload: hyperswitch_domain_models::payments::HeaderPayload,_return_raw_connector_response: Option<bool>,- _gateway_context: payments::gateway::context::RouterGatewayContext,+ gateway_context: payments::gateway::context::RouterGatewayContext,) -> RouterResult<Self> {- let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<- api::IncrementalAuthorization,- types::PaymentsIncrementalAuthorizationData,- types::PaymentsResponseData,- > = connector.connector.get_connector_integration();-- let resp = services::execute_connector_processing_step(+ payments::gateway::handle_gateway_call::<_, _, _, PaymentFlowData, _>(state,- connector_integration,- &self,+ self,+ connector,+ &gateway_context,call_connector_action,connector_request,None,).await- .to_payment_failed_response()?;-- Ok(resp)}async fn add_access_token<'a>(diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rsindex 5ba5fdd302..45d6fbed07 100644--- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs+++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs@@ -250,6 +250,9 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setuppre_authenticate_router_data,connector,gateway_context,+ payments::CallConnectorAction::Trigger,+ None,+ None,)).await?;let pre_authenticate_response = pre_authenticate_router_data.response.clone();diff --git a/crates/router/src/core/payments/gateway.rs b/crates/router/src/core/payments/gateway.rsindex 57cd4eca05..4dc57295b5 100644--- a/crates/router/src/core/payments/gateway.rs+++ b/crates/router/src/core/payments/gateway.rs@@ -7,6 +7,7 @@ pub mod complete_authorize_gateway;pub mod context;pub mod create_customer_gateway;pub mod create_order_gateway;+pub mod incremental_authorization_gateway;pub mod payment_method_token_create_gateway;pub mod post_authenticate_gateway;pub mod pre_authenticate_gateway;@@ -46,6 +47,9 @@ pub async fn handle_gateway_call<Flow, Req, Resp, ResourceCommonData, FlowOutputrouter_data: types::RouterData<Flow, Req, Resp>,connector: &api::ConnectorData,gateway_context: &gateway_context::RouterGatewayContext,+ call_connector_action: common_enums::CallConnectorAction,+ connector_request: Option<services::Request>,+ return_raw_connector_response: Option<bool>,) -> RouterResult<FlowOutput>whereFlow: gateway::FlowGateway<@@ -72,9 +76,9 @@ wherestate,connector_integration,&router_data,- common_enums::CallConnectorAction::Trigger,- None,- None,+ call_connector_action,+ connector_request,+ return_raw_connector_response,gateway_context.clone(),).awaitdiff --git a/crates/router/src/core/payments/gateway/authorize_gateway.rs b/crates/router/src/core/payments/gateway/authorize_gateway.rsindex 633f22d584..711af43a97 100644--- a/crates/router/src/core/payments/gateway/authorize_gateway.rs+++ b/crates/router/src/core/payments/gateway/authorize_gateway.rs@@ -242,8 +242,8 @@ where.map(|raw_connector_response| raw_connector_response.expose().into());router_data.connector_http_status_code = Some(ucs_data.status_code);- ucs_data.connector_response.map(|customer_response| {- router_data.connector_response = Some(customer_response);+ ucs_data.connector_response.map(|connector_response| {+ router_data.connector_response = Some(connector_response);});Ok((router_data, (), payment_authorize_response))diff --git a/crates/router/src/core/payments/gateway/incremental_authorization_gateway.rs b/crates/router/src/core/payments/gateway/incremental_authorization_gateway.rsnew file mode 100644index 0000000000..016e7706b9--- /dev/null+++ b/crates/router/src/core/payments/gateway/incremental_authorization_gateway.rs@@ -0,0 +1,195 @@+use std::str::FromStr;++use async_trait::async_trait;+use common_enums::{CallConnectorAction, ExecutionPath};+use common_utils::{errors::CustomResult, id_type, request::Request, ucs_types};+use error_stack::ResultExt;+use hyperswitch_domain_models::{router_data::RouterData, router_flow_types as domain};+use hyperswitch_interfaces::{+ api::gateway as payment_gateway,+ connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},+ errors::ConnectorError,+};+use unified_connector_service_client::payments as payments_grpc;++use crate::{+ core::{+ payments::gateway::context::RouterGatewayContext,+ unified_connector_service::{+ self, handle_unified_connector_service_response_for_incremental_authorization,+ },+ },+ routes::SessionState,+ services::logger,+ types::{self, transformers::ForeignTryFrom},+};++// =============================================================================+// PaymentGateway Implementation for domain::IncrementalAuthorization+// =============================================================================++/// Implementation of PaymentGateway for api::IncrementalAuthorization flow+#[async_trait]+impl<RCD>+ payment_gateway::PaymentGateway<+ SessionState,+ RCD,+ Self,+ types::PaymentsIncrementalAuthorizationData,+ types::PaymentsResponseData,+ RouterGatewayContext,+ > for domain::IncrementalAuthorization+where+ RCD: Clone+ + Send+ + Sync+ + 'static+ + RouterDataConversion<+ Self,+ types::PaymentsIncrementalAuthorizationData,+ types::PaymentsResponseData,+ >,+{+ async fn execute(+ self: Box<Self>,+ state: &SessionState,+ _connector_integration: BoxedConnectorIntegrationInterface<+ Self,+ RCD,+ types::PaymentsIncrementalAuthorizationData,+ types::PaymentsResponseData,+ >,+ router_data: &RouterData<+ Self,+ types::PaymentsIncrementalAuthorizationData,+ types::PaymentsResponseData,+ >,+ _call_connector_action: CallConnectorAction,+ _connector_request: Option<Request>,+ _return_raw_connector_response: Option<bool>,+ context: RouterGatewayContext,+ ) -> CustomResult<+ RouterData<Self, types::PaymentsIncrementalAuthorizationData, types::PaymentsResponseData>,+ ConnectorError,+ > {+ let merchant_connector_account = context.merchant_connector_account;+ let platform = context.platform;+ let lineage_ids = context.lineage_ids;+ let header_payload = context.header_payload;+ let unified_connector_service_execution_mode = context.execution_mode;+ let merchant_order_reference_id = header_payload.x_reference_id.clone();+ let client = state+ .grpc_client+ .unified_connector_service_client+ .clone()+ .ok_or(ConnectorError::RequestEncodingFailed)+ .attach_printable("Failed to fetch Unified Connector Service client")?;++ let incremental_authorization_request =+ payments_grpc::PaymentServiceIncrementalAuthorizationRequest::foreign_try_from(+ router_data,+ )+ .change_context(ConnectorError::RequestEncodingFailed)+ .attach_printable("Failed to construct Payment IncrementalAuthorization Request")?;++ let connector_auth_metadata =+ unified_connector_service::build_unified_connector_service_auth_metadata(+ merchant_connector_account,+ &platform,+ router_data.connector.clone(),+ )+ .change_context(ConnectorError::RequestEncodingFailed)+ .attach_printable("Failed to construct request metadata")?;+ let merchant_reference_id = header_payload+ .x_reference_id+ .clone()+ .or(merchant_order_reference_id)+ .map(|id| id_type::PaymentReferenceId::from_str(id.as_str()))+ .transpose()+ .inspect_err(|err| logger::warn!(error=?err, "Invalid Merchant ReferenceId found"))+ .ok()+ .flatten()+ .map(ucs_types::UcsReferenceId::Payment);+ let header_payload = state+ .get_grpc_headers_ucs(unified_connector_service_execution_mode)+ .external_vault_proxy_metadata(None)+ .merchant_reference_id(merchant_reference_id)+ .lineage_ids(lineage_ids);+ let updated_router_data =+ Box::pin(unified_connector_service::ucs_logging_wrapper_granular(+ router_data.clone(),+ state,+ incremental_authorization_request,+ header_payload,+ |mut router_data, incremental_authorization_request, grpc_headers| async move {+ let response = Box::pin(client.incremental_authorization(+ incremental_authorization_request,+ connector_auth_metadata,+ grpc_headers,+ ))+ .await+ .attach_printable("Failed to in incremental authorize payment")?;++ let incremental_authorization_response = response.into_inner();++ let (router_data_response, status_code) =+ handle_unified_connector_service_response_for_incremental_authorization(+ incremental_authorization_response.clone(),+ )+ .attach_printable("Failed to deserialize UCS response")?;++ router_data.response = router_data_response;+ router_data.connector_http_status_code = Some(status_code);++ Ok((router_data, (), incremental_authorization_response))+ },+ ))+ .await+ .map(|(router_data, _)| router_data)+ .change_context(ConnectorError::ResponseHandlingFailed)?;++ Ok(updated_router_data)+ }+}++/// Implementation of FlowGateway for api::IncrementalAuthorization+///+/// This allows the flow to provide its specific gateway based on execution path+impl<RCD>+ payment_gateway::FlowGateway<+ SessionState,+ RCD,+ types::PaymentsIncrementalAuthorizationData,+ types::PaymentsResponseData,+ RouterGatewayContext,+ > for domain::IncrementalAuthorization+where+ RCD: Clone+ + Send+ + Sync+ + 'static+ + RouterDataConversion<+ Self,+ types::PaymentsIncrementalAuthorizationData,+ types::PaymentsResponseData,+ >,+{+ fn get_gateway(+ execution_path: ExecutionPath,+ ) -> Box<+ dyn payment_gateway::PaymentGateway<+ SessionState,+ RCD,+ Self,+ types::PaymentsIncrementalAuthorizationData,+ types::PaymentsResponseData,+ RouterGatewayContext,+ >,+ > {+ match execution_path {+ ExecutionPath::Direct => Box::new(payment_gateway::DirectGateway),+ ExecutionPath::UnifiedConnectorService+ | ExecutionPath::ShadowUnifiedConnectorService => Box::new(Self),+ }+ }+}diff --git a/crates/router/src/core/payments/gateway/setup_mandate.rs b/crates/router/src/core/payments/gateway/setup_mandate.rsindex 70b554e679..484d8bfc97 100644--- a/crates/router/src/core/payments/gateway/setup_mandate.rs+++ b/crates/router/src/core/payments/gateway/setup_mandate.rs@@ -145,6 +145,10 @@ whererouter_data.connector_customer = Some(connector_customer_id);});+ ucs_data.connector_response.map(|connector_response| {+ router_data.connector_response = Some(connector_response);+ });+Ok((router_data, (), setup_mandate_response))},))diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rsindex 2bfdde89f1..cc8fb004ea 100644--- a/crates/router/src/core/unified_connector_service.rs+++ b/crates/router/src/core/unified_connector_service.rs@@ -1360,6 +1360,18 @@ pub fn handle_unified_connector_service_response_for_sdk_session_token(Ok((router_data_response, status_code))}+pub fn handle_unified_connector_service_response_for_incremental_authorization(+ response: payments_grpc::PaymentServiceIncrementalAuthorizationResponse,+) -> CustomResult<(Result<PaymentsResponseData, ErrorResponse>, u16), UnifiedConnectorServiceError>+{+ let status_code = transformers::convert_connector_service_status_code(response.status_code)?;++ let router_data_response =+ Result::<PaymentsResponseData, ErrorResponse>::foreign_try_from(response)?;++ Ok((router_data_response, status_code))+}+pub fn handle_unified_connector_service_response_for_payment_authenticate(response: payments_grpc::PaymentServiceAuthenticateResponse,) -> UnifiedConnectorServiceResult {diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rsindex 859fc2ee5c..aa84ead710 100644--- a/crates/router/src/core/unified_connector_service/transformers.rs+++ b/crates/router/src/core/unified_connector_service/transformers.rs@@ -9,7 +9,7 @@ use api_models::payments::{PaypalSessionTokenResponse, PaypalTransactionInfo, SdkNextAction, SecretInfoToInitiateSdk,SessionToken, ThirdPartySdkSessionResponse,};-use common_enums::{AttemptStatus, AuthenticationType, RefundStatus};+use common_enums::{AttemptStatus, AuthenticationType, AuthorizationStatus, RefundStatus};use common_utils::{ext_traits::Encode,request::Method,@@ -24,12 +24,14 @@ use hyperswitch_domain_models::{router_flow_types::{payments::{Authorize, Capture, PSync, SetupMandate},refunds::{Execute, RSync},- unified_authentication_service as uas_flows, ExternalVaultProxy, Session,+ unified_authentication_service as uas_flows, ExternalVaultProxy, IncrementalAuthorization,+ Session,},router_request_types::{self, AuthenticationData, ExternalVaultProxyPaymentsData, PaymentsAuthorizeData,- PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,- RefundsData, SetupMandateRequestData, SyncRequestType,+ PaymentsCancelData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData,+ PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData,+ SyncRequestType,},router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},};@@ -2001,6 +2003,58 @@ impl transformers::ForeignTryFrom<&RouterData<Session, PaymentsSessionData, Paym}}+impl+ transformers::ForeignTryFrom<+ &RouterData<+ IncrementalAuthorization,+ PaymentsIncrementalAuthorizationData,+ PaymentsResponseData,+ >,+ > for payments_grpc::PaymentServiceIncrementalAuthorizationRequest+{+ type Error = error_stack::Report<UnifiedConnectorServiceError>;++ fn foreign_try_from(+ router_data: &RouterData<+ IncrementalAuthorization,+ PaymentsIncrementalAuthorizationData,+ PaymentsResponseData,+ >,+ ) -> Result<Self, Self::Error> {+ let currency = payments_grpc::Currency::foreign_try_from(router_data.request.currency)?;++ let state = router_data+ .access_token+ .as_ref()+ .map(ConnectorState::foreign_from);++ Ok(Self {+ minor_amount: router_data.request.total_amount,+ transaction_id: Some(Identifier {+ id_type: Some(payments_grpc::identifier::IdType::Id(+ router_data.request.connector_transaction_id.clone(),+ )),+ }),+ request_ref_id: Some(Identifier {+ id_type: Some(payments_grpc::identifier::IdType::Id(+ router_data.connector_request_reference_id.clone(),+ )),+ }),+ currency: currency.into(),+ reason: router_data.request.reason.clone(),+ connector_metadata: router_data+ .request+ .connector_meta+ .as_ref()+ .map(serde_json::to_string)+ .transpose()+ .change_context(UnifiedConnectorServiceError::RequestEncodingFailed)?+ .map(|s| s.into()),+ state,+ })+ }+}+impl transformers::ForeignTryFrom<payments_grpc::PaymentServicePreAuthenticateResponse>for Result<(PaymentsResponseData, AttemptStatus), ErrorResponse>{@@ -4019,6 +4073,43 @@ impl transformers::ForeignTryFrom<payments_grpc::PaymentServiceCreatePaymentMeth}}+impl transformers::ForeignTryFrom<payments_grpc::PaymentServiceIncrementalAuthorizationResponse>+ for Result<PaymentsResponseData, ErrorResponse>+{+ type Error = error_stack::Report<UnifiedConnectorServiceError>;++ fn foreign_try_from(+ response: payments_grpc::PaymentServiceIncrementalAuthorizationResponse,+ ) -> Result<Self, Self::Error> {+ let status_code = convert_connector_service_status_code(response.status_code)?;++ let response = if response.error_code.is_some() {+ Err(ErrorResponse {+ code: response.error_code().to_owned(),+ message: response.error_message().to_owned(),+ reason: response.error_reason,+ status_code,+ attempt_status: None,+ connector_transaction_id: None,+ connector_response_reference_id: None,+ network_decline_code: None,+ network_advice_code: None,+ network_error_message: None,+ connector_metadata: None,+ })+ } else {+ Ok(PaymentsResponseData::IncrementalAuthorizationResponse {+ status: AuthorizationStatus::foreign_from(response.status()),+ connector_authorization_id: response.connector_authorization_id,+ error_code: response.error_code,+ error_message: response.error_message,+ })+ };++ Ok(response)+ }+}+impl transformers::ForeignTryFrom<payments_grpc::PaymentServiceSdkSessionTokenResponse>for Result<PaymentsResponseData, ErrorResponse>{@@ -4684,6 +4775,18 @@ impl ForeignFrom<&SyncRequestType> for payments_grpc::SyncRequestType {}}+impl ForeignFrom<payments_grpc::AuthorizationStatus> for AuthorizationStatus {+ fn foreign_from(grpc_status: payments_grpc::AuthorizationStatus) -> Self {+ match grpc_status {+ payments_grpc::AuthorizationStatus::AuthorizationSuccess => Self::Success,+ payments_grpc::AuthorizationStatus::AuthorizationFailure => Self::Failure,+ payments_grpc::AuthorizationStatus::AuthorizationProcessing => Self::Processing,+ payments_grpc::AuthorizationStatus::AuthorizationUnresolved => Self::Unresolved,+ payments_grpc::AuthorizationStatus::Unspecified => Self::Processing,+ }+ }+}+impl ForeignFrom<&common_types::payments::BillingDescriptor> for payments_grpc::BillingDescriptor {fn foreign_from(billing_descriptor: &common_types::payments::BillingDescriptor) -> Self {Self {