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: implement UCS granular Session Token create Flow (#10364)
Hrithikesh27f5dce90202
diff --git a/crates/external_services/src/grpc_client/unified_connector_service.rs b/crates/external_services/src/grpc_client/unified_connector_service.rsindex adb6c62752..572be007cb 100644--- a/crates/external_services/src/grpc_client/unified_connector_service.rs+++ b/crates/external_services/src/grpc_client/unified_connector_service.rs@@ -246,6 +246,37 @@ impl UnifiedConnectorServiceClient {})}+ /// Performs Payment Session token create+ pub async fn payment_session_token_create(+ &self,+ payment_create_session_token_request: payments_grpc::PaymentServiceCreateSessionTokenRequest,+ connector_auth_metadata: ConnectorAuthMetadata,+ grpc_headers: GrpcHeadersUcs,+ ) -> UnifiedConnectorServiceResult<+ tonic::Response<payments_grpc::PaymentServiceCreateSessionTokenResponse>,+ > {+ let mut request = tonic::Request::new(payment_create_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()+ .create_session_token(request)+ .await+ .change_context(UnifiedConnectorServiceError::PaymentCreateSessionTokenFailure)+ .inspect_err(|error| {+ logger::error!(+ grpc_error=?error,+ method="create_session_token",+ connector_name=?connector_name,+ "UCS payment create_session_token gRPC call failed"+ )+ })+ }+/// Performs Payment Post Authenticatepub async fn payment_post_authenticate(&self,diff --git a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rsindex 29a6f35bb6..5174d2b644 100644--- a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs+++ b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs@@ -79,23 +79,23 @@ pub enum UnifiedConnectorServiceError {HeaderInjectionFailed(String),/// Failed to perform Payment Authorize from gRPC Server- #[error("Failed to perform Payment Authorize from gRPC Server")]+ #[error("Failed to perform. Granular Payment Authorize from gRPC Server")]PaymentAuthorizeGranularFailure,/// Failed to perform Payment Authorize from gRPC Server- #[error("Failed to perform Payment Authorize from gRPC Server")]+ #[error("Failed to perform Payment Session Token Create from gRPC Server")]PaymentCreateSessionTokenFailure,/// Failed to perform Payment Authorize from gRPC Server- #[error("Failed to perform Payment Authorize from gRPC Server")]+ #[error("Failed to perform Payment Access Token Create from gRPC Server")]PaymentCreateAccessTokenFailure,/// Failed to perform Payment Authorize from gRPC Server- #[error("Failed to perform Payment Authorize from gRPC Server")]+ #[error("Failed to perform Payment Method Token Create from gRPC Server")]PaymentMethodTokenCreateFailure,/// Failed to perform Payment Authorize from gRPC Server- #[error("Failed to perform Payment Authorize from gRPC Server")]+ #[error("Failed to perform Connector Customer Create from gRPC Server")]PaymentConnectorCustomerCreateFailure,/// Failed to perform Payment Authorize from gRPC Server@@ -111,7 +111,7 @@ pub enum UnifiedConnectorServiceError {PaymentAuthenticateFailure,/// Failed to perform Payment Authenticate from gRPC Server- #[error("Failed to perform Payment Poat Authenticate from gRPC Server")]+ #[error("Failed to perform Payment Post Authenticate from gRPC Server")]PaymentPostAuthenticateFailure,/// Failed to perform Payment Get from gRPC Serverdiff --git a/crates/router/src/core/payments/gateway.rs b/crates/router/src/core/payments/gateway.rsindex 4c83b668a5..0afe118ecb 100644--- a/crates/router/src/core/payments/gateway.rs+++ b/crates/router/src/core/payments/gateway.rs@@ -1,7 +1,7 @@pub mod authorize_gateway;pub mod context;pub mod psync_gateway;-+pub mod session_token_gateway;use std::sync;use hyperswitch_domain_models::router_flow_types::payments;diff --git a/crates/router/src/core/payments/gateway/session_token_gateway.rs b/crates/router/src/core/payments/gateway/session_token_gateway.rsnew file mode 100644index 0000000000..5c985e9cd4--- /dev/null+++ b/crates/router/src/core/payments/gateway/session_token_gateway.rs@@ -0,0 +1,186 @@+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,+ unified_connector_service::handle_unified_connector_service_response_for_session_token_create,+ },+ routes::SessionState,+ services::logger,+ types::{self, transformers::ForeignTryFrom},+};++// =============================================================================+// PaymentGateway Implementation for domain::AuthorizeSessionToken+// =============================================================================++/// Implementation of PaymentGateway for api::PSync flow+#[async_trait]+impl<RCD>+ payment_gateway::PaymentGateway<+ SessionState,+ RCD,+ Self,+ types::AuthorizeSessionTokenData,+ types::PaymentsResponseData,+ RouterGatewayContext,+ > for domain::AuthorizeSessionToken+where+ RCD: Clone+ + Send+ + Sync+ + 'static+ + RouterDataConversion<Self, types::AuthorizeSessionTokenData, types::PaymentsResponseData>,+{+ async fn execute(+ self: Box<Self>,+ state: &SessionState,+ _connector_integration: BoxedConnectorIntegrationInterface<+ Self,+ RCD,+ types::AuthorizeSessionTokenData,+ types::PaymentsResponseData,+ >,+ router_data: &RouterData<+ Self,+ types::AuthorizeSessionTokenData,+ types::PaymentsResponseData,+ >,+ _call_connector_action: CallConnectorAction,+ _connector_request: Option<Request>,+ _return_raw_connector_response: Option<bool>,+ context: RouterGatewayContext,+ ) -> CustomResult<+ RouterData<Self, types::AuthorizeSessionTokenData, 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 authorize_session_token_request =+ payments_grpc::PaymentServiceCreateSessionTokenRequest::foreign_try_from(router_data)+ .change_context(ConnectorError::RequestEncodingFailed)+ .attach_printable("Failed to construct Payment Session Create 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,+ authorize_session_token_request,+ header_payload,+ |mut router_data, authorize_session_token_request, grpc_headers| async move {+ let response = client+ .payment_session_token_create(+ authorize_session_token_request,+ connector_auth_metadata,+ grpc_headers,+ )+ .await+ .attach_printable("Failed to get payment")?;++ let payment_session_token_response = response.into_inner();++ let (router_data_response, status_code) =+ handle_unified_connector_service_response_for_session_token_create(+ payment_session_token_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;+ router_data.connector_http_status_code = Some(status_code);++ Ok((router_data, payment_session_token_response))+ },+ ))+ .await+ .change_context(ConnectorError::ResponseHandlingFailed)?;++ Ok(updated_router_data)+ }+}++/// Implementation of FlowGateway for api::PSync+///+/// This allows the flow to provide its specific gateway based on execution path+impl<RCD>+ payment_gateway::FlowGateway<+ SessionState,+ RCD,+ types::AuthorizeSessionTokenData,+ types::PaymentsResponseData,+ RouterGatewayContext,+ > for domain::AuthorizeSessionToken+where+ RCD: Clone+ + Send+ + Sync+ + 'static+ + RouterDataConversion<Self, types::AuthorizeSessionTokenData, types::PaymentsResponseData>,+{+ fn get_gateway(+ execution_path: ExecutionPath,+ ) -> Box<+ dyn payment_gateway::PaymentGateway<+ SessionState,+ RCD,+ Self,+ types::AuthorizeSessionTokenData,+ 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.rsindex 396e913266..723214c707 100644--- a/crates/router/src/core/unified_connector_service.rs+++ b/crates/router/src/core/unified_connector_service.rs@@ -1233,6 +1233,17 @@ pub fn handle_unified_connector_service_response_for_payment_register(})}+pub fn handle_unified_connector_service_response_for_session_token_create(+ response: payments_grpc::PaymentServiceCreateSessionTokenResponse,+) -> 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_repeat(response: payments_grpc::PaymentServiceRepeatEverythingResponse,) -> CustomResult<UcsRepeatPaymentResponseData, UnifiedConnectorServiceError> {diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rsindex bd3fa708cc..c263e710c9 100644--- a/crates/router/src/core/unified_connector_service/transformers.rs+++ b/crates/router/src/core/unified_connector_service/transformers.rs@@ -3,7 +3,7 @@ use std::{collections::HashMap, str::FromStr};use common_enums::{AttemptStatus, AuthenticationType, RefundStatus};use common_utils::{ext_traits::Encode, request::Method, types};use diesel_models::enums as storage_enums;-use error_stack::ResultExt;+use error_stack::{report, ResultExt};use external_services::grpc_client::unified_connector_service::UnifiedConnectorServiceError;use hyperswitch_domain_models::{mandates::MandateData,@@ -331,6 +331,47 @@ impl})}}++impl+ transformers::ForeignTryFrom<+ &RouterData<+ api::AuthorizeSessionToken,+ router_request_types::AuthorizeSessionTokenData,+ PaymentsResponseData,+ >,+ > for payments_grpc::PaymentServiceCreateSessionTokenRequest+{+ type Error = error_stack::Report<UnifiedConnectorServiceError>;+ fn foreign_try_from(+ router_data: &RouterData<+ api::AuthorizeSessionToken,+ router_request_types::AuthorizeSessionTokenData,+ 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+ .amount+ .ok_or(report!(UnifiedConnectorServiceError::RequestEncodingFailed))?,+ currency: currency.into(),+ minor_amount: router_data+ .request+ .amount+ .ok_or(report!(UnifiedConnectorServiceError::RequestEncodingFailed))?,+ metadata: HashMap::new(),+ state: None,+ browser_info: None,+ })+ }+}+impltransformers::ForeignTryFrom<&RouterData<@@ -2583,6 +2624,44 @@ impl transformers::ForeignTryFrom<&MandateData> for payments_grpc::SetupMandateD}}+impl transformers::ForeignTryFrom<payments_grpc::PaymentServiceCreateSessionTokenResponse>+ for Result<(PaymentsResponseData, AttemptStatus), ErrorResponse>+{+ type Error = error_stack::Report<UnifiedConnectorServiceError>;++ fn foreign_try_from(+ response: payments_grpc::PaymentServiceCreateSessionTokenResponse,+ ) -> 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 {+ // For session token creation, we typically return a successful response with the session token+ // Since this is not a standard payment response, we'll create a simple success response+ Ok((+ PaymentsResponseData::SessionTokenResponse {+ session_token: response.session_token.clone(),+ },+ AttemptStatus::Charged, // Assuming successful creation+ ))+ };++ Ok(response)+ }+}+impltransformers::ForeignTryFrom<&hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,