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(router): Add create order granular flow (#10379)

Anurag Thakurb1ec9a292e24
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 063ab2387a..24b7d86400 100644
--- a/crates/external_services/src/grpc_client/unified_connector_service.rs
+++ b/crates/external_services/src/grpc_client/unified_connector_service.rs
@@ -213,6 +213,37 @@ impl UnifiedConnectorServiceClient {
})
}
+ /// Performs Payment Create Order
+ pub async fn payment_create_order(
+ &self,
+ payment_create_order_request: payments_grpc::PaymentServiceCreateOrderRequest,
+ connector_auth_metadata: ConnectorAuthMetadata,
+ grpc_headers: GrpcHeadersUcs,
+ ) -> UnifiedConnectorServiceResult<
+ tonic::Response<payments_grpc::PaymentServiceCreateOrderResponse>,
+ > {
+ let mut request = tonic::Request::new(payment_create_order_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()
+ .create_order(request)
+ .await
+ .change_context(UnifiedConnectorServiceError::PaymentCreateOrderFailure)
+ .inspect_err(|error| {
+ logger::error!(
+ grpc_error=?error,
+ method="create_order",
+ connector_name=?connector_name,
+ "UCS create_order gRPC call failed"
+ )
+ })
+ }
+
/// Performs Payment Pre Authenticate
pub async fn payment_pre_authenticate(
&self,
diff --git a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
index 5174d2b644..b9562061d0 100644
--- a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
+++ b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
@@ -78,6 +78,10 @@ pub enum UnifiedConnectorServiceError {
#[error("Failed to inject metadata into request headers: {0}")]
HeaderInjectionFailed(String),
+ /// Failed to perform Create Order from gRPC Server
+ #[error("Failed to perform Create Order from gRPC Server")]
+ PaymentCreateOrderFailure,
+
/// Failed to perform Payment Authorize from gRPC Server
#[error("Failed to perform. Granular Payment Authorize from gRPC Server")]
PaymentAuthorizeGranularFailure,
diff --git a/crates/router/src/core/payments/gateway.rs b/crates/router/src/core/payments/gateway.rs
index 082cbf73d4..31d45d593e 100644
--- a/crates/router/src/core/payments/gateway.rs
+++ b/crates/router/src/core/payments/gateway.rs
@@ -2,6 +2,7 @@ pub mod access_token_gateway;
pub mod authorize_gateway;
pub mod context;
pub mod create_customer_gateway;
+pub mod create_order_gateway;
pub mod psync_gateway;
pub mod session_token_gateway;
use std::sync;
diff --git a/crates/router/src/core/payments/gateway/create_order_gateway.rs b/crates/router/src/core/payments/gateway/create_order_gateway.rs
new file mode 100644
index 0000000000..8d34177920
--- /dev/null
+++ b/crates/router/src/core/payments/gateway/create_order_gateway.rs
@@ -0,0 +1,180 @@
+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_create_order,
+ },
+ },
+ routes::SessionState,
+ services::logger,
+ types::{self, transformers::ForeignTryFrom},
+};
+
+// =============================================================================
+// PaymentGateway Implementation for domain::CreateOrder
+// =============================================================================
+
+/// Implementation of PaymentGateway for api::CreateOrder flow
+#[async_trait]
+impl<RCD>
+ payment_gateway::PaymentGateway<
+ SessionState,
+ RCD,
+ Self,
+ types::CreateOrderRequestData,
+ types::PaymentsResponseData,
+ RouterGatewayContext,
+ > for domain::CreateOrder
+where
+ RCD: Clone
+ + Send
+ + Sync
+ + 'static
+ + RouterDataConversion<Self, types::CreateOrderRequestData, types::PaymentsResponseData>,
+{
+ async fn execute(
+ self: Box<Self>,
+ state: &SessionState,
+ _connector_integration: BoxedConnectorIntegrationInterface<
+ Self,
+ RCD,
+ types::CreateOrderRequestData,
+ types::PaymentsResponseData,
+ >,
+ router_data: &RouterData<Self, types::CreateOrderRequestData, types::PaymentsResponseData>,
+ _call_connector_action: CallConnectorAction,
+ _connector_request: Option<Request>,
+ _return_raw_connector_response: Option<bool>,
+ context: RouterGatewayContext,
+ ) -> CustomResult<
+ RouterData<Self, types::CreateOrderRequestData, 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 create_order_request =
+ payments_grpc::PaymentServiceCreateOrderRequest::foreign_try_from(router_data)
+ .change_context(ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to construct Payment Create Order Request")?;
+
+ let connector_auth_metadata =
+ unified_connector_service::build_unified_connector_service_auth_metadata(
+ merchant_connector_account,
+ &platform,
+ )
+ .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_new(
+ router_data.clone(),
+ state,
+ create_order_request,
+ header_payload,
+ |mut router_data, create_order_request, grpc_headers| async move {
+ let response = Box::pin(client.payment_create_order(
+ create_order_request,
+ connector_auth_metadata,
+ grpc_headers,
+ ))
+ .await
+ .attach_printable("Failed to create order")?;
+
+ let create_order_response = response.into_inner();
+
+ let (router_data_response, _status_code) =
+ handle_unified_connector_service_response_for_create_order(
+ create_order_response.clone(),
+ )
+ .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;
+ Ok((router_data, create_order_response))
+ },
+ ))
+ .await
+ .change_context(ConnectorError::ResponseHandlingFailed)?;
+
+ Ok(updated_router_data)
+ }
+}
+
+/// Implementation of FlowGateway for api::CreateOrder
+///
+/// This allows the flow to provide its specific gateway based on execution path
+impl<RCD>
+ payment_gateway::FlowGateway<
+ SessionState,
+ RCD,
+ types::CreateOrderRequestData,
+ types::PaymentsResponseData,
+ RouterGatewayContext,
+ > for domain::CreateOrder
+where
+ RCD: Clone
+ + Send
+ + Sync
+ + 'static
+ + RouterDataConversion<Self, types::CreateOrderRequestData, types::PaymentsResponseData>,
+{
+ fn get_gateway(
+ execution_path: ExecutionPath,
+ ) -> Box<
+ dyn payment_gateway::PaymentGateway<
+ SessionState,
+ RCD,
+ Self,
+ types::CreateOrderRequestData,
+ 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/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rs
index 6a76d29ea2..066b443c07 100644
--- a/crates/router/src/core/unified_connector_service.rs
+++ b/crates/router/src/core/unified_connector_service.rs
@@ -1169,6 +1169,17 @@ pub fn handle_unified_connector_service_response_for_create_connector_customer(
Ok((connector_customer_result, status_code))
}
+pub fn handle_unified_connector_service_response_for_create_order(
+ response: payments_grpc::PaymentServiceCreateOrderResponse,
+) -> 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_post_authenticate(
response: payments_grpc::PaymentServicePostAuthenticateResponse,
) -> UnifiedConnectorServiceResult {
diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rs
index 6d864da8ed..a591b9b04c 100644
--- a/crates/router/src/core/unified_connector_service/transformers.rs
+++ b/crates/router/src/core/unified_connector_service/transformers.rs
@@ -241,6 +241,39 @@ impl
}
}
+impl
+ transformers::ForeignTryFrom<
+ &RouterData<
+ api::CreateOrder,
+ router_request_types::CreateOrderRequestData,
+ PaymentsResponseData,
+ >,
+ > for payments_grpc::PaymentServiceCreateOrderRequest
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+ fn foreign_try_from(
+ router_data: &RouterData<
+ api::CreateOrder,
+ router_request_types::CreateOrderRequestData,
+ PaymentsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ let currency = payments_grpc::Currency::foreign_try_from(router_data.request.currency)?;
+ Ok(Self {
+ request_ref_id: Some(Identifier {
+ id_type: Some(payments_grpc::identifier::IdType::Id(
+ router_data.connector_request_reference_id.clone(),
+ )),
+ }),
+ amount: router_data.request.minor_amount.get_amount_as_i64(),
+ currency: currency.into(),
+
+ metadata: HashMap::new(),
+ webhook_url: None,
+ })
+ }
+}
+
impl
transformers::ForeignTryFrom<(
&RouterData<
@@ -2671,6 +2704,54 @@ impl ForeignFrom<common_enums::TransactionStatus> for payments_grpc::Transaction
}
}
+impl transformers::ForeignTryFrom<payments_grpc::PaymentServiceCreateOrderResponse>
+ for Result<(PaymentsResponseData, AttemptStatus), ErrorResponse>
+{
+ type Error = error_stack::Report<UnifiedConnectorServiceError>;
+
+ fn foreign_try_from(
+ response: payments_grpc::PaymentServiceCreateOrderResponse,
+ ) -> 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: Some(response.error_message().to_owned()),
+ status_code,
+ attempt_status: None,
+ connector_transaction_id: None,
+ network_decline_code: None,
+ network_advice_code: None,
+ network_error_message: None,
+ connector_metadata: None,
+ })
+ } else {
+ let order_id = response
+ .order_id
+ .and_then(|id| id.id_type)
+ .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,
+ })
+ .ok_or(UnifiedConnectorServiceError::ResponseDeserializationFailed)?;
+
+ // For order creation, we typically return a successful response with the order_id
+ // Since this is not a standard payment response, we'll create a simple success response
+ Ok((
+ PaymentsResponseData::PaymentsCreateOrderResponse { order_id },
+ AttemptStatus::Charged, // Assuming successful creation
+ ))
+ };
+
+ Ok(response)
+ }
+}
+
impl transformers::ForeignTryFrom<payments_grpc::PaymentServiceAuthenticateResponse>
for Result<(PaymentsResponseData, AttemptStatus), ErrorResponse>
{