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(account_updater): add force_sync trigger and UCS refresh call (#13510)
Kanika Bansal02f8303d4abb
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.jsonindex a18417500a..b55b3106bf 100644--- a/api-reference/v1/openapi_spec_v1.json+++ b/api-reference/v1/openapi_spec_v1.json@@ -17314,6 +17314,7 @@"imerchantsolutions","itaubank","jpmorgan",+ "juspay","juspaythreedsserver","klarna","loonio",diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.jsonindex b6acdcd27e..c42eed3334 100644--- a/api-reference/v2/openapi_spec_v2.json+++ b/api-reference/v2/openapi_spec_v2.json@@ -11483,6 +11483,7 @@"imerchantsolutions","itaubank","jpmorgan",+ "juspay","juspaythreedsserver","klarna","loonio",@@ -23132,6 +23133,10 @@"properties": {"fetch_raw_detail": {"type": "boolean"+ },+ "force_sync": {+ "type": "boolean",+ "description": "Trigger an Account Updater check for the stored payment method."}},"additionalProperties": falsediff --git a/config/config.example.toml b/config/config.example.tomlindex 7e943c17cc..9cd7a37120 100644--- a/config/config.example.toml+++ b/config/config.example.toml@@ -1524,7 +1524,7 @@ base_url = "https://offer-engine.example.com/" # Base URL of the Offer Engine seapi_key = "" # API key for API-key authenticated Offer Engine callsmerchant_id = "" # Offer Engine merchant id sent in request bodies-# Credentials forwarded to UCS for the Account Updater flow; omit the section entirely to keep it off+# Credentials and call settings for the Account Updater flow; omit the section entirely to keep it off[account_updater.juspay]base_url = "https://account-updater.example.com/" # Account Updater base URLapi_key = "" # API key for the Account Updater provider@@ -1532,6 +1532,8 @@ merchant_id = "" # Merchant id sent in Account Updater request beuler_encryption_public_key = "" # Provider RSA public key, used to seal outbound card dataau_decryption_pvt_key = "" # Our RSA private key, used to open the response payloadcard_sync_key_id = "" # Id of our public key as registered with the provider+supported_card_networks = "Visa, Mastercard" # Supported card networks for Account Updater refresh+refresh_timeout_in_secs = 5 # Optional, defaults to 5. Per-call deadline for the refresh request sent to UCS[micro_services]# Base URLs for modular microservicesdiff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rsindex 91b92476fe..84d4439c16 100644--- a/crates/api_models/src/payment_methods.rs+++ b/crates/api_models/src/payment_methods.rs@@ -121,6 +121,9 @@ pub struct PaymentMethodCreate {pub struct PaymentMethodRetrieveRequest {#[serde(default)]pub fetch_raw_detail: bool,+ /// Trigger an Account Updater check for the stored payment method.+ #[serde(default)]+ pub force_sync: bool,}#[cfg(feature = "v2")]diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rsindex 1834d703e3..c6f37019f5 100644--- a/crates/common_enums/src/connector_enums.rs+++ b/crates/common_enums/src/connector_enums.rs@@ -131,6 +131,7 @@ pub enum Connector {Imerchantsolutions,Itaubank,Jpmorgan,+ Juspay,Juspaythreedsserver,Klarna,Loonio,@@ -382,6 +383,7 @@ impl Connector {| Self::Inespay| Self::Itaubank| Self::Jpmorgan+ | Self::Juspay| Self::Juspaythreedsserver| Self::Klarna| Self::Looniodiff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rsindex bfc505dc5d..b95e18e78a 100644--- a/crates/connector_configs/src/connector.rs+++ b/crates/connector_configs/src/connector.rs@@ -622,6 +622,7 @@ impl ConnectorConfig {Connector::Helcim => Ok(connector_data.helcim),Connector::Inespay => Ok(connector_data.inespay),Connector::Jpmorgan => Ok(connector_data.jpmorgan),+ Connector::Juspay => Err("Configured through application config".to_string()),Connector::Juspaythreedsserver => Ok(connector_data.juspaythreedsserver),Connector::Klarna => Ok(connector_data.klarna),Connector::Loonio => Ok(connector_data.loonio),diff --git a/crates/euclid/src/enums.rs b/crates/euclid/src/enums.rsindex feb0192b24..e0d437c1d6 100644--- a/crates/euclid/src/enums.rs+++ b/crates/euclid/src/enums.rs@@ -528,6 +528,7 @@ impl TryFrom<Connector> for RoutableConnectors {Connector::CtpMastercard| Connector::Gpayments| Connector::HyperswitchVault+ | Connector::Juspay| Connector::Juspaythreedsserver| Connector::Netcetera| Connector::Taxjardiff --git a/crates/external_services/src/grpc_client/unified_connector_service.rs b/crates/external_services/src/grpc_client/unified_connector_service.rsindex ea5fa49b8c..e48967feaf 100644--- a/crates/external_services/src/grpc_client/unified_connector_service.rs+++ b/crates/external_services/src/grpc_client/unified_connector_service.rs@@ -423,6 +423,44 @@ impl UnifiedConnectorServiceClient {})}+ /// Performs Payment Method Refresh+ pub async fn payment_method_refresh(+ &self,+ payment_method_refresh_request: payments_grpc::PaymentMethodServiceRefreshRequest,+ connector_auth_metadata: ConnectorAuthMetadata,+ grpc_headers: GrpcHeadersUcs,+ timeout: Duration,+ ) -> UnifiedConnectorServiceResult<+ tonic::Response<payments_grpc::PaymentMethodServiceRefreshResponse>,+ > {+ let mut request = tonic::Request::new(payment_method_refresh_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;+ request.set_timeout(timeout);++ self.payment_method_service_client+ .clone()+ .refresh(request)+ .await+ .map_err(|error| {+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(+ &error,+ &connector_name,+ ))+ })+ .inspect_err(|error| {+ logger::error!(+ grpc_error=?error,+ method="payment_method_refresh",+ connector_name=?connector_name,+ "UCS payment_method_refresh gRPC call failed"+ )+ })+ }+/// Performs SDK Session Token Createpub async fn create_sdk_session_token(&self,diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rsindex 9cbb866656..3b382b3243 100644--- a/crates/router/src/configs/settings.rs+++ b/crates/router/src/configs/settings.rs@@ -401,6 +401,14 @@ pub struct JuspayAccountUpdaterConfig {pub euler_encryption_public_key: Secret<String>,pub au_decryption_pvt_key: Secret<String>,pub card_sync_key_id: String,+ #[serde(deserialize_with = "deserialize_hashset")]+ pub supported_card_networks: HashSet<enums::CardNetwork>,+ #[serde(default = "default_account_updater_refresh_timeout_in_secs")]+ pub refresh_timeout_in_secs: u64,+}++fn default_account_updater_refresh_timeout_in_secs() -> u64 {+ 5}#[derive(Debug, Deserialize, Clone, Default)]diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rsindex 56770947e2..3b54f7fb7b 100644--- a/crates/router/src/configs/validations.rs+++ b/crates/router/src/configs/validations.rs@@ -411,6 +411,19 @@ impl super::settings::JuspayAccountUpdaterConfig {})?;}+ when(self.supported_card_networks.is_empty(), || {+ Err(ApplicationError::InvalidConfigurationValueError(+ "account_updater.juspay.supported_card_networks must list at least one card network"+ .into(),+ ))+ })?;++ when(self.refresh_timeout_in_secs == 0, || {+ Err(ApplicationError::InvalidConfigurationValueError(+ "account_updater.juspay.refresh_timeout_in_secs must be greater than zero".into(),+ ))+ })?;+Ok(())}}diff --git a/crates/router/src/core.rs b/crates/router/src/core.rsindex 73a3703074..30526246c9 100644--- a/crates/router/src/core.rs+++ b/crates/router/src/core.rs@@ -1,3 +1,4 @@+#[cfg(feature = "v2")]pub mod account_updater;pub mod admin;pub mod api_keys;diff --git a/crates/router/src/core/account_updater.rs b/crates/router/src/core/account_updater.rsindex 8a0560dcb6..c28273edbc 100644--- a/crates/router/src/core/account_updater.rs+++ b/crates/router/src/core/account_updater.rs@@ -1,3 +1,77 @@+mod config;+mod eligibility;+mod refresh;pub mod types;-pub use types::AccountUpdaterCredentialSource;+use api_models::payment_methods::RawPaymentMethodData;+use common_utils::errors::CustomResult;+use router_env::{instrument, logger, tracing};+use unified_connector_service_client::payments as payments_grpc;++use self::{+ config::resolve_account_updater_config,+ eligibility::check_eligibility_and_build_payment_method,+ refresh::request_account_updater_refresh,+ types::{AccountUpdaterError, ResolvedAccountUpdaterConfig},+};+use crate::{core::configs::dimension_state, routes::SessionState, types::domain};++#[instrument(skip_all)]+pub async fn run_account_updater<D>(+ state: &SessionState,+ platform: &domain::Platform,+ profile: &domain::Profile,+ payment_method: &domain::PaymentMethod,+ raw_payment_method_data: Option<&RawPaymentMethodData>,+ dimensions: &D,+) where+ D: dimension_state::DimensionsBase,+{+ let config = match resolve_account_updater_config(state, dimensions).await {+ Ok(Some(config)) => config,+ Ok(None) => {+ logger::debug!("Account Updater is not enabled for these dimensions");+ return;+ }+ Err(error) => {+ logger::warn!(?error, "Account Updater config could not be resolved");+ return;+ }+ };++ let outcome = refresh_stored_payment_method(+ state,+ platform,+ profile,+ payment_method,+ raw_payment_method_data,+ &config,+ )+ .await;++ match outcome {+ Ok(refresh_outcome) => logger::info!(+ account_updater_outcome = refresh_outcome.as_str_name(),+ "Account Updater refresh completed"+ ),+ Err(error) => logger::warn!(?error, "Account Updater refresh did not complete"),+ }+}++async fn refresh_stored_payment_method(+ state: &SessionState,+ platform: &domain::Platform,+ profile: &domain::Profile,+ payment_method: &domain::PaymentMethod,+ raw_payment_method_data: Option<&RawPaymentMethodData>,+ config: &ResolvedAccountUpdaterConfig,+) -> CustomResult<payments_grpc::CardRefreshOutcome, AccountUpdaterError> {+ let refreshable_payment_method = check_eligibility_and_build_payment_method(+ payment_method,+ raw_payment_method_data,+ config,+ )?;++ request_account_updater_refresh(state, platform, profile, config, refreshable_payment_method)+ .await+}diff --git a/crates/router/src/core/account_updater/config.rs b/crates/router/src/core/account_updater/config.rsnew file mode 100644index 0000000000..1c0c0d555a--- /dev/null+++ b/crates/router/src/core/account_updater/config.rs@@ -0,0 +1,62 @@+use common_utils::errors::CustomResult;+use error_stack::report;++use super::types::{+ AccountUpdaterCredentialSource, AccountUpdaterError, ResolvedAccountUpdaterConfig,+};+use crate::{+ core::configs::{self, dimension_config, dimension_state},+ routes::SessionState,+};++pub async fn resolve_account_updater_config<D>(+ state: &SessionState,+ dimensions: &D,+) -> CustomResult<Option<ResolvedAccountUpdaterConfig>, AccountUpdaterError>+where+ D: dimension_state::DimensionsBase,+{+ let store = state.store.as_ref();+ let superposition = state.superposition_service.as_ref();++ let enabled =+ configs::fetch_db_config_for_dimensions::<dimension_config::AccountUpdaterEnabled>(+ store,+ superposition,+ dimensions,+ None,+ )+ .await;++ let source = if enabled {+ configs::fetch_db_config_for_string_enum::<+ dimension_config::AccountUpdaterCredentialSource,+ AccountUpdaterCredentialSource,+ >(store, superposition, dimensions, None)+ .await+ .unwrap_or(AccountUpdaterCredentialSource::None)+ } else {+ AccountUpdaterCredentialSource::None+ };++ match source {+ AccountUpdaterCredentialSource::None => Ok(None),+ AccountUpdaterCredentialSource::Application => resolve_application_config(state).map(Some),+ }+}++fn resolve_application_config(+ state: &SessionState,+) -> CustomResult<ResolvedAccountUpdaterConfig, AccountUpdaterError> {+ state+ .conf+ .account_updater+ .as_ref()+ .map(|account_updater| ResolvedAccountUpdaterConfig::from(account_updater.get_inner()))+ .ok_or_else(|| {+ report!(AccountUpdaterError::MissingApplicationConfig).attach_printable(+ "Account Updater credential source is 'application' but the account_updater \+ section is not configured",+ )+ })+}diff --git a/crates/router/src/core/account_updater/eligibility.rs b/crates/router/src/core/account_updater/eligibility.rsnew file mode 100644index 0000000000..4ef9d76dd8--- /dev/null+++ b/crates/router/src/core/account_updater/eligibility.rs@@ -0,0 +1,100 @@+use std::str::FromStr;++use api_models::payment_methods::{CardDetail, RawPaymentMethodData};+use common_enums::{PaymentMethod, PaymentMethodStatus};+use common_utils::{errors::CustomResult, fp_utils::when};+use error_stack::{report, ResultExt};+use hyperswitch_domain_models::payment_method_data::PaymentMethodsData;+use router_env::{instrument, tracing};+use unified_connector_service_cards::CardNumber;+use unified_connector_service_client::payments as payments_grpc;++use super::types::{AccountUpdaterError, ResolvedAccountUpdaterConfig};+use crate::types::{domain, transformers::ForeignFrom};++#[instrument(skip_all)]+pub fn check_eligibility_and_build_payment_method(+ payment_method: &domain::PaymentMethod,+ raw_payment_method_data: Option<&RawPaymentMethodData>,+ config: &ResolvedAccountUpdaterConfig,+) -> CustomResult<payments_grpc::PaymentMethod, AccountUpdaterError> {+ when(payment_method.status != PaymentMethodStatus::Active, || {+ Err(report!(AccountUpdaterError::PaymentMethodNotActive))+ })?;++ match payment_method.get_payment_method_type() {+ Some(PaymentMethod::Card) => check_stored_card_eligibility_and_build_payment_method(+ payment_method,+ raw_payment_method_data,+ config,+ ),+ _ => Err(report!(AccountUpdaterError::PaymentMethodNotACard)),+ }+}++fn check_stored_card_eligibility_and_build_payment_method(+ payment_method: &domain::PaymentMethod,+ raw_payment_method_data: Option<&RawPaymentMethodData>,+ config: &ResolvedAccountUpdaterConfig,+) -> CustomResult<payments_grpc::PaymentMethod, AccountUpdaterError> {+ let card_details = payment_method+ .payment_method_data+ .as_ref()+ .map(|payment_method_data| payment_method_data.get_inner())+ .and_then(|payment_method_data| match payment_method_data {+ PaymentMethodsData::Card(card_details) => Some(card_details),+ _ => None,+ })+ .ok_or_else(|| report!(AccountUpdaterError::PaymentMethodNotACard))+ .attach_printable("Stored payment method data holds no card details")?;++ card_details+ .card_network+ .as_ref()+ .filter(|card_network| config.supported_card_networks().contains(*card_network))+ .ok_or_else(|| report!(AccountUpdaterError::UnsupportedNetwork))+ .attach_printable("Stored card network is not configured for Account Updater")?;++ build_refreshable_payment_method(raw_payment_method_data)+}++fn build_refreshable_payment_method(+ raw_payment_method_data: Option<&RawPaymentMethodData>,+) -> CustomResult<payments_grpc::PaymentMethod, AccountUpdaterError> {+ let card_details: &CardDetail = match raw_payment_method_data {+ Some(RawPaymentMethodData::Card(card_details)) => Some(card_details),+ Some(RawPaymentMethodData::CardWithNT(details)) => Some(&details.card_details),+ Some(RawPaymentMethodData::BankDebit(_) | RawPaymentMethodData::ProxyCard(_)) | None => {+ None+ }+ }+ .ok_or_else(|| report!(AccountUpdaterError::CardUnusable))+ .attach_printable("Unvaulted payment method data holds no card")?;++ let card_number = CardNumber::from_str(&card_details.card_number.get_card_no())+ .change_context(AccountUpdaterError::CardUnusable)+ .attach_printable("Failed to parse the unvaulted card number")?;++ let network = card_details+ .card_network+ .clone()+ .ok_or_else(|| report!(AccountUpdaterError::CardUnusable))+ .attach_printable("Unvaulted card carries no network")?;++ Ok(payments_grpc::PaymentMethod {+ payment_method: Some(payments_grpc::payment_method::PaymentMethod::CardWithNoCvc(+ payments_grpc::CardDetailsWithNoCvc {+ card_number: Some(card_number),+ card_exp_month: Some(card_details.card_exp_month.clone()),+ card_exp_year: Some(card_details.card_exp_year.clone()),+ card_network: Some(i32::from(payments_grpc::CardNetwork::foreign_from(network))),+ card_holder_name: None,+ card_issuer: None,+ card_type: None,+ card_issuing_country_alpha2: None,+ bank_code: None,+ nick_name: None,+ },+ )),+ })+}diff --git a/crates/router/src/core/account_updater/refresh.rs b/crates/router/src/core/account_updater/refresh.rsnew file mode 100644index 0000000000..bb1916e9c5--- /dev/null+++ b/crates/router/src/core/account_updater/refresh.rs@@ -0,0 +1,89 @@+use common_enums::ExecutionMode;+use common_utils::errors::CustomResult;+use error_stack::{report, ResultExt};+use external_services::grpc_client::LineageIds;+use router_env::{instrument, tracing};+use unified_connector_service_client::payments as payments_grpc;++use super::types::{AccountUpdaterError, ResolvedAccountUpdaterConfig};+use crate::{+ core::unified_connector_service::build_unified_connector_service_auth_metadata_without_mca,+ routes::SessionState, types::domain,+};++#[instrument(skip_all)]+pub async fn request_account_updater_refresh(+ state: &SessionState,+ platform: &domain::Platform,+ profile: &domain::Profile,+ config: &ResolvedAccountUpdaterConfig,+ refreshable_payment_method: payments_grpc::PaymentMethod,+) -> CustomResult<payments_grpc::CardRefreshOutcome, AccountUpdaterError> {+ let client = state+ .grpc_client+ .unified_connector_service_client+ .as_ref()+ .ok_or_else(|| report!(AccountUpdaterError::RefreshCallFailed))+ .attach_printable("Unified Connector Service client is not configured")?;++ let request = payments_grpc::PaymentMethodServiceRefreshRequest {+ payment_method: Some(refreshable_payment_method),+ };++ let (connector, auth_type, metadata) = config+ .build_connector_credentials()+ .change_context(AccountUpdaterError::RefreshCallFailed)+ .attach_printable("Failed to build the Account Updater connector metadata")?;++ let connector_auth_metadata = build_unified_connector_service_auth_metadata_without_mca(+ connector,+ &auth_type,+ platform.get_processor().get_account().get_id(),+ Some(&metadata),+ )+ .change_context(AccountUpdaterError::RefreshCallFailed)+ .attach_printable("Failed to build the Account Updater auth metadata")?;++ let grpc_headers = state+ .get_grpc_headers_ucs(ExecutionMode::Primary)+ .external_vault_proxy_metadata(None)+ .merchant_reference_id(None)+ .resource_id(None)+ .lineage_ids(LineageIds::new(+ platform.get_processor().get_account().get_id().clone(),+ profile.get_id().clone(),+ ))+ .build();++ let response = Box::pin(client.payment_method_refresh(+ request,+ connector_auth_metadata,+ grpc_headers,+ config.refresh_timeout(),+ ))+ .await+ .change_context(AccountUpdaterError::RefreshCallFailed)+ .attach_printable("Account Updater refresh call to UCS failed")?+ .into_inner();++ if let Some(error) = response.error.as_ref() {+ return Err(+ report!(AccountUpdaterError::RefreshReturnedError).attach_printable(format!(+ "UCS returned error {error:?} with status code {}",+ response.status_code+ )),+ );+ }++ response+ .result+ .and_then(|result| result.result)+ .map(|result| match result {+ payments_grpc::refresh_result::Result::Card(card) => {+ payments_grpc::CardRefreshOutcome::try_from(card.outcome)+ .unwrap_or(payments_grpc::CardRefreshOutcome::Unspecified)+ }+ })+ .ok_or_else(|| report!(AccountUpdaterError::RefreshReturnedError))+ .attach_printable("UCS returned neither a result nor an error")+}diff --git a/crates/router/src/core/account_updater/types.rs b/crates/router/src/core/account_updater/types.rsindex ea1652d80d..32c2ff6857 100644--- a/crates/router/src/core/account_updater/types.rs+++ b/crates/router/src/core/account_updater/types.rs@@ -1,3 +1,18 @@+use std::{collections::HashSet, time::Duration};++use common_enums::{connector_enums::Connector, CardNetwork};+use error_stack::ResultExt;+use hyperswitch_domain_models::router_data::ConnectorAuthType;+use hyperswitch_masking::Secret;++use crate::{+ configs::settings,+ core::{+ errors::{self, RouterResult},+ unified_connector_service::connector_config::JuspayMetadata,+ },+};+#[derive(Debug,Clone,@@ -15,3 +30,102 @@ pub enum AccountUpdaterCredentialSource {None,Application,}++#[derive(Debug, Clone)]+pub enum ResolvedAccountUpdaterConfig {+ Juspay(JuspayConfig),+}++impl ResolvedAccountUpdaterConfig {+ pub fn supported_card_networks(&self) -> &HashSet<CardNetwork> {+ match self {+ Self::Juspay(juspay) => &juspay.supported_card_networks,+ }+ }++ pub fn refresh_timeout(&self) -> Duration {+ match self {+ Self::Juspay(juspay) => juspay.refresh_timeout,+ }+ }++ /// Builds the connector, auth type and metadata the connector config is resolved from.+ pub fn build_connector_credentials(+ &self,+ ) -> RouterResult<(Connector, ConnectorAuthType, serde_json::Value)> {+ match self {+ Self::Juspay(juspay) => {+ let metadata = serde_json::to_value(JuspayMetadata {+ merchant_id: juspay.merchant_id.clone(),+ base_url: juspay.base_url.to_string(),+ juspay_encryption_public_key: juspay.euler_encryption_public_key.clone(),+ response_decryption_private_key: juspay.au_decryption_pvt_key.clone(),+ card_sync_key_id: juspay.card_sync_key_id.clone(),+ })+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to serialize the Juspay Account Updater metadata")?;++ Ok((+ Connector::Juspay,+ ConnectorAuthType::HeaderKey {+ api_key: juspay.api_key.clone(),+ },+ metadata,+ ))+ }+ }+ }+}++#[derive(Debug, Clone)]+pub struct JuspayConfig {+ pub base_url: url::Url,+ pub api_key: Secret<String>,+ pub merchant_id: String,+ pub euler_encryption_public_key: Secret<String>,+ pub au_decryption_pvt_key: Secret<String>,+ pub card_sync_key_id: String,+ pub supported_card_networks: HashSet<CardNetwork>,+ pub refresh_timeout: Duration,+}++impl From<&settings::JuspayAccountUpdaterConfig> for JuspayConfig {+ fn from(config: &settings::JuspayAccountUpdaterConfig) -> Self {+ Self {+ base_url: config.base_url.clone(),+ api_key: config.api_key.clone(),+ merchant_id: config.merchant_id.clone(),+ euler_encryption_public_key: config.euler_encryption_public_key.clone(),+ au_decryption_pvt_key: config.au_decryption_pvt_key.clone(),+ card_sync_key_id: config.card_sync_key_id.clone(),+ supported_card_networks: config.supported_card_networks.clone(),+ refresh_timeout: Duration::from_secs(config.refresh_timeout_in_secs),+ }+ }+}++impl From<&settings::AccountUpdaterConfig> for ResolvedAccountUpdaterConfig {+ fn from(config: &settings::AccountUpdaterConfig) -> Self {+ match config {+ settings::AccountUpdaterConfig::Juspay(juspay) => Self::Juspay(juspay.into()),+ }+ }+}++#[derive(Debug, thiserror::Error)]+pub enum AccountUpdaterError {+ #[error("Account Updater application config is missing or invalid")]+ MissingApplicationConfig,+ #[error("Payment method is not a card")]+ PaymentMethodNotACard,+ #[error("Payment method is not active")]+ PaymentMethodNotActive,+ #[error("Card network is not supported by Account Updater")]+ UnsupportedNetwork,+ #[error("Stored card cannot be used for Account Updater")]+ CardUnusable,+ #[error("Account Updater refresh call failed")]+ RefreshCallFailed,+ #[error("Account Updater refresh returned an error")]+ RefreshReturnedError,+}diff --git a/crates/router/src/core/configs/dimension_config.rs b/crates/router/src/core/configs/dimension_config.rsindex b292588239..b9ab4f6e3a 100644--- a/crates/router/src/core/configs/dimension_config.rs+++ b/crates/router/src/core/configs/dimension_config.rs@@ -834,6 +834,7 @@ impl DatabaseBackedConfig for OfferEngineCredentialSource {const KEY: &'static str = "offer_engine_credential_source";}+#[cfg(feature = "v2")]config! {superposition_key = ACCOUNT_UPDATER_ENABLED,output = bool,@@ -842,10 +843,12 @@ config! {targeting_key = id_type::PaymentId}+#[cfg(feature = "v2")]impl DatabaseBackedConfig for AccountUpdaterEnabled {const KEY: &'static str = "account_updater_enabled";}+#[cfg(feature = "v2")]config! {superposition_key = ACCOUNT_UPDATER_CREDENTIAL_SOURCE,output = crate::core::account_updater::types::AccountUpdaterCredentialSource,@@ -855,6 +858,7 @@ config! {targeting_key = id_type::PaymentId}+#[cfg(feature = "v2")]impl DatabaseBackedConfig for AccountUpdaterCredentialSource {const KEY: &'static str = "account_updater_credential_source";}diff --git a/crates/router/src/core/connector_validation.rs b/crates/router/src/core/connector_validation.rsindex 9449bdd4ce..24a682e78f 100644--- a/crates/router/src/core/connector_validation.rs+++ b/crates/router/src/core/connector_validation.rs@@ -353,7 +353,7 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> {)?;Ok(())}- api_enums::Connector::Juspaythreedsserver => Ok(()),+ api_enums::Connector::Juspay | api_enums::Connector::Juspaythreedsserver => Ok(()),api_enums::Connector::Klarna => {klarna::transformers::KlarnaAuthType::try_from(self.auth_type)?;klarna::transformers::KlarnaConnectorMetadataObject::try_from(diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rsindex cdda5b5fed..b08ed79c02 100644--- a/crates/router/src/core/payment_methods.rs+++ b/crates/router/src/core/payment_methods.rs@@ -84,6 +84,7 @@ use crate::routes::metrics;use crate::{configs::settings,core::{+ account_updater,payment_methods::{transformers as pm_transforms, utils as payment_method_utils},tokenization as tokenization_core,},@@ -5727,7 +5728,7 @@ pub async fn retrieve_payment_method(profile: domain::Profile,platform: domain::Platform,api_key_type: enums::ApiKeyType,- fetch_raw_detail_query_param: bool,+ request: payment_methods::PaymentMethodRetrieveRequest,) -> RouterResponse<api::PaymentMethodResponse> {let db = state.store.as_ref();@@ -5762,11 +5763,12 @@ pub async fn retrieve_payment_method(},)?;- let raw_payment_method_fetch_access = get_raw_payment_method_data_fetch_access(+ let raw_payment_method_access = get_raw_payment_method_data_fetch_access(&state,&dimensions,api_key_type,- fetch_raw_detail_query_param,+ request.fetch_raw_detail,+ request.force_sync,payment_method.customer_id.as_ref(),).await@@ -5788,39 +5790,32 @@ pub async fn retrieve_payment_method(.attach_printable("Failed to retrieve cvc from redis").ok();- let cvc_read_mode = get_cvc_read_mode(- api_key_type,- profile.is_manual_retry_enabled,- profile.get_order_fulfillment_time(),- );-- let raw_payment_method_data =- Box::pin(raw_payment_method_fetch_access.get_raw_payment_method_data(- &state,- &platform,- &profile,- &payment_method,- storage_type,- cvc_read_mode,- ))- .await- .attach_printable("Failed to get raw payment method data")?;+ let mut raw_payment_method_data = Box::pin(+ raw_payment_method_access+ .retrieve_raw_card+ .get_raw_payment_method_data(+ &state,+ &platform,+ &profile,+ &payment_method,+ storage_type,+ ),+ )+ .await+ .attach_printable("Failed to get raw payment method data")?;- let raw_network_token_details =- Box::pin(raw_payment_method_fetch_access.get_raw_network_token_data(- &state,- &platform,- &profile,- &payment_method,- storage_type,- ))- .await- .inspect_err(|err| {- logger::warn!(?err, "Failed to fetch raw network token details");- })- .ok();+ let raw_network_token_details = Box::pin(+ raw_payment_method_access+ .response+ .get_raw_network_token_data(&state, &platform, &profile, &payment_method, storage_type),+ )+ .await+ .inspect_err(|err| {+ logger::warn!(?err, "Failed to fetch raw network token details");+ })+ .ok();- let raw_payment_method_data = match (raw_payment_method_data, raw_network_token_details) {+ raw_payment_method_data = match (raw_payment_method_data, raw_network_token_details) {(Some(payment_methods::RawPaymentMethodData::Card(card_details)),Some(network_token_details),@@ -5833,6 +5828,66 @@ pub async fn retrieve_payment_method((raw_payment_method_data, _) => raw_payment_method_data,};+ if matches!(+ raw_payment_method_access.account_updater,+ RawPaymentMethodFetchAccess::Allowed+ ) {+ let account_updater_dimensions = dimensions+ .with_organization_id(platform.get_provider().get_account().get_org_id().clone())+ .with_profile_id(profile.get_id().clone());++ Box::pin(account_updater::run_account_updater(+ &state,+ &platform,+ &profile,+ &payment_method,+ raw_payment_method_data.as_ref(),+ &account_updater_dimensions,+ ))+ .await;+ }++ match raw_payment_method_access.response {+ RawPaymentMethodFetchAccess::Allowed => {+ let card_details = match &mut raw_payment_method_data {+ Some(payment_methods::RawPaymentMethodData::Card(card_details)) => {+ Some(card_details)+ }+ Some(payment_methods::RawPaymentMethodData::CardWithNT(details)) => {+ Some(&mut details.card_details)+ }+ Some(+ payment_methods::RawPaymentMethodData::BankDebit(_)+ | payment_methods::RawPaymentMethodData::ProxyCard(_),+ )+ | None => None,+ };++ if let Some(card_details) = card_details {+ let cvc_read_mode = get_cvc_read_mode(+ api_key_type,+ profile.is_manual_retry_enabled,+ profile.get_order_fulfillment_time(),+ );++ card_details.card_cvc = vault::retrieve_cvc_from_payment_token(+ &state,+ &payment_method.id.get_string_repr().to_string(),+ platform.get_provider().get_key_store(),+ cvc_read_mode,+ )+ .await+ .inspect_err(|err| {+ logger::warn!(?err, "Failed to retrieve cvc from redis");+ })+ .ok();+ }+ }+ RawPaymentMethodFetchAccess::Denied => {+ raw_payment_method_data = get_proxy_card_data(&payment_method);+ }+ }+let billing = payment_method.payment_method_billing_address.clone()@@ -5868,7 +5923,10 @@ pub async fn retrieve_payment_method_olap(profile,platform,enums::ApiKeyType::External,- false,+ payment_methods::PaymentMethodRetrieveRequest {+ fetch_raw_detail: false,+ force_sync: false,+ },)).await?.get_json_body()@@ -6074,6 +6132,14 @@ pub enum RawPaymentMethodFetchAccess {Denied,}+#[cfg(feature = "v2")]+#[derive(Clone, Copy, Debug)]+pub struct RawPaymentMethodAccess {+ pub response: RawPaymentMethodFetchAccess,+ pub retrieve_raw_card: RawPaymentMethodFetchAccess,+ pub account_updater: RawPaymentMethodFetchAccess,+}+#[cfg(feature = "v2")]fn get_cvc_read_mode(api_key_type: enums::ApiKeyType,@@ -6099,7 +6165,6 @@ impl RawPaymentMethodFetchAccess {profile: &domain::Profile,payment_method: &domain::PaymentMethod,storage_type: common_enums::StorageType,- cvc_read_mode: vault::CvcReadMode,) -> RouterResult<Option<payment_methods::RawPaymentMethodData>> {match self {Self::Denied => {@@ -6107,22 +6172,7 @@ impl RawPaymentMethodFetchAccess {// When access is denied, check if the payment method has external vault token data.// If present, return it as a ProxyCard so non-PCI-compliant merchants can still// receive a tokenized card reference in the retrieve response.- let proxy_card_data = payment_method- .external_vault_token_data- .clone()- .map(|enc| enc.into_inner());- match proxy_card_data {- Some(external_vault_token_data) => {- Ok(Some(payment_methods::RawPaymentMethodData::ProxyCard(- payment_methods::RawProxyCardDataResponse {- card_number: external_vault_token_data.tokenized_card_number,- card_exp_year: None,- card_exp_month: None,- },- )))- }- None => Ok(None),- }+ Ok(get_proxy_card_data(payment_method))}Self::Allowed => {@@ -6154,13 +6204,15 @@ impl RawPaymentMethodFetchAccess {logger::debug!("Skipping raw payment method fetch for wallet or bank redirect payment method");Ok(None)} else {+ // A pure unvault: the CVC is attached by the caller, under the caller's own+ // grant, so that an unvault escalated for Account Updater never consumes it.let vault_data = Box::pin(vault::retrieve_payment_method_data_from_storage(state,platform,profile,payment_method,storage_type,- Some(cvc_read_mode),+ None,)).await.change_context(errors::ApiErrorResponse::InternalServerError)@@ -6266,23 +6318,43 @@ impl RawPaymentMethodFetchAccess {}}+#[cfg(feature = "v2")]+fn get_proxy_card_data(+ payment_method: &domain::PaymentMethod,+) -> Option<payment_methods::RawPaymentMethodData> {+ payment_method+ .external_vault_token_data+ .clone()+ .map(|enc| enc.into_inner())+ .map(|external_vault_token_data| {+ payment_methods::RawPaymentMethodData::ProxyCard(+ payment_methods::RawProxyCardDataResponse {+ card_number: external_vault_token_data.tokenized_card_number,+ card_exp_year: None,+ card_exp_month: None,+ },+ )+ })+}+#[cfg(feature = "v2")]pub async fn get_raw_payment_method_data_fetch_access(state: &SessionState,dimensions: &dimension_state::DimensionsWithProviderMerchantId,api_key_type: enums::ApiKeyType,fetch_raw_detail_query_param: bool,+ force_sync: bool,customer_id: Option<&id_type::GlobalCustomerId>,-) -> RouterResult<RawPaymentMethodFetchAccess> {+) -> RouterResult<RawPaymentMethodAccess> {// If query param not set, never allowed to fetch raw payment method detailslet fetch_access = match fetch_raw_detail_query_param {true => RawPaymentMethodFetchAccess::Allowed,false => RawPaymentMethodFetchAccess::Denied,};- match api_key_type {+ let response = match api_key_type {// Internal API keys always allowed- enums::ApiKeyType::Internal => Ok(fetch_access),+ enums::ApiKeyType::Internal => fetch_access,// External API keys allowed only via org-level config// This supports cases where a PCI-compliant entity needs to retrieve raw payment method details.@@ -6296,11 +6368,30 @@ pub async fn get_raw_payment_method_data_fetch_access(.await;match allowed {- true => Ok(fetch_access),- false => Ok(RawPaymentMethodFetchAccess::Denied),+ true => fetch_access,+ false => RawPaymentMethodFetchAccess::Denied,}}- }+ };++ let account_updater = match api_key_type {+ enums::ApiKeyType::Internal if force_sync => RawPaymentMethodFetchAccess::Allowed,+ enums::ApiKeyType::Internal | enums::ApiKeyType::External => {+ RawPaymentMethodFetchAccess::Denied+ }+ };++ // Account Updater needs the card unvaulted even when the response cannot carry it.+ let retrieve_raw_card = match account_updater {+ RawPaymentMethodFetchAccess::Allowed => RawPaymentMethodFetchAccess::Allowed,+ RawPaymentMethodFetchAccess::Denied => response,+ };++ Ok(RawPaymentMethodAccess {+ response,+ retrieve_raw_card,+ account_updater,+ })}// TODO: When we separate out microservices, this function will be an endpoint in payment_methodsdiff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rsindex 7cc18c3506..6f9fffc645 100644--- a/crates/router/src/core/unified_connector_service.rs+++ b/crates/router/src/core/unified_connector_service.rs@@ -1909,6 +1909,27 @@ fn get_ucs_client(})}+/// Builds auth metadata for flows whose credentials come from application config.+pub fn build_unified_connector_service_auth_metadata_without_mca(+ connector: Connector,+ auth_type: &ConnectorAuthType,+ processor_merchant_id: &id_type::MerchantId,+ metadata: Option<&serde_json::Value>,+) -> CustomResult<ConnectorAuthMetadata, UnifiedConnectorServiceError> {+ let connector_config =+ connector_config::build_connector_config_header(connector, auth_type, metadata)+ .change_context(UnifiedConnectorServiceError::FailedToObtainAuthType)+ .attach_printable("Failed to build connector config header")?+ .map(Secret::new);++ build_connector_auth_metadata(+ connector,+ auth_type,+ processor_merchant_id,+ connector_config,+ )+}+// The UCS proto has no first-class fields for Netcetera-style authentication-connector// metadata (force_3ds_challenge, results/notification URLs, acquirer details), so these are// merged into the authentication-connector MCA's metadata JSON and passed through the generic@@ -1984,7 +2005,6 @@ pub fn build_unified_connector_service_auth_metadata(.get_connector_account_details().change_context(UnifiedConnectorServiceError::FailedToObtainAuthType).attach_printable("Failed to obtain ConnectorAuthType")?;- let merchant_id = processor_merchant_id.get_string_repr();let connector = Connector::from_str(&connector_name).change_context(UnifiedConnectorServiceError::FailedToObtainAuthType).attach_printable_lazy(|| format!("Invalid connector name: {connector_name}"))?;@@ -2003,7 +2023,25 @@ pub fn build_unified_connector_service_auth_metadata(.attach_printable("Failed to build connector config header")?.map(Secret::new);- match &auth_type {+ build_connector_auth_metadata(+ connector,+ &auth_type,+ processor_merchant_id,+ connector_config,+ )+}++/// Maps a [`ConnectorAuthType`] onto the credential fields UCS expects.+fn build_connector_auth_metadata(+ connector: Connector,+ auth_type: &ConnectorAuthType,+ processor_merchant_id: &id_type::MerchantId,+ connector_config: Option<Secret<String>>,+) -> CustomResult<ConnectorAuthMetadata, UnifiedConnectorServiceError> {+ let connector_name = connector.to_string();+ let merchant_id = processor_merchant_id.get_string_repr();++ match auth_type {ConnectorAuthType::SignatureKey {api_key,key1,diff --git a/crates/router/src/core/unified_connector_service/connector_config.rs b/crates/router/src/core/unified_connector_service/connector_config.rsindex 356c778029..4f22b5328f 100644--- a/crates/router/src/core/unified_connector_service/connector_config.rs+++ b/crates/router/src/core/unified_connector_service/connector_config.rs@@ -194,6 +194,15 @@ pub struct TsysTransitMetadata {merchant_url: Option<url::Url>,}+#[derive(Debug, serde::Serialize, serde::Deserialize)]+pub struct JuspayMetadata {+ pub merchant_id: String,+ pub base_url: String,+ pub juspay_encryption_public_key: Secret<String>,+ pub response_decryption_private_key: Secret<String>,+ pub card_sync_key_id: String,+}+/// Connector-specific configuration enum for all supported connectors#[derive(Debug, Clone, serde::Serialize)]pub enum ConnectorSpecificConfig {@@ -664,6 +673,15 @@ pub enum ConnectorSpecificConfig {},/// Givepayments connector configurationGivepayments { api_key: Secret<String> },+ /// Juspay Account Updater configuration+ Juspay {+ api_key: Secret<String>,+ merchant_id: String,+ base_url: String,+ juspay_encryption_public_key: Secret<String>,+ response_decryption_private_key: Secret<String>,+ card_sync_key_id: String,+ },/// Netcetera authentication connector configuration (no connector-specific config needed)Netcetera,/// Santander payout connector configuration@@ -1700,6 +1718,21 @@ impl ForeignTryFrom<(Connector, &ConnectorAuthType, Option<&serde_json::Value>)>}),_ => Err(err("Givepayments requires HeaderKey auth type")),},+ Connector::Juspay => match auth {+ ConnectorAuthType::HeaderKey { api_key } => {+ let juspay_meta = metadata+ .map(|meta| {+ serde_json::from_value::<JuspayMetadata>(meta.clone())+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Invalid Juspay metadata format")+ })+ .transpose()?+ .ok_or_else(|| err("Juspay requires metadata"))?;++ Ok(Self::from((api_key.clone(), juspay_meta)))+ }+ _ => Err(err("Juspay requires HeaderKey auth type")),+ },Connector::Netcetera => Ok(Self::Netcetera),Connector::Santander => match auth {ConnectorAuthType::CertificateAuth {@@ -1755,6 +1788,19 @@ impl ForeignTryFrom<(Connector, &ConnectorAuthType, Option<&serde_json::Value>)>}}+impl From<(Secret<String>, JuspayMetadata)> for ConnectorSpecificConfig {+ fn from((api_key, metadata): (Secret<String>, JuspayMetadata)) -> Self {+ Self::Juspay {+ api_key,+ merchant_id: metadata.merchant_id,+ base_url: metadata.base_url,+ juspay_encryption_public_key: metadata.juspay_encryption_public_key,+ response_decryption_private_key: metadata.response_decryption_private_key,+ card_sync_key_id: metadata.card_sync_key_id,+ }+ }+}+/// Build the X_CONNECTOR_CONFIG header value for any connectorpub fn build_connector_config_header(connector: Connector,diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rsindex 0eb4dbbb43..7b5725f914 100644--- a/crates/router/src/routes/payment_methods.rs+++ b/crates/router/src/routes/payment_methods.rs@@ -336,6 +336,7 @@ pub async fn payment_method_retrieve_api(payment_method_id: path.into_inner(),}).into_inner();+ let retrieve_request = query_payload.into_inner();let api_auth = auth::V2ApiKeyAuth {allow_connected_scope_operation: true,@@ -365,7 +366,7 @@ pub async fn payment_method_retrieve_api(auth.profile,auth.platform,api_key_type,- query_payload.fetch_raw_detail,+ retrieve_request.clone(),),)},diff --git a/crates/router/src/types/api/connector_mapping.rs b/crates/router/src/types/api/connector_mapping.rsindex 382f959e7a..c31a5c8b72 100644--- a/crates/router/src/types/api/connector_mapping.rs+++ b/crates/router/src/types/api/connector_mapping.rs@@ -518,6 +518,7 @@ impl ConnectorData {| enums::Connector::Gpayments| enums::Connector::Threedsecureio| enums::Connector::Cardinal+ | enums::Connector::Juspay| enums::Connector::Taxjar => {Err(report!(errors::ConnectorError::InvalidConnectorName).attach_printable(format!("invalid connector name: {connector_name}")))diff --git a/crates/router/src/types/api/feature_matrix.rs b/crates/router/src/types/api/feature_matrix.rsindex fa1463e31d..fcb4ebe166 100644--- a/crates/router/src/types/api/feature_matrix.rs+++ b/crates/router/src/types/api/feature_matrix.rs@@ -457,7 +457,7 @@ impl FeatureMatrixConnectorData {enums::Connector::Interpayments => Ok(ConnectorEnum::Old(Box::new(connector::Interpayments::new(),))),- enums::Connector::Cardinal => {+ enums::Connector::Cardinal | enums::Connector::Juspay => {Err(report!(errors::ConnectorError::InvalidConnectorName).attach_printable(format!("invalid connector name: {connector_name}"))).change_context(errors::ApiErrorResponse::InternalServerError)diff --git a/crates/router/src/types/connector_transformers.rs b/crates/router/src/types/connector_transformers.rsindex 0f87cc9616..7c62520393 100644--- a/crates/router/src/types/connector_transformers.rs+++ b/crates/router/src/types/connector_transformers.rs@@ -95,6 +95,11 @@ impl ForeignTryFrom<api_enums::Connector> for euclid::enums::RoutableConnectorsapi_enums::Connector::Interpayments => Self::Interpayments,api_enums::Connector::Itaubank => Self::Itaubank,api_enums::Connector::Jpmorgan => Self::Jpmorgan,+ api_enums::Connector::Juspay => {+ Err(common_utils::errors::ValidationError::InvalidValue {+ message: "juspay is not a routable connector".to_string(),+ })?+ }api_enums::Connector::Juspaythreedsserver => {Err(common_utils::errors::ValidationError::InvalidValue {message: "juspaythreedsserver is not a routable connector".to_string(),