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
refactor: Simplify payment processing flow and unify gateway context handling v2 (#10774)
Hrithikesh45b7d287163e
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex b1a8a21e99..a712634ec1 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -5018,62 +5018,45 @@ where).await?;- let profile_id = payment_data.get_payment_intent().profile_id.clone();- let default_gateway_context = gateway_context::RouterGatewayContext::direct(- platform.clone(),- merchant_connector_account_type_details.clone(),- payment_data.get_payment_intent().merchant_id.clone(),- profile_id,- payment_data.get_creds_identifier().map(|id| id.to_string()),+ let lineage_ids = grpc_client::LineageIds::new(+ business_profile.merchant_id.clone(),+ business_profile.get_id().clone(),);- let (connector_request, should_continue_further) =- if matches!(execution_path, ExecutionPath::Direct) {- let mut should_continue_further = true;+ let execution_mode = match execution_path {+ ExecutionPath::UnifiedConnectorService => ExecutionMode::Primary,+ ExecutionPath::ShadowUnifiedConnectorService => ExecutionMode::Shadow,+ // ExecutionMode is irrelevant for Direct path in this context+ ExecutionPath::Direct => ExecutionMode::NotApplicable,+ };- let should_continue = match router_data- .create_order_at_connector(- state,- &connector,- should_continue_further,- &default_gateway_context,- )- .await?- {- Some(create_order_response) => {- if let Ok(order_id) = create_order_response.clone().create_order_result {- payment_data.set_connector_response_reference_id(Some(order_id))- }+ let gateway_context = gateway_context::RouterGatewayContext {+ creds_identifier: payment_data.get_creds_identifier().map(|id| id.to_string()),+ platform: platform.clone(),+ header_payload: header_payload.clone(),+ lineage_ids,+ merchant_connector_account: merchant_connector_account_type_details.clone(),+ execution_path,+ execution_mode,+ };- // Set the response in routerdata response to carry forward- router_data.update_router_data_with_create_order_response(- create_order_response.clone(),- );- create_order_response.create_order_result.ok().map(|_| ())- }- // If create order is not required, then we can proceed with further processing- None => Some(()),- };+ let should_continue = match router_data+ .create_order_at_connector(state, &connector, true, &gateway_context)+ .await?+ {+ Some(create_order_response) => {+ if let Ok(order_id) = create_order_response.clone().create_order_result {+ payment_data.set_connector_response_reference_id(Some(order_id))+ }- let should_continue: (Option<common_utils::request::Request>, bool) =- match should_continue {- Some(_) => {- router_data- .build_flow_specific_connector_request(- state,- &connector,- call_connector_action.clone(),- )- .await?- }- None => (None, false),- };- should_continue- } else {- // If unified connector service is called, these values are not used- // as the request is built in the unified connector service call- (None, false)- };+ // Set the response in routerdata response to carry forward+ router_data+ .update_router_data_with_create_order_response(create_order_response.clone());+ create_order_response.create_order_result.is_ok()+ }+ // If create order is not required, then we can proceed with further processing+ None => true,+ };(_, *payment_data) = operation.to_update_tracker()?@@ -5088,45 +5071,27 @@ where).await?;- record_time_taken_with(|| async {- if matches!(execution_path, ExecutionPath::UnifiedConnectorService) {- router_env::logger::info!(- "Processing payment through UCS gateway system- payment_id={}, attempt_id={}",- payment_data.get_payment_intent().id.get_string_repr(),- payment_data.get_payment_attempt().id.get_string_repr()- );- let lineage_ids = grpc_client::LineageIds::new(business_profile.merchant_id.clone(), business_profile.get_id().clone());-- // Extract merchant_order_reference_id from payment data for UCS audit trail- let merchant_order_reference_id = payment_data.get_payment_intent().merchant_reference_id- .clone()- .map(|id| id.get_string_repr().to_string());- let creds_identifier = payment_data.get_creds_identifier().map(str::to_owned);-- router_data- .call_unified_connector_service(- state,- &header_payload,- lineage_ids,- merchant_connector_account_type_details.clone(),- platform,- &connector,- ExecutionMode::Primary, // UCS is called in primary mode- merchant_order_reference_id,- call_connector_action,- creds_identifier,- )- .await?;-- Ok(router_data)- } else {- Err(- errors::ApiErrorResponse::InternalServerError+ if should_continue {+ // The status of payment_attempt and intent will be updated in the previous step+ // update this in router_data.+ // This is added because few connector integrations do not update the status,+ // and rely on previous status set in router_data+ router_data.status = payment_data.get_payment_attempt().status;+ router_data+ .decide_flows(+ state,+ &connector,+ call_connector_action,+ None,+ business_profile,+ header_payload.clone(),+ return_raw_connector_response,+ gateway_context,)- .attach_printable("Unified connector service is down and traditional connector service fallback is not implemented")- }- })- .await+ .await+ } else {+ Ok(router_data)+ }}#[cfg(feature = "v2")]diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rsindex 9922309f8b..ee6e935da3 100644--- a/crates/router/src/core/payments/flows.rs+++ b/crates/router/src/core/payments/flows.rs@@ -256,30 +256,6 @@ pub trait Feature<F, T> {) {}- #[cfg(feature = "v2")]- 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,- _platform: &domain::Platform,- _connector_data: &api::ConnectorData,- _unified_connector_service_execution_mode: common_enums::ExecutionMode,- _merchant_order_reference_id: Option<String>,- _call_connector_action: common_enums::CallConnectorAction,- _creds_identifier: Option<String>,- ) -> RouterResult<()>- where- F: Clone,- Self: Sized,- dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>,- {- Ok(())- }-#[cfg(feature = "v2")]async fn call_unified_connector_service_with_external_vault_proxy<'a>(&mut self,diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rsindex 046c683c65..8064275724 100644--- a/crates/router/src/core/payments/flows/authorize_flow.rs+++ b/crates/router/src/core/payments/flows/authorize_flow.rs@@ -588,106 +588,6 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu}}}-- #[cfg(feature = "v2")]- 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,- platform: &domain::Platform,- connector_data: &api::ConnectorData,- unified_connector_service_execution_mode: enums::ExecutionMode,- merchant_order_reference_id: Option<String>,- _call_connector_action: common_enums::CallConnectorAction,- creds_identifier: Option<String>,- ) -> RouterResult<()> {- if self.request.mandate_id.is_some() {- Box::pin(call_unified_connector_service_repeat_payment(- self,- state,- header_payload,- lineage_ids,- merchant_connector_account,- platform,- unified_connector_service_execution_mode,- merchant_order_reference_id,- creds_identifier,- ))- .await- } else {- let alternate_flow = connector_data.connector.get_alternate_flow_if_needed(- api_interface::CurrentFlowInfo::Authorize {- auth_type: &self.auth_type,- request_data: &self.request,- },- );- match alternate_flow {- Some(api_interface::AlternateFlow::PreAuthenticate) => {- let authorize_request_data = self.request.clone();- let pre_authneticate_request_data =- types::PaymentsPreAuthenticateData::try_from(self.request.to_owned())?;- let pre_authneticate_response_data: Result<- types::PaymentsResponseData,- types::ErrorResponse,- > = Err(types::ErrorResponse::default());- let pre_authenticate_router_data = helpers::router_data_type_conversion::<- _,- api::PreAuthenticate,- _,- _,- _,- _,- >(- self.clone(),- pre_authneticate_request_data,- pre_authneticate_response_data,- );- let (pre_authenticate_router_data, _) =- call_unified_connector_service_pre_authenticate(- &pre_authenticate_router_data,- state,- header_payload,- lineage_ids,- merchant_connector_account,- platform,- connector_data.connector_name,- unified_connector_service_execution_mode,- merchant_order_reference_id,- )- .await- .to_payment_failed_response()?;- // Convert back to authorize router data while preserving preprocessing response data.- let pre_authenticate_response = pre_authenticate_router_data.response.clone();- let authorize_router_data =- helpers::router_data_type_conversion::<_, api::Authorize, _, _, _, _>(- pre_authenticate_router_data,- authorize_request_data,- pre_authenticate_response,- );- *self = authorize_router_data;- Ok(())- }- None => {- Box::pin(call_unified_connector_service_authorize(- self,- state,- header_payload,- lineage_ids,- merchant_connector_account,- platform,- unified_connector_service_execution_mode,- merchant_order_reference_id,- creds_identifier,- ))- .await- }- }- }- }}pub trait RouterDataAuthorize {@@ -975,150 +875,6 @@ async fn process_capture_flow(Ok(router_data)}-#[cfg(feature = "v2")]-#[allow(clippy::too_many_arguments)]-async fn call_unified_connector_service_authorize(- router_data: &mut types::RouterData<- api::Authorize,- types::PaymentsAuthorizeData,- types::PaymentsResponseData,- >,- 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,- platform: &domain::Platform,- unified_connector_service_execution_mode: enums::ExecutionMode,- merchant_order_reference_id: Option<String>,- creds_identifier: 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_authorize_request =- payments_grpc::PaymentServiceAuthorizeRequest::foreign_try_from(&*router_data)- .change_context(ApiErrorResponse::InternalServerError)- .attach_printable("Failed to construct Payment Authorize Request")?;-- let merchant_connector_id = merchant_connector_account.get_mca_id();-- let connector_auth_metadata = build_unified_connector_service_auth_metadata(- merchant_connector_account,- platform,- router_data.connector.clone(),- )- .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_logging_wrapper(- router_data.clone(),- state,- payment_authorize_request,- headers_builder,- |mut router_data, payment_authorize_request, grpc_headers| async move {- let response = Box::pin(client.payment_authorize(- payment_authorize_request,- connector_auth_metadata,- grpc_headers,- ))- .await- .change_context(ApiErrorResponse::InternalServerError)- .attach_printable("Failed to authorize payment")?;-- let payment_authorize_response = response.into_inner();-- let ucs_data = handle_unified_connector_service_response_for_payment_authorize(- payment_authorize_response.clone(),- )- .change_context(ApiErrorResponse::InternalServerError)- .attach_printable("Failed to deserialize UCS response")?;-- // Extract and store access token if present- if let Some(access_token) = get_access_token_from_ucs_response(- state,- platform,- &router_data.connector,- merchant_connector_id.as_ref(),- creds_identifier.clone(),- payment_authorize_response.state.as_ref(),- )- .await- {- if let Err(error) = set_access_token_for_ucs(- state,- platform,- &router_data.connector,- access_token,- merchant_connector_id.as_ref(),- creds_identifier,- )- .await- {- logger::error!(- ?error,- "Failed to store UCS access token from authorize response"- );- } else {- logger::debug!("Successfully stored access token from UCS authorize response");- }- }-- let router_data_response = ucs_data.router_data_response.map(|(response, status)| {- router_data.status = status;- response- });- router_data.response = router_data_response;- router_data.amount_captured = payment_authorize_response.captured_amount;- router_data.minor_amount_captured = payment_authorize_response- .minor_captured_amount- .map(MinorUnit::new);- router_data.minor_amount_capturable = payment_authorize_response- .minor_capturable_amount- .map(MinorUnit::new);- router_data.raw_connector_response = payment_authorize_response- .raw_connector_response- .clone()- .map(|raw_connector_response| raw_connector_response.expose().into());- router_data.connector_http_status_code = Some(ucs_data.status_code);-- // Populate connector_customer_id if present- ucs_data.connector_customer_id.map(|connector_customer_id| {- router_data.connector_customer = Some(connector_customer_id);- });-- ucs_data.connector_response.map(|connector_response| {- router_data.connector_response = Some(connector_response);- });-- Ok((router_data, (), payment_authorize_response))- },- ))- .await?;-- // Copy back the updated data- *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,@@ -1309,146 +1065,3 @@ pub async fn call_unified_connector_service_pre_authenticate(.await.change_context(interface_errors::ConnectorError::ResponseHandlingFailed)}--#[cfg(feature = "v2")]-#[allow(clippy::too_many_arguments)]-async fn call_unified_connector_service_repeat_payment(- router_data: &mut types::RouterData<- api::Authorize,- types::PaymentsAuthorizeData,- types::PaymentsResponseData,- >,- 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,- platform: &domain::Platform,- unified_connector_service_execution_mode: enums::ExecutionMode,- merchant_order_reference_id: Option<String>,- creds_identifier: 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_repeat_request =- payments_grpc::PaymentServiceRepeatEverythingRequest::foreign_try_from(&*router_data)- .change_context(ApiErrorResponse::InternalServerError)- .attach_printable("Failed to construct Payment Repeat Request")?;-- let merchant_connector_id = merchant_connector_account.get_mca_id();-- let connector_auth_metadata = build_unified_connector_service_auth_metadata(- merchant_connector_account,- platform,- router_data.connector.clone(),- )- .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_logging_wrapper(- router_data.clone(),- state,- payment_repeat_request,- headers_builder,- |mut router_data, payment_repeat_request, grpc_headers| async move {- let response = client- .payment_repeat(- payment_repeat_request,- connector_auth_metadata.clone(),- grpc_headers,- )- .await- .change_context(ApiErrorResponse::InternalServerError)- .attach_printable("Failed to repeat payment")?;-- let payment_repeat_response = response.into_inner();-- let ucs_data = handle_unified_connector_service_response_for_payment_repeat(- payment_repeat_response.clone(),- )- .change_context(ApiErrorResponse::InternalServerError)- .attach_printable("Failed to deserialize UCS response")?;-- // Extract and store access token if present- if let Some(access_token) = get_access_token_from_ucs_response(- state,- platform,- &router_data.connector,- merchant_connector_id.as_ref(),- creds_identifier.clone(),- payment_repeat_response.state.as_ref(),- )- .await- {- if let Err(error) = set_access_token_for_ucs(- state,- platform,- &router_data.connector,- access_token,- merchant_connector_id.as_ref(),- creds_identifier,- )- .await- {- logger::error!(- ?error,- "Failed to store UCS access token from repeat response"- );- } else {- logger::debug!("Successfully stored access token from UCS repeat response");- }- }-- let router_data_response = ucs_data.router_data_response.map(|(response, status)| {- router_data.status = status;- response- });- router_data.response = router_data_response;- router_data.amount_captured = payment_repeat_response.captured_amount;- router_data.minor_amount_captured = payment_repeat_response- .minor_captured_amount- .map(MinorUnit::new);- router_data.raw_connector_response = payment_repeat_response- .raw_connector_response- .clone()- .map(|raw_connector_response| raw_connector_response.expose().into());- router_data.connector_http_status_code = Some(ucs_data.status_code);-- // Populate connector_customer_id if present- ucs_data.connector_customer_id.map(|connector_customer_id| {- router_data.connector_customer = Some(connector_customer_id);- });-- // Populate connector_response if present- ucs_data.connector_response.map(|connector_response| {- router_data.connector_response = Some(connector_response);- });-- Ok((router_data, (), payment_repeat_response))- },- ))- .await?;-- // Copy back the updated data- *router_data = updated_router_data;- Ok(())-}