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): Add UCS authentication and post-authentication flows for payment processing (#9959)
Hrithikesh558f60bb3d0f
diff --git a/crates/external_services/src/grpc_client.rs b/crates/external_services/src/grpc_client.rsindex 5352c81c27..e33cbc7a62 100644--- a/crates/external_services/src/grpc_client.rs+++ b/crates/external_services/src/grpc_client.rs@@ -182,7 +182,7 @@ pub type GrpcHeadersUcsBuilderFinal = GrpcHeadersUcsBuilder<()>;/// struct to represent set of Lineage ids-#[derive(Debug, serde::Serialize)]+#[derive(Debug, Clone, serde::Serialize)]pub struct LineageIds {merchant_id: id_type::MerchantId,profile_id: id_type::ProfileId,diff --git a/crates/external_services/src/grpc_client/unified_connector_service.rs b/crates/external_services/src/grpc_client/unified_connector_service.rsindex fd39db5c3b..cec3f4bb4f 100644--- a/crates/external_services/src/grpc_client/unified_connector_service.rs+++ b/crates/external_services/src/grpc_client/unified_connector_service.rs@@ -182,6 +182,70 @@ impl UnifiedConnectorServiceClient {})}+ /// Performs Payment Authenticate+ pub async fn payment_authenticate(+ &self,+ payment_authenticate_request: payments_grpc::PaymentServiceAuthenticateRequest,+ connector_auth_metadata: ConnectorAuthMetadata,+ grpc_headers: GrpcHeadersUcs,+ ) -> UnifiedConnectorServiceResult<+ tonic::Response<payments_grpc::PaymentServiceAuthenticateResponse>,+ > {+ let mut request = tonic::Request::new(payment_authenticate_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()+ .authenticate(request)+ .await+ .change_context(UnifiedConnectorServiceError::PaymentAuthenticateFailure)+ .inspect_err(|error| {+ logger::error!(+ grpc_error=?error,+ method="payment_pre_authenticate",+ connector_name=?connector_name,+ "UCS payment pre authenticate gRPC call failed"+ )+ })+ }++ /// Performs Payment Post Authenticate+ pub async fn payment_post_authenticate(+ &self,+ payment_post_authenticate_request: payments_grpc::PaymentServicePostAuthenticateRequest,+ connector_auth_metadata: ConnectorAuthMetadata,+ grpc_headers: GrpcHeadersUcs,+ ) -> UnifiedConnectorServiceResult<+ tonic::Response<payments_grpc::PaymentServicePostAuthenticateResponse>,+ > {+ let mut request = tonic::Request::new(payment_post_authenticate_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()+ .post_authenticate(request)+ .await+ .change_context(UnifiedConnectorServiceError::PaymentPostAuthenticateFailure)+ .inspect_err(|error| {+ logger::error!(+ grpc_error=?error,+ method="payment_pre_authenticate",+ connector_name=?connector_name,+ "UCS payment pre authenticate gRPC call failed"+ )+ })+ }+/// Performs Payment Authorizepub async fn payment_authorize(&self,diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rsindex f89c22d7b7..639cbc026c 100644--- a/crates/hyperswitch_domain_models/src/router_request_types.rs+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs@@ -689,35 +689,26 @@ pub struct PaymentsPostAuthenticateData {pub amount: Option<i64>,pub email: Option<pii::Email>,pub currency: Option<storage_enums::Currency>,- pub payment_method_type: Option<storage_enums::PaymentMethodType>,- pub router_return_url: Option<String>,- pub complete_authorize_url: Option<String>,pub browser_info: Option<BrowserInformation>,pub connector_transaction_id: Option<String>,- pub enrolled_for_3ds: bool,pub redirect_response: Option<CompleteAuthorizeRedirectResponse>,-// New amount for amount frame workpub minor_amount: Option<MinorUnit>,}-impl TryFrom<PaymentsAuthorizeData> for PaymentsPostAuthenticateData {+impl TryFrom<CompleteAuthorizeData> for PaymentsPostAuthenticateData {type Error = error_stack::Report<ApiErrorResponse>;- fn try_from(data: PaymentsAuthorizeData) -> Result<Self, Self::Error> {+ fn try_from(data: CompleteAuthorizeData) -> Result<Self, Self::Error> {Ok(Self {- payment_method_data: Some(data.payment_method_data),+ payment_method_data: data.payment_method_data,amount: Some(data.amount),minor_amount: Some(data.minor_amount),email: data.email,currency: Some(data.currency),- payment_method_type: data.payment_method_type,- router_return_url: data.router_return_url,- complete_authorize_url: data.complete_authorize_url,browser_info: data.browser_info,connector_transaction_id: None,redirect_response: None,- enrolled_for_3ds: data.enrolled_for_3ds,})}}diff --git a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rsindex 678328f9d8..84b887369f 100644--- a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs+++ b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs@@ -86,6 +86,14 @@ pub enum UnifiedConnectorServiceError {#[error("Failed to perform Payment Pre Authenticate from gRPC Server")]PaymentPreAuthenticateFailure,+ /// Failed to perform Payment Authenticate from gRPC Server+ #[error("Failed to perform Payment Authenticate from gRPC Server")]+ PaymentAuthenticateFailure,++ /// Failed to perform Payment Authenticate from gRPC Server+ #[error("Failed to perform Payment Poat Authenticate from gRPC Server")]+ PaymentPostAuthenticateFailure,+/// Failed to perform Payment Get from gRPC Server#[error("Failed to perform Payment Get from gRPC Server")]PaymentGetFailure,diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rsindex e77f5b51f1..8e22eaaf2d 100644--- a/crates/router/src/core/payments/flows/authorize_flow.rs+++ b/crates/router/src/core/payments/flows/authorize_flow.rs@@ -10,6 +10,7 @@ use external_services::grpc_client;use hyperswitch_domain_models::payments::PaymentConfirmData;use hyperswitch_domain_models::{errors::api_error_response::ApiErrorResponse, payments as domain_payments,+ router_response_types,};use hyperswitch_interfaces::{api as api_interface, api::ConnectorSpecifications};use masking::ExposeInterface;@@ -591,6 +592,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAulineage_ids,merchant_connector_account,merchant_context,+ connector_data.connector_name,unified_connector_service_execution_mode,merchant_order_reference_id,)@@ -1008,6 +1010,84 @@ async fn call_unified_connector_service_authorize(*router_data = updated_router_data;Ok(())}+fn transform_redirection_response_for_pre_authenticate_flow(+ connector: enums::connector_enums::Connector,+ response_data: router_response_types::RedirectForm,+) -> RouterResult<router_response_types::RedirectForm> {+ match (connector, &response_data) {+ (+ enums::connector_enums::Connector::Cybersource,+ router_response_types::RedirectForm::Form {+ endpoint,+ method: _,+ ref form_fields,+ },+ ) => {+ let access_token = form_fields.get("access_token").cloned().ok_or(+ ApiErrorResponse::MissingRequiredField {+ field_name: "access_token",+ },+ )?;+ let ddc_url = form_fields.get("ddc_url").unwrap_or(endpoint).clone();+ let reference_id = form_fields.get("reference_id").cloned().ok_or(+ ApiErrorResponse::MissingRequiredField {+ field_name: "reference_id",+ },+ )?;+ Ok(router_response_types::RedirectForm::CybersourceAuthSetup {+ access_token,+ ddc_url,+ reference_id,+ })+ }+ _ => Ok(response_data),+ }+}+fn transform_response_for_pre_authenticate_flow(+ connector: enums::connector_enums::Connector,+ response_data: router_response_types::PaymentsResponseData,+) -> RouterResult<router_response_types::PaymentsResponseData> {+ match (connector, response_data.clone()) {+ (+ enums::connector_enums::Connector::Cybersource,+ router_response_types::PaymentsResponseData::TransactionResponse {+ resource_id,+ redirection_data,+ mandate_reference,+ connector_metadata,+ network_txn_id,+ connector_response_reference_id,+ incremental_authorization_allowed,+ charges,+ },+ ) => {+ let redirection_data = Box::new(+ (*redirection_data)+ .clone()+ .map(|redirection_data| {+ transform_redirection_response_for_pre_authenticate_flow(+ connector,+ redirection_data,+ )+ })+ .transpose()?,+ );+ Ok(+ router_response_types::PaymentsResponseData::TransactionResponse {+ resource_id,+ redirection_data,+ mandate_reference,+ connector_metadata,+ network_txn_id,+ connector_response_reference_id,+ incremental_authorization_allowed,+ charges,+ },+ )+ }+ _ => Ok(response_data),+ }+}#[allow(clippy::too_many_arguments)]async fn call_unified_connector_service_pre_authenticate(@@ -1022,6 +1102,7 @@ async fn call_unified_connector_service_pre_authenticate(#[cfg(feature = "v1")] merchant_connector_account: helpers::MerchantConnectorAccountType,#[cfg(feature = "v2")] merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,merchant_context: &domain::MerchantContext,+ connector: enums::connector_enums::Connector,unified_connector_service_execution_mode: enums::ExecutionMode,merchant_order_reference_id: Option<String>,) -> RouterResult<()> {@@ -1085,6 +1166,10 @@ async fn call_unified_connector_service_pre_authenticate(router_data.status = status;response});+ let router_data_response = match router_data_response {+ Ok(response) => Ok(transform_response_for_pre_authenticate_flow(connector, response)?),+ Err(err) => Err(err)+ };router_data.response = router_data_response;router_data.raw_connector_response = payment_pre_authenticate_response.raw_connector_responsediff --git a/crates/router/src/core/payments/flows/complete_authorize_flow.rs b/crates/router/src/core/payments/flows/complete_authorize_flow.rsindex 6f72dfbc96..6206599064 100644--- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs+++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs@@ -1,14 +1,24 @@+use std::str::FromStr;+use async_trait::async_trait;+use common_enums::connector_enums;+use common_utils::{id_type, ucs_types};+use error_stack::ResultExt;use external_services::grpc_client;+use hyperswitch_domain_models::router_response_types;use hyperswitch_interfaces::{api as api_interface, api::ConnectorSpecifications};-use masking::ExposeInterface;+use masking::{self, ExposeInterface};+use unified_connector_service_client::payments as payments_grpc;+use unified_connector_service_masking::ExposeInterface as UcsMaskingExposeInterface;use super::{ConstructFlowSpecificData, Feature};use crate::{core::{errors::{ApiErrorResponse, ConnectorErrorExt, RouterResult},payments::{self, access_token, helpers, transformers, PaymentData},+ unified_connector_service as ucs_core,},+ logger,routes::{metrics, SessionState},services,types::{self, api, domain, transformers::ForeignTryFrom},@@ -242,7 +252,7 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData>self,state,header_payload,- lineage_ids,+ lineage_ids.clone(),merchant_connector_account.clone(),merchant_context,connector_data,@@ -292,20 +302,20 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData>#[allow(clippy::too_many_arguments)]async fn handle_preprocessing_through_unified_connector_service(- router_data: types::RouterData<+ mut router_data: types::RouterData<api::CompleteAuthorize,types::CompleteAuthorizeData,types::PaymentsResponseData,>,- _state: &SessionState,- _header_payload: &hyperswitch_domain_models::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>,+ state: &SessionState,+ header_payload: &hyperswitch_domain_models::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>,preprocessing_flow_name: api_interface::PreProcessingFlowName,) -> RouterResult<types::RouterData<@@ -316,16 +326,363 @@ async fn handle_preprocessing_through_unified_connector_service(> {match preprocessing_flow_name {api_interface::PreProcessingFlowName::Authenticate => {+ // Convert CompleteAuthorize to Authenticate for UCS call+ let complete_authorize_request_data = router_data.request.clone();+ let authenticate_request_data =+ types::PaymentsAuthenticateData::try_from(router_data.request.to_owned())?;+ let authenticate_response_data: Result<+ types::PaymentsResponseData,+ types::ErrorResponse,+ > = Err(types::ErrorResponse::default());+ let mut authenticate_router_data =+ helpers::router_data_type_conversion::<_, api::Authenticate, _, _, _, _>(+ router_data.clone(),+ authenticate_request_data,+ authenticate_response_data,+ );+// Call UCS for Authenticate flow+ call_unified_connector_service_authenticate(+ &mut authenticate_router_data,+ state,+ header_payload,+ lineage_ids,+ merchant_connector_account,+ merchant_context,+ connector_data.connector_name,+ unified_connector_service_execution_mode,+ merchant_order_reference_id,+ )+ .await?;++ // Convert back to CompleteAuthorize router data while preserving preprocessing response data+ let authenticate_response = authenticate_router_data.response.clone();+ let complete_authorize_router_data =+ helpers::router_data_type_conversion::<_, api::CompleteAuthorize, _, _, _, _>(+ authenticate_router_data,+ complete_authorize_request_data,+ authenticate_response,+ );+ router_data = complete_authorize_router_data;+Ok(router_data)}api_interface::PreProcessingFlowName::PostAuthenticate => {+ // Convert CompleteAuthorize to PostAuthenticate for UCS call+ let complete_authorize_request_data = router_data.request.clone();+ let post_authenticate_request_data =+ types::PaymentsPostAuthenticateData::try_from(router_data.request.to_owned())?;+ let post_authenticate_response_data: Result<+ types::PaymentsResponseData,+ types::ErrorResponse,+ > = Err(types::ErrorResponse::default());+ let mut post_authenticate_router_data =+ helpers::router_data_type_conversion::<_, api::PostAuthenticate, _, _, _, _>(+ router_data.clone(),+ post_authenticate_request_data,+ post_authenticate_response_data,+ );+// Call UCS for PostAuthenticate flow+ call_unified_connector_service_post_authenticate(+ &mut post_authenticate_router_data,+ state,+ header_payload,+ lineage_ids,+ merchant_connector_account,+ merchant_context,+ unified_connector_service_execution_mode,+ merchant_order_reference_id,+ )+ .await?;++ // Convert back to CompleteAuthorize router data while preserving preprocessing response data+ let post_authenticate_response = post_authenticate_router_data.response.clone();+ let complete_authorize_router_data =+ helpers::router_data_type_conversion::<_, api::CompleteAuthorize, _, _, _, _>(+ post_authenticate_router_data,+ complete_authorize_request_data,+ post_authenticate_response,+ );+ router_data = complete_authorize_router_data;+Ok(router_data)}}}+fn transform_redirection_response_for_authenticate_flow(+ connector: connector_enums::Connector,+ response_data: router_response_types::RedirectForm,+) -> RouterResult<router_response_types::RedirectForm> {+ match (connector, &response_data) {+ (+ connector_enums::Connector::Cybersource,+ router_response_types::RedirectForm::Form {+ endpoint,+ method: _,+ ref form_fields,+ },+ ) => {+ let access_token = form_fields.get("access_token").cloned().ok_or(+ ApiErrorResponse::MissingRequiredField {+ field_name: "access_token",+ },+ )?;+ let step_up_url = form_fields.get("step_up_url").unwrap_or(endpoint).clone();+ Ok(+ router_response_types::RedirectForm::CybersourceConsumerAuth {+ access_token,+ step_up_url,+ },+ )+ }+ _ => Ok(response_data),+ }+}+fn transform_response_for_authenticate_flow(+ connector: connector_enums::Connector,+ response_data: router_response_types::PaymentsResponseData,+) -> RouterResult<router_response_types::PaymentsResponseData> {+ match (connector, response_data.clone()) {+ (+ connector_enums::Connector::Cybersource,+ router_response_types::PaymentsResponseData::TransactionResponse {+ resource_id,+ redirection_data,+ mandate_reference,+ connector_metadata,+ network_txn_id,+ connector_response_reference_id,+ incremental_authorization_allowed,+ charges,+ },+ ) => {+ let redirection_data = Box::new(+ (*redirection_data)+ .clone()+ .map(|redirection_data| {+ transform_redirection_response_for_authenticate_flow(+ connector,+ redirection_data,+ )+ })+ .transpose()?,+ );+ Ok(+ router_response_types::PaymentsResponseData::TransactionResponse {+ resource_id,+ redirection_data,+ mandate_reference,+ connector_metadata,+ network_txn_id,+ connector_response_reference_id,+ incremental_authorization_allowed,+ charges,+ },+ )+ }+ _ => Ok(response_data),+ }+}++#[allow(dead_code, clippy::too_many_arguments)]+async fn call_unified_connector_service_authenticate(+ router_data: &mut types::RouterData<+ api::Authenticate,+ types::PaymentsAuthenticateData,+ types::PaymentsResponseData,+ >,+ state: &SessionState,+ header_payload: &hyperswitch_domain_models::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: connector_enums::Connector,+ unified_connector_service_execution_mode: common_enums::ExecutionMode,+ merchant_order_reference_id: Option<String>,+) -> 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_authenticate_request =+ payments_grpc::PaymentServiceAuthenticateRequest::foreign_try_from(&*router_data)+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to construct Payment Authorize Request")?;++ let connector_auth_metadata = ucs_core::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 headers_builder = 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_core::ucs_logging_wrapper(+ router_data.clone(),+ state,+ payment_authenticate_request,+ headers_builder,+ |mut router_data, payment_authenticate_request, grpc_headers| async move {+ let response = client+ .payment_authenticate(+ payment_authenticate_request,+ connector_auth_metadata,+ grpc_headers,+ )+ .await+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to authorize payment")?;++ let payment_authenticate_response = response.into_inner();++ let (router_data_response, status_code) =+ ucs_core::handle_unified_connector_service_response_for_payment_authenticate(+ payment_authenticate_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+ });+ let router_data_response = match router_data_response {+ Ok(response) => Ok(transform_response_for_authenticate_flow(+ connector, response,+ )?),+ Err(err) => Err(err),+ };+ router_data.response = router_data_response;+ router_data.raw_connector_response = payment_authenticate_response+ .raw_connector_response+ .clone()+ .map(|raw_connector_response| raw_connector_response.expose().into());+ router_data.connector_http_status_code = Some(status_code);++ Ok((router_data, payment_authenticate_response))+ },+ ))+ .await?;++ // Copy back the updated data+ *router_data = updated_router_data;+ Ok(())+}++#[allow(dead_code, clippy::too_many_arguments)]+async fn call_unified_connector_service_post_authenticate(+ router_data: &mut types::RouterData<+ api::PostAuthenticate,+ types::PaymentsPostAuthenticateData,+ types::PaymentsResponseData,+ >,+ state: &SessionState,+ header_payload: &hyperswitch_domain_models::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,+ unified_connector_service_execution_mode: common_enums::ExecutionMode,+ merchant_order_reference_id: Option<String>,+) -> 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_post_authenticate_request =+ payments_grpc::PaymentServicePostAuthenticateRequest::foreign_try_from(&*router_data)+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to construct Payment Authorize Request")?;++ let connector_auth_metadata = ucs_core::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 headers_builder = 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_core::ucs_logging_wrapper(+ router_data.clone(),+ state,+ payment_post_authenticate_request,+ headers_builder,+ |mut router_data, payment_post_authenticate_request, grpc_headers| async move {+ let response = client+ .payment_post_authenticate(+ payment_post_authenticate_request,+ connector_auth_metadata,+ grpc_headers,+ )+ .await+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to authorize payment")?;++ let payment_post_authenticate_response = response.into_inner();++ let (router_data_response, status_code) =+ ucs_core::handle_unified_connector_service_response_for_payment_post_authenticate(+ payment_post_authenticate_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.raw_connector_response = payment_post_authenticate_response+ .raw_connector_response+ .clone()+ .map(|raw_connector_response| raw_connector_response.expose().into());+ router_data.connector_http_status_code = Some(status_code);++ Ok((router_data, payment_post_authenticate_response))+ },+ ))+ .await?;++ // Copy back the updated data+ *router_data = updated_router_data;+ Ok(())+}+pub async fn complete_authorize_preprocessing_steps<F: Clone>(state: &SessionState,router_data: &types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>,diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rsindex e0917f26f8..2f652a5da8 100644--- a/crates/router/src/core/unified_connector_service.rs+++ b/crates/router/src/core/unified_connector_service.rs@@ -1003,6 +1003,28 @@ pub fn handle_unified_connector_service_response_for_payment_authorize(})}+pub fn handle_unified_connector_service_response_for_payment_post_authenticate(+ response: payments_grpc::PaymentServicePostAuthenticateResponse,+) -> 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_authenticate(+ response: payments_grpc::PaymentServiceAuthenticateResponse,+) -> 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_pre_authenticate(response: payments_grpc::PaymentServicePreAuthenticateResponse,) -> UnifiedConnectorServiceResult {diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rsindex db15bef26d..e2914bf4c1 100644--- a/crates/router/src/core/unified_connector_service/transformers.rs+++ b/crates/router/src/core/unified_connector_service/transformers.rs@@ -119,6 +119,137 @@ impl})}}+impl+ transformers::ForeignTryFrom<+ &RouterData<+ uas_flows::Authenticate,+ router_request_types::PaymentsAuthenticateData,+ PaymentsResponseData,+ >,+ > for payments_grpc::PaymentServiceAuthenticateRequest+{+ type Error = error_stack::Report<UnifiedConnectorServiceError>;+ fn foreign_try_from(+ router_data: &RouterData<+ uas_flows::Authenticate,+ router_request_types::PaymentsAuthenticateData,+ PaymentsResponseData,+ >,+ ) -> Result<Self, Self::Error> {+ // Based on the pattern from PaymentServicePreAuthenticateRequest+ let currency = payments_grpc::Currency::foreign_try_from(+ router_data.request.currency.unwrap_or_default(),+ )?;++ let payment_method = router_data+ .request+ .payment_method_data+ .clone()+ .map(|payment_method_data| {+ unified_connector_service::build_unified_connector_service_payment_method(+ payment_method_data,+ common_enums::PaymentMethodType::Credit, // Default to Credit for now+ )+ })+ .transpose()?;++ let address = payments_grpc::PaymentAddress::foreign_try_from(router_data.address.clone())?;++ 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.unwrap_or(0),+ currency: currency.into(),+ minor_amount: router_data+ .request+ .minor_amount+ .map(|amount| amount.get_amount_as_i64())+ .unwrap_or(0),+ payment_method,+ email: router_data+ .request+ .clone()+ .map(|e| e.expose().expose().into()),+ customer_name: None, // PaymentsAuthenticateData doesn't have customer_name+ address: Some(address),+ authentication_data: None, // PaymentsAuthenticateData doesn't have enrolled_for_3ds+ metadata: HashMap::new(), // PaymentsAuthenticateData doesn't have metadata+ return_url: None, // PaymentsAuthenticateData doesn't have router_return_url+ continue_redirection_url: router_data.request.complete_authorize_url.clone(),+ access_token: None,+ browser_info: router_data+ .request+ .browser_info+ .clone()+ .map(payments_grpc::BrowserInformation::foreign_try_from)+ .transpose()?,+ })+ }+}++impl+ transformers::ForeignTryFrom<+ &RouterData<+ uas_flows::PostAuthenticate,+ router_request_types::PaymentsPostAuthenticateData,+ PaymentsResponseData,+ >,+ > for payments_grpc::PaymentServicePostAuthenticateRequest+{+ type Error = error_stack::Report<UnifiedConnectorServiceError>;+ fn foreign_try_from(+ router_data: &RouterData<+ uas_flows::PostAuthenticate,+ router_request_types::PaymentsPostAuthenticateData,+ PaymentsResponseData,+ >,+ ) -> Result<Self, Self::Error> {+ // Based on the pattern from PaymentServicePreAuthenticateRequest+ let currency = payments_grpc::Currency::foreign_try_from(+ router_data.request.currency.unwrap_or_default(),+ )?;++ let address = payments_grpc::PaymentAddress::foreign_try_from(router_data.address.clone())?;++ 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.unwrap_or(0),+ currency: currency.into(),+ minor_amount: router_data+ .request+ .minor_amount+ .map(|amount| amount.get_amount_as_i64())+ .unwrap_or(0),+ payment_method: None,+ email: router_data+ .request+ .clone()+ .map(|e| e.expose().expose().into()),+ customer_name: None, // PaymentsPostAuthenticateData doesn't have customer_name+ address: Some(address),+ authentication_data: None,+ metadata: HashMap::new(),+ return_url: None,+ continue_redirection_url: None,+ access_token: None,+ browser_info: router_data+ .request+ .browser_info+ .clone()+ .map(payments_grpc::BrowserInformation::foreign_try_from)+ .transpose()?,+ })+ }+}impltransformers::ForeignTryFrom<@@ -804,31 +935,11 @@ impl transformers::ForeignTryFrom<payments_grpc::PaymentServicePreAuthenticateRe}};- let (connector_metadata, redirection_data) = match response.redirection_data.clone() {- Some(redirection_data) => match redirection_data.form_type {- Some(ref form_type) => match form_type {- payments_grpc::redirect_form::FormType::Uri(uri) => {- // For UPI intent, store the URI in connector_metadata for SDK UPI intent pattern- let sdk_uri_info = api_models::payments::SdkUpiIntentInformation {- sdk_uri: Url::parse(&uri.uri)- .change_context(UnifiedConnectorServiceError::ParsingFailed)?,- };- (- Some(sdk_uri_info.encode_to_value())- .transpose()- .change_context(UnifiedConnectorServiceError::ParsingFailed)?,- None,- )- }- _ => (- None,- Some(RedirectForm::foreign_try_from(redirection_data)).transpose()?,- ),- },- None => (None, None),- },- None => (None, None),- };+ let redirection_data = response+ .redirection_data+ .clone()+ .map(RedirectForm::foreign_try_from)+ .transpose()?;let status_code = convert_connector_service_status_code(response.status_code)?;@@ -858,7 +969,7 @@ impl transformers::ForeignTryFrom<payments_grpc::PaymentServicePreAuthenticateReresource_id,redirection_data: Box::new(redirection_data),mandate_reference: Box::new(None),- connector_metadata,+ connector_metadata: None,network_txn_id: response.network_txn_id.clone(),connector_response_reference_id,incremental_authorization_allowed: None,@@ -1044,7 +1155,6 @@ impl transformers::ForeignTryFrom<payments_grpc::PaymentServiceCaptureResponse>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(),@@ -1059,7 +1169,6 @@ impl transformers::ForeignTryFrom<payments_grpc::PaymentServiceCaptureResponse>})} else {let status = AttemptStatus::foreign_try_from(response.status())?;-Ok((PaymentsResponseData::TransactionResponse {resource_id,@@ -1081,7 +1190,6 @@ impl transformers::ForeignTryFrom<payments_grpc::PaymentServiceCaptureResponse>status,))};-Ok(response)}}@@ -1570,6 +1678,216 @@ impl transformers::ForeignTryFrom<storage_enums::FutureUsage> for payments_grpc:}}+impl transformers::ForeignTryFrom<payments_grpc::PaymentServicePostAuthenticateResponse>+ for Result<(PaymentsResponseData, AttemptStatus), ErrorResponse>+{+ type Error = error_stack::Report<UnifiedConnectorServiceError>;+ fn foreign_try_from(+ response: payments_grpc::PaymentServicePostAuthenticateResponse,+ ) -> 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 resource_id: router_request_types::ResponseId = match response+ .transaction_id+ .as_ref()+ .and_then(|id| id.id_type.clone())+ {+ Some(payments_grpc::identifier::IdType::Id(id)) => {+ router_request_types::ResponseId::ConnectorTransactionId(id)+ }+ Some(payments_grpc::identifier::IdType::EncodedData(encoded_data)) => {+ router_request_types::ResponseId::EncodedData(encoded_data)+ }+ Some(payments_grpc::identifier::IdType::NoResponseIdMarker(_)) | None => {+ router_request_types::ResponseId::NoResponseId+ }+ };++ let (connector_metadata, redirection_data) = match response.redirection_data.clone() {+ Some(redirection_data) => match redirection_data.form_type {+ Some(ref form_type) => match form_type {+ payments_grpc::redirect_form::FormType::Uri(uri) => {+ // For UPI intent, store the URI in connector_metadata for SDK UPI intent pattern+ let sdk_uri_info = api_models::payments::SdkUpiIntentInformation {+ sdk_uri: Url::parse(&uri.uri)+ .change_context(UnifiedConnectorServiceError::ParsingFailed)?,+ };+ (+ Some(sdk_uri_info.encode_to_value())+ .transpose()+ .change_context(UnifiedConnectorServiceError::ParsingFailed)?,+ None,+ )+ }+ _ => (+ None,+ Some(RedirectForm::foreign_try_from(redirection_data)).transpose()?,+ ),+ },+ None => (None, None),+ },+ None => (None, None),+ };++ let status_code = convert_connector_service_status_code(response.status_code)?;++ 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(redirection_data),+ mandate_reference: Box::new(None),+ connector_metadata,+ network_txn_id: response.network_txn_id.clone(),+ connector_response_reference_id,+ incremental_authorization_allowed: None,+ charges: None,+ },+ status,+ ))+ };++ Ok(response)+ }+}++impl transformers::ForeignTryFrom<payments_grpc::PaymentServiceAuthenticateResponse>+ for Result<(PaymentsResponseData, AttemptStatus), ErrorResponse>+{+ type Error = error_stack::Report<UnifiedConnectorServiceError>;+ fn foreign_try_from(+ response: payments_grpc::PaymentServiceAuthenticateResponse,+ ) -> 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 resource_id: router_request_types::ResponseId = match response+ .transaction_id+ .as_ref()+ .and_then(|id| id.id_type.clone())+ {+ Some(payments_grpc::identifier::IdType::Id(id)) => {+ router_request_types::ResponseId::ConnectorTransactionId(id)+ }+ Some(payments_grpc::identifier::IdType::EncodedData(encoded_data)) => {+ router_request_types::ResponseId::EncodedData(encoded_data)+ }+ Some(payments_grpc::identifier::IdType::NoResponseIdMarker(_)) | None => {+ router_request_types::ResponseId::NoResponseId+ }+ };++ let (connector_metadata, redirection_data) = match response.redirection_data.clone() {+ Some(redirection_data) => match redirection_data.form_type {+ Some(ref form_type) => match form_type {+ payments_grpc::redirect_form::FormType::Uri(uri) => {+ // For UPI intent, store the URI in connector_metadata for SDK UPI intent pattern+ let sdk_uri_info = api_models::payments::SdkUpiIntentInformation {+ sdk_uri: Url::parse(&uri.uri)+ .change_context(UnifiedConnectorServiceError::ParsingFailed)?,+ };+ (+ Some(sdk_uri_info.encode_to_value())+ .transpose()+ .change_context(UnifiedConnectorServiceError::ParsingFailed)?,+ None,+ )+ }+ _ => (+ None,+ Some(RedirectForm::foreign_try_from(redirection_data)).transpose()?,+ ),+ },+ None => (None, None),+ },+ None => (None, None),+ };++ let status_code = convert_connector_service_status_code(response.status_code)?;++ 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(redirection_data),+ mandate_reference: Box::new(None),+ connector_metadata,+ network_txn_id: response.network_txn_id.clone(),+ connector_response_reference_id,+ incremental_authorization_allowed: None,+ charges: None,+ },+ status,+ ))+ };++ Ok(response)+ }+}+impl transformers::ForeignTryFrom<common_types::payments::CustomerAcceptance>for payments_grpc::CustomerAcceptance{diff --git a/crates/router/src/types.rs b/crates/router/src/types.rsindex 2cff2a4d02..adc21e2ea3 100644--- a/crates/router/src/types.rs+++ b/crates/router/src/types.rs@@ -74,15 +74,16 @@ pub use hyperswitch_domain_models::{CreateOrderRequestData, DefendDisputeRequestData, DestinationChargeRefund,DirectChargeRefund, DisputeSyncData, ExternalVaultProxyPaymentsData,FetchDisputesRequestData, MandateRevokeRequestData, MultipleCaptureRequestData,- PaymentMethodTokenizationData, PaymentsApproveData, PaymentsAuthorizeData,- PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData,- PaymentsExtendAuthorizationData, PaymentsIncrementalAuthorizationData,- PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreAuthenticateData,- PaymentsPreProcessingData, PaymentsRejectData, PaymentsSessionData, PaymentsSyncData,- PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RefundsData, ResponseId,- RetrieveFileRequestData, SdkPaymentsSessionUpdateData, SetupMandateRequestData,- SplitRefundsRequest, SubmitEvidenceRequestData, SyncRequestType, UploadFileRequestData,- VaultRequestData, VerifyWebhookSourceRequestData,+ PaymentMethodTokenizationData, PaymentsApproveData, PaymentsAuthenticateData,+ PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData,+ PaymentsCaptureData, PaymentsExtendAuthorizationData, PaymentsIncrementalAuthorizationData,+ PaymentsPostAuthenticateData, PaymentsPostProcessingData, PaymentsPostSessionTokensData,+ PaymentsPreAuthenticateData, PaymentsPreProcessingData, PaymentsRejectData,+ PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData,+ PaymentsUpdateMetadataData, RefundsData, ResponseId, RetrieveFileRequestData,+ SdkPaymentsSessionUpdateData, SetupMandateRequestData, SplitRefundsRequest,+ SubmitEvidenceRequestData, SyncRequestType, UploadFileRequestData, VaultRequestData,+ VerifyWebhookSourceRequestData,},router_response_types::{revenue_recovery::{