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(offers): add merchant-level Offer Engine credential source (#13831)

Apoorv Dixit33b91704cac3
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json
index 5c4ef69f52..4dfc804873 100644
--- a/api-reference/v1/openapi_spec_v1.json
+++ b/api-reference/v1/openapi_spec_v1.json
@@ -26823,6 +26823,14 @@
}
],
"nullable": true
+ },
+ "offer_engine_config": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/OfferEngineMerchantConfig"
+ }
+ ],
+ "nullable": true
}
},
"additionalProperties": false
@@ -28843,6 +28851,24 @@
}
}
},
+ "OfferEngineMerchantConfig": {
+ "type": "object",
+ "description": "Merchant-level Offer Engine credentials (Offer Engine issues one account per merchant)",
+ "required": [
+ "api_key",
+ "merchant_id"
+ ],
+ "properties": {
+ "api_key": {
+ "type": "string",
+ "description": "API key issued by Offer Engine for this merchant"
+ },
+ "merchant_id": {
+ "type": "string",
+ "description": "The Offer Engine merchant id sent in Offer Engine request bodies"
+ }
+ }
+ },
"OfferSelection": {
"type": "object",
"description": "Offer selection sent in a confirm request to apply an offer.",
diff --git a/config/superposition_seed.toml b/config/superposition_seed.toml
index d32e27a9d0..502aecacd6 100644
--- a/config/superposition_seed.toml
+++ b/config/superposition_seed.toml
@@ -15,11 +15,12 @@
[default-configs]
deja_record = { value = false, schema = { type = "boolean" }, description = "Deja per-request recording decision — default SKIP (false). The deja_dimension cohort override (seeded by scripts/seed_superposition.sh) sets this true for the recordable endpoint bucket; /health and other probe traffic fall through to false.", change_reason = "Deja recording sampler" }
-offer_engine_enabled = { value = false, schema = { type = "boolean" }, description = "Master gate for the Offer Engine integration. When false (default) Offer Engine is never called, regardless of offer_engine_credential_source. Set true (per tenant/env override) to allow Offer Engine calls.", change_reason = "Offer Engine disabled by default; enable via Superposition override" }
-offer_engine_credential_source = { value = "none", schema = { type = "string", enum = [
+"offer_engine.enabled" = { value = false, schema = { type = "boolean" }, description = "Master gate for the Offer Engine integration. When false (default) Offer Engine is never called, regardless of offer_engine.credential_source. Set true (per tenant/env override) to allow Offer Engine calls.", change_reason = "Offer Engine disabled by default; enable via Superposition override" }
+"offer_engine.credential_source" = { value = "none", schema = { type = "string", enum = [
"none",
"application",
-] }, description = "Source of Offer Engine credentials once offer_engine_enabled is true: 'none' skips Offer Engine; 'application' uses the static offer_engine application config. Future org/merchant/profile sources will extend the enum alongside their credential storage.", change_reason = "Offer Engine credential source is a string enum: 'none' disables, 'application' enables; extensible to org/merchant/profile sources" }
+ "merchant",
+] }, description = "Source of Offer Engine credentials once offer_engine.enabled is true: 'none' skips Offer Engine; 'application' uses the static offer_engine application config; 'merchant' uses the per-merchant credentials stored on the merchant account. Future org/profile sources will extend the enum alongside their credential storage.", change_reason = "Offer Engine credential source is a string enum: 'none' disables, 'application' uses app config, 'merchant' uses merchant-account credentials; extensible to org/profile sources" }
"account_updater.enabled" = { value = false, schema = { type = "boolean" }, description = "Master gate for the Account Updater integration. When false (default) Account Updater is never called, regardless of account_updater.credential_source. Set true (per tenant/env override) to allow Account Updater calls.", change_reason = "Account Updater disabled by default; enable via Superposition override" }
"account_updater.credential_source" = { value = "none", schema = { type = "string", enum = [
"none",
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index 29ab275d67..b67adf44b2 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -421,6 +421,17 @@ pub struct MerchantAccountMetadata {
pub data: Option<pii::SecretSerdeValue>,
}
+/// Merchant-level Offer Engine credentials (Offer Engine issues one account per merchant)
+#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
+pub struct OfferEngineMerchantConfig {
+ /// API key issued by Offer Engine for this merchant
+ #[schema(value_type = String)]
+ pub api_key: Secret<String>,
+
+ /// The Offer Engine merchant id sent in Offer Engine request bodies
+ pub merchant_id: String,
+}
+
#[cfg(feature = "v1")]
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
#[serde(deny_unknown_fields)]
@@ -502,6 +513,10 @@ pub struct MerchantAccountUpdate {
/// Network tokenization credentials for this merchant account
#[schema(value_type = Option<NetworkTokeizationProviderCredentials>)]
pub network_tokenization_credentials: Option<NetworkTokeizationProviderCredentials>,
+
+ /// Merchant-level Offer Engine credentials, used when the resolved credential source is `merchant`
+ #[schema(value_type = Option<OfferEngineMerchantConfig>)]
+ pub offer_engine_config: Option<OfferEngineMerchantConfig>,
}
#[cfg(feature = "v1")]
diff --git a/crates/diesel_models/src/merchant_account.rs b/crates/diesel_models/src/merchant_account.rs
index fe7394faf2..03b89fed57 100644
--- a/crates/diesel_models/src/merchant_account.rs
+++ b/crates/diesel_models/src/merchant_account.rs
@@ -58,6 +58,7 @@ pub struct MerchantAccount {
pub merchant_account_type: Option<common_enums::MerchantAccountType>,
pub network_tokenization_credentials: Option<Encryption>,
pub fingerprint_secret: Option<Secret<String>>,
+ pub offer_engine_config: Option<Encryption>,
}
#[cfg(feature = "v1")]
@@ -95,6 +96,7 @@ pub struct MerchantAccountSetter {
pub merchant_account_type: common_enums::MerchantAccountType,
pub network_tokenization_credentials: Option<Encryption>,
pub fingerprint_secret: Option<Secret<String>>,
+ pub offer_engine_config: Option<Encryption>,
}
#[cfg(feature = "v1")]
@@ -135,6 +137,7 @@ impl From<MerchantAccountSetter> for MerchantAccount {
merchant_account_type: Some(item.merchant_account_type),
network_tokenization_credentials: item.network_tokenization_credentials,
fingerprint_secret: item.fingerprint_secret,
+ offer_engine_config: item.offer_engine_config,
}
}
}
@@ -171,6 +174,7 @@ pub struct MerchantAccount {
pub merchant_account_type: Option<common_enums::MerchantAccountType>,
pub network_tokenization_credentials: Option<Encryption>,
pub fingerprint_secret: Option<Secret<String>>,
+ pub offer_engine_config: Option<Encryption>,
}
#[cfg(feature = "v2")]
@@ -193,6 +197,7 @@ impl From<MerchantAccountSetter> for MerchantAccount {
merchant_account_type: Some(item.merchant_account_type),
network_tokenization_credentials: None, // need to check if we can have this column in v2
fingerprint_secret: item.fingerprint_secret,
+ offer_engine_config: None,
}
}
}
@@ -267,6 +272,7 @@ pub struct MerchantAccountNew {
pub merchant_account_type: common_enums::MerchantAccountType,
pub network_tokenization_credentials: Option<Encryption>,
pub fingerprint_secret: Option<Secret<String>>,
+ pub offer_engine_config: Option<Encryption>,
}
#[cfg(feature = "v2")]
@@ -340,4 +346,5 @@ pub struct MerchantAccountUpdateInternal {
pub is_platform_account: Option<bool>,
pub product_type: Option<common_enums::MerchantProductType>,
pub network_tokenization_credentials: Option<Encryption>,
+ pub offer_engine_config: Option<Encryption>,
}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 63148108ad..cd7b90a3c8 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -1039,6 +1039,7 @@ diesel::table! {
network_tokenization_credentials -> Nullable<Bytea>,
#[max_length = 128]
fingerprint_secret -> Nullable<Varchar>,
+ offer_engine_config -> Nullable<Bytea>,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index 35a1c0b753..23c899a9dc 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -1005,6 +1005,7 @@ diesel::table! {
network_tokenization_credentials -> Nullable<Bytea>,
#[max_length = 128]
fingerprint_secret -> Nullable<Varchar>,
+ offer_engine_config -> Nullable<Bytea>,
}
}
diff --git a/crates/hyperswitch_domain_models/src/merchant_account.rs b/crates/hyperswitch_domain_models/src/merchant_account.rs
index 938ac2f9e4..50a659d6fe 100644
--- a/crates/hyperswitch_domain_models/src/merchant_account.rs
+++ b/crates/hyperswitch_domain_models/src/merchant_account.rs
@@ -56,6 +56,7 @@ pub struct MerchantAccount {
pub merchant_account_type: common_enums::MerchantAccountType,
pub network_tokenization_credentials: OptionalEncryptableValue,
pub fingerprint_secret: Option<Secret<String>>,
+ pub offer_engine_config: OptionalEncryptableValue,
}
#[cfg(feature = "v1")]
@@ -95,6 +96,7 @@ pub struct MerchantAccountSetter {
pub merchant_account_type: common_enums::MerchantAccountType,
pub network_tokenization_credentials: OptionalEncryptableValue,
pub fingerprint_secret: Option<Secret<String>>,
+ pub offer_engine_config: OptionalEncryptableValue,
}
#[cfg(feature = "v1")]
@@ -134,6 +136,7 @@ impl From<MerchantAccountSetter> for MerchantAccount {
merchant_account_type: item.merchant_account_type,
network_tokenization_credentials: item.network_tokenization_credentials,
fingerprint_secret: item.fingerprint_secret,
+ offer_engine_config: item.offer_engine_config,
}
}
}
@@ -232,6 +235,14 @@ impl MerchantAccount {
&self.default_profile
}
+ #[cfg(feature = "v1")]
+ /// Get the decrypted merchant-level Offer Engine config JSON, if configured
+ pub fn get_offer_engine_config(&self) -> Option<&pii::SecretSerdeValue> {
+ self.offer_engine_config
+ .as_ref()
+ .map(|config| config.get_inner())
+ }
+
#[cfg(feature = "v2")]
/// Get the unique identifier of MerchantAccount
pub fn get_id(&self) -> &common_utils::id_type::MerchantId {
@@ -294,6 +305,7 @@ pub enum MerchantAccountUpdate {
payment_link_config: Option<serde_json::Value>,
pm_collect_link_config: Option<serde_json::Value>,
network_tokenization_credentials: OptionalEncryptableValue,
+ offer_engine_config: OptionalEncryptableValue,
},
StorageSchemeUpdate {
storage_scheme: MerchantStorageScheme,
@@ -351,6 +363,7 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal {
payment_link_config,
pm_collect_link_config,
network_tokenization_credentials,
+ offer_engine_config,
} => Self {
merchant_name: merchant_name.map(Encryption::from),
merchant_details: merchant_details.map(Encryption::from),
@@ -381,6 +394,7 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal {
product_type: None,
network_tokenization_credentials: network_tokenization_credentials
.map(Encryption::from),
+ offer_engine_config: offer_engine_config.map(Encryption::from),
},
MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme } => Self {
storage_scheme: Some(storage_scheme),
@@ -411,6 +425,7 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal {
is_platform_account: None,
product_type: None,
network_tokenization_credentials: None,
+ offer_engine_config: None,
},
MerchantAccountUpdate::ReconUpdate { recon_status } => Self {
recon_status: Some(recon_status),
@@ -441,6 +456,7 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal {
is_platform_account: None,
product_type: None,
network_tokenization_credentials: None,
+ offer_engine_config: None,
},
MerchantAccountUpdate::UnsetDefaultProfile => Self {
default_profile: Some(None),
@@ -471,6 +487,7 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal {
is_platform_account: None,
product_type: None,
network_tokenization_credentials: None,
+ offer_engine_config: None,
},
MerchantAccountUpdate::ModifiedAtUpdate => Self {
modified_at: now,
@@ -501,6 +518,7 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal {
is_platform_account: None,
product_type: None,
network_tokenization_credentials: None,
+ offer_engine_config: None,
},
}
}
@@ -731,6 +749,7 @@ impl Conversion for MerchantAccount {
.network_tokenization_credentials
.map(|credentials| credentials.into()),
fingerprint_secret: self.fingerprint_secret,
+ offer_engine_config: self.offer_engine_config.map(|config| config.into()),
};
Ok(diesel_models::MerchantAccount::from(setter))
@@ -826,6 +845,20 @@ impl Conversion for MerchantAccount {
})
.await?,
fingerprint_secret: item.fingerprint_secret,
+ offer_engine_config: item
+ .offer_engine_config
+ .async_lift(|inner| async {
+ crypto_operation(
+ state,
+ type_name!(Self::DstType),
+ CryptoOperation::DecryptOptional(inner),
+ key_manager_identifier.clone(),
+ key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_optionaloperation())
+ })
+ .await?,
})
}
.await
@@ -875,6 +908,7 @@ impl Conversion for MerchantAccount {
.network_tokenization_credentials
.map(|credentials| credentials.into()),
fingerprint_secret: self.fingerprint_secret,
+ offer_engine_config: self.offer_engine_config.map(|config| config.into()),
})
}
}
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index f0bfb3fea1..7bda18b097 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -392,6 +392,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::admin::CardTestingGuardConfig,
api_models::admin::CardTestingGuardStatus,
api_models::admin::NetworkTokeizationProviderCredentials,
+ api_models::admin::OfferEngineMerchantConfig,
api_models::admin::InternalNetworkTokenizationCredentials,
api_models::admin::PaymentMethodBlockingConfig,
api_models::admin::CardBlockingConfig,
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index c79f6088da..1f096284b6 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -406,9 +406,9 @@ pub const UCS_DDC_METHOD_URL_KEY: &str = "threeDsMethodUrl";
/// Superposition configuration keys
pub mod superposition {
/// Offer Engine master gate key: boolean, `false` (default) disables all Offer Engine calls.
- pub const OFFER_ENGINE_ENABLED: &str = "offer_engine_enabled";
- /// Offer Engine credential source key: `"none"` skips Offer Engine, `"application"` uses the static app config.
- pub const OFFER_ENGINE_CREDENTIAL_SOURCE: &str = "offer_engine_credential_source";
+ pub const OFFER_ENGINE_ENABLED: &str = "offer_engine.enabled";
+ /// Offer Engine credential source key: `"none"` skips Offer Engine, `"application"` uses the static app config, `"merchant"` uses per-merchant credentials.
+ pub const OFFER_ENGINE_CREDENTIAL_SOURCE: &str = "offer_engine.credential_source";
/// Account Updater master gate key: `false` (default) disables all Account Updater calls.
pub const ACCOUNT_UPDATER_ENABLED: &str = "account_updater.enabled";
/// Account Updater credential source key: `"none"` skips Account Updater, `"application"` uses the static application config.
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 8e5d1d7ae7..f8d6a56225 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -643,6 +643,7 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate {
consts::FINGERPRINT_SECRET_LENGTH,
"fs",
))),
+ offer_engine_config: None,
},
)
}
@@ -1217,6 +1218,21 @@ impl MerchantAccountUpdateBridge for api::MerchantAccountUpdate {
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt network_tokenization_credentials")?;
+ let offer_engine_config = self
+ .offer_engine_config
+ .async_map(|value| {
+ core_utils::create_encrypted_data(
+ key_manager_state,
+ key_store,
+ value,
+ type_name!(storage::MerchantAccount),
+ )
+ })
+ .await
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to encrypt offer_engine_config")?;
+
let identifier = km_types::Identifier::Merchant(key_store.merchant_id.clone());
Ok(storage::MerchantAccountUpdate::Update {
merchant_name: self
@@ -1273,6 +1289,7 @@ impl MerchantAccountUpdateBridge for api::MerchantAccountUpdate {
pm_collect_link_config,
routing_algorithm: self.routing_algorithm,
network_tokenization_credentials,
+ offer_engine_config,
})
}
}
diff --git a/crates/router/src/core/configs/dimension_config.rs b/crates/router/src/core/configs/dimension_config.rs
index 488de56879..0e57e27bba 100644
--- a/crates/router/src/core/configs/dimension_config.rs
+++ b/crates/router/src/core/configs/dimension_config.rs
@@ -872,7 +872,7 @@ config! {
}
impl DatabaseBackedConfig for OfferEngineEnabled {
- const KEY: &'static str = "offer_engine_enabled";
+ const KEY: &'static str = "offer_engine.enabled";
}
config! {
@@ -897,7 +897,7 @@ config! {
}
impl DatabaseBackedConfig for OfferEngineCredentialSource {
- const KEY: &'static str = "offer_engine_credential_source";
+ const KEY: &'static str = "offer_engine.credential_source";
}
#[cfg(feature = "v2")]
diff --git a/crates/router/src/core/external_service_auth.rs b/crates/router/src/core/external_service_auth.rs
index ed4ea63da5..366cc38bf7 100644
--- a/crates/router/src/core/external_service_auth.rs
+++ b/crates/router/src/core/external_service_auth.rs
@@ -147,19 +147,42 @@ async fn resolve_offer_engine_merchant_id(
.with_organization_id(payload.org_id.clone())
.with_profile_id(payload.profile_id.clone());
- offer_engine::resolve_offer_engine_config(state, &dimensions)
- .await
- .inspect_err(|error| {
- router_env::logger::warn!(?error, "failed to resolve Offer Engine config");
- })
- .ok()
- .flatten()
- .map(|config| config.merchant_id)
- .ok_or_else(|| {
- error_stack::report!(errors::ApiErrorResponse::AccessForbidden {
- resource: "offer_engine".to_string(),
- })
- })
+ let config =
+ match offer_engine::resolve_offer_engine_credential_source(state, &dimensions).await {
+ offer_engine::OfferEngineCredentialSource::None => {
+ return Err(error_stack::report!(
+ errors::ApiErrorResponse::AccessForbidden {
+ resource: "offer_engine".to_string(),
+ }
+ ));
+ }
+ offer_engine::OfferEngineCredentialSource::Application => {
+ offer_engine::OfferEngineCredentialSource::resolve_application_offer_config(state)
+ }
+ offer_engine::OfferEngineCredentialSource::Merchant => {
+ let db = &*state.store;
+ let key_store = db
+ .get_merchant_key_store_by_merchant_id(
+ &payload.merchant_id,
+ &db.get_master_key().to_vec().into(),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
+ let merchant_account = db
+ .find_merchant_account_by_merchant_id(&payload.merchant_id, &key_store)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
+ offer_engine::OfferEngineCredentialSource::resolve_merchant_offer_config(
+ state,
+ &merchant_account,
+ )
+ }
+ }
+ .change_context(errors::ApiErrorResponse::AccessForbidden {
+ resource: "offer_engine".to_string(),
+ })?;
+
+ Ok(config.merchant_id)
}
/// Offer permissions held by the role. Empty means no offer access.
diff --git a/crates/router/src/core/offer_engine.rs b/crates/router/src/core/offer_engine.rs
index a77357a276..32c44a8649 100644
--- a/crates/router/src/core/offer_engine.rs
+++ b/crates/router/src/core/offer_engine.rs
@@ -11,7 +11,7 @@ pub mod types;
pub mod velocity;
pub use client::OfferEngineClient;
-pub use config::resolve_offer_engine_config;
+pub use config::resolve_offer_engine_credential_source;
#[cfg(feature = "v1")]
pub use notify::{schedule_payment_notification_for_attempt, schedule_refund_notification};
pub use types::{OfferEngineCredentialSource, OfferEngineError, ResolvedOfferEngineConfig};
diff --git a/crates/router/src/core/offer_engine/config.rs b/crates/router/src/core/offer_engine/config.rs
index 1052b2f400..1d23562e64 100644
--- a/crates/router/src/core/offer_engine/config.rs
+++ b/crates/router/src/core/offer_engine/config.rs
@@ -1,18 +1,18 @@
use common_utils::errors::CustomResult;
+use error_stack::ResultExt;
+use hyperswitch_masking::PeekInterface;
use super::types::{OfferEngineCredentialSource, OfferEngineError, ResolvedOfferEngineConfig};
use crate::{
core::configs::{self, dimension_config, dimension_state},
routes::SessionState,
+ types::domain,
};
-/// Resolve the Offer Engine config for the given dimensions. Generic over the
-/// dimension so callers can target at any level (connectivity uses the global
-/// dimension; payments pass merchant/org/profile for superposition targeting).
-pub async fn resolve_offer_engine_config<D>(
+pub async fn resolve_offer_engine_credential_source<D>(
state: &SessionState,
dimensions: &D,
-) -> CustomResult<Option<ResolvedOfferEngineConfig>, OfferEngineError>
+) -> OfferEngineCredentialSource
where
D: dimension_state::DimensionsBase,
{
@@ -25,23 +25,35 @@ where
.await;
if enabled {
- resolve_offer_engine_credentials(state, dimensions).await
+ configs::fetch_db_config_for_string_enum::<
+ dimension_config::OfferEngineCredentialSource,
+ OfferEngineCredentialSource,
+ >(
+ state.store.as_ref(),
+ state.superposition_service.as_ref(),
+ dimensions,
+ None,
+ )
+ .await
+ .unwrap_or_else(|| {
+ router_env::logger::warn!(
+ "Offer Engine credential source config could not be parsed; defaulting to none"
+ );
+ OfferEngineCredentialSource::None
+ })
} else {
- Ok(None)
+ OfferEngineCredentialSource::None
}
}
-/// Resolve the Offer Engine credentials for the given dimensions by credential
-/// source, independent of the `enabled` toggle. The notification path uses this:
-/// an applied offer's outcome must be reported even after the feature is disabled.
-pub async fn resolve_offer_engine_credentials<D>(
+pub async fn fetch_offer_engine_credential_source_for_notify<D>(
state: &SessionState,
dimensions: &D,
-) -> CustomResult<Option<ResolvedOfferEngineConfig>, OfferEngineError>
+) -> OfferEngineCredentialSource
where
D: dimension_state::DimensionsBase,
{
- let source = configs::fetch_db_config_for_string_enum::<
+ configs::fetch_db_config_for_string_enum::<
dimension_config::OfferEngineCredentialSource,
OfferEngineCredentialSource,
>(
@@ -51,31 +63,84 @@ where
None,
)
.await
- .unwrap_or(OfferEngineCredentialSource::None);
+ .unwrap_or_else(|| {
+ router_env::logger::warn!(
+ "Offer Engine credential source config could not be parsed; defaulting to none"
+ );
+ OfferEngineCredentialSource::None
+ })
+}
+
+impl OfferEngineCredentialSource {
+ pub fn resolve_application_offer_config(
+ state: &SessionState,
+ ) -> CustomResult<ResolvedOfferEngineConfig, OfferEngineError> {
+ let app_config = state
+ .conf
+ .offer_engine
+ .as_ref()
+ .ok_or_else(|| {
+ error_stack::report!(OfferEngineError::MissingApplicationConfig(
+ "offer_engine application config is not set".to_string()
+ ))
+ })?
+ .get_inner();
- match source {
- OfferEngineCredentialSource::None => Ok(None),
- OfferEngineCredentialSource::Application => resolve_application_config(state).map(Some),
+ Ok(ResolvedOfferEngineConfig {
+ base_url: app_config.base_url.clone(),
+ api_key: app_config.api_key.clone(),
+ merchant_id: app_config.merchant_id.clone(),
+ })
}
-}
-fn resolve_application_config(
- state: &SessionState,
-) -> CustomResult<ResolvedOfferEngineConfig, OfferEngineError> {
- let app_config = state
- .conf
- .offer_engine
- .as_ref()
- .ok_or_else(|| {
- error_stack::report!(OfferEngineError::MissingApplicationConfig(
- "offer_engine application config is not set".to_string()
- ))
- })?
- .get_inner();
+ #[cfg(feature = "v1")]
+ pub fn resolve_merchant_offer_config(
+ state: &SessionState,
+ merchant_account: &domain::MerchantAccount,
+ ) -> CustomResult<ResolvedOfferEngineConfig, OfferEngineError> {
+ let base_url = state
+ .conf
+ .offer_engine
+ .as_ref()
+ .ok_or_else(|| {
+ error_stack::report!(OfferEngineError::MissingApplicationConfig(
+ "offer_engine base_url is not set in application config".to_string()
+ ))
+ })?
+ .get_inner()
+ .base_url
+ .clone();
- Ok(ResolvedOfferEngineConfig {
- base_url: app_config.base_url.clone(),
- api_key: app_config.api_key.clone(),
- merchant_id: app_config.merchant_id.clone(),
- })
+ let merchant_offer_config =
+ merchant_account.get_offer_engine_config().ok_or_else(|| {
+ error_stack::report!(OfferEngineError::MissingMerchantConfig(
+ "merchant Offer Engine config is not set on the merchant account".to_string()
+ ))
+ })?;
+
+ let merchant_config: api_models::admin::OfferEngineMerchantConfig = serde_json::from_value(
+ merchant_offer_config.peek().clone(),
+ )
+ .change_context(OfferEngineError::MissingMerchantConfig(
+ "merchant Offer Engine config is invalid".to_string(),
+ ))?;
+
+ Ok(ResolvedOfferEngineConfig {
+ base_url,
+ api_key: merchant_config.api_key,
+ merchant_id: merchant_config.merchant_id,
+ })
+ }
+
+ #[cfg(feature = "v2")]
+ pub fn resolve_merchant_offer_config(
+ _state: &SessionState,
+ _merchant_account: &domain::MerchantAccount,
+ ) -> CustomResult<ResolvedOfferEngineConfig, OfferEngineError> {
+ Err(error_stack::report!(
+ OfferEngineError::MissingMerchantConfig(
+ "merchant-level Offer Engine credentials are only supported in v1".to_string()
+ )
+ ))
+ }
}
diff --git a/crates/router/src/core/offer_engine/connectivity.rs b/crates/router/src/core/offer_engine/connectivity.rs
index f33df96955..5261347f50 100644
--- a/crates/router/src/core/offer_engine/connectivity.rs
+++ b/crates/router/src/core/offer_engine/connectivity.rs
@@ -1,4 +1,7 @@
-use super::{client::OfferEngineClient, config::resolve_offer_engine_config};
+use super::{
+ client::OfferEngineClient, config::resolve_offer_engine_credential_source,
+ types::OfferEngineCredentialSource,
+};
use crate::{
core::{configs::dimension_state, errors::RouterResponse},
routes::SessionState,
@@ -24,22 +27,35 @@ pub async fn check_offer_engine_connectivity(
state: SessionState,
) -> RouterResponse<OfferEngineConnectivityResponse> {
let dimensions: dimension_state::DimensionsGlobal = dimension_state::Dimensions::new();
- let response = match resolve_offer_engine_config(&state, &dimensions).await {
- Err(err) => OfferEngineConnectivityResponse {
+ let resolved_config = match resolve_offer_engine_credential_source(&state, &dimensions).await {
+ OfferEngineCredentialSource::None => None,
+ OfferEngineCredentialSource::Application => {
+ Some(OfferEngineCredentialSource::resolve_application_offer_config(&state))
+ }
+ OfferEngineCredentialSource::Merchant => Some(Err(error_stack::report!(
+ super::types::OfferEngineError::MissingMerchantConfig(
+ "credential source is 'merchant' but no merchant context is available in a \
+ global connectivity check"
+ .to_string()
+ )
+ ))),
+ };
+ let response = match resolved_config {
+ Some(Err(err)) => OfferEngineConnectivityResponse {
enabled: false,
reachable: None,
status_code: None,
detail: format!("Offer Engine config could not be resolved: {err:?}"),
},
- Ok(None) => OfferEngineConnectivityResponse {
+ None => OfferEngineConnectivityResponse {
enabled: false,
reachable: None,
status_code: None,
detail: "Offer Engine is not enabled in global config \
- (offer_engine_enabled is false or credential source is none)"
+ (offer_engine.enabled is false or credential source is none)"
.to_string(),
},
- Ok(Some(config)) => {
+ Some(Ok(config)) => {
let result = OfferEngineClient::new(config, &state.conf.trace_header.header_name)
.check_connectivity(&state)
.await;
diff --git a/crates/router/src/core/offer_engine/notify.rs b/crates/router/src/core/offer_engine/notify.rs
index 716818025b..be6d68387d 100644
--- a/crates/router/src/core/offer_engine/notify.rs
+++ b/crates/router/src/core/offer_engine/notify.rs
@@ -5,8 +5,11 @@ use scheduler::{consumer::types::process_data, utils as pt_utils};
use super::{
client::OfferEngineClient,
- config::resolve_offer_engine_credentials,
- types::{OfferNotifyOffer, OfferNotifyRequest, OfferNotifyStatus, OfferTxnStatus},
+ config::fetch_offer_engine_credential_source_for_notify,
+ types::{
+ OfferEngineCredentialSource, OfferNotifyOffer, OfferNotifyRequest, OfferNotifyStatus,
+ OfferTxnStatus,
+ },
};
use crate::{
core::{configs::dimension_state, errors},
@@ -210,8 +213,21 @@ pub async fn execute_notification(
))
.with_organization_id(payment_attempt.organization_id.clone())
.with_profile_id(payment_attempt.profile_id.clone());
- match resolve_offer_engine_credentials(state, &dimensions).await {
- Ok(Some(config)) => {
+ let config =
+ match fetch_offer_engine_credential_source_for_notify(state, &dimensions).await {
+ OfferEngineCredentialSource::None => None,
+ OfferEngineCredentialSource::Application => {
+ Some(OfferEngineCredentialSource::resolve_application_offer_config(state))
+ }
+ OfferEngineCredentialSource::Merchant => {
+ Some(OfferEngineCredentialSource::resolve_merchant_offer_config(
+ state,
+ &merchant_account,
+ ))
+ }
+ };
+ match config {
+ Some(Ok(config)) => {
let applied = applied.inner();
let request = OfferNotifyRequest {
order_id: tracking_data.payment_id.get_string_repr().to_string(),
diff --git a/crates/router/src/core/offer_engine/types.rs b/crates/router/src/core/offer_engine/types.rs
index e52a042d76..755e8e8c09 100644
--- a/crates/router/src/core/offer_engine/types.rs
+++ b/crates/router/src/core/offer_engine/types.rs
@@ -19,6 +19,7 @@ use super::amount;
pub enum OfferEngineCredentialSource {
None,
Application,
+ Merchant,
}
#[derive(Debug, Clone)]
@@ -32,6 +33,8 @@ pub struct ResolvedOfferEngineConfig {
pub enum OfferEngineError {
#[error("Offer Engine application config is missing or invalid: {0}")]
MissingApplicationConfig(String),
+ #[error("Offer Engine merchant config is missing or invalid: {0}")]
+ MissingMerchantConfig(String),
#[error("Offer Engine request failed")]
RequestFailed,
#[error("Failed to parse Offer Engine response")]
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index e7170067f1..762944b193 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -4954,10 +4954,21 @@ pub async fn build_merchant_enabled_pms_context(
None => false,
};
- let offers_enabled = matches!(
- offer_engine::resolve_offer_engine_config(state, &dimensions).await,
- Ok(Some(_))
- );
+ let offers_enabled =
+ match offer_engine::resolve_offer_engine_credential_source(state, &dimensions).await {
+ offer_engine::OfferEngineCredentialSource::None => false,
+ offer_engine::OfferEngineCredentialSource::Application => {
+ offer_engine::OfferEngineCredentialSource::resolve_application_offer_config(state)
+ .is_ok()
+ }
+ offer_engine::OfferEngineCredentialSource::Merchant => {
+ offer_engine::OfferEngineCredentialSource::resolve_merchant_offer_config(
+ state,
+ platform.get_processor().get_account(),
+ )
+ .is_ok()
+ }
+ };
let sdk_next_action = payment_method_utils::get_sdk_next_action_for_payment_method_list(
state,
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index adf5c1cb76..801b27986c 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -14993,11 +14993,38 @@ async fn resolve_offer_eligibility_details(
.with_processor_merchant_id(processor.get_processor_merchant_id())
.with_organization_id(processor.get_account().get_org_id().clone())
.with_profile_id(profile_id.clone());
- offer_engine::resolve_offer_engine_config(state, &offer_dimensions)
- .await
- .ok()
- .flatten()
- .zip(currency)
+ let resolved_config =
+ match offer_engine::resolve_offer_engine_credential_source(state, &offer_dimensions)
+ .await
+ {
+ offer_engine::OfferEngineCredentialSource::None => None,
+ offer_engine::OfferEngineCredentialSource::Application => {
+ offer_engine::OfferEngineCredentialSource::resolve_application_offer_config(
+ state,
+ )
+ .inspect_err(|error| {
+ logger::warn!(
+ ?error,
+ "offer engine: unable to resolve offer config; offers unavailable"
+ )
+ })
+ .ok()
+ }
+ offer_engine::OfferEngineCredentialSource::Merchant => {
+ offer_engine::OfferEngineCredentialSource::resolve_merchant_offer_config(
+ state,
+ processor.get_account(),
+ )
+ .inspect_err(|error| {
+ logger::warn!(
+ ?error,
+ "offer engine: unable to resolve offer config; offers unavailable"
+ )
+ })
+ .ok()
+ }
+ };
+ resolved_config.zip(currency)
};
match offer_context {
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 536e703189..f52e25d71e 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -3238,13 +3238,30 @@ async fn apply_selected_offer<F: Clone + Send + Sync>(
.with_processor_merchant_id(processor.get_processor_merchant_id())
.with_organization_id(processor.get_account().get_org_id().clone())
.with_profile_id(profile_id.clone());
- let offer_config = offer_engine::resolve_offer_engine_config(state, &offer_dimensions)
- .await
- .ok()
- .flatten()
- .ok_or(report!(errors::ApiErrorResponse::PreconditionFailed {
- message: "Offer Engine is not available for this offer selection".to_string(),
- }))?;
+ let offer_config = match offer_engine::resolve_offer_engine_credential_source(
+ state,
+ &offer_dimensions,
+ )
+ .await
+ {
+ offer_engine::OfferEngineCredentialSource::None => {
+ return Err(report!(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Offer Engine is not available for this offer selection".to_string(),
+ }));
+ }
+ offer_engine::OfferEngineCredentialSource::Application => {
+ offer_engine::OfferEngineCredentialSource::resolve_application_offer_config(state)
+ }
+ offer_engine::OfferEngineCredentialSource::Merchant => {
+ offer_engine::OfferEngineCredentialSource::resolve_merchant_offer_config(
+ state,
+ processor.get_account(),
+ )
+ }
+ }
+ .change_context(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Offer Engine is not available for this offer selection".to_string(),
+ })?;
let processor_merchant_id = processor.get_account().get_id().clone();
let payment_id = payment_data.payment_attempt.payment_id.clone();
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index 5c9345e769..ba95825f6c 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -206,6 +206,7 @@ pub async fn update_merchant_active_algorithm_ref(
payment_link_config: None,
pm_collect_link_config: None,
network_tokenization_credentials: None,
+ offer_engine_config: None,
};
let db = &*state.store;
diff --git a/crates/router/src/db/events.rs b/crates/router/src/db/events.rs
index ccb5a156e5..1b0a18542b 100644
--- a/crates/router/src/db/events.rs
+++ b/crates/router/src/db/events.rs
@@ -1997,6 +1997,7 @@ mod tests {
version: common_enums::ApiVersion::V1,
network_tokenization_credentials: None,
fingerprint_secret: None,
+ offer_engine_config: None,
});
let merchant_account = state
.store
diff --git a/migrations/2026-08-24-100000_add_offer_engine_config_to_merchant_account/down.sql b/migrations/2026-08-24-100000_add_offer_engine_config_to_merchant_account/down.sql
new file mode 100644
index 0000000000..56de33e9fb
--- /dev/null
+++ b/migrations/2026-08-24-100000_add_offer_engine_config_to_merchant_account/down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE merchant_account
+DROP COLUMN IF EXISTS offer_engine_config;
diff --git a/migrations/2026-08-24-100000_add_offer_engine_config_to_merchant_account/up.sql b/migrations/2026-08-24-100000_add_offer_engine_config_to_merchant_account/up.sql
new file mode 100644
index 0000000000..cc0b6f2793
--- /dev/null
+++ b/migrations/2026-08-24-100000_add_offer_engine_config_to_merchant_account/up.sql
@@ -0,0 +1,4 @@
+-- Merchant-level Offer Engine credentials (encrypted), used when the resolved
+-- credential source is `merchant`.
+ALTER TABLE merchant_account
+ADD COLUMN IF NOT EXISTS offer_engine_config BYTEA;