Skip to content

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

feat(core): Added Capture flow support for Hyperswitch <> UCS Integration (#9735)

Saptak Duttab354d63bd58f
diff --git a/crates/external_services/src/grpc_client/unified_connector_service.rs b/crates/external_services/src/grpc_client/unified_connector_service.rs
index a4b0f71156..d78e5e8981 100644
--- a/crates/external_services/src/grpc_client/unified_connector_service.rs
+++ b/crates/external_services/src/grpc_client/unified_connector_service.rs
@@ -198,6 +198,36 @@ impl UnifiedConnectorServiceClient {
})
}
+ /// Performs Payment Capture
+ pub async fn payment_capture(
+ &self,
+ payment_capture_request: payments_grpc::PaymentServiceCaptureRequest,
+ connector_auth_metadata: ConnectorAuthMetadata,
+ grpc_headers: GrpcHeadersUcs,
+ ) -> UnifiedConnectorServiceResult<tonic::Response<payments_grpc::PaymentServiceCaptureResponse>>
+ {
+ let mut request = tonic::Request::new(payment_capture_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()
+ .capture(request)
+ .await
+ .change_context(UnifiedConnectorServiceError::PaymentCaptureFailure)
+ .inspect_err(|error| {
+ logger::error!(
+ grpc_error=?error,
+ method="payment_capture",
+ connector_name=?connector_name,
+ "UCS payment capture gRPC call failed"
+ )
+ })
+ }
+
/// Performs Payment Setup Mandate
pub async fn payment_setup_mandate(
&self,
diff --git a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
index ab94501e2b..65a64a4a2d 100644
--- a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
+++ b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
@@ -81,6 +81,10 @@ pub enum UnifiedConnectorServiceError {
#[error("Failed to perform Payment Get from gRPC Server")]
PaymentGetFailure,
+ /// Failed to perform Payment Capture from gRPC Server
+ #[error("Failed to perform Payment Capture from gRPC Server")]
+ PaymentCaptureFailure,
+
/// Failed to perform Payment Setup Mandate from gRPC Server
#[error("Failed to perform Setup Mandate from gRPC Server")]
PaymentRegisterFailure,
diff --git a/crates/router/src/core/payments/flows/capture_flow.rs b/crates/router/src/core/payments/flows/capture_flow.rs
index d761a163a5..581cf6ad83 100644
--- a/crates/router/src/core/payments/flows/capture_flow.rs
+++ b/crates/router/src/core/payments/flows/capture_flow.rs
@@ -1,14 +1,27 @@
+use std::str::FromStr;
+
use async_trait::async_trait;
+use common_utils::{id_type, types::MinorUnit, ucs_types};
+use error_stack::ResultExt;
+use external_services::grpc_client;
+use hyperswitch_domain_models::{
+ errors::api_error_response::ApiErrorResponse, payments as domain_payments,
+};
+use unified_connector_service_client::payments as payments_grpc;
use super::ConstructFlowSpecificData;
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
payments::{self, access_token, helpers, transformers, Feature, PaymentData},
+ unified_connector_service::{
+ build_unified_connector_service_auth_metadata,
+ handle_unified_connector_service_response_for_payment_capture, ucs_logging_wrapper,
+ },
},
routes::SessionState,
- services,
- types::{self, api, domain},
+ services::{self, logger},
+ types::{self, api, domain, transformers::ForeignTryFrom},
};
#[cfg(feature = "v1")]
@@ -160,4 +173,97 @@ impl Feature<api::Capture, types::PaymentsCaptureData>
Ok((request, true))
}
+
+ async fn call_unified_connector_service<'a>(
+ &mut self,
+ state: &SessionState,
+ header_payload: &domain_payments::HeaderPayload,
+ lineage_ids: grpc_client::LineageIds,
+ #[cfg(feature = "v1")] merchant_connector_account: helpers::MerchantConnectorAccountType,
+ #[cfg(feature = "v2")]
+ merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
+ merchant_context: &domain::MerchantContext,
+ _connector_data: &api::ConnectorData,
+ unified_connector_service_execution_mode: common_enums::ExecutionMode,
+ merchant_order_reference_id: Option<String>,
+ _call_connector_action: common_enums::CallConnectorAction,
+ ) -> RouterResult<()> {
+ let client = state
+ .grpc_client
+ .unified_connector_service_client
+ .clone()
+ .ok_or(ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to fetch Unified Connector Service client")?;
+
+ let payment_capture_request =
+ payments_grpc::PaymentServiceCaptureRequest::foreign_try_from(&*self)
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to construct Payment Capture Request")?;
+
+ let connector_auth_metadata = build_unified_connector_service_auth_metadata(
+ merchant_connector_account,
+ merchant_context,
+ )
+ .change_context(ApiErrorResponse::InternalServerError)
+ .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(ucs_logging_wrapper(
+ self.clone(),
+ state,
+ payment_capture_request,
+ header_payload,
+ |mut router_data, payment_capture_request, grpc_headers| async move {
+ let response = client
+ .payment_capture(
+ payment_capture_request,
+ connector_auth_metadata,
+ grpc_headers,
+ )
+ .await
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to capture payment")?;
+
+ let payment_capture_response = response.into_inner();
+
+ let (router_data_response, status_code) =
+ handle_unified_connector_service_response_for_payment_capture(
+ payment_capture_response.clone(),
+ )
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to deserialize UCS response")?;
+
+ let router_data_response = router_data_response.map(|(response, status)| {
+ router_data.status = status;
+ response
+ });
+ router_data.response = router_data_response;
+ router_data.amount_captured = payment_capture_response.captured_amount;
+ router_data.minor_amount_captured = payment_capture_response
+ .minor_captured_amount
+ .map(MinorUnit::new);
+ router_data.connector_http_status_code = Some(status_code);
+
+ Ok((router_data, payment_capture_response))
+ },
+ ))
+ .await?;
+
+ // Copy back the updated data
+ *self = updated_router_data;
+ Ok(())
+ }
}
diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rs
index 2ef7d89488..2339d62dc9 100644
--- a/crates/router/src/core/unified_connector_service.rs
+++ b/crates/router/src/core/unified_connector_service.rs
@@ -770,6 +770,17 @@ pub fn handle_unified_connector_service_response_for_payment_authorize(
Ok((router_data_response, status_code))
}
+pub fn handle_unified_connector_service_response_for_payment_capture(
+ response: payments_grpc::PaymentServiceCaptureResponse,
+) -> UnifiedConnectorServiceResult {
+ let status_code = transformers::convert_connector_service_status_code(response.status_code)?;
+
+ let router_data_response =
+ Result::<(PaymentsResponseData, AttemptStatus), ErrorResponse>::foreign_try_from(response)?;
+
+ Ok((router_data_response, status_code))
+}
+
pub fn handle_unified_connector_service_response_for_payment_register(
response: payments_grpc::PaymentServiceRegisterResponse,
) -> UnifiedConnectorServiceResult {
diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rs
index 9ef122958d..1f90deec2c 100644
--- a/crates/router/src/core/unified_connector_service/transformers.rs
+++ b/crates/router/src/core/unified_connector_service/transformers.rs
@@ -8,12 +8,12 @@ use external_services::grpc_client::unified_connector_service::UnifiedConnectorS
use hyperswitch_domain_models::{
router_data::{ErrorResponse, RouterData},
router_flow_types::{
- payments::{Authorize, PSync, SetupMandate},
+ payments::{Authorize, Capture, PSync, SetupMandate},
ExternalVaultProxy,
},
router_request_types::{
AuthenticationData, ExternalVaultProxyPaymentsData, PaymentsAuthorizeData,
- PaymentsCancelData, PaymentsSyncData, SetupMandateRequestData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSyncData, SetupMandateRequestData,
},
router_response_types::{PaymentsResponseData, RedirectForm},
};
@@ -118,6 +118,71 @@ impl
}
}
+impl transformers::ForeignTryFrom<&RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>>
+ for payments_grpc::PaymentServiceCaptureRequest
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(
+ router_data: &RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>,
+ ) -> Result<Self, Self::Error> {
+ let connector_transaction_id = router_data.request.connector_transaction_id.clone();
+
+ let currency = payments_grpc::Currency::foreign_try_from(router_data.request.currency)?;
+
+ let browser_info = router_data
+ .request
+ .browser_info
+ .clone()
+ .map(payments_grpc::BrowserInformation::foreign_try_from)
+ .transpose()?;
+
+ let capture_method = router_data
+ .request
+ .capture_method
+ .map(payments_grpc::CaptureMethod::foreign_try_from)
+ .transpose()?;
+
+ Ok(Self {
+ transaction_id: Some(Identifier {
+ id_type: Some(payments_grpc::identifier::IdType::Id(
+ connector_transaction_id,
+ )),
+ }),
+ request_ref_id: Some(Identifier {
+ id_type: Some(payments_grpc::identifier::IdType::Id(
+ router_data.connector_request_reference_id.clone(),
+ )),
+ }),
+ access_token: None,
+ amount_to_capture: router_data
+ .request
+ .minor_amount_to_capture
+ .get_amount_as_i64(),
+ currency: currency.into(),
+ capture_method: capture_method.map(|capture_method| capture_method.into()),
+ connector_metadata: router_data
+ .request
+ .metadata
+ .as_ref()
+ .and_then(|val| val.as_object())
+ .map(|map| {
+ map.iter()
+ .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
+ .collect::<HashMap<String, String>>()
+ })
+ .unwrap_or_default(),
+ browser_info,
+ multiple_capture_data: router_data.request.multiple_capture_data.as_ref().map(
+ |multiple_capture_request_data| payments_grpc::MultipleCaptureRequestData {
+ capture_sequence: multiple_capture_request_data.capture_sequence.into(),
+ capture_reference: multiple_capture_request_data.capture_reference.clone(),
+ },
+ ),
+ })
+ }
+}
+
impl
transformers::ForeignTryFrom<
&RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>,
@@ -365,7 +430,7 @@ impl
.collect::<HashMap<String, String>>()
})
.unwrap_or_default(),
- test_mode: None,
+ test_mode: router_data.test_mode,
connector_customer_id: router_data.connector_customer.clone(),
merchant_account_metadata: HashMap::new(),
})
@@ -556,7 +621,7 @@ impl
.clone()
.map(|e| e.expose().expose().into()),
browser_info,
- test_mode: None,
+ test_mode: router_data.test_mode,
payment_method_type: None,
access_token: None,
merchant_account_metadata: HashMap::new(),
@@ -660,6 +725,83 @@ impl transformers::ForeignTryFrom<payments_grpc::PaymentServiceAuthorizeResponse
}
}
+impl transformers::ForeignTryFrom<payments_grpc::PaymentServiceCaptureResponse>
+ for Result<(PaymentsResponseData, AttemptStatus), ErrorResponse>
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(
+ response: payments_grpc::PaymentServiceCaptureResponse,
+ ) -> Result<Self, Self::Error> {
+ let connector_response_reference_id =
+ response.response_ref_id.as_ref().and_then(|identifier| {
+ identifier
+ .id_type
+ .clone()
+ .and_then(|id_type| match id_type {
+ payments_grpc::identifier::IdType::Id(id) => Some(id),
+ payments_grpc::identifier::IdType::EncodedData(encoded_data) => {
+ Some(encoded_data)
+ }
+ payments_grpc::identifier::IdType::NoResponseIdMarker(_) => None,
+ })
+ });
+
+ let status_code = convert_connector_service_status_code(response.status_code)?;
+
+ let resource_id: hyperswitch_domain_models::router_request_types::ResponseId = match response.transaction_id.as_ref().and_then(|id| id.id_type.clone()) {
+ Some(payments_grpc::identifier::IdType::Id(id)) => hyperswitch_domain_models::router_request_types::ResponseId::ConnectorTransactionId(id),
+ Some(payments_grpc::identifier::IdType::EncodedData(encoded_data)) => hyperswitch_domain_models::router_request_types::ResponseId::EncodedData(encoded_data),
+ Some(payments_grpc::identifier::IdType::NoResponseIdMarker(_)) | None => hyperswitch_domain_models::router_request_types::ResponseId::NoResponseId,
+ };
+
+ let response = if response.error_code.is_some() {
+ let attempt_status = match response.status() {
+ payments_grpc::PaymentStatus::AttemptStatusUnspecified => None,
+ _ => Some(AttemptStatus::foreign_try_from(response.status())?),
+ };
+
+ Err(ErrorResponse {
+ code: response.error_code().to_owned(),
+ message: response.error_message().to_owned(),
+ reason: Some(response.error_message().to_owned()),
+ status_code,
+ attempt_status,
+ connector_transaction_id: connector_response_reference_id,
+ network_decline_code: None,
+ network_advice_code: None,
+ network_error_message: None,
+ connector_metadata: None,
+ })
+ } else {
+ let status = AttemptStatus::foreign_try_from(response.status())?;
+
+ Ok((
+ PaymentsResponseData::TransactionResponse {
+ resource_id,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(response.mandate_reference.map(|grpc_mandate| {
+ hyperswitch_domain_models::router_response_types::MandateReference {
+ connector_mandate_id: grpc_mandate.mandate_id,
+ payment_method_id: grpc_mandate.payment_method_id,
+ mandate_metadata: None,
+ connector_mandate_request_reference_id: None,
+ }
+ })),
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id,
+ incremental_authorization_allowed: response.incremental_authorization_allowed,
+ charges: None,
+ },
+ status,
+ ))
+ };
+
+ Ok(response)
+ }
+}
+
impl transformers::ForeignTryFrom<payments_grpc::PaymentServiceRegisterResponse>
for Result<(PaymentsResponseData, AttemptStatus), ErrorResponse>
{