Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(core): Added eligible connector and payment_method as a part of sdk configs api (#12667)
Sahkal Poddar7525026e448f
diff --git a/crates/api_models/src/superposition_sdk_config.rs b/crates/api_models/src/superposition_sdk_config.rsindex cb50beceed..860d2c4fca 100644--- a/crates/api_models/src/superposition_sdk_config.rs+++ b/crates/api_models/src/superposition_sdk_config.rs@@ -1,34 +1,42 @@-use std::collections::HashMap;-use common_utils::events::ApiEventMetric;use serde_json::{Map, Value};use superposition_types::Config;use crate::enums as api_enums;-#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]-pub struct SuperPositionConfigResponse {- pub raw_configs: Option<Config>,- pub resolved_configs: Option<Map<String, Value>>,- pub context_used: Map<String, Value>,- pub dynamic_fields: Option<DynamicFields>,+#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq)]+#[serde(rename_all = "snake_case")]+pub enum PaymentMethodCriteria {+ CardNetwork,+ BankName,+ PaymentExperience,}-impl ApiEventMetric for SuperPositionConfigResponse {}+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]+pub struct SdkCriteriaRule {+ pub criteria_value: String,+ pub eligible_connectors: Vec<String>,+}#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]-pub struct DynamicFields {- pub payment_methods: Vec<PaymentMethodGroup>,+pub struct SdkPaymentMethodType {+ pub payment_method_type: api_enums::PaymentMethodType,+ pub payment_method_criteria: Option<PaymentMethodCriteria>,+ pub criteria_rules: Vec<SdkCriteriaRule>,}#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]-pub struct PaymentMethodGroup {+pub struct SdkPaymentMethod {pub payment_method: api_enums::PaymentMethod,- pub payment_method_types: Vec<PaymentMethodTypeWithFields>,+ pub payment_method_types: Vec<SdkPaymentMethodType>,}#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]-pub struct PaymentMethodTypeWithFields {- pub payment_method_type: api_enums::PaymentMethodType,- pub required_fields: HashMap<String, crate::payment_methods::RequiredFieldInfo>,+pub struct SuperPositionConfigResponse {+ pub raw_configs: Config,+ pub resolved_configs: Option<Map<String, Value>>,+ pub context_used: Map<String, Value>,+ pub payment_methods: Option<Vec<SdkPaymentMethod>>,}++impl ApiEventMetric for SuperPositionConfigResponse {}diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rsindex ae89f5947b..8f9acc3e9d 100644--- a/crates/router/src/core/payment_methods/cards.rs+++ b/crates/router/src/core/payment_methods/cards.rs@@ -3381,6 +3381,41 @@ pub struct MerchantEnabledPmsContext {#[cfg(feature = "v1")]impl MerchantEnabledPmsContext {+ /// Collects all unique eligible connectors across all payment methods in the context.+ pub fn get_eligible_connectors(&self) -> HashSet<String> {+ let mut connectors = HashSet::new();++ for pmt_map in self.payment_experiences_consolidated_hm.values() {+ for pe_map in pmt_map.values() {+ for conn_list in pe_map.values() {+ connectors.extend(conn_list.iter().cloned());+ }+ }+ }++ for pmt_map in self.card_networks_consolidated_hm.values() {+ for cn_map in pmt_map.values() {+ for conn_list in cn_map.values() {+ connectors.extend(conn_list.iter().cloned());+ }+ }+ }++ for conn_list in self.banks_consolidated_hm.values() {+ connectors.extend(conn_list.iter().cloned());+ }++ for conn_list in self.bank_debits_consolidated_hm.values() {+ connectors.extend(conn_list.iter().cloned());+ }++ for conn_list in self.bank_transfer_consolidated_hm.values() {+ connectors.extend(conn_list.iter().cloned());+ }++ connectors+ }+/// Converts `payment_experiences_consolidated_hm` → client PM entries (wallet, pay_later, upi, …)pub fn payment_experience_pms_for_client(&self) -> Vec<ResponsePaymentMethodsEnabledForClient> {let mut out = vec![];diff --git a/crates/router/src/core/superposition_sdk_config.rs b/crates/router/src/core/superposition_sdk_config.rsindex 8d61110d82..8e7b6c032c 100644--- a/crates/router/src/core/superposition_sdk_config.rs+++ b/crates/router/src/core/superposition_sdk_config.rs@@ -1,223 +1,175 @@-use std::collections::HashMap;-use api_models::{- admin::PaymentMethodsEnabled,- enums::{self as api_enums, Connector},- payment_methods::RequestPaymentMethodTypes,+ enums as api_enums,superposition_sdk_config::{- DynamicFields, PaymentMethodGroup, PaymentMethodTypeWithFields, SuperPositionConfigResponse,+ PaymentMethodCriteria, SdkCriteriaRule, SdkPaymentMethod, SdkPaymentMethodType,+ SuperPositionConfigResponse,},};-use common_utils::{- ext_traits::StringExt,- id_type::{MerchantId, ProfileId},-};-use hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount;-use hyperswitch_masking::ExposeInterface;+use common_utils::ext_traits::AsyncExt;+use error_stack::ResultExt;use serde_json::Map;use crate::{- configs,consts::superposition::DYNAMIC_FIELDS,- core::errors::{self, RouterResponse, StorageErrorExt},+ core::{+ errors::{self, RouterResponse, StorageErrorExt},+ payment_methods::cards::{+ build_merchant_enabled_pms_context, get_banks, MerchantEnabledPmsContext,+ },+ payments::helpers,+ },routes::SessionState,types::domain,};-/// Type alias for required fields grouped by payment method type.-type RequiredFieldsByPmType = HashMap<- api_enums::PaymentMethodType,- HashMap<String, api_models::payment_methods::RequiredFieldInfo>,->;--/// Type alias for grouped payment method data.-type GroupedPaymentMethods = HashMap<api_enums::PaymentMethod, RequiredFieldsByPmType>;--/// Builds a superset of required fields from common, mandate, and non-mandate fields.-///-/// All field values are set to `None` for configuration responses.-fn build_superset_required_fields(- common: &HashMap<String, api_models::payment_methods::RequiredFieldInfo>,- mandate: &HashMap<String, api_models::payment_methods::RequiredFieldInfo>,- non_mandate: &HashMap<String, api_models::payment_methods::RequiredFieldInfo>,-) -> HashMap<String, api_models::payment_methods::RequiredFieldInfo> {- let mut superset = HashMap::with_capacity(common.len() + mandate.len() + non_mandate.len());-- // Insert common fields directly- for (key, field) in common {- superset.insert(key.clone(), field.for_config());- }-- // Merge mandate fields (don't overwrite existing entries)- for (key, field) in mandate {- superset- .entry(key.clone())- .or_insert_with(|| field.for_config());- }-- // Merge non-mandate fields (don't overwrite existing entries)- for (key, field) in non_mandate {- superset- .entry(key.clone())- .or_insert_with(|| field.for_config());- }-- superset-}--/// Processes payment methods from an MCA and groups required fields.-fn process_mca_payment_methods(- mca: &MerchantConnectorAccount,- required_fields_config: &configs::settings::RequiredFields,- grouped_data: &mut GroupedPaymentMethods,-) {- if let Some(payment_methods_enabled) = &mca.payment_methods_enabled {- for pm_secret in payment_methods_enabled {- match serde_json::from_value::<PaymentMethodsEnabled>(pm_secret.clone().expose()) {- Ok(pm_enabled) => {- if let Some(pm_types) = &pm_enabled.payment_method_types {- for pm_type in pm_types {- process_payment_method_type(- pm_enabled.payment_method,- pm_type,- &mca.connector_name,- required_fields_config,- grouped_data,- );- }- }- }- Err(e) => {- router_env::logger::debug!(error=%e, "Failed to deserialize payment methods enabled");- }- }- }- }+pub struct SdkPaymentContext {+ pub payment_attempt: Option<domain::PaymentAttempt>,+ pub shipping_address: Option<domain::Address>,+ pub billing_address: Option<domain::Address>,+ pub customer: Option<domain::Customer>,+ pub is_cit_transaction: bool,}-/// Processes a single payment method type and adds its required fields to the grouped data.-fn process_payment_method_type(- payment_method: api_enums::PaymentMethod,- pm_type: &RequestPaymentMethodTypes,- connector_name: &str,- required_fields_config: &configs::settings::RequiredFields,- grouped_data: &mut GroupedPaymentMethods,-) {- let payment_method_type = pm_type.payment_method_type;-- if let Ok(connector) =- StringExt::<Connector>::parse_enum(connector_name.to_string(), "Connector").inspect_err(- |err| {- router_env::logger::warn!(- error=%err,- connector=%connector_name,- "Failed to parse connector name to Connector enum"- );- },- )- {- if let Some(required_field_final) = required_fields_config- .0- .get(&payment_method)- .and_then(|pm_type_map| pm_type_map.0.get(&payment_method_type))- .and_then(|connector_fields| connector_fields.fields.get(&connector))- {- let superset = build_superset_required_fields(- &required_field_final.common,- &required_field_final.mandate,- &required_field_final.non_mandate,- );-- grouped_data- .entry(payment_method)- .or_default()- .entry(payment_method_type)- .or_default()- .extend(superset);- } else {- router_env::logger::debug!(- payment_method=?payment_method,- payment_method_type=?payment_method_type,- connector=%connector_name,- "No required fields found in config"- );- }- }-}+async fn get_payment_context(+ state: &SessionState,+ platform: &domain::Platform,+ payment_intent: Option<&hyperswitch_domain_models::payments::PaymentIntent>,+) -> error_stack::Result<SdkPaymentContext, errors::ApiErrorResponse> {+ let db = &*state.store;-/// Converts grouped payment method data into the response structure.-fn convert_to_response(grouped_data: GroupedPaymentMethods) -> DynamicFields {- let payment_methods = grouped_data- .into_iter()- .map(|(payment_method, pm_types_map)| PaymentMethodGroup {- payment_method,- payment_method_types: pm_types_map- .into_iter()- .map(- |(payment_method_type, fields_map)| PaymentMethodTypeWithFields {- payment_method_type,- required_fields: fields_map,- },- )- .collect(),+ let payment_attempt = payment_intent+ .as_ref()+ .async_map(|pi| async {+ db.find_payment_attempt_by_payment_id_processor_merchant_id_attempt_id(+ &pi.payment_id,+ &pi.processor_merchant_id,+ &pi.active_attempt.get_id(),+ platform.get_processor().get_account().storage_scheme,+ platform.get_processor().get_key_store(),+ )+ .await+ .change_context(errors::ApiErrorResponse::PaymentNotFound)})- .collect();-- DynamicFields { payment_methods }-}+ .await+ .transpose()?;-async fn get_dynamic_fields(- state: &SessionState,- platform: &domain::Platform,- profile_id: &ProfileId,- merchant_id: &MerchantId,-) -> error_stack::Result<DynamicFields, errors::ApiErrorResponse> {- let key_store = platform.get_processor().get_key_store();+ let shipping_address = payment_intent+ .as_ref()+ .async_map(|pi| async {+ helpers::get_address_by_id(+ state,+ pi.shipping_address_id.clone(),+ platform.get_processor().get_key_store(),+ &pi.payment_id,+ platform.get_processor().get_account().get_id(),+ platform.get_processor().get_account().storage_scheme,+ )+ .await+ })+ .await+ .transpose()?+ .flatten();- // Fetch all enabled merchant connector accounts for the merchant- let all_mcas = state- .store- .find_merchant_connector_account_by_merchant_id_and_disabled_list(- merchant_id,- false,- key_store,- )+ let billing_address = payment_intent+ .as_ref()+ .async_map(|pi| async {+ helpers::get_address_by_id(+ state,+ pi.billing_address_id.clone(),+ platform.get_processor().get_key_store(),+ &pi.payment_id,+ platform.get_processor().get_account().get_id(),+ platform.get_processor().get_account().storage_scheme,+ )+ .await+ }).await- .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;+ .transpose()?+ .flatten();- // Group required fields by payment method- let mut grouped_data: GroupedPaymentMethods = HashMap::new();+ let customer = payment_intent+ .as_ref()+ .async_and_then(|pi| async {+ pi.customer_id+ .as_ref()+ .async_and_then(|cust| async {+ db.find_customer_by_customer_id_merchant_id(+ cust,+ &pi.merchant_id,+ platform.get_provider().get_key_store(),+ platform.get_provider().get_account().storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)+ .ok()+ })+ .await+ })+ .await;- for mca in all_mcas.iter() {- // Filter MCAs by profile ID- if mca.profile_id == *profile_id {- process_mca_payment_methods(mca, &state.conf.required_fields, &mut grouped_data);- }- }+ let setup_future_usage = payment_intent.as_ref().and_then(|pi| pi.setup_future_usage);++ let is_cit_transaction = payment_attempt+ .as_ref()+ .map(|pa| pa.mandate_details.is_some())+ .unwrap_or(false)+ || setup_future_usage+ .map(|future_usage| future_usage == common_enums::FutureUsage::OffSession)+ .unwrap_or(false);- Ok(convert_to_response(grouped_data))+ Ok(SdkPaymentContext {+ payment_attempt,+ shipping_address,+ billing_address,+ customer,+ is_cit_transaction,+ })}pub async fn get_superposition_sdk_config(state: SessionState,platform: domain::Platform,- profile_id: ProfileId,+ payment_id: common_utils::id_type::PaymentId,) -> RouterResponse<SuperPositionConfigResponse> {let merchant_account = platform.get_processor().get_account();+ let db = &*state.store;+ let payment_intent = db+ .find_payment_intent_by_payment_id_processor_merchant_id(+ &payment_id,+ merchant_account.get_id(),+ platform.get_processor().get_key_store(),+ merchant_account.storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::PaymentNotFound)?;- let dynamic_fields =- get_dynamic_fields(&state, &platform, &profile_id, merchant_account.get_id()).await?;+ let payment_context = get_payment_context(&state, &platform, Some(&payment_intent)).await?;- // we want resolve config with filters which is not yet available in any version of superposition yet. so we are commenting it for future usecase+ let profile_id = payment_intent.profile_id.clone().ok_or(+ errors::ApiErrorResponse::GenericNotFoundError {+ message: "Profile id not found".to_string(),+ },+ )?;++ let business_profile = db+ .find_business_profile_by_profile_id(platform.get_processor().get_key_store(), &profile_id)+ .await+ .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {+ id: profile_id.get_string_repr().to_owned(),+ })?;- // let resolved_configs = state- // .superposition_service- // .as_ref()- // .async_map(|sp| async move { sp.as_ref().resolve_full_config(None, None).await })- // .await- // .transpose()- // .change_context(errors::ApiErrorResponse::InternalServerError)- // .attach_printable("Failed to resolve superposition sdk config")?;+ let merchant_enabled_context = Box::pin(build_merchant_enabled_pms_context(+ &state,+ &platform,+ &business_profile,+ Some(&payment_intent),+ payment_context.payment_attempt.as_ref(),+ payment_context.billing_address.as_ref(),+ payment_context.shipping_address.as_ref(),+ payment_context.customer.as_ref(),+ payment_context.is_cit_transaction,+ ))+ .await?;// Build dimension filter for superposition contextlet mut dimension_filter = Map::new();@@ -233,9 +185,17 @@ pub async fn get_superposition_sdk_config("organization_id".to_string(),serde_json::Value::String(merchant_account.get_org_id().get_string_repr().to_string()),);+ dimension_filter.insert(+ "connector".to_string(),+ serde_json::Value::Array(+ merchant_enabled_context+ .get_eligible_connectors()+ .into_iter()+ .map(serde_json::Value::String)+ .collect(),+ ),+ );- // NOTE: We intentionally ignore Superposition errors to prevent them from blocking dynamic fields functionality.- // This will be removed in future once the superposition service is stable.let raw_configs = state.superposition_service.get_cached_config(@@ -243,17 +203,159 @@ pub async fn get_superposition_sdk_config(Some(dimension_filter.clone()),).await- .inspect_err(|err| {- router_env::logger::warn!(error=%err, "Failed to fetch cached superposition config");- })- .ok();+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable_lazy(|| {+ format!(+ "Failed to fetch superposition config for dimension filter: {dimension_filter:?}"+ )+ })?;++ let payment_methods = translate_to_sdk_payment_methods(&state, &merchant_enabled_context)?;Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(SuperPositionConfigResponse {raw_configs,resolved_configs: None,context_used: dimension_filter,- dynamic_fields: Some(dynamic_fields),+ payment_methods: Some(payment_methods),},))}++fn format_criteria_value(+ card_network: Option<String>,+ bank_name: Option<String>,+ payment_experience: Option<String>,+) -> String {+ let mut parts = Vec::new();+ if let Some(cn) = card_network {+ parts.push(cn);+ }+ if let Some(bn) = bank_name {+ parts.push(bn);+ }+ if let Some(pe) = payment_experience {+ parts.push(pe);+ }+ if parts.is_empty() {+ "default".to_string()+ } else {+ parts.join("/")+ }+}++fn translate_to_sdk_payment_methods(+ state: &SessionState,+ pms_ctx: &MerchantEnabledPmsContext,+) -> error_stack::Result<Vec<SdkPaymentMethod>, errors::ApiErrorResponse> {+ let mut consolidated_rules: std::collections::HashMap<+ (api_enums::PaymentMethod, api_enums::PaymentMethodType),+ (Option<PaymentMethodCriteria>, Vec<SdkCriteriaRule>),+ > = std::collections::HashMap::new();++ // 1. Payment experiences (wallets, paylater, etc.)+ for (payment_method, pmt_map) in &pms_ctx.payment_experiences_consolidated_hm {+ for (payment_method_type, pe_map) in pmt_map {+ let (_, rules) = consolidated_rules+ .entry((*payment_method, *payment_method_type))+ .or_insert_with(|| (Some(PaymentMethodCriteria::PaymentExperience), Vec::new()));+ for (payment_experience, connectors) in pe_map {+ let criteria_value =+ format_criteria_value(None, None, Some(payment_experience.to_string()));+ rules.push(SdkCriteriaRule {+ criteria_value,+ eligible_connectors: connectors.clone(),+ });+ }+ }+ }++ // 2. Card networks (cards)+ for (payment_method, pmt_map) in &pms_ctx.card_networks_consolidated_hm {+ for (payment_method_type, card_network_map) in pmt_map {+ let (_, rules) = consolidated_rules+ .entry((*payment_method, *payment_method_type))+ .or_insert_with(|| (Some(PaymentMethodCriteria::CardNetwork), Vec::new()));+ for (card_network, connectors) in card_network_map {+ let criteria_value =+ format_criteria_value(Some(card_network.to_string()), None, None);+ rules.push(SdkCriteriaRule {+ criteria_value,+ eligible_connectors: connectors.clone(),+ });+ }+ }+ }++ // 3. Banks (bank redirect)+ for (payment_method_type, connectors) in &pms_ctx.banks_consolidated_hm {+ let bank_names = get_banks(state, *payment_method_type, connectors.clone())+ .change_context(errors::ApiErrorResponse::InternalServerError)?;+ let (_, rules) = consolidated_rules+ .entry((api_enums::PaymentMethod::BankRedirect, *payment_method_type))+ .or_insert_with(|| (Some(PaymentMethodCriteria::BankName), Vec::new()));+ for bank_code_res in bank_names {+ for bank_name in bank_code_res.bank_name {+ let criteria_value = format_criteria_value(None, Some(bank_name.to_string()), None);+ rules.push(SdkCriteriaRule {+ criteria_value,+ eligible_connectors: bank_code_res.eligible_connectors.clone(),+ });+ }+ }+ }++ // 4. Bank debits+ for (payment_method_type, connectors) in &pms_ctx.bank_debits_consolidated_hm {+ let (_, rules) = consolidated_rules+ .entry((api_enums::PaymentMethod::BankDebit, *payment_method_type))+ .or_insert_with(|| (None, Vec::new()));+ let criteria_value = format_criteria_value(None, None, None);+ rules.push(SdkCriteriaRule {+ criteria_value,+ eligible_connectors: connectors.clone(),+ });+ }++ // 5. Bank transfers+ for (payment_method_type, connectors) in &pms_ctx.bank_transfer_consolidated_hm {+ let (_, rules) = consolidated_rules+ .entry((api_enums::PaymentMethod::BankTransfer, *payment_method_type))+ .or_insert_with(|| (None, Vec::new()));+ let criteria_value = format_criteria_value(None, None, None);+ rules.push(SdkCriteriaRule {+ criteria_value,+ eligible_connectors: connectors.clone(),+ });+ }++ let mut payment_methods_map: std::collections::HashMap<+ api_enums::PaymentMethod,+ Vec<SdkPaymentMethodType>,+ > = std::collections::HashMap::new();++ for ((payment_method, payment_method_type), (payment_method_criteria, rules)) in+ consolidated_rules+ {+ if !rules.is_empty() {+ let method_types = payment_methods_map.entry(payment_method).or_default();+ method_types.push(SdkPaymentMethodType {+ payment_method_type,+ payment_method_criteria,+ criteria_rules: rules,+ });+ }+ }++ let mut payment_methods = vec![];+ for (payment_method, mut payment_method_types) in payment_methods_map {+ payment_method_types.sort_by_key(|pmt| pmt.payment_method_type.to_string());+ payment_methods.push(SdkPaymentMethod {+ payment_method,+ payment_method_types,+ });+ }+ payment_methods.sort_by_key(|pm| pm.payment_method.to_string());++ Ok(payment_methods)+}diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rsindex d691797b3b..68ca06debb 100644--- a/crates/router/src/lib.rs+++ b/crates/router/src/lib.rs@@ -93,6 +93,8 @@ pub mod headers {pub const X_CLIENT_SECRET: &str = "X-Client-Secret";pub const X_CUSTOMER_ID: &str = "X-Customer-Id";pub const X_CONNECTED_MERCHANT_ID: &str = "x-connected-merchant-id";+ pub const CLIENT_SECRET: &str = "client-secret";+ pub const SDK_AUTHORIZATION: &str = "sdk-authorization";// Header value for X_CONNECTOR_HTTP_STATUS_CODE differs by version.// Constant name is kept the same for consistency across versions.#[cfg(feature = "v1")]diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex 5ed9541698..e67afe8259 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -3403,7 +3403,7 @@ impl SdkConfig {web::scope("/v1/sdk/configs").app_data(web::Data::new(state)).service(- web::resource("{profile_id}/{platform}/{sdk_config.json}")+ web::resource("{platform}/sdk_config.json").route(web::get().to(super::superposition_sdk_config::get_sdk_config)),)}diff --git a/crates/router/src/routes/superposition_sdk_config.rs b/crates/router/src/routes/superposition_sdk_config.rsindex 46979913ba..cb609bd270 100644--- a/crates/router/src/routes/superposition_sdk_config.rs+++ b/crates/router/src/routes/superposition_sdk_config.rs@@ -1,23 +1,64 @@use actix_web::{web, HttpRequest, HttpResponse};+use error_stack::ResultExt;+#[cfg(feature = "v1")]+use hyperswitch_domain_models::sdk_auth::SdkAuthorization;use router_env::{instrument, tracing, Flow};use super::app::AppState;#[cfg(feature = "v1")]-use crate::core::superposition_sdk_config;+use crate::core::{payments, superposition_sdk_config};use crate::{- core::api_locking,+ core::{api_locking, errors},+ headers::{CLIENT_SECRET, SDK_AUTHORIZATION},services::{api, authentication as auth},};+#[cfg(feature = "v1")]+fn get_payment_id_from_headers(+ headers: &actix_web::http::header::HeaderMap,+) -> error_stack::Result<common_utils::id_type::PaymentId, errors::ApiErrorResponse> {+ if let Some(sdk_auth_val) =+ auth::get_header_value_by_key(SDK_AUTHORIZATION.to_string(), headers)?+ {+ let sdk_auth = SdkAuthorization::decode(sdk_auth_val)+ .change_context(errors::ApiErrorResponse::Unauthorized)?;+ sdk_auth.payment_id.ok_or_else(|| {+ error_stack::report!(errors::ApiErrorResponse::MissingRequiredField {+ field_name: "payment_id",+ })+ })+ } else {+ let client_secret = auth::get_header_value_by_key(CLIENT_SECRET.to_string(), headers)?+ .ok_or_else(|| {+ error_stack::report!(errors::ApiErrorResponse::MissingRequiredField {+ field_name: CLIENT_SECRET,+ })+ })?+ .to_string();++ let payment_id_str = payments::helpers::get_payment_id_from_client_secret(&client_secret)?;+ common_utils::id_type::PaymentId::wrap(payment_id_str).change_context(+ errors::ApiErrorResponse::InvalidDataValue {+ field_name: "payment_id",+ },+ )+ }+}+#[cfg(feature = "v1")]#[instrument(skip_all, fields(flow = ?Flow::GetSuperpositionSdkConfig))]pub async fn get_sdk_config(state: web::Data<AppState>,req: HttpRequest,- path: web::Path<(common_utils::id_type::ProfileId, String, String)>,+ path: web::Path<String>,) -> HttpResponse {let flow = Flow::GetSuperpositionSdkConfig;- let (profile_id, _platform, _sdk_config) = path.into_inner();+ let _platform = path.into_inner();++ let payment_id = match get_payment_id_from_headers(req.headers()) {+ Ok(payment_id) => payment_id,+ Err(err) => return api::log_and_return_error_response(err),+ };Box::pin(api::server_wrap(flow,@@ -28,7 +69,7 @@ pub async fn get_sdk_config(superposition_sdk_config::get_superposition_sdk_config(state,auth_data.platform,- profile_id.clone(),+ payment_id.clone(),)},&auth::HeaderAuth(auth::PublishableKeyAuth {