Skip to content

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

feat(core): Get Access Token Redis Key From Connector (#10080)

Sayak Bhattacharya18f7353dfd81
diff --git a/crates/common_utils/src/access_token.rs b/crates/common_utils/src/access_token.rs
index 3407d2840d..bea7019654 100644
--- a/crates/common_utils/src/access_token.rs
+++ b/crates/common_utils/src/access_token.rs
@@ -1,13 +1,16 @@
//! Commonly used utilities for access token
-
use std::fmt::Display;
use crate::id_type;
-/// Create a key for fetching the access token from redis
-pub fn create_access_token_key(
+/// Create a default key for fetching the access token from redis
+pub fn get_default_access_token_key(
merchant_id: &id_type::MerchantId,
merchant_connector_id_or_connector_name: impl Display,
) -> String {
- merchant_id.get_access_token_key(merchant_connector_id_or_connector_name)
+ format!(
+ "access_token_{}_{}",
+ merchant_id.get_string_repr(),
+ merchant_connector_id_or_connector_name
+ )
}
diff --git a/crates/common_utils/src/id_type/merchant.rs b/crates/common_utils/src/id_type/merchant.rs
index d65cd4f266..d11e9742a7 100644
--- a/crates/common_utils/src/id_type/merchant.rs
+++ b/crates/common_utils/src/id_type/merchant.rs
@@ -3,8 +3,6 @@
//! Ids for merchant account are derived from the merchant name
//! If there are any special characters, they are removed
-use std::fmt::Display;
-
use crate::{
date_time,
errors::{CustomResult, ValidationError},
@@ -147,17 +145,6 @@ impl MerchantId {
format!("poll_{}_{unique_id}", self.get_string_repr())
}
- /// get_access_token_key
- pub fn get_access_token_key(
- &self,
- merchant_connector_id_or_connector_name: impl Display,
- ) -> String {
- format!(
- "access_token_{}_{merchant_connector_id_or_connector_name}",
- self.get_string_repr()
- )
- }
-
/// get_skip_saving_wallet_at_connector_key
pub fn get_skip_saving_wallet_at_connector_key(&self) -> String {
format!("skip_saving_wallet_at_connector_{}", self.get_string_repr())
diff --git a/crates/hyperswitch_connectors/src/connectors/santander.rs b/crates/hyperswitch_connectors/src/connectors/santander.rs
index ee2b396417..2094b6f44d 100644
--- a/crates/hyperswitch_connectors/src/connectors/santander.rs
+++ b/crates/hyperswitch_connectors/src/connectors/santander.rs
@@ -35,8 +35,8 @@ use hyperswitch_domain_models::{
};
use hyperswitch_interfaces::{
api::{
- self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
- ConnectorValidation,
+ self, ConnectorAccessTokenSuffix, ConnectorCommon, ConnectorCommonExt,
+ ConnectorIntegration, ConnectorSpecifications, ConnectorValidation,
},
configs::Connectors,
consts::NO_ERROR_MESSAGE,
@@ -1098,3 +1098,29 @@ impl ConnectorSpecifications for Santander {
Some(&SANTANDER_SUPPORTED_WEBHOOK_FLOWS)
}
}
+
+impl ConnectorAccessTokenSuffix for Santander {
+ fn get_access_token_key<F, Req, Res>(
+ &self,
+ router_data: &RouterData<F, Req, Res>,
+ merchant_connector_id_or_connector_name: String,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ let key_suffix = router_data
+ .payment_method_type
+ .as_ref()
+ .map(|pmt| pmt.to_string());
+
+ match key_suffix {
+ Some(key) => Ok(format!(
+ "access_token_{}_{}_{}",
+ router_data.merchant_id.get_string_repr(),
+ merchant_connector_id_or_connector_name,
+ key
+ )),
+ None => Ok(common_utils::access_token::get_default_access_token_key(
+ &router_data.merchant_id,
+ merchant_connector_id_or_connector_name,
+ )),
+ }
+ }
+}
diff --git a/crates/hyperswitch_interfaces/src/api.rs b/crates/hyperswitch_interfaces/src/api.rs
index 738f27d03b..1703658ae5 100644
--- a/crates/hyperswitch_interfaces/src/api.rs
+++ b/crates/hyperswitch_interfaces/src/api.rs
@@ -382,6 +382,8 @@ pub trait ConnectorCommon {
}
}
+impl ConnectorAccessTokenSuffix for BoxedConnector {}
+
/// Current flow information passed to the connector specifications trait
///
/// In order to make some desicion about the preprocessing or alternate flow
@@ -902,3 +904,18 @@ pub trait ConnectorTransactionId: ConnectorCommon + Sync {
.map(ToString::to_string))
}
}
+
+/// Trait ConnectorAccessTokenSuffix
+pub trait ConnectorAccessTokenSuffix {
+ /// Function to get dynamic access token key suffix from Connector
+ fn get_access_token_key<F, Req, Res>(
+ &self,
+ router_data: &RouterData<F, Req, Res>,
+ merchant_connector_id_or_connector_name: String,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(common_utils::access_token::get_default_access_token_key(
+ &router_data.merchant_id,
+ merchant_connector_id_or_connector_name,
+ ))
+ }
+}
diff --git a/crates/hyperswitch_interfaces/src/connector_integration_interface.rs b/crates/hyperswitch_interfaces/src/connector_integration_interface.rs
index 82efc039cb..06b10df957 100644
--- a/crates/hyperswitch_interfaces/src/connector_integration_interface.rs
+++ b/crates/hyperswitch_interfaces/src/connector_integration_interface.rs
@@ -14,8 +14,8 @@ use hyperswitch_domain_models::{
use crate::{
api,
api::{
- BoxedConnectorIntegration, CaptureSyncMethod, Connector, ConnectorCommon,
- ConnectorIntegration, ConnectorRedirectResponse, ConnectorSpecifications,
+ BoxedConnectorIntegration, CaptureSyncMethod, Connector, ConnectorAccessTokenSuffix,
+ ConnectorCommon, ConnectorIntegration, ConnectorRedirectResponse, ConnectorSpecifications,
ConnectorValidation, CurrencyUnit,
},
authentication::ExternalAuthenticationPayload,
@@ -769,6 +769,23 @@ impl ConnectorCommon for ConnectorEnum {
}
}
+impl ConnectorAccessTokenSuffix for ConnectorEnum {
+ fn get_access_token_key<F, Req, Res>(
+ &self,
+ router_data: &RouterData<F, Req, Res>,
+ merchant_connector_id_or_connector_name: String,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ match self {
+ Self::Old(connector) => {
+ connector.get_access_token_key(router_data, merchant_connector_id_or_connector_name)
+ }
+ Self::New(connector) => {
+ connector.get_access_token_key(router_data, merchant_connector_id_or_connector_name)
+ }
+ }
+ }
+}
+
/// Trait representing the connector integration interface
///
/// This trait defines the methods required for a connector integration interface.
diff --git a/crates/hyperswitch_interfaces/src/connector_integration_v2.rs b/crates/hyperswitch_interfaces/src/connector_integration_v2.rs
index 1b870646dd..169c3c25a1 100644
--- a/crates/hyperswitch_interfaces/src/connector_integration_v2.rs
+++ b/crates/hyperswitch_interfaces/src/connector_integration_v2.rs
@@ -65,6 +65,8 @@ impl<
/// Alias for Box<&'static (dyn ConnectorV2 + Sync)>
pub type BoxedConnectorV2 = Box<&'static (dyn ConnectorV2 + Sync)>;
+impl api::ConnectorAccessTokenSuffix for BoxedConnectorV2 {}
+
/// alias for Box of a type that implements trait ConnectorIntegrationV2
pub type BoxedConnectorIntegrationV2<'a, Flow, ResourceCommonData, Req, Resp> =
Box<&'a (dyn ConnectorIntegrationV2<Flow, ResourceCommonData, Req, Resp> + Send + Sync)>;
diff --git a/crates/router/src/core/payment_methods/access_token.rs b/crates/router/src/core/payment_methods/access_token.rs
index c75088546b..0ba64edf25 100644
--- a/crates/router/src/core/payment_methods/access_token.rs
+++ b/crates/router/src/core/payment_methods/access_token.rs
@@ -53,8 +53,12 @@ pub async fn add_access_token_for_external_vault<F: Clone + 'static>(
{
let merchant_id = merchant_account.get_id();
let store = &*state.store;
+ let key = common_utils::access_token::get_default_access_token_key(
+ merchant_id,
+ connector.connector.id(),
+ );
let old_access_token = store
- .get_access_token(merchant_id, connector.connector.id())
+ .get_access_token(key)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("DB error when accessing the access token")?;
@@ -91,12 +95,12 @@ pub async fn add_access_token_for_external_vault<F: Clone + 'static>(
let store = &*state.store;
// This error should not be propagated, we don't want payments to fail once we have
// the access token, the next request will create new access token
+ let key = common_utils::access_token::get_default_access_token_key(
+ merchant_id,
+ connector.connector.id(),
+ );
let _ = store
- .set_access_token(
- merchant_id,
- connector.connector.id(),
- access_token.clone(),
- )
+ .set_access_token(key, access_token.clone())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("DB error when setting the access token");
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index f8ba64686f..080896ed82 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -547,7 +547,7 @@ pub async fn payments_operation_core<'a, F, Req, Op, FData, D>(
header_payload: HeaderPayload,
) -> RouterResult<(D, Req, Option<domain::Customer>, Option<u16>, Option<u128>)>
where
- F: Send + Clone + Sync + 'static,
+ F: Send + Clone + Sync + Debug + 'static,
Req: Authenticate + Clone,
Op: Operation<F, Req, Data = D> + Send + Sync,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
@@ -2141,7 +2141,7 @@ pub async fn payments_core<F, Res, Req, Op, FData, D>(
header_payload: HeaderPayload,
) -> RouterResponse<Res>
where
- F: Send + Clone + Sync + 'static,
+ F: Send + Clone + Sync + Debug + 'static,
FData: Send + Sync + Clone + router_types::Capturable + 'static + serde::Serialize,
Op: Operation<F, Req, Data = D> + Send + Sync + Clone,
Req: Debug + Authenticate + Clone,
@@ -4329,7 +4329,7 @@ pub async fn decide_unified_connector_service_call<'a, F, RouterDReq, ApiRequest
helpers::MerchantConnectorAccountType,
)>
where
- F: Send + Clone + Sync + 'static,
+ F: Send + Clone + Sync + Debug + 'static,
RouterDReq: Send + Sync + Clone + 'static + serde::Serialize,
// To create connector flow specific interface data
diff --git a/crates/router/src/core/payments/access_token.rs b/crates/router/src/core/payments/access_token.rs
index 551267857f..56c98632ab 100644
--- a/crates/router/src/core/payments/access_token.rs
+++ b/crates/router/src/core/payments/access_token.rs
@@ -2,7 +2,7 @@ use std::fmt::Debug;
use common_utils::ext_traits::AsyncExt;
use error_stack::ResultExt;
-use hyperswitch_interfaces::api::ConnectorSpecifications;
+use hyperswitch_interfaces::api::{ConnectorAccessTokenSuffix, ConnectorSpecifications};
use crate::{
consts,
@@ -37,8 +37,13 @@ pub async fn get_cached_access_token_for_ucs(
.or(creds_identifier.map(|id| id.to_string()))
.unwrap_or(connector.connector_name.to_string());
+ let key = common_utils::access_token::get_default_access_token_key(
+ merchant_id,
+ merchant_connector_id_or_connector_name,
+ );
+
let cached_access_token = store
- .get_access_token(merchant_id, &merchant_connector_id_or_connector_name)
+ .get_access_token(key)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("DB error when accessing the access token")?;
@@ -136,8 +141,17 @@ pub async fn add_access_token<
.or(creds_identifier.map(|id| id.to_string()))
.unwrap_or(connector.connector_name.to_string());
+ let key = connector
+ .connector
+ .get_access_token_key(router_data, merchant_connector_id_or_connector_name.clone())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(format!(
+ "Failed to get access token key for connector: {:?}",
+ connector.connector_name
+ ))?;
+
let old_access_token = store
- .get_access_token(merchant_id, &merchant_connector_id_or_connector_name)
+ .get_access_token(key.clone())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("DB error when accessing the access token")?;
@@ -220,8 +234,7 @@ pub async fn add_access_token<
if let Err(access_token_set_error) = store
.set_access_token(
- merchant_id,
- &merchant_connector_id_or_connector_name,
+ key.clone(),
modified_access_token_with_expiry.clone(),
)
.await
diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs
index e1e739476b..8d1be8da01 100644
--- a/crates/router/src/core/payments/retry.rs
+++ b/crates/router/src/core/payments/retry.rs
@@ -48,7 +48,7 @@ pub async fn do_gsm_actions<'a, F, ApiRequest, FData, D>(
business_profile: &domain::Profile,
) -> RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>>
where
- F: Clone + Send + Sync + 'static,
+ F: Clone + Send + Sync + std::fmt::Debug + 'static,
FData: Send + Sync + types::Capturable + Clone + 'static + serde::Serialize,
payments::PaymentResponse: operations::Operation<F, FData>,
D: payments::OperationSessionGetters<F>
@@ -356,7 +356,7 @@ pub async fn do_retry<'a, F, ApiRequest, FData, D>(
routing_decision: Option<routing_helpers::RoutingDecisionData>,
) -> RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>>
where
- F: Clone + Send + Sync + 'static,
+ F: Clone + Send + Sync + std::fmt::Debug + 'static,
FData: Send + Sync + types::Capturable + Clone + 'static + serde::Serialize,
payments::PaymentResponse: operations::Operation<F, FData>,
D: payments::OperationSessionGetters<F>
diff --git a/crates/router/src/core/payouts/access_token.rs b/crates/router/src/core/payouts/access_token.rs
index b08ba0ccc2..1a8164b97f 100644
--- a/crates/router/src/core/payouts/access_token.rs
+++ b/crates/router/src/core/payouts/access_token.rs
@@ -1,5 +1,6 @@
use common_utils::ext_traits::AsyncExt;
use error_stack::ResultExt;
+use hyperswitch_interfaces::api::{ConnectorAccessTokenSuffix, ConnectorCommon};
use crate::{
consts,
@@ -49,16 +50,19 @@ pub async fn add_access_token_for_payout<F: Clone + 'static>(
router_data: &types::PayoutsRouterData<F>,
payout_type: Option<enums::PayoutType>,
) -> RouterResult<types::AddAccessTokenResult> {
- use crate::types::api::ConnectorCommon;
-
if connector
.connector_name
.supports_access_token_for_payout(payout_type)
{
- let merchant_id = platform.get_processor().get_account().get_id();
let store = &*state.store;
+
+ let key = connector
+ .connector
+ .get_access_token_key(router_data, connector.connector.id().to_string())
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
+
let old_access_token = store
- .get_access_token(merchant_id, connector.connector.id())
+ .get_access_token(key.clone())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("DB error when accessing the access token")?;
@@ -96,11 +100,7 @@ pub async fn add_access_token_for_payout<F: Clone + 'static>(
// This error should not be propagated, we don't want payments to fail once we have
// the access token, the next request will create new access token
let _ = store
- .set_access_token(
- merchant_id,
- connector.connector.id(),
- access_token.clone(),
- )
+ .set_access_token(key, access_token.clone())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("DB error when setting the access token");
diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rs
index 8c70b65eb7..c95e9f3967 100644
--- a/crates/router/src/core/unified_connector_service.rs
+++ b/crates/router/src/core/unified_connector_service.rs
@@ -91,11 +91,12 @@ pub async fn get_access_token_from_ucs_response(
.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
- {
+ let key = common_utils::access_token::get_default_access_token_key(
+ merchant_id,
+ merchant_connector_id_or_connector_name,
+ );
+
+ if let Ok(Some(cached_token)) = session_state.store.get_access_token(key).await {
if cached_token.token.peek() == ucs_access_token.token.peek() {
return None;
}
@@ -119,6 +120,11 @@ pub async fn set_access_token_for_ucs(
.or(creds_identifier.map(|id| id.to_string()))
.unwrap_or(connector_name.to_string());
+ let key = common_utils::access_token::get_default_access_token_key(
+ merchant_id,
+ &merchant_connector_id_or_connector_name,
+ );
+
let modified_access_token = AccessToken {
expires: access_token
.expires
@@ -135,11 +141,7 @@ pub async fn set_access_token_for_ucs(
if let Err(access_token_set_error) = state
.store
- .set_access_token(
- merchant_id,
- &merchant_connector_id_or_connector_name,
- modified_access_token,
- )
+ .set_access_token(key, 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
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 0e4acc2770..075f2e7fb2 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1120,23 +1120,17 @@ impl MerchantAccountInterface for KafkaStore {
impl ConnectorAccessToken for KafkaStore {
async fn get_access_token(
&self,
- merchant_id: &id_type::MerchantId,
- merchant_connector_id: &str,
+ key: String,
) -> CustomResult<Option<AccessToken>, errors::StorageError> {
- self.diesel_store
- .get_access_token(merchant_id, merchant_connector_id)
- .await
+ self.diesel_store.get_access_token(key).await
}
async fn set_access_token(
&self,
- merchant_id: &id_type::MerchantId,
- merchant_connector_id: &str,
+ key: String,
access_token: AccessToken,
) -> CustomResult<(), errors::StorageError> {
- self.diesel_store
- .set_access_token(merchant_id, merchant_connector_id, access_token)
- .await
+ self.diesel_store.set_access_token(key, access_token).await
}
}
diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs
index 887d85eec1..1a0bffdfd3 100644
--- a/crates/router/src/db/merchant_connector_account.rs
+++ b/crates/router/src/db/merchant_connector_account.rs
@@ -14,14 +14,12 @@ use crate::{
pub trait ConnectorAccessToken {
async fn get_access_token(
&self,
- merchant_id: &common_utils::id_type::MerchantId,
- merchant_connector_id_or_connector_name: &str,
+ &key: String,
) -> CustomResult<Option<types::AccessToken>, errors::StorageError>;
async fn set_access_token(
&self,
- merchant_id: &common_utils::id_type::MerchantId,
- merchant_connector_id_or_connector_name: &str,
+ key: String,
access_token: types::AccessToken,
) -> CustomResult<(), errors::StorageError>;
}
@@ -31,16 +29,11 @@ impl ConnectorAccessToken for Store {
#[instrument(skip_all)]
async fn get_access_token(
&self,
- merchant_id: &common_utils::id_type::MerchantId,
- merchant_connector_id_or_connector_name: &str,
+ key: String,
) -> CustomResult<Option<types::AccessToken>, errors::StorageError> {
//TODO: Handle race condition
// This function should acquire a global lock on some resource, if access token is already
// being refreshed by other request then wait till it finishes and use the same access token
- let key = common_utils::access_token::create_access_token_key(
- merchant_id,
- merchant_connector_id_or_connector_name,
- );
let maybe_token = self
.get_redis_conn()
@@ -61,14 +54,9 @@ impl ConnectorAccessToken for Store {
#[instrument(skip_all)]
async fn set_access_token(
&self,
- merchant_id: &common_utils::id_type::MerchantId,
- merchant_connector_id_or_connector_name: &str,
+ key: String,
access_token: types::AccessToken,
) -> CustomResult<(), errors::StorageError> {
- let key = common_utils::access_token::create_access_token_key(
- merchant_id,
- merchant_connector_id_or_connector_name,
- );
let serialized_access_token = access_token
.encode_to_string_of_json()
.change_context(errors::StorageError::SerializationFailed)?;
@@ -84,16 +72,14 @@ impl ConnectorAccessToken for Store {
impl ConnectorAccessToken for MockDb {
async fn get_access_token(
&self,
- _merchant_id: &common_utils::id_type::MerchantId,
- _merchant_connector_id_or_connector_name: &str,
+ _key: String,
) -> CustomResult<Option<types::AccessToken>, errors::StorageError> {
Ok(None)
}
async fn set_access_token(
&self,
- _merchant_id: &common_utils::id_type::MerchantId,
- _merchant_connector_id_or_connector_name: &str,
+ _key: String,
_access_token: types::AccessToken,
) -> CustomResult<(), errors::StorageError> {
Ok(())