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(core): Added BankRedirect PaymentMethod and AccessToken caching for Hyperswitch <> UCS Integration (#9421)
kanikac199cb037603b06c
diff --git a/Cargo.lock b/Cargo.lockindex 02b0037dd2..4c26b6867e 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3813,7 +3813,7 @@ dependencies = [[[package]]name = "grpc-api-types"version = "0.1.0"-source = "git+https://github.com/juspay/connector-service?rev=2f8b321665485d4ccf12a4ab06f4b8f36ece5135#2f8b321665485d4ccf12a4ab06f4b8f36ece5135"+source = "git+https://github.com/juspay/connector-service?rev=1d0d1e2b31f20e3127e9bf2c5b759a7c4dd91484#1d0d1e2b31f20e3127e9bf2c5b759a7c4dd91484"dependencies = ["axum 0.8.4","error-stack 0.5.0",@@ -7457,7 +7457,7 @@ dependencies = [[[package]]name = "rust-grpc-client"version = "0.1.0"-source = "git+https://github.com/juspay/connector-service?rev=2f8b321665485d4ccf12a4ab06f4b8f36ece5135#2f8b321665485d4ccf12a4ab06f4b8f36ece5135"+source = "git+https://github.com/juspay/connector-service?rev=1d0d1e2b31f20e3127e9bf2c5b759a7c4dd91484#1d0d1e2b31f20e3127e9bf2c5b759a7c4dd91484"dependencies = ["grpc-api-types",]@@ -10244,7 +10244,7 @@ checksum = "ed646292ffc8188ef8ea4d1e0e0150fb15a5c2e12ad9b8fc191ae7a8a7f3c4b9"[[package]]name = "ucs_cards"version = "0.1.0"-source = "git+https://github.com/juspay/connector-service?rev=2f8b321665485d4ccf12a4ab06f4b8f36ece5135#2f8b321665485d4ccf12a4ab06f4b8f36ece5135"+source = "git+https://github.com/juspay/connector-service?rev=1d0d1e2b31f20e3127e9bf2c5b759a7c4dd91484#1d0d1e2b31f20e3127e9bf2c5b759a7c4dd91484"dependencies = ["bytes 1.10.1","error-stack 0.4.1",@@ -10260,7 +10260,7 @@ dependencies = [[[package]]name = "ucs_common_enums"version = "0.1.0"-source = "git+https://github.com/juspay/connector-service?rev=2f8b321665485d4ccf12a4ab06f4b8f36ece5135#2f8b321665485d4ccf12a4ab06f4b8f36ece5135"+source = "git+https://github.com/juspay/connector-service?rev=1d0d1e2b31f20e3127e9bf2c5b759a7c4dd91484#1d0d1e2b31f20e3127e9bf2c5b759a7c4dd91484"dependencies = ["serde","strum 0.26.3",@@ -10271,7 +10271,7 @@ dependencies = [[[package]]name = "ucs_common_utils"version = "0.1.0"-source = "git+https://github.com/juspay/connector-service?rev=2f8b321665485d4ccf12a4ab06f4b8f36ece5135#2f8b321665485d4ccf12a4ab06f4b8f36ece5135"+source = "git+https://github.com/juspay/connector-service?rev=1d0d1e2b31f20e3127e9bf2c5b759a7c4dd91484#1d0d1e2b31f20e3127e9bf2c5b759a7c4dd91484"dependencies = ["anyhow","base64 0.21.7",diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.tomlindex 582d437d1a..331cf031a3 100644--- a/crates/external_services/Cargo.toml+++ b/crates/external_services/Cargo.toml@@ -69,7 +69,7 @@ reqwest = { version = "0.11.27", features = ["rustls-tls"] }http = "0.2.12"url = { version = "2.5.4", features = ["serde"] }quick-xml = { version = "0.31.0", features = ["serialize"] }-unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "2f8b321665485d4ccf12a4ab06f4b8f36ece5135", package = "rust-grpc-client" }+unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "1d0d1e2b31f20e3127e9bf2c5b759a7c4dd91484", package = "rust-grpc-client" }open-feature = { version = "0.2.5", optional = true }superposition_provider = { version = "0.88.1", optional = true }diff --git a/crates/external_services/src/grpc_client/unified_connector_service.rs b/crates/external_services/src/grpc_client/unified_connector_service.rsindex cec3f4bb4f..c41c7016fa 100644--- a/crates/external_services/src/grpc_client/unified_connector_service.rs+++ b/crates/external_services/src/grpc_client/unified_connector_service.rs@@ -68,6 +68,9 @@ pub struct ConnectorAuthMetadata {/// Optional additional key used by some authentication types.pub key1: Option<Secret<String>>,+ /// Optional second additional key used by multi-auth authentication types.+ pub key2: Option<Secret<String>>,+/// Optional API secret used for signature or secure authentication.pub api_secret: Option<Secret<String>>,@@ -547,6 +550,9 @@ pub fn build_unified_connector_service_grpc_headers(if let Some(key1) = meta.key1 {metadata.append(consts::UCS_HEADER_KEY1, parse("key1", key1.peek())?);}+ if let Some(key2) = meta.key2 {+ metadata.append(consts::UCS_HEADER_KEY2, parse("key2", key2.peek())?);+ }if let Some(api_secret) = meta.api_secret {metadata.append(consts::UCS_HEADER_API_SECRET,diff --git a/crates/external_services/src/lib.rs b/crates/external_services/src/lib.rsindex 8b318d0235..5e82b54d48 100644--- a/crates/external_services/src/lib.rs+++ b/crates/external_services/src/lib.rs@@ -82,6 +82,9 @@ pub mod consts {/// Header key for sending the API secret in signature-based authentication.pub(crate) const UCS_HEADER_API_SECRET: &str = "x-api-secret";+ /// Header key for sending a second additional key used in multi-auth authentication.+ pub(crate) const UCS_HEADER_KEY2: &str = "x-key2";+/// Header key for sending the AUTH KEY MAP in currency-based authentication.pub(crate) const UCS_HEADER_AUTH_KEY_MAP: &str = "x-auth-key-map";diff --git a/crates/hyperswitch_interfaces/Cargo.toml b/crates/hyperswitch_interfaces/Cargo.tomlindex d7c08f3423..df2accdbd4 100644--- a/crates/hyperswitch_interfaces/Cargo.toml+++ b/crates/hyperswitch_interfaces/Cargo.toml@@ -29,7 +29,7 @@ serde_json = "1.0.140"strum = { version = "0.26", features = ["derive"] }thiserror = "1.0.69"time = "0.3.41"-unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "2f8b321665485d4ccf12a4ab06f4b8f36ece5135", package = "rust-grpc-client" }+unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "1d0d1e2b31f20e3127e9bf2c5b759a7c4dd91484", package = "rust-grpc-client" }unified-connector-service-masking = { git = "https://github.com/juspay/hyperswitch", tag = "2025.09.24.0", package = "masking" }# First party cratesdiff --git a/crates/router/Cargo.toml b/crates/router/Cargo.tomlindex 5610d69502..d0bf766567 100644--- a/crates/router/Cargo.toml+++ b/crates/router/Cargo.toml@@ -89,8 +89,8 @@ reqwest = { version = "0.11.27", features = ["json", "rustls-tls", "gzip", "multring = "0.17.14"rust_decimal = { version = "1.37.1", features = ["serde-with-float", "serde-with-str"] }rust-i18n = { git = "https://github.com/kashif-m/rust-i18n", rev = "f2d8096aaaff7a87a847c35a5394c269f75e077a" }-unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "2f8b321665485d4ccf12a4ab06f4b8f36ece5135", package = "rust-grpc-client" }-unified-connector-service-cards = { git = "https://github.com/juspay/connector-service", rev = "2f8b321665485d4ccf12a4ab06f4b8f36ece5135", package = "ucs_cards" }+unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "1d0d1e2b31f20e3127e9bf2c5b759a7c4dd91484", package = "rust-grpc-client" }+unified-connector-service-cards = { git = "https://github.com/juspay/connector-service", rev = "1d0d1e2b31f20e3127e9bf2c5b759a7c4dd91484", package = "ucs_cards" }unified-connector-service-masking = { git = "https://github.com/juspay/hyperswitch", tag = "2025.09.24.0", package = "masking" }rustc-hash = "1.1.0"rustls = "0.22"diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rsindex ca57eee0a9..42cac5800a 100644--- a/crates/router/src/consts.rs+++ b/crates/router/src/consts.rs@@ -333,6 +333,9 @@ pub const UCS_AUTH_BODY_KEY: &str = "body-key";/// Header value indicating that header-key-based authentication is used.pub const UCS_AUTH_HEADER_KEY: &str = "header-key";+/// Header value indicating that multi-key-based authentication is used.+pub const UCS_AUTH_MULTI_KEY: &str = "multi-auth-key";+/// Header value indicating that currency-auth-key-based authentication is used.pub const UCS_AUTH_CURRENCY_AUTH_KEY: &str = "currency-auth-key";diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex c8f2d0f14a..37954242ab 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -4271,7 +4271,7 @@ pub async fn decide_unified_connector_service_call<'a, F, RouterDReq, ApiRequestis_retry_payment: bool,all_keys_required: Option<bool>,merchant_connector_account: helpers::MerchantConnectorAccountType,- router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>,+ mut router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>,tokenization_action: TokenizationAction,) -> RouterResult<(RouterData<F, RouterDReq, router_types::PaymentsResponseData>,@@ -4300,6 +4300,25 @@ where).await?;+ if matches!(+ execution_path,+ ExecutionPath::UnifiedConnectorService | ExecutionPath::ShadowUnifiedConnectorService+ ) {+ let cached_access_token = access_token::get_cached_access_token_for_ucs(+ state,+ &connector,+ merchant_context,+ router_data.payment_method,+ payment_data.get_creds_identifier(),+ )+ .await?;++ // Set cached access token in router_data if available+ if let Some(access_token) = cached_access_token {+ router_data.access_token = Some(access_token);+ }+ }+record_time_taken_with(|| async {match execution_path {// Process through UCS when system is UCS and not handling response or if it is a UCS webhook action@@ -4905,6 +4924,7 @@ wherelet 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(@@ -4917,6 +4937,7 @@ whereExecutionMode::Primary, // UCS is called in primary modemerchant_order_reference_id,call_connector_action,+ creds_identifier,).await?;@@ -5020,6 +5041,22 @@ wherelet 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);++ // Check for cached access token in Redis (no generation for UCS flows)+ let cached_access_token = access_token::get_cached_access_token_for_ucs(+ state,+ &connector,+ merchant_context,+ router_data.payment_method,+ payment_data.get_creds_identifier(),+ )+ .await?;++ // Set cached access token in router_data if available+ if let Some(access_token) = cached_access_token {+ router_data.access_token = Some(access_token);+ }router_data.call_unified_connector_service(@@ -5032,6 +5069,7 @@ whereExecutionMode::Primary, //UCS is called in primary modemerchant_order_reference_id,call_connector_action,+ creds_identifier).await?;diff --git a/crates/router/src/core/payments/access_token.rs b/crates/router/src/core/payments/access_token.rsindex 4ddf998bde..b38d55a95f 100644--- a/crates/router/src/core/payments/access_token.rs+++ b/crates/router/src/core/payments/access_token.rs@@ -1,5 +1,6 @@use std::fmt::Debug;+use common_enums;use common_utils::ext_traits::AsyncExt;use error_stack::ResultExt;use hyperswitch_interfaces::api::ConnectorSpecifications;@@ -12,9 +13,66 @@ use crate::{},routes::{metrics, SessionState},services::{self, logger},- types::{self, api as api_types},+ types::{self, api as api_types, domain},};+/// Get cached access token for UCS flows - only reads from cache, never generates+pub async fn get_cached_access_token_for_ucs(+ state: &SessionState,+ connector: &api_types::ConnectorData,+ merchant_context: &domain::MerchantContext,+ payment_method: common_enums::PaymentMethod,+ creds_identifier: Option<&str>,+) -> RouterResult<Option<types::AccessToken>> {+ if connector+ .connector_name+ .supports_access_token(payment_method)+ {+ let merchant_id = merchant_context.get_merchant_account().get_id();+ let store = &*state.store;++ let merchant_connector_id_or_connector_name = connector+ .merchant_connector_id+ .clone()+ .map(|mca_id| mca_id.get_string_repr().to_string())+ .or(creds_identifier.map(|id| id.to_string()))+ .unwrap_or(connector.connector_name.to_string());++ let cached_access_token = store+ .get_access_token(merchant_id, &merchant_connector_id_or_connector_name)+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("DB error when accessing the access token")?;++ if let Some(access_token) = cached_access_token {+ router_env::logger::info!(+ "Cached access token found for UCS flow - merchant_id: {:?}, connector: {} with expiry of: {} seconds",+ merchant_context.get_merchant_account().get_id(),+ connector.connector_name,+ access_token.expires+ );+ metrics::ACCESS_TOKEN_CACHE_HIT.add(+ 1,+ router_env::metric_attributes!(("connector", connector.connector_name.to_string())),+ );+ Ok(Some(access_token))+ } else {+ router_env::logger::info!(+ "No cached access token found for UCS flow - UCS will generate internally - merchant_id: {:?}, connector: {}",+ merchant_context.get_merchant_account().get_id(),+ connector.connector_name+ );+ metrics::ACCESS_TOKEN_CACHE_MISS.add(+ 1,+ router_env::metric_attributes!(("connector", connector.connector_name.to_string())),+ );+ Ok(None)+ }+ } else {+ Ok(None)+ }+}+/// After we get the access token, check if there was an error and if the flow should proceed further/// Returns bool/// true - Everything is well, continue with the flowdiff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rsindex d2575306c7..b70cef74db 100644--- a/crates/router/src/core/payments/flows.rs+++ b/crates/router/src/core/payments/flows.rs@@ -250,6 +250,7 @@ pub trait Feature<F, T> {_unified_connector_service_execution_mode: ExecutionMode,_merchant_order_reference_id: Option<String>,_call_connector_action: common_enums::CallConnectorAction,+ _creds_identifier: Option<String>,) -> RouterResult<()>whereF: Clone,diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rsindex 8e22eaaf2d..210126fc4d 100644--- a/crates/router/src/core/payments/flows/authorize_flow.rs+++ b/crates/router/src/core/payments/flows/authorize_flow.rs@@ -28,8 +28,10 @@ use crate::{},unified_connector_service::{self, build_unified_connector_service_auth_metadata,+ get_access_token_from_ucs_response,handle_unified_connector_service_response_for_payment_authorize,- handle_unified_connector_service_response_for_payment_repeat, ucs_logging_wrapper,+ handle_unified_connector_service_response_for_payment_repeat, set_access_token_for_ucs,+ ucs_logging_wrapper,},},logger,@@ -544,6 +546,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAuunified_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(@@ -555,6 +558,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAumerchant_context,unified_connector_service_execution_mode,merchant_order_reference_id,+ creds_identifier,)).await} else {@@ -619,6 +623,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAumerchant_context,unified_connector_service_execution_mode,merchant_order_reference_id,+ creds_identifier,)).await}@@ -924,6 +929,7 @@ async fn call_unified_connector_service_authorize(merchant_context: &domain::MerchantContext,unified_connector_service_execution_mode: enums::ExecutionMode,merchant_order_reference_id: Option<String>,+ creds_identifier: Option<String>,) -> RouterResult<()> {let client = state.grpc_client@@ -937,6 +943,8 @@ async fn call_unified_connector_service_authorize(.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, merchant_context).change_context(ApiErrorResponse::InternalServerError)@@ -981,6 +989,36 @@ async fn call_unified_connector_service_authorize(.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,+ merchant_context,+ &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,+ merchant_context,+ &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@@ -1202,6 +1240,7 @@ async fn call_unified_connector_service_repeat_payment(merchant_context: &domain::MerchantContext,unified_connector_service_execution_mode: enums::ExecutionMode,merchant_order_reference_id: Option<String>,+ creds_identifier: Option<String>,) -> RouterResult<()> {let client = state.grpc_client@@ -1215,6 +1254,8 @@ async fn call_unified_connector_service_repeat_payment(.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, merchant_context).change_context(ApiErrorResponse::InternalServerError)@@ -1258,6 +1299,36 @@ async fn call_unified_connector_service_repeat_payment(.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,+ merchant_context,+ &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,+ merchant_context,+ &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;responsediff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rsindex 5702778761..af30f13bf5 100644--- a/crates/router/src/core/payments/flows/cancel_flow.rs+++ b/crates/router/src/core/payments/flows/cancel_flow.rs@@ -178,6 +178,7 @@ impl Feature<api::Void, types::PaymentsCancelData>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<()> {let client = state.grpc_clientdiff --git a/crates/router/src/core/payments/flows/capture_flow.rs b/crates/router/src/core/payments/flows/capture_flow.rsindex 581cf6ad83..01ba9a7bb5 100644--- a/crates/router/src/core/payments/flows/capture_flow.rs+++ b/crates/router/src/core/payments/flows/capture_flow.rs@@ -187,6 +187,7 @@ impl Feature<api::Capture, types::PaymentsCaptureData>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<()> {let client = state.grpc_clientdiff --git a/crates/router/src/core/payments/flows/complete_authorize_flow.rs b/crates/router/src/core/payments/flows/complete_authorize_flow.rsindex 6206599064..472231a9cc 100644--- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs+++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs@@ -294,6 +294,7 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData>_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<()> {// Call UCS for Authorize flowOk(())diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rsindex 9605457546..42ad5b0064 100644--- a/crates/router/src/core/payments/flows/psync_flow.rs+++ b/crates/router/src/core/payments/flows/psync_flow.rs@@ -20,7 +20,8 @@ use crate::{errors::{ApiErrorResponse, ConnectorErrorExt, RouterResult},payments::{self, access_token, helpers, transformers, PaymentData},unified_connector_service::{- build_unified_connector_service_auth_metadata, ucs_logging_wrapper,+ build_unified_connector_service_auth_metadata, get_access_token_from_ucs_response,+ set_access_token_for_ucs, ucs_logging_wrapper,},},routes::SessionState,@@ -241,6 +242,7 @@ impl Feature<api::PSync, types::PaymentsSyncData>unified_connector_service_execution_mode: enums::ExecutionMode,merchant_order_reference_id: Option<String>,call_connector_action: common_enums::CallConnectorAction,+ creds_identifier: Option<String>,) -> RouterResult<()> {match call_connector_action {common_enums::CallConnectorAction::UCSConsumeResponse(transform_data_bytes) => {@@ -303,7 +305,6 @@ impl Feature<api::PSync, types::PaymentsSyncData>);return Ok(());}-let client = state.grpc_client.unified_connector_service_client@@ -319,6 +320,8 @@ impl Feature<api::PSync, types::PaymentsSyncData>.change_context(ApiErrorResponse::InternalServerError).attach_printable("Failed to construct Payment Get Request")?;+ let merchant_connector_id = merchant_connector_account.get_mca_id();+let connector_auth_metadata = build_unified_connector_service_auth_metadata(merchant_connector_account,merchant_context,@@ -342,6 +345,7 @@ impl Feature<api::PSync, types::PaymentsSyncData>.external_vault_proxy_metadata(None).merchant_reference_id(merchant_reference_id).lineage_ids(lineage_ids);+ let connector_name = self.connector.clone();let updated_router_data = Box::pin(ucs_logging_wrapper(self.clone(),state,@@ -363,6 +367,38 @@ impl Feature<api::PSync, types::PaymentsSyncData>.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,+ merchant_context,+ &connector_name,+ merchant_connector_id.as_ref(),+ creds_identifier.clone(),+ payment_get_response.state.as_ref(),+ )+ .await+ {+ if let Err(error) = set_access_token_for_ucs(+ state,+ merchant_context,+ &connector_name,+ access_token,+ merchant_connector_id.as_ref(),+ creds_identifier,+ )+ .await+ {+ logger::error!(+ ?error,+ "Failed to store UCS access token from psync response"+ );+ } else {+ logger::debug!(+ "Successfully stored access token from UCS psync response"+ );+ }+ }+let router_data_response =router_data_response.map(|(response, status)| {router_data.status = status;diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rsindex a9336b2f37..1202770e4d 100644--- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs+++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs@@ -20,8 +20,9 @@ use crate::{self, access_token, customers, helpers, tokenization, transformers, PaymentData,},unified_connector_service::{- build_unified_connector_service_auth_metadata,- handle_unified_connector_service_response_for_payment_register, ucs_logging_wrapper,+ build_unified_connector_service_auth_metadata, get_access_token_from_ucs_response,+ handle_unified_connector_service_response_for_payment_register,+ set_access_token_for_ucs, ucs_logging_wrapper,},},routes::SessionState,@@ -290,6 +291,7 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setupunified_connector_service_execution_mode: enums::ExecutionMode,merchant_order_reference_id: Option<String>,_call_connector_action: common_enums::CallConnectorAction,+ creds_identifier: Option<String>,) -> RouterResult<()> {let client = state.grpc_client@@ -303,6 +305,8 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup.change_context(ApiErrorResponse::InternalServerError).attach_printable("Failed to construct Payment Setup Mandate Request")?;+ let merchant_connector_id = merchant_connector_account.get_mca_id();+let connector_auth_metadata = build_unified_connector_service_auth_metadata(merchant_connector_account,merchant_context,@@ -324,6 +328,7 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup.external_vault_proxy_metadata(None).merchant_reference_id(merchant_reference_id).lineage_ids(lineage_ids);+ let connector_name = self.connector.clone();let updated_router_data = Box::pin(ucs_logging_wrapper(self.clone(),state,@@ -348,6 +353,37 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup.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,+ merchant_context,+ &router_data.connector,+ merchant_connector_id.as_ref(),+ creds_identifier.clone(),+ payment_register_response.state.as_ref(),+ )+ .await+ {+ if let Err(error) = set_access_token_for_ucs(+ state,+ merchant_context,+ &connector_name,+ access_token,+ merchant_connector_id.as_ref(),+ creds_identifier,+ )+ .await+ {+ logger::error!(+ ?error,+ "Failed to store UCS access token from setup mandate response"+ );+ } else {+ logger::debug!(+ "Successfully stored access token from UCS setup mandate response"+ );+ }+ }let router_data_response =ucs_data.router_data_response.map(|(response, status)| {router_data.status = status;diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex b3549b7523..d3972de4ff 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -8336,7 +8336,7 @@ whereheader_payload.clone(),).await?;-+ let creds_identifier = payment_data.get_creds_identifier().map(str::to_owned);// Calculate connector label once for reuselet connector_label =get_connector_label_for_customer(&merchant_connector_account, payment_data);@@ -8376,6 +8376,7 @@ whereExecutionMode::Primary, // UCS is called in primary modemerchant_order_reference_id,call_connector_action,+ creds_identifier,).await?;}@@ -8537,6 +8538,8 @@ wherelet unified_connector_service_connector_label =get_connector_label_for_customer(&merchant_connector_account, payment_data);+ let creds_identifier = payment_data.get_creds_identifier().map(str::to_owned);+// Clone data needed for shadow UCS calllet unified_connector_service_router_data = router_data.clone();let unified_connector_service_merchant_connector_account = merchant_connector_account.clone();@@ -8544,6 +8547,7 @@ wherelet unified_connector_service_header_payload = header_payload.clone();let unified_connector_service_state = state.clone();let unified_connector_service_merchant_order_reference_id = merchant_order_reference_id;+ let unified_connector_service_creds_identifier = creds_identifier.clone();let unified_connector_service_customer = customer.clone();let unified_connector_service_payment_attempt_data = payment_data.get_payment_attempt().clone();let unified_connector_service_connector_payment_id = payment_data@@ -8598,6 +8602,7 @@ whereunified_connector_service_merchant_order_reference_id,call_connector_action,shadow_ucs_call_connector_action,+ unified_connector_service_creds_identifier,unified_connector_service_customer,unified_connector_service_payment_attempt_data,unified_connector_service_connector_label,@@ -8632,6 +8637,7 @@ pub async fn execute_shadow_unified_connector_service_call<F, RouterDReq>(merchant_order_reference_id: Option<String>,call_connector_action: CallConnectorAction,shadow_ucs_call_connector_action: Option<CallConnectorAction>,+ creds_identifier: Option<String>,customer: Option<domain::Customer>,payment_attempt_data: PaymentAttempt,unified_connector_service_connector_label: Option<String>,@@ -8670,6 +8676,7 @@ whereExecutionMode::Shadow, // Shadow mode for UCSmerchant_order_reference_id,shadow_ucs_call_connector_action.unwrap_or(call_connector_action),+ creds_identifier,).await.map_err(|e| router_env::logger::debug!("Shadow UCS call failed: {:?}", e));diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rsindex 1b18406626..d4d1e3ec29 100644--- a/crates/router/src/core/unified_connector_service.rs+++ b/crates/router/src/core/unified_connector_service.rs@@ -33,7 +33,7 @@ use hyperswitch_domain_models::merchant_connector_account::{};use hyperswitch_domain_models::{merchant_context::MerchantContext,- router_data::{ConnectorAuthType, ErrorResponse, RouterData},+ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},router_flow_types::refunds,router_request_types::RefundsData,router_response_types::{PaymentsResponseData, RefundsResponseData},@@ -65,13 +65,92 @@ use crate::{headers::{CONTENT_TYPE, X_REQUEST_ID},routes::SessionState,types::{- transformers::ForeignTryFrom, UcsAuthorizeResponseData, UcsRepeatPaymentResponseData,- UcsSetupMandateResponseData,+ transformers::{ForeignFrom, ForeignTryFrom},+ UcsAuthorizeResponseData, UcsRepeatPaymentResponseData, UcsSetupMandateResponseData,},};pub mod transformers;+pub async fn get_access_token_from_ucs_response(+ session_state: &SessionState,+ merchant_context: &MerchantContext,+ connector_name: &str,+ merchant_connector_id: Option<&id_type::MerchantConnectorAccountId>,+ creds_identifier: Option<String>,+ ucs_state: Option<&unified_connector_service_client::payments::ConnectorState>,+) -> Option<AccessToken> {+ let ucs_access_token = ucs_state+ .and_then(|state| state.access_token.as_ref())+ .map(AccessToken::foreign_from)?;++ let merchant_id = merchant_context.get_merchant_account().get_id();++ let merchant_connector_id_or_connector_name = merchant_connector_id+ .map(|mca_id| mca_id.get_string_repr().to_string())+ .or(creds_identifier.map(|id| id.to_string()))+ .unwrap_or(connector_name.to_string());++ if let Ok(Some(cached_token)) = session_state+ .store+ .get_access_token(merchant_id, &merchant_connector_id_or_connector_name)+ .await+ {+ if cached_token.token.peek() == ucs_access_token.token.peek() {+ return None;+ }+ }++ Some(ucs_access_token)+}++pub async fn set_access_token_for_ucs(+ state: &SessionState,+ merchant_context: &MerchantContext,+ connector_name: &str,+ access_token: AccessToken,+ merchant_connector_id: Option<&id_type::MerchantConnectorAccountId>,+ creds_identifier: Option<String>,+) -> Result<(), errors::StorageError> {+ let merchant_id = merchant_context.get_merchant_account().get_id();++ let merchant_connector_id_or_connector_name = merchant_connector_id+ .map(|mca_id| mca_id.get_string_repr().to_string())+ .or(creds_identifier.map(|id| id.to_string()))+ .unwrap_or(connector_name.to_string());++ let modified_access_token = AccessToken {+ expires: access_token+ .expires+ .saturating_sub(consts::REDUCE_ACCESS_TOKEN_EXPIRY_TIME.into()),+ ..access_token+ };++ logger::debug!(+ access_token_expiry_after_modification = modified_access_token.expires,+ merchant_id = ?merchant_id,+ connector_name = connector_name,+ merchant_connector_id_or_connector_name = merchant_connector_id_or_connector_name+ );++ if let Err(access_token_set_error) = state+ .store+ .set_access_token(+ merchant_id,+ &merchant_connector_id_or_connector_name,+ modified_access_token,+ )+ .await+ {+ // If we are not able to set the access token in redis, the error should just be logged and proceed with the payment+ // Payments should not fail, once the access token is successfully created+ // The next request will create new access token, if required+ logger::error!(access_token_set_error=?access_token_set_error, "Failed to store UCS access token");+ }++ Ok(())+}+// Re-export webhook transformer types for easier accesspub use transformers::{WebhookTransformData, WebhookTransformationStatus};@@ -749,6 +828,33 @@ pub fn build_unified_connector_service_payment_method(payment_method: Some(upi_type),})}+ hyperswitch_domain_models::payment_method_data::PaymentMethodData::BankRedirect(+ bank_redirect_data,+ ) => match bank_redirect_data {+ hyperswitch_domain_models::payment_method_data::BankRedirectData::OpenBankingUk {+ issuer,+ country,+ } => {+ let open_banking_uk = payments_grpc::OpenBankingUk {+ issuer: issuer.map(|issuer| issuer.to_string()),+ country: country.map(|country| country.to_string()),+ };++ Ok(payments_grpc::PaymentMethod {+ payment_method: Some(PaymentMethod::OnlineBanking(+ payments_grpc::OnlineBankingPaymentMethodType {+ online_banking_type: Some(+ payments_grpc::online_banking_payment_method_type::OnlineBankingType::OpenBankingUk(open_banking_uk)+ ),+ }+ )),+ })+ }+ _ => Err(UnifiedConnectorServiceError::NotImplemented(format!(+ "Unimplemented bank redirect type: {bank_redirect_data:?}"+ ))+ .into()),+ },hyperswitch_domain_models::payment_method_data::PaymentMethodData::Reward => {match payment_method_type {PaymentMethodType::ClassicReward => Ok(payments_grpc::PaymentMethod {@@ -899,6 +1005,7 @@ pub fn build_unified_connector_service_auth_metadata(auth_type: consts::UCS_AUTH_SIGNATURE_KEY.to_string(),api_key: Some(api_key.clone()),key1: Some(key1.clone()),+ key2: None,api_secret: Some(api_secret.clone()),auth_key_map: None,merchant_id: Secret::new(merchant_id.to_string()),@@ -908,6 +1015,7 @@ pub fn build_unified_connector_service_auth_metadata(auth_type: consts::UCS_AUTH_BODY_KEY.to_string(),api_key: Some(api_key.clone()),key1: Some(key1.clone()),+ key2: None,api_secret: None,auth_key_map: None,merchant_id: Secret::new(merchant_id.to_string()),@@ -917,6 +1025,7 @@ pub fn build_unified_connector_service_auth_metadata(auth_type: consts::UCS_AUTH_HEADER_KEY.to_string(),api_key: Some(api_key.clone()),key1: None,+ key2: None,api_secret: None,auth_key_map: None,merchant_id: Secret::new(merchant_id.to_string()),@@ -926,10 +1035,26 @@ pub fn build_unified_connector_service_auth_metadata(auth_type: consts::UCS_AUTH_CURRENCY_AUTH_KEY.to_string(),api_key: None,key1: None,+ key2: None,api_secret: None,auth_key_map: Some(auth_key_map.clone()),merchant_id: Secret::new(merchant_id.to_string()),}),+ ConnectorAuthType::MultiAuthKey {+ api_key,+ key1,+ api_secret,+ key2,+ } => Ok(ConnectorAuthMetadata {+ connector_name,+ auth_type: consts::UCS_AUTH_MULTI_KEY.to_string(),+ api_key: Some(api_key.clone()),+ key1: Some(key1.clone()),+ key2: Some(key2.clone()),+ api_secret: Some(api_secret.clone()),+ auth_key_map: None,+ merchant_id: Secret::new(merchant_id.to_string()),+ }),_ => Err(UnifiedConnectorServiceError::FailedToObtainAuthType).attach_printable("Unsupported ConnectorAuthType for header injection"),}diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rsindex e2914bf4c1..1300d072ac 100644--- a/crates/router/src/core/unified_connector_service/transformers.rs+++ b/crates/router/src/core/unified_connector_service/transformers.rs@@ -6,7 +6,7 @@ use diesel_models::enums as storage_enums;use error_stack::ResultExt;use external_services::grpc_client::unified_connector_service::UnifiedConnectorServiceError;use hyperswitch_domain_models::{- router_data::{ErrorResponse, RouterData},+ router_data::{AccessToken, ErrorResponse, RouterData},router_flow_types::{payments::{Authorize, Capture, PSync, SetupMandate},refunds::{Execute, RSync},@@ -29,15 +29,40 @@ pub use hyperswitch_interfaces::{use masking::{ExposeInterface, PeekInterface};use router_env::tracing;use unified_connector_service_client::payments::{- self as payments_grpc, Identifier, PaymentServiceTransformRequest,+ self as payments_grpc, ConnectorState, Identifier, PaymentServiceTransformRequest,PaymentServiceTransformResponse,};use url::Url;use crate::{core::{errors, unified_connector_service},- types::{api, transformers},+ types::{+ api,+ transformers::{self, ForeignFrom},+ },};++impl ForeignFrom<&payments_grpc::AccessToken> for AccessToken {+ fn foreign_from(grpc_token: &payments_grpc::AccessToken) -> Self {+ Self {+ token: masking::Secret::new(grpc_token.token.clone()),+ expires: grpc_token.expires_in_seconds.unwrap_or_default(),+ }+ }+}++impl ForeignFrom<&AccessToken> for ConnectorState {+ fn foreign_from(access_token: &AccessToken) -> Self {+ Self {+ access_token: Some(payments_grpc::AccessToken {+ token: access_token.token.peek().to_string(),+ expires_in_seconds: Some(access_token.expires),+ token_type: None,+ }),+ connector_customer_id: None,+ }+ }+}impltransformers::ForeignTryFrom<(&RouterData<PSync, PaymentsSyncData, PaymentsResponseData>,@@ -108,14 +133,19 @@ impl.map(payments_grpc::CaptureMethod::foreign_try_from).transpose()?;+ let state = router_data+ .access_token+ .as_ref()+ .map(ConnectorState::foreign_from);+Ok(Self {transaction_id: connector_transaction_id.or(encoded_data),request_ref_id: connector_ref_id,capture_method: capture_method.map(|capture_method| capture_method.into()),handle_response,- access_token: None,amount: router_data.request.amount.get_amount_as_i64(),currency: currency.into(),+ state,})}}@@ -180,7 +210,7 @@ implmetadata: HashMap::new(), // PaymentsAuthenticateData doesn't have metadatareturn_url: None, // PaymentsAuthenticateData doesn't have router_return_urlcontinue_redirection_url: router_data.request.complete_authorize_url.clone(),- access_token: None,+ state: None,browser_info: router_data.request.browser_info@@ -240,7 +270,7 @@ implmetadata: HashMap::new(),return_url: None,continue_redirection_url: None,- access_token: None,+ state: None,browser_info: router_data.request.browser_info@@ -335,7 +365,7 @@ implmetadata,return_url: router_data.request.router_return_url.clone(),continue_redirection_url: router_data.request.complete_authorize_url.clone(),- access_token: None,+ state: None,browser_info: router_data.request.browser_info@@ -382,7 +412,6 @@ impl transformers::ForeignTryFrom<&RouterData<Capture, PaymentsCaptureData, Paymrouter_data.connector_request_reference_id.clone(),)),}),- access_token: None,amount_to_capture: router_data.request.minor_amount_to_capture@@ -407,6 +436,7 @@ impl transformers::ForeignTryFrom<&RouterData<Capture, PaymentsCaptureData, Paymcapture_reference: multiple_capture_request_data.capture_reference.clone(),},),+ state: None,})}}@@ -496,6 +526,11 @@ impl.map(payments_grpc::CustomerAcceptance::foreign_try_from).transpose()?;+ let state = router_data+ .access_token+ .as_ref()+ .map(ConnectorState::foreign_from);+Ok(Self {amount: router_data.request.amount,currency: currency.into(),@@ -514,7 +549,6 @@ impl.clone().map(|e| e.expose().expose().into()),browser_info,- access_token: None,session_token: None,order_tax_amount: router_data.request@@ -556,6 +590,7 @@ implmetadata,test_mode: router_data.test_mode,connector_customer_id: router_data.connector_customer.clone(),+ state,merchant_account_metadata: HashMap::new(),})}@@ -643,7 +678,6 @@ impl.clone().map(|e| e.expose().expose().into()),browser_info,- access_token: None,session_token: None,order_tax_amount: router_data.request@@ -701,6 +735,7 @@ impl.unwrap_or_default(),test_mode: router_data.test_mode,connector_customer_id: router_data.connector_customer.clone(),+ state: None,merchant_account_metadata: HashMap::new(),})}@@ -747,6 +782,11 @@ impl.map(payments_grpc::CustomerAcceptance::foreign_try_from).transpose()?;+ let state = router_data+ .access_token+ .as_ref()+ .map(ConnectorState::foreign_from);+Ok(Self {request_ref_id: Some(Identifier {id_type: Some(payments_grpc::identifier::IdType::Id(@@ -790,7 +830,6 @@ implreturn_url: router_data.request.router_return_url.clone(),webhook_url: router_data.request.webhook_url.clone(),complete_authorize_url: router_data.request.complete_authorize_url.clone(),- access_token: None,session_token: None,order_tax_amount: None,order_category: None,@@ -810,6 +849,7 @@ implpayment_experience: None,connector_customer_id: router_data.connector_customer.clone(),merchant_account_metadata: HashMap::new(),+ state,})}}@@ -860,6 +900,11 @@ impl}};+ let state = router_data+ .access_token+ .as_ref()+ .map(ConnectorState::foreign_from);+Ok(Self {request_ref_id: Some(Identifier {id_type: Some(payments_grpc::identifier::IdType::Id(@@ -892,8 +937,8 @@ implbrowser_info,test_mode: router_data.test_mode,payment_method_type: None,- access_token: None,merchant_account_metadata: HashMap::new(),+ state,})}}@@ -2025,7 +2070,7 @@ pub fn build_webhook_transform_request(}),request_details: Some(request_details_grpc),webhook_secrets,- access_token: None,+ state: None,})}@@ -2092,6 +2137,11 @@ impl transformers::ForeignTryFrom<&RouterData<Execute, RefundsData, RefundsRespo}).unwrap_or_default();+ let state = router_data+ .access_token+ .as_ref()+ .map(ConnectorState::foreign_from);+Ok(Self {request_ref_id,refund_id: router_data.request.refund_id.clone(),@@ -2132,10 +2182,7 @@ impl transformers::ForeignTryFrom<&RouterData<Execute, RefundsData, RefundsRespo"Failed to convert browser info".to_string(),)})?,- access_token: router_data- .access_token- .as_ref()- .map(|token| token.token.clone().expose()),+ state,})}}@@ -2161,6 +2208,11 @@ impl transformers::ForeignTryFrom<&RouterData<RSync, RefundsData, RefundsRespons)),});+ let state = router_data+ .access_token+ .as_ref()+ .map(ConnectorState::foreign_from);+Ok(Self {request_ref_id,transaction_id: Some(transaction_id),@@ -2181,10 +2233,7 @@ impl transformers::ForeignTryFrom<&RouterData<RSync, RefundsData, RefundsRespons"Failed to convert browser info".to_string(),)})?,- access_token: router_data- .access_token- .as_ref()- .map(|token| token.token.clone().expose()),+ state,refund_metadata: router_data.request.refund_connector_metadata@@ -2294,7 +2343,6 @@ impl transformers::ForeignTryFrom<&RouterData<api::Void, PaymentsCancelData, Paycancellation_reason: router_data.request.cancellation_reason.clone(),all_keys_required: None,browser_info,- access_token: None,amount: router_data.request.amount,currency: currency.map(|c| c.into()),connector_metadata: router_data@@ -2308,6 +2356,7 @@ impl transformers::ForeignTryFrom<&RouterData<api::Void, PaymentsCancelData, Pay.collect::<HashMap<String, String>>()}).unwrap_or_default(),+ state: None,})}}