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

refactor(core): use profile id to find connector (#2020)

Narayan Bhat5b29c25210ed
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index 5f00321ad8..e0be641fe9 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -488,7 +488,7 @@ impl From<StraightThroughAlgorithm> for StraightThroughAlgorithmSerde {
}
}
-#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
+#[derive(Clone, Debug, Deserialize, ToSchema, Serialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct PrimaryBusinessDetails {
#[schema(value_type = CountryAlpha2)]
@@ -615,10 +615,10 @@ pub struct MerchantConnectorCreate {
#[schema(example = json!(common_utils::consts::FRM_CONFIGS_EG))]
pub frm_configs: Option<Vec<FrmConfigs>>,
- #[schema(value_type = CountryAlpha2, example = "US")]
- pub business_country: api_enums::CountryAlpha2,
+ #[schema(value_type = Option<CountryAlpha2>, example = "US")]
+ pub business_country: Option<api_enums::CountryAlpha2>,
- pub business_label: String,
+ pub business_label: Option<String>,
/// Business Sub label of the merchant
#[schema(example = "chase")]
@@ -658,7 +658,7 @@ pub struct MerchantConnectorResponse {
// /// Connector label for specific country and Business
#[serde(skip_deserializing)]
#[schema(example = "stripe_US_travel")]
- pub connector_label: String,
+ pub connector_label: Option<String>,
/// Unique ID of the connector
#[schema(example = "mca_5apGeP94tMts6rg3U3kR")]
@@ -708,12 +708,12 @@ pub struct MerchantConnectorResponse {
pub metadata: Option<pii::SecretSerdeValue>,
/// Business Country of the connector
- #[schema(value_type = CountryAlpha2, example = "US")]
- pub business_country: api_enums::CountryAlpha2,
+ #[schema(value_type = Option<CountryAlpha2>, example = "US")]
+ pub business_country: Option<api_enums::CountryAlpha2>,
///Business Type of the merchant
#[schema(example = "travel")]
- pub business_label: String,
+ pub business_label: Option<String>,
/// Business Sub label of the merchant
#[schema(example = "chase")]
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 559682a43d..6b1c71f803 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -1866,11 +1866,11 @@ pub struct PaymentsResponse {
pub connector_label: Option<String>,
/// The business country of merchant for this payment
- #[schema(value_type = CountryAlpha2, example = "US")]
- pub business_country: api_enums::CountryAlpha2,
+ #[schema(value_type = Option<CountryAlpha2>, example = "US")]
+ pub business_country: Option<api_enums::CountryAlpha2>,
/// The business label of merchant for this payment
- pub business_label: String,
+ pub business_label: Option<String>,
/// The business_sub_label for this payment
pub business_sub_label: Option<String>,
diff --git a/crates/data_models/src/payments/payment_intent.rs b/crates/data_models/src/payments/payment_intent.rs
index a34cb8bd0f..26c244782a 100644
--- a/crates/data_models/src/payments/payment_intent.rs
+++ b/crates/data_models/src/payments/payment_intent.rs
@@ -93,8 +93,8 @@ pub struct PaymentIntent {
pub off_session: Option<bool>,
pub client_secret: Option<String>,
pub active_attempt_id: String,
- pub business_country: storage_enums::CountryAlpha2,
- pub business_label: String,
+ pub business_country: Option<storage_enums::CountryAlpha2>,
+ pub business_label: Option<String>,
pub order_details: Option<Vec<pii::SecretSerdeValue>>,
pub allowed_payment_method_types: Option<serde_json::Value>,
pub connector_metadata: Option<serde_json::Value>,
@@ -134,8 +134,8 @@ pub struct PaymentIntentNew {
pub off_session: Option<bool>,
pub client_secret: Option<String>,
pub active_attempt_id: String,
- pub business_country: storage_enums::CountryAlpha2,
- pub business_label: String,
+ pub business_country: Option<storage_enums::CountryAlpha2>,
+ pub business_label: Option<String>,
pub order_details: Option<Vec<pii::SecretSerdeValue>>,
pub allowed_payment_method_types: Option<serde_json::Value>,
pub connector_metadata: Option<serde_json::Value>,
diff --git a/crates/diesel_models/src/file.rs b/crates/diesel_models/src/file.rs
index baa37507e9..d6efcbbc6a 100644
--- a/crates/diesel_models/src/file.rs
+++ b/crates/diesel_models/src/file.rs
@@ -17,6 +17,7 @@ pub struct FileMetadataNew {
pub file_upload_provider: Option<common_enums::FileUploadProvider>,
pub available: bool,
pub connector_label: Option<String>,
+ pub profile_id: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Serialize, Identifiable, Queryable)]
@@ -34,6 +35,7 @@ pub struct FileMetadata {
#[serde(with = "custom_serde::iso8601")]
pub created_at: time::PrimitiveDateTime,
pub connector_label: Option<String>,
+ pub profile_id: Option<String>,
}
#[derive(Debug)]
diff --git a/crates/diesel_models/src/merchant_connector_account.rs b/crates/diesel_models/src/merchant_connector_account.rs
index 29d4709050..5ccfea2bb0 100644
--- a/crates/diesel_models/src/merchant_connector_account.rs
+++ b/crates/diesel_models/src/merchant_connector_account.rs
@@ -28,9 +28,9 @@ pub struct MerchantConnectorAccount {
pub payment_methods_enabled: Option<Vec<serde_json::Value>>,
pub connector_type: storage_enums::ConnectorType,
pub metadata: Option<pii::SecretSerdeValue>,
- pub connector_label: String,
- pub business_country: storage_enums::CountryAlpha2,
- pub business_label: String,
+ pub connector_label: Option<String>,
+ pub business_country: Option<storage_enums::CountryAlpha2>,
+ pub business_label: Option<String>,
pub business_sub_label: Option<String>,
pub frm_configs: Option<Secret<serde_json::Value>>,
pub created_at: time::PrimitiveDateTime,
@@ -53,9 +53,9 @@ pub struct MerchantConnectorAccountNew {
pub merchant_connector_id: String,
pub payment_methods_enabled: Option<Vec<serde_json::Value>>,
pub metadata: Option<pii::SecretSerdeValue>,
- pub connector_label: String,
- pub business_country: storage_enums::CountryAlpha2,
- pub business_label: String,
+ pub connector_label: Option<String>,
+ pub business_country: Option<storage_enums::CountryAlpha2>,
+ pub business_label: Option<String>,
pub business_sub_label: Option<String>,
pub frm_configs: Option<Secret<serde_json::Value>>,
pub created_at: time::PrimitiveDateTime,
diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs
index 6468a8b1df..1212c9d524 100644
--- a/crates/diesel_models/src/payment_intent.rs
+++ b/crates/diesel_models/src/payment_intent.rs
@@ -34,8 +34,8 @@ pub struct PaymentIntent {
pub off_session: Option<bool>,
pub client_secret: Option<String>,
pub active_attempt_id: String,
- pub business_country: storage_enums::CountryAlpha2,
- pub business_label: String,
+ pub business_country: Option<storage_enums::CountryAlpha2>,
+ pub business_label: Option<String>,
#[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)]
pub order_details: Option<Vec<pii::SecretSerdeValue>>,
pub allowed_payment_method_types: Option<serde_json::Value>,
@@ -87,8 +87,8 @@ pub struct PaymentIntentNew {
pub off_session: Option<bool>,
pub client_secret: Option<String>,
pub active_attempt_id: String,
- pub business_country: storage_enums::CountryAlpha2,
- pub business_label: String,
+ pub business_country: Option<storage_enums::CountryAlpha2>,
+ pub business_label: Option<String>,
#[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)]
pub order_details: Option<Vec<pii::SecretSerdeValue>>,
pub allowed_payment_method_types: Option<serde_json::Value>,
@@ -186,6 +186,7 @@ pub struct PaymentIntentUpdateInternal {
#[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)]
pub order_details: Option<Vec<pii::SecretSerdeValue>>,
pub attempt_count: Option<i16>,
+ pub profile_id: Option<String>,
merchant_decision: Option<String>,
payment_confirm_source: Option<storage_enums::PaymentSource>,
}
diff --git a/crates/diesel_models/src/query/business_profile.rs b/crates/diesel_models/src/query/business_profile.rs
index 0c9737ef61..fcdd97ca9d 100644
--- a/crates/diesel_models/src/query/business_profile.rs
+++ b/crates/diesel_models/src/query/business_profile.rs
@@ -47,6 +47,21 @@ impl BusinessProfile {
.await
}
+ #[instrument(skip(conn))]
+ pub async fn find_by_profile_name_merchant_id(
+ conn: &PgPooledConn,
+ profile_name: &str,
+ merchant_id: &str,
+ ) -> StorageResult<Self> {
+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
+ conn,
+ dsl::profile_name
+ .eq(profile_name.to_owned())
+ .and(dsl::merchant_id.eq(merchant_id.to_owned())),
+ )
+ .await
+ }
+
pub async fn list_business_profile_by_merchant_id(
conn: &PgPooledConn,
merchant_id: &str,
diff --git a/crates/diesel_models/src/query/merchant_connector_account.rs b/crates/diesel_models/src/query/merchant_connector_account.rs
index 4f11e3c13e..17e34b2a86 100644
--- a/crates/diesel_models/src/query/merchant_connector_account.rs
+++ b/crates/diesel_models/src/query/merchant_connector_account.rs
@@ -70,6 +70,21 @@ impl MerchantConnectorAccount {
.await
}
+ #[instrument(skip(conn))]
+ pub async fn find_by_profile_id_connector_name(
+ conn: &PgPooledConn,
+ profile_id: &str,
+ connector_name: &str,
+ ) -> StorageResult<Self> {
+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
+ conn,
+ dsl::profile_id
+ .eq(profile_id.to_owned())
+ .and(dsl::connector_name.eq(connector_name.to_owned())),
+ )
+ .await
+ }
+
#[instrument(skip(conn))]
pub async fn find_by_merchant_id_connector_name(
conn: &PgPooledConn,
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index fe22efd744..31aa03ff4a 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -282,6 +282,8 @@ diesel::table! {
created_at -> Timestamp,
#[max_length = 255]
connector_label -> Nullable<Varchar>,
+ #[max_length = 64]
+ profile_id -> Nullable<Varchar>,
}
}
@@ -455,10 +457,10 @@ diesel::table! {
connector_type -> ConnectorType,
metadata -> Nullable<Jsonb>,
#[max_length = 255]
- connector_label -> Varchar,
- business_country -> CountryAlpha2,
+ connector_label -> Nullable<Varchar>,
+ business_country -> Nullable<CountryAlpha2>,
#[max_length = 255]
- business_label -> Varchar,
+ business_label -> Nullable<Varchar>,
#[max_length = 64]
business_sub_label -> Nullable<Varchar>,
frm_configs -> Nullable<Jsonb>,
@@ -585,9 +587,9 @@ diesel::table! {
client_secret -> Nullable<Varchar>,
#[max_length = 64]
active_attempt_id -> Varchar,
- business_country -> CountryAlpha2,
+ business_country -> Nullable<CountryAlpha2>,
#[max_length = 64]
- business_label -> Varchar,
+ business_label -> Nullable<Varchar>,
order_details -> Nullable<Array<Nullable<Jsonb>>>,
allowed_payment_method_types -> Nullable<Json>,
connector_metadata -> Nullable<Json>,
diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs
index 8c3c62b01f..926482bf5a 100644
--- a/crates/router/src/compatibility/stripe/errors.rs
+++ b/crates/router/src/compatibility/stripe/errors.rs
@@ -124,8 +124,11 @@ pub enum StripeErrorCode {
#[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "duplicate merchant account")]
DuplicateMerchantAccount,
- #[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "The merchant connector account with the specified connector_label '{connector_label}' already exists in our records")]
- DuplicateMerchantConnectorAccount { connector_label: String },
+ #[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "The merchant connector account with the specified profile_id '{profile_id}' and connector_name '{connector_name}' already exists in our records")]
+ DuplicateMerchantConnectorAccount {
+ profile_id: String,
+ connector_name: String,
+ },
#[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "duplicate payment method")]
DuplicatePaymentMethod,
@@ -391,7 +394,7 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode {
errors::ApiErrorResponse::Unauthorized
| errors::ApiErrorResponse::InvalidJwtToken
| errors::ApiErrorResponse::GenericUnauthorized { .. }
- | errors::ApiErrorResponse::AccessForbidden
+ | errors::ApiErrorResponse::AccessForbidden { .. }
| errors::ApiErrorResponse::InvalidEphemeralKey => Self::Unauthorized,
errors::ApiErrorResponse::InvalidRequestUrl
| errors::ApiErrorResponse::InvalidHttpMethod
@@ -495,9 +498,13 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode {
}
errors::ApiErrorResponse::ReturnUrlUnavailable => Self::ReturnUrlUnavailable,
errors::ApiErrorResponse::DuplicateMerchantAccount => Self::DuplicateMerchantAccount,
- errors::ApiErrorResponse::DuplicateMerchantConnectorAccount { connector_label } => {
- Self::DuplicateMerchantConnectorAccount { connector_label }
- }
+ errors::ApiErrorResponse::DuplicateMerchantConnectorAccount {
+ profile_id,
+ connector_name,
+ } => Self::DuplicateMerchantConnectorAccount {
+ profile_id,
+ connector_name,
+ },
errors::ApiErrorResponse::DuplicatePaymentMethod => Self::DuplicatePaymentMethod,
errors::ApiErrorResponse::ClientSecretInvalid => Self::PaymentIntentInvalidParameter {
param: "client_secret".to_owned(),
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 2de2c0725e..e146400685 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -2,7 +2,7 @@ use api_models::{admin as admin_types, enums as api_enums};
use common_utils::{
crypto::{generate_cryptographically_secure_random_string, OptionalSecretValue},
date_time,
- ext_traits::{ConfigExt, Encode, ValueExt},
+ ext_traits::{AsyncExt, ConfigExt, Encode, ValueExt},
};
use data_models::MerchantStorageScheme;
use error_stack::{report, FutureExt, ResultExt};
@@ -54,7 +54,7 @@ pub async fn create_merchant_account(
let primary_business_details =
utils::Encode::<Vec<admin_types::PrimaryBusinessDetails>>::encode_to_value(
- &req.primary_business_details.unwrap_or_default(),
+ &req.primary_business_details.clone().unwrap_or_default(),
)
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "primary_business_details",
@@ -173,15 +173,46 @@ pub async fn create_merchant_account(
.change_context(errors::ApiErrorResponse::InternalServerError)?;
// Create a default business profile
- let business_profile = create_and_insert_business_profile(
- db,
- api_models::admin::BusinessProfileCreate::default(),
- merchant_account.clone(),
- )
- .await?;
+ // If business_labels are passed, then use it as the profile_name
+ // else use `default` as the profile_name
+ if let Some(business_details) = req.primary_business_details.as_ref() {
+ for business_profile in business_details {
+ let profile_name =
+ format!("{}_{}", business_profile.country, business_profile.business);
+
+ let business_profile_create_request = api_models::admin::BusinessProfileCreate {
+ profile_name: Some(profile_name),
+ ..Default::default()
+ };
+
+ let _ = create_and_insert_business_profile(
+ db,
+ business_profile_create_request,
+ merchant_account.clone(),
+ )
+ .await
+ .map_err(|business_profile_insert_error| {
+ crate::logger::warn!(
+ "Business profile already exists {business_profile_insert_error:?}"
+ );
+ })
+ .map(|business_profile| {
+ if business_details.len() == 1 && merchant_account.default_profile.is_none() {
+ merchant_account.default_profile = Some(business_profile.profile_id);
+ }
+ });
+ }
+ } else {
+ let business_profile = create_and_insert_business_profile(
+ db,
+ api_models::admin::BusinessProfileCreate::default(),
+ merchant_account.clone(),
+ )
+ .await?;
- // Update merchant account with the business profile id
- merchant_account.default_profile = Some(business_profile.profile_id);
+ // Update merchant account with the business profile id
+ merchant_account.default_profile = Some(business_profile.profile_id);
+ };
let merchant_account = db
.insert_merchant(merchant_account, &key_store)
@@ -219,6 +250,67 @@ pub async fn get_merchant_account(
.attach_printable("Failed to construct response")?,
))
}
+
+/// For backwards compatibility, whenever new business labels are passed in
+/// primary_business_details, create a business profile
+pub async fn create_business_profile_from_business_labels(
+ db: &dyn StorageInterface,
+ key_store: &domain::MerchantKeyStore,
+ merchant_id: &str,
+ new_business_details: Vec<admin_types::PrimaryBusinessDetails>,
+) -> RouterResult<()> {
+ let merchant_account = db
+ .find_merchant_account_by_merchant_id(merchant_id, key_store)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
+
+ let old_business_details = merchant_account
+ .primary_business_details
+ .clone()
+ .parse_value::<Vec<admin_types::PrimaryBusinessDetails>>("PrimaryBusinessDetails")
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "routing_algorithm",
+ })
+ .attach_printable("Invalid routing algorithm given")?;
+
+ // find the diff between two vectors
+ let business_profiles_to_create = new_business_details
+ .into_iter()
+ .filter(|business_details| !old_business_details.contains(business_details))
+ .collect::<Vec<_>>();
+
+ for business_profile in business_profiles_to_create {
+ let profile_name = format!("{}_{}", business_profile.country, business_profile.business);
+
+ let business_profile_create_request = admin_types::BusinessProfileCreate {
+ profile_name: Some(profile_name),
+ ..Default::default()
+ };
+
+ let business_profile_create_result = create_and_insert_business_profile(
+ db,
+ business_profile_create_request,
+ merchant_account.clone(),
+ )
+ .await
+ .map_err(|business_profile_insert_error| {
+ // If there is any duplicate error, we need not take any action
+ crate::logger::warn!(
+ "Business profile already exists {business_profile_insert_error:?}"
+ );
+ });
+
+ // If a business_profile is created, then unset the default profile
+ if business_profile_create_result.is_ok() && merchant_account.default_profile.is_some() {
+ let unset_default_profile = domain::MerchantAccountUpdate::UnsetDefaultProfile;
+ db.update_merchant(merchant_account.clone(), unset_default_profile, key_store)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
+ }
+ }
+
+ Ok(())
+}
pub async fn merchant_account_update(
db: &dyn StorageInterface,
merchant_id: &String,
@@ -267,6 +359,20 @@ pub async fn merchant_account_update(
})
.transpose()?;
+ // In order to support backwards compatibility, if a business_labels are passed in the update
+ // call, then create new business_profiles with the profile_name as business_label
+ req.primary_business_details
+ .async_map(|primary_business_details| async {
+ let _ = create_business_profile_from_business_labels(
+ db,
+ &key_store,
+ merchant_id,
+ primary_business_details,
+ )
+ .await;
+ })
+ .await;
+
let key = key_store.key.get_inner().peek();
let business_profile_id_update = if let Some(profile_id) = req.default_profile {
@@ -342,6 +448,8 @@ pub async fn merchant_account_update(
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
+ // If there are any new business labels generated, create business profile
+
Ok(service_api::ApplicationResponse::Json(
response
.try_into()
@@ -460,13 +568,13 @@ pub async fn create_payment_connector(
helpers::validate_business_details(
req.business_country,
- &req.business_label,
+ req.business_label.as_ref(),
&merchant_account,
)?;
- let connector_label = helpers::get_connector_label(
+ let connector_label = core_utils::get_connector_label(
req.business_country,
- &req.business_label,
+ req.business_label.as_ref(),
req.business_sub_label.as_ref(),
&req.connector_name.to_string(),
);
@@ -511,14 +619,14 @@ pub async fn create_payment_connector(
let frm_configs = get_frm_config_as_secret(req.frm_configs);
- // Validate whether profile_id passed in request is valid and is linked to the merchant
- let business_profile_from_request =
- core_utils::validate_and_get_business_profile(store, req.profile_id.as_ref(), merchant_id)
- .await?;
-
- let profile_id = business_profile_from_request
- .map(|business_profile| business_profile.profile_id)
- .or(merchant_account.default_profile.clone());
+ let profile_id = core_utils::get_profile_id_from_business_details(
+ req.business_country,
+ req.business_label.as_ref(),
+ &merchant_account,
+ req.profile_id.as_ref(),
+ store,
+ )
+ .await?;
let merchant_connector_account = domain::MerchantConnectorAccount {
merchant_id: merchant_id.to_string(),
@@ -560,7 +668,7 @@ pub async fn create_payment_connector(
}
None => None,
},
- profile_id,
+ profile_id: Some(profile_id.clone()),
};
let mca = store
@@ -568,7 +676,8 @@ pub async fn create_payment_connector(
.await
.to_duplicate_response(
errors::ApiErrorResponse::DuplicateMerchantConnectorAccount {
- connector_label: connector_label.clone(),
+ profile_id,
+ connector_name: req.connector_name.to_string(),
},
)?;
@@ -896,9 +1005,15 @@ pub async fn create_and_insert_business_profile(
request,
))?;
+ let profile_name = business_profile_new.profile_name.clone();
+
db.insert_business_profile(business_profile_new)
.await
- .to_duplicate_response(errors::ApiErrorResponse::InternalServerError)
+ .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {
+ message: format!(
+ "Business Profile with the profile_name {profile_name} already exists"
+ ),
+ })
.attach_printable("Failed to insert Business profile because of duplication error")
}
@@ -906,25 +1021,18 @@ pub async fn create_business_profile(
db: &dyn StorageInterface,
request: api::BusinessProfileCreate,
merchant_id: &str,
- merchant_account: Option<domain::MerchantAccount>,
) -> RouterResponse<api_models::admin::BusinessProfileResponse> {
- let merchant_account = if let Some(merchant_account) = merchant_account {
- merchant_account
- } else {
- let key_store = db
- .get_merchant_key_store_by_merchant_id(
- merchant_id,
- &db.get_master_key().to_vec().into(),
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
+ let key_store = db
+ .get_merchant_key_store_by_merchant_id(merchant_id, &db.get_master_key().to_vec().into())
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
- // Get the merchant account, if few fields are not passed, then they will be inherited from
- // merchant account
- db.find_merchant_account_by_merchant_id(merchant_id, &key_store)
- .await
- .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?
- };
+ // Get the merchant account, if few fields are not passed, then they will be inherited from
+ // merchant account
+ let merchant_account = db
+ .find_merchant_account_by_merchant_id(merchant_id, &key_store)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
if let Some(ref routing_algorithm) = request.routing_algorithm {
let _: api::RoutingAlgorithm = routing_algorithm
@@ -937,7 +1045,14 @@ pub async fn create_business_profile(
}
let business_profile =
- create_and_insert_business_profile(db, request, merchant_account).await?;
+ create_and_insert_business_profile(db, request, merchant_account.clone()).await?;
+
+ if merchant_account.default_profile.is_some() {
+ let unset_default_profile = domain::MerchantAccountUpdate::UnsetDefaultProfile;
+ db.update_merchant(merchant_account, unset_default_profile, &key_store)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
+ }
Ok(service_api::ApplicationResponse::Json(
api_models::admin::BusinessProfileResponse::foreign_try_from(business_profile)
@@ -1010,7 +1125,9 @@ pub async fn update_business_profile(
})?;
if business_profile.merchant_id != merchant_id {
- Err(errors::ApiErrorResponse::AccessForbidden)?
+ Err(errors::ApiErrorResponse::AccessForbidden {
+ resource: profile_id.to_string(),
+ })?
}
let webhook_details = request
diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs
index bae5d0e00d..f38891931f 100644
--- a/crates/router/src/core/errors/api_error_response.rs
+++ b/crates/router/src/core/errors/api_error_response.rs
@@ -89,8 +89,8 @@ pub enum ApiErrorResponse {
FlowNotSupported { flow: String, connector: String },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_21", message = "Missing required params")]
MissingRequiredFields { field_names: Vec<&'static str> },
- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_22", message = "Access forbidden. Not authorized to access this resource")]
- AccessForbidden,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_22", message = "Access forbidden. Not authorized to access this resource {resource}")]
+ AccessForbidden { resource: String },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_23", message = "{message}")]
FileProviderNotSupported { message: String },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_23", message = "{message}")]
@@ -130,8 +130,11 @@ pub enum ApiErrorResponse {
DuplicateMandate,
#[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The merchant account with the specified details already exists in our records")]
DuplicateMerchantAccount,
- #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The merchant connector account with the specified connector_label '{connector_label}' already exists in our records")]
- DuplicateMerchantConnectorAccount { connector_label: String },
+ #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The merchant connector account with the specified profile_id '{profile_id}' and connector_name '{connector_name}' already exists in our records")]
+ DuplicateMerchantConnectorAccount {
+ profile_id: String,
+ connector_name: String,
+ },
#[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The payment method with the specified details already exists in our records")]
DuplicatePaymentMethod,
#[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The payment with the specified payment_id '{payment_id}' already exists in our records")]
diff --git a/crates/router/src/core/errors/transformers.rs b/crates/router/src/core/errors/transformers.rs
index 208aad56ee..7ffcd6bdf4 100644
--- a/crates/router/src/core/errors/transformers.rs
+++ b/crates/router/src/core/errors/transformers.rs
@@ -89,7 +89,9 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorRespon
Self::MissingRequiredFields { field_names } => AER::BadRequest(
ApiError::new("IR", 21, "Missing required params".to_string(), Some(Extra {data: Some(serde_json::json!(field_names)), ..Default::default() })),
),
- Self::AccessForbidden => AER::ForbiddenCommonResource(ApiError::new("IR", 22, "Access forbidden. Not authorized to access this resource", None)),
+ Self::AccessForbidden {resource} => {
+ AER::ForbiddenCommonResource(ApiError::new("IR", 22, format!("Access forbidden. Not authorized to access this resource {resource}"), None))
+ },
Self::FileProviderNotSupported { message } => {
AER::BadRequest(ApiError::new("IR", 23, message.to_string(), None))
},
@@ -128,8 +130,8 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorRespon
Self::DuplicateRefundRequest => AER::BadRequest(ApiError::new("HE", 1, "Duplicate refund request. Refund already attempted with the refund ID", None)),
Self::DuplicateMandate => AER::BadRequest(ApiError::new("HE", 1, "Duplicate mandate request. Mandate already attempted with the Mandate ID", None)),
Self::DuplicateMerchantAccount => AER::BadRequest(ApiError::new("HE", 1, "The merchant account with the specified details already exists in our records", None)),
- Self::DuplicateMerchantConnectorAccount { connector_label } => {
- AER::BadRequest(ApiError::new("HE", 1, format!("The merchant connector account with the specified connector_label '{connector_label}' already exists in our records"), None))
+ Self::DuplicateMerchantConnectorAccount { profile_id, connector_name } => {
+ AER::BadRequest(ApiError::new("HE", 1, format!("The merchant connector account with the specified profile_id '{profile_id}' and connector_name '{connector_name}' already exists in our records"), None))
}
Self::DuplicatePaymentMethod => AER::BadRequest(ApiError::new("HE", 1, "The payment method with the specified details already exists in our records", None)),
Self::DuplicatePayment { payment_id } => {
diff --git a/crates/router/src/core/files.rs b/crates/router/src/core/files.rs
index c16b915bb9..e6a0d3122d 100644
--- a/crates/router/src/core/files.rs
+++ b/crates/router/src/core/files.rs
@@ -39,6 +39,7 @@ pub async fn files_create_core(
file_upload_provider: None,
available: false,
connector_label: None,
+ profile_id: None,
};
let file_metadata_object = state
.store
@@ -47,7 +48,7 @@ pub async fn files_create_core(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to insert file_metadata")?;
let (provider_file_id, file_upload_provider, connector_label) =
- helpers::upload_and_get_provider_provider_file_id_connector_label(
+ helpers::upload_and_get_provider_provider_file_id_profile_id(
state,
&merchant_account,
&key_store,
diff --git a/crates/router/src/core/files/helpers.rs b/crates/router/src/core/files/helpers.rs
index b9d5c6afc1..7d7e694b42 100644
--- a/crates/router/src/core/files/helpers.rs
+++ b/crates/router/src/core/files/helpers.rs
@@ -6,9 +6,7 @@ use futures::TryStreamExt;
use crate::{
core::{
errors::{self, StorageErrorExt},
- files,
- payments::{self, helpers as payments_helpers},
- utils,
+ files, payments, utils,
},
routes::AppState,
services,
@@ -262,7 +260,7 @@ pub async fn retrieve_file_and_provider_file_id_from_file_id(
}
//Upload file to connector if it supports / store it in S3 and return file_upload_provider, provider_file_id accordingly
-pub async fn upload_and_get_provider_provider_file_id_connector_label(
+pub async fn upload_and_get_provider_provider_file_id_profile_id(
state: &AppState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
@@ -311,12 +309,7 @@ pub async fn upload_and_get_provider_provider_file_id_connector_label(
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
- let connector_label = payments_helpers::get_connector_label(
- payment_intent.business_country,
- &payment_intent.business_label,
- payment_attempt.business_sub_label.as_ref(),
- &dispute.connector,
- );
+
let connector_integration: services::BoxedConnectorIntegration<
'_,
api::Upload,
@@ -332,7 +325,6 @@ pub async fn upload_and_get_provider_provider_file_id_connector_label(
create_file_request,
&dispute.connector,
file_key,
- connector_label.clone(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -361,7 +353,7 @@ pub async fn upload_and_get_provider_provider_file_id_connector_label(
api_models::enums::FileUploadProvider::foreign_try_from(
&connector_data.connector_name,
)?,
- Some(connector_label),
+ payment_intent.profile_id,
))
} else {
upload_file(
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 7396edc0cb..fffd127937 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -856,7 +856,7 @@ pub async fn list_payment_methods(
// filter out connectors based on the business country
let filtered_mcas =
- helpers::filter_mca_based_on_business_details(all_mcas, payment_intent.as_ref());
+ helpers::filter_mca_based_on_business_profile(all_mcas, payment_intent.as_ref());
logger::debug!(mca_before_filtering=?filtered_mcas);
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 1dcfd09b1d..b5f8f22363 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -33,7 +33,10 @@ use self::{
use super::errors::StorageErrorExt;
use crate::{
configs::settings::PaymentMethodTypeTokenFilter,
- core::errors::{self, CustomResult, RouterResponse, RouterResult},
+ core::{
+ errors::{self, CustomResult, RouterResponse, RouterResult},
+ utils,
+ },
db::StorageInterface,
logger,
routes::{metrics, payment_methods::ParentPaymentMethodToken, AppState},
@@ -589,7 +592,7 @@ where
.as_ref()
.get_required_value("connector")?;
- let merchant_connector_account = construct_connector_label_and_get_mca(
+ let merchant_connector_account = construct_profile_id_and_get_mca(
state,
merchant_account,
payment_data,
@@ -787,7 +790,7 @@ where
for session_connector_data in connectors.iter() {
let connector_id = session_connector_data.connector.connector.id();
- let merchant_connector_account = construct_connector_label_and_get_mca(
+ let merchant_connector_account = construct_profile_id_and_get_mca(
state,
merchant_account,
&mut payment_data,
@@ -885,7 +888,7 @@ where
match connector_name {
Some(connector_name) => {
- let merchant_connector_account = construct_connector_label_and_get_mca(
+ let merchant_connector_account = construct_profile_id_and_get_mca(
state,
merchant_account,
payment_data,
@@ -900,13 +903,29 @@ where
api::GetToken::Connector,
)?;
- let connector_label = helpers::get_connector_label(
+ let connector_label = super::utils::get_connector_label(
payment_data.payment_intent.business_country,
- &payment_data.payment_intent.business_label,
+ payment_data.payment_intent.business_label.as_ref(),
payment_data.payment_attempt.business_sub_label.as_ref(),
&connector_name,
);
+ let connector_label = if let Some(connector_label) = connector_label {
+ connector_label
+ } else {
+ let profile_id = utils::get_profile_id_from_business_details(
+ payment_data.payment_intent.business_country,
+ payment_data.payment_intent.business_label.as_ref(),
+ merchant_account,
+ payment_data.payment_intent.profile_id.as_ref(),
+ &*state.store,
+ )
+ .await
+ .attach_printable("Could not find profile id from business details")?;
+
+ format!("{connector_name}_{profile_id}")
+ };
+
let (should_call_connector, existing_connector_customer_id) =
customers::should_call_connector_create_customer(
state,
@@ -1021,7 +1040,7 @@ pub fn is_preprocessing_required_for_wallets(connector_name: String) -> bool {
connector_name == *"trustpay" || connector_name == *"payme"
}
-pub async fn construct_connector_label_and_get_mca<'a, F>(
+pub async fn construct_profile_id_and_get_mca<'a, F>(
state: &'a AppState,
merchant_account: &domain::MerchantAccount,
payment_data: &mut PaymentData<F>,
@@ -1031,19 +1050,24 @@ pub async fn construct_connector_label_and_get_mca<'a, F>(
where
F: Clone,
{
- let connector_label = helpers::get_connector_label(
+ let profile_id = utils::get_profile_id_from_business_details(
payment_data.payment_intent.business_country,
- &payment_data.payment_intent.business_label,
- payment_data.payment_attempt.business_sub_label.as_ref(),
- connector_id,
- );
+ payment_data.payment_intent.business_label.as_ref(),
+ merchant_account,
+ payment_data.payment_intent.profile_id.as_ref(),
+ &*state.store,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("profile_id is not set in payment_intent")?;
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
merchant_account.merchant_id.as_str(),
- &connector_label,
payment_data.creds_identifier.to_owned(),
key_store,
+ &profile_id,
+ connector_id,
)
.await?;
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 055e7f8f61..ed94e2a3d6 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -86,17 +86,14 @@ pub fn create_identity_from_certificate_and_key(
.change_context(errors::ApiClientError::CertificateDecodeFailed)
}
-pub fn filter_mca_based_on_business_details(
+pub fn filter_mca_based_on_business_profile(
merchant_connector_accounts: Vec<domain::MerchantConnectorAccount>,
payment_intent: Option<&PaymentIntent>,
) -> Vec<domain::MerchantConnectorAccount> {
if let Some(payment_intent) = payment_intent {
merchant_connector_accounts
.into_iter()
- .filter(|mca| {
- mca.business_country == payment_intent.business_country
- && mca.business_label == payment_intent.business_label
- })
+ .filter(|mca| mca.profile_id == payment_intent.profile_id)
.collect::<Vec<_>>()
} else {
merchant_connector_accounts
@@ -2102,43 +2099,10 @@ pub async fn verify_payment_intent_time_and_client_secret(
.transpose()
}
-fn connector_needs_business_sub_label(connector_name: &str) -> bool {
- let connectors_list = [api_models::enums::Connector::Cybersource];
- connectors_list
- .map(|connector| connector.to_string())
- .contains(&connector_name.to_string())
-}
-
-/// Create the connector label
-/// {connector_name}_{country}_{business_label}
-pub fn get_connector_label(
- business_country: api_models::enums::CountryAlpha2,
- business_label: &str,
- business_sub_label: Option<&String>,
- connector_name: &str,
-) -> String {
- let mut connector_label = format!("{connector_name}_{business_country}_{business_label}");
-
- // Business sub label is currently being used only for cybersource
- // To ensure backwards compatibality, cybersource mca's created before this change
- // will have the business_sub_label value as default.
- //
- // Even when creating the connector account, if no sub label is provided, default will be used
- if connector_needs_business_sub_label(connector_name) {
- if let Some(sub_label) = business_sub_label {
- connector_label.push_str(&format!("_{sub_label}"));
- } else {
- connector_label.push_str("_default"); // For backwards compatibality
- }
- }
-
- connector_label
-}
-
/// Check whether the business details are configured in the merchant account
pub fn validate_business_details(
- business_country: api_enums::CountryAlpha2,
- business_label: &String,
+ business_country: Option<api_enums::CountryAlpha2>,
+ business_label: Option<&String>,
merchant_account: &domain::MerchantAccount,
) -> RouterResult<()> {
let primary_business_details = merchant_account
@@ -2148,15 +2112,21 @@ pub fn validate_business_details(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to parse primary business details")?;
- primary_business_details
- .iter()
- .find(|business_details| {
- &business_details.business == business_label
- && business_details.country == business_country
+ business_country
+ .zip(business_label)
+ .map(|(business_country, business_label)| {
+ primary_business_details
+ .iter()
+ .find(|business_details| {
+ &business_details.business == business_label
+ && business_details.country == business_country
+ })
+ .ok_or(errors::ApiErrorResponse::PreconditionFailed {
+ message: "business_details are not configured in the merchant account"
+ .to_string(),
+ })
})
- .ok_or(errors::ApiErrorResponse::PreconditionFailed {
- message: "business_details are not configured in the merchant account".to_string(),
- })?;
+ .transpose()?;
Ok(())
}
@@ -2236,8 +2206,8 @@ mod tests {
off_session: None,
client_secret: Some("1".to_string()),
active_attempt_id: "nopes".to_string(),
- business_country: storage_enums::CountryAlpha2::AG,
- business_label: "no".to_string(),
+ business_country: None,
+ business_label: None,
order_details: None,
allowed_payment_method_types: None,
connector_metadata: None,
@@ -2283,8 +2253,8 @@ mod tests {
off_session: None,
client_secret: Some("1".to_string()),
active_attempt_id: "nopes".to_string(),
- business_country: storage_enums::CountryAlpha2::AG,
- business_label: "no".to_string(),
+ business_country: None,
+ business_label: None,
order_details: None,
allowed_payment_method_types: None,
connector_metadata: None,
@@ -2330,8 +2300,8 @@ mod tests {
off_session: None,
client_secret: None,
active_attempt_id: "nopes".to_string(),
- business_country: storage_enums::CountryAlpha2::AG,
- business_label: "no".to_string(),
+ business_country: None,
+ business_label: None,
order_details: None,
allowed_payment_method_types: None,
connector_metadata: None,
@@ -2423,12 +2393,15 @@ impl MerchantConnectorAccountType {
}
}
+/// Query for merchant connector account either by business label or profile id
+/// If profile_id is passed use it, or use connector_label to query merchant connector account
pub async fn get_merchant_connector_account(
state: &AppState,
merchant_id: &str,
- connector_label: &str,
creds_identifier: Option<String>,
key_store: &domain::MerchantKeyStore,
+ profile_id: &String,
+ connector_name: &str,
) -> RouterResult<MerchantConnectorAccountType> {
let db = &*state.store;
match creds_identifier {
@@ -2438,7 +2411,7 @@ pub async fn get_merchant_connector_account(
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
- id: connector_label.to_string(),
+ id: format!("mcd_{merchant_id}_{creds_identifier}"),
},
)?;
@@ -2470,17 +2443,20 @@ pub async fn get_merchant_connector_account(
Ok(MerchantConnectorAccountType::CacheVal(res))
}
- None => db
- .find_merchant_connector_account_by_merchant_id_connector_label(
- merchant_id,
- connector_label,
+ None => {
+ db.find_merchant_connector_account_by_profile_id_connector_name(
+ profile_id,
+ connector_name,
key_store,
)
.await
- .map(MerchantConnectorAccountType::DbVal)
- .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
- id: connector_label.to_string(),
- }),
+ .to_not_found_response(
+ errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
+ id: format!("profile id {profile_id} and connector name {connector_name}"),
+ },
+ )
+ }
+ .map(MerchantConnectorAccountType::DbVal),
}
}
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 796ce87488..bccfbd81c3 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -511,8 +511,8 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
let customer_id = customer.clone().map(|c| c.customer_id);
let return_url = payment_data.payment_intent.return_url.take();
let setup_future_usage = payment_data.payment_intent.setup_future_usage;
- let business_label = Some(payment_data.payment_intent.business_label.clone());
- let business_country = Some(payment_data.payment_intent.business_country);
+ let business_label = payment_data.payment_intent.business_label.clone();
+ let business_country = payment_data.payment_intent.business_country;
let description = payment_data.payment_intent.description.take();
let statement_descriptor_name =
payment_data.payment_intent.statement_descriptor_name.take();
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index ba4a6eb5b3..68f37eaa57 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -65,17 +65,15 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
- // Validate whether profile_id passed in request is valid and is linked to the merchant
- let business_profile_from_request = core_utils::validate_and_get_business_profile(
- db,
- request.profile_id.as_ref(),
- merchant_id,
- )
- .await?;
+ helpers::validate_business_details(
+ request.business_country,
+ request.business_label.as_ref(),
+ merchant_account,
+ )?;
- let profile_id = business_profile_from_request
- .map(|business_profile| business_profile.profile_id)
- .or(merchant_account.default_profile.clone());
+ // Validate whether profile_id passed in request is valid and is linked to the merchant
+ core_utils::validate_and_get_business_profile(db, request.profile_id.as_ref(), merchant_id)
+ .await?;
let (
token,
@@ -155,8 +153,9 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
shipping_address.clone().map(|x| x.address_id),
billing_address.clone().map(|x| x.address_id),
payment_attempt.attempt_id.to_owned(),
- profile_id,
- )?,
+ state,
+ )
+ .await?,
storage_scheme,
)
.await
@@ -584,7 +583,7 @@ impl PaymentCreate {
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
- fn make_payment_intent(
+ async fn make_payment_intent(
payment_id: &str,
merchant_account: &types::domain::MerchantAccount,
money: (api::Amount, enums::Currency),
@@ -592,7 +591,7 @@ impl PaymentCreate {
shipping_address_id: Option<String>,
billing_address_id: Option<String>,
active_attempt_id: String,
- profile_id: Option<String>,
+ state: &AppState,
) -> RouterResult<storage::PaymentIntentNew> {
let created_at @ modified_at @ last_synced = Some(common_utils::date_time::now());
let status =
@@ -606,29 +605,15 @@ impl PaymentCreate {
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert order details to value")?;
- let (business_country, business_label) =
- match (request.business_country, request.business_label.as_ref()) {
- (Some(business_country), Some(business_label)) => {
- helpers::validate_business_details(
- business_country,
- business_label,
- merchant_account,
- )?;
-
- Ok((business_country, business_label.clone()))
- }
- (None, Some(_)) => Err(errors::ApiErrorResponse::MissingRequiredField {
- field_name: "business_country",
- }),
- (Some(_), None) => Err(errors::ApiErrorResponse::MissingRequiredField {
- field_name: "business_label",
- }),
- (None, None) => Ok(helpers::get_business_details(
- request.business_country,
- request.business_label.as_ref(),
- merchant_account,
- )?),
- }?;
+ // If profile id is not passed, get it from the business_country and business_label
+ let profile_id = core_utils::get_profile_id_from_business_details(
+ request.business_country,
+ request.business_label.as_ref(),
+ merchant_account,
+ request.profile_id.as_ref(),
+ &*state.store,
+ )
+ .await?;
let allowed_payment_method_types = request
.get_allowed_payment_method_types_as_value()
@@ -664,8 +649,8 @@ impl PaymentCreate {
statement_descriptor_name: request.statement_descriptor_name.clone(),
statement_descriptor_suffix: request.statement_descriptor_suffix.clone(),
metadata: request.metadata.clone(),
- business_country,
- business_label,
+ business_country: request.business_country,
+ business_label: request.business_label.clone(),
active_attempt_id,
order_details,
amount_captured: None,
@@ -675,7 +660,7 @@ impl PaymentCreate {
connector_metadata,
feature_metadata,
attempt_count: 1,
- profile_id,
+ profile_id: Some(profile_id),
merchant_decision: None,
payment_confirm_source: None,
})
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index e432e0cdb6..a37dbfcf2e 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -330,7 +330,7 @@ where
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Database error when querying for merchant connector accounts")?;
- let filtered_connector_accounts = helpers::filter_mca_based_on_business_details(
+ let filtered_connector_accounts = helpers::filter_mca_based_on_business_profile(
all_connector_accounts,
Some(payment_intent),
);
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index ec0c33e29e..dbd61d274d 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -510,8 +510,8 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
let return_url = payment_data.payment_intent.return_url.clone();
let setup_future_usage = payment_data.payment_intent.setup_future_usage;
- let business_label = Some(payment_data.payment_intent.business_label.clone());
- let business_country = Some(payment_data.payment_intent.business_country);
+ let business_label = payment_data.payment_intent.business_label.clone();
+ let business_country = payment_data.payment_intent.business_country;
let description = payment_data.payment_intent.description.clone();
let statement_descriptor_name = payment_data
.payment_intent
@@ -647,13 +647,10 @@ impl PaymentUpdate {
.clone()
.map(|i| payment_intent.return_url.replace(i.to_string()));
- payment_intent.business_country = request
- .business_country
- .unwrap_or(payment_intent.business_country);
- payment_intent.business_label = request
- .business_label
- .clone()
- .unwrap_or(payment_intent.business_label.clone());
+ payment_intent.business_country = request.business_country;
+
+ payment_intent.business_label = request.business_label.clone();
+
request
.description
.clone()
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 2362c6a297..596c2ff725 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -510,10 +510,10 @@ where
let mut response: api::PaymentsResponse = Default::default();
let routed_through = payment_attempt.connector.clone();
- let connector_label = routed_through.as_ref().map(|connector_name| {
- helpers::get_connector_label(
+ let connector_label = routed_through.as_ref().and_then(|connector_name| {
+ core_utils::get_connector_label(
payment_intent.business_country,
- &payment_intent.business_label,
+ payment_intent.business_label.as_ref(),
payment_attempt.business_sub_label.as_ref(),
connector_name,
)
diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs
index ab60989fa6..60fa889dc4 100644
--- a/crates/router/src/core/payouts.rs
+++ b/crates/router/src/core/payouts.rs
@@ -559,19 +559,17 @@ pub async fn create_recipient(
let customer_details = payout_data.customer_details.to_owned();
let connector_name = connector_data.connector_name.to_string();
- let connector_label = payment_helpers::get_connector_label(
- payout_data
- .payout_attempt
- .business_country
- .unwrap_or_default(),
- &payout_data
- .payout_attempt
- .business_label
- .to_owned()
- .unwrap_or_default(),
- None,
- &connector_name,
- );
+ let profile_id = core_utils::get_profile_id_from_business_details(
+ payout_data.payout_attempt.business_country,
+ payout_data.payout_attempt.business_label.as_ref(),
+ merchant_account,
+ payout_data.payout_attempt.profile_id.as_ref(),
+ &*state.store,
+ )
+ .await?;
+
+ // Create the connector label using {profile_id}_{connector_name}
+ let connector_label = format!("{profile_id}_{}", connector_name);
let (should_call_connector, _connector_customer_id) =
helpers::should_call_payout_connector_create_customer(
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index f933f76a63..eab55f458e 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -4,7 +4,7 @@ use api_models::enums::{DisputeStage, DisputeStatus};
#[cfg(feature = "payouts")]
use common_utils::{crypto::Encryptable, pii::Email};
use common_utils::{errors::CustomResult, ext_traits::AsyncExt};
-use error_stack::{IntoReport, ResultExt};
+use error_stack::{report, IntoReport, ResultExt};
use router_env::{instrument, tracing};
use uuid::Uuid;
@@ -45,21 +45,23 @@ pub async fn get_mca_for_payout<'a>(
match payout_data.merchant_connector_account.to_owned() {
Some(mca) => Ok(mca),
None => {
- let (business_country, business_label) = helpers::get_business_details(
- payout_attempt.business_country,
- payout_attempt.business_label.as_ref(),
- merchant_account,
- )?;
-
- let connector_label =
- helpers::get_connector_label(business_country, &business_label, None, connector_id);
+ let profile_id = payout_attempt
+ .profile_id
+ .as_ref()
+ .ok_or(errors::ApiErrorResponse::MissingRequiredField {
+ field_name: "business_profile",
+ })
+ .into_report()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("profile_id is not set in payment_intent")?;
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
merchant_account.merchant_id.as_str(),
- &connector_label,
None,
key_store,
+ profile_id,
+ connector_id,
)
.await?;
Ok(merchant_connector_account)
@@ -203,19 +205,24 @@ pub async fn construct_refund_router_data<'a, F>(
refund: &'a storage::Refund,
creds_identifier: Option<String>,
) -> RouterResult<types::RefundsRouterData<F>> {
- let connector_label = helpers::get_connector_label(
+ let profile_id = get_profile_id_from_business_details(
payment_intent.business_country,
- &payment_intent.business_label,
- None,
- connector_id,
- );
+ payment_intent.business_label.as_ref(),
+ merchant_account,
+ payment_intent.profile_id.as_ref(),
+ &*state.store,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("profile_id is not set in payment_intent")?;
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
merchant_account.merchant_id.as_str(),
- &connector_label,
creds_identifier,
key_store,
+ &profile_id,
+ connector_id,
)
.await?;
@@ -471,21 +478,27 @@ pub async fn construct_accept_dispute_router_data<'a>(
key_store: &domain::MerchantKeyStore,
dispute: &storage::Dispute,
) -> RouterResult<types::AcceptDisputeRouterData> {
- let connector_id = &dispute.connector;
- let connector_label = helpers::get_connector_label(
+ let profile_id = get_profile_id_from_business_details(
payment_intent.business_country,
- &payment_intent.business_label,
- payment_attempt.business_sub_label.as_ref(),
- connector_id,
- );
+ payment_intent.business_label.as_ref(),
+ merchant_account,
+ payment_intent.profile_id.as_ref(),
+ &*state.store,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("profile_id is not set in payment_intent")?;
+
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
merchant_account.merchant_id.as_str(),
- &connector_label,
None,
key_store,
+ &profile_id,
+ &dispute.connector,
)
.await?;
+
let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on();
let auth_type: types::ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
@@ -497,7 +510,7 @@ pub async fn construct_accept_dispute_router_data<'a>(
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_account.merchant_id.clone(),
- connector: connector_id.to_string(),
+ connector: dispute.connector.to_string(),
payment_id: payment_attempt.payment_id.clone(),
attempt_id: payment_attempt.attempt_id.clone(),
status: payment_attempt.status,
@@ -551,20 +564,27 @@ pub async fn construct_submit_evidence_router_data<'a>(
submit_evidence_request_data: types::SubmitEvidenceRequestData,
) -> RouterResult<types::SubmitEvidenceRouterData> {
let connector_id = &dispute.connector;
- let connector_label = helpers::get_connector_label(
+ let profile_id = get_profile_id_from_business_details(
payment_intent.business_country,
- &payment_intent.business_label,
- payment_attempt.business_sub_label.as_ref(),
- connector_id,
- );
+ payment_intent.business_label.as_ref(),
+ merchant_account,
+ payment_intent.profile_id.as_ref(),
+ &*state.store,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("profile_id is not set in payment_intent")?;
+
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
merchant_account.merchant_id.as_str(),
- &connector_label,
None,
key_store,
+ &profile_id,
+ connector_id,
)
.await?;
+
let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on();
let auth_type: types::ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
@@ -627,14 +647,25 @@ pub async fn construct_upload_file_router_data<'a>(
create_file_request: &types::api::CreateFileRequest,
connector_id: &str,
file_key: String,
- connector_label: String,
) -> RouterResult<types::UploadFileRouterData> {
+ let profile_id = get_profile_id_from_business_details(
+ payment_intent.business_country,
+ payment_intent.business_label.as_ref(),
+ merchant_account,
+ payment_intent.profile_id.as_ref(),
+ &*state.store,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("profile_id is not set in payment_intent")?;
+
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
merchant_account.merchant_id.as_str(),
- &connector_label,
None,
key_store,
+ &profile_id,
+ connector_id,
)
.await?;
let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on();
@@ -704,20 +735,27 @@ pub async fn construct_defend_dispute_router_data<'a>(
) -> RouterResult<types::DefendDisputeRouterData> {
let _db = &*state.store;
let connector_id = &dispute.connector;
- let connector_label = helpers::get_connector_label(
+ let profile_id = get_profile_id_from_business_details(
payment_intent.business_country,
- &payment_intent.business_label,
- payment_attempt.business_sub_label.as_ref(),
- connector_id,
- );
+ payment_intent.business_label.as_ref(),
+ merchant_account,
+ payment_intent.profile_id.as_ref(),
+ &*state.store,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("profile_id is not set in payment_intent")?;
+
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
merchant_account.merchant_id.as_str(),
- &connector_label,
None,
key_store,
+ &profile_id,
+ connector_id,
)
.await?;
+
let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on();
let auth_type: types::ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
@@ -780,20 +818,26 @@ pub async fn construct_retrieve_file_router_data<'a>(
file_metadata: &diesel_models::file::FileMetadata,
connector_id: &str,
) -> RouterResult<types::RetrieveFileRouterData> {
- let connector_label = file_metadata
- .connector_label
- .clone()
- .ok_or(errors::ApiErrorResponse::InternalServerError)
+ let profile_id = file_metadata
+ .profile_id
+ .as_ref()
+ .ok_or(errors::ApiErrorResponse::MissingRequiredField {
+ field_name: "profile_id",
+ })
.into_report()
- .attach_printable("Missing connector label")?;
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("profile_id is not set in file_metadata")?;
+
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
merchant_account.merchant_id.as_str(),
- &connector_label,
None,
key_store,
+ profile_id,
+ connector_id,
)
.await?;
+
let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on();
let auth_type: types::ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
@@ -890,7 +934,9 @@ pub async fn validate_and_get_business_profile(
.map(|business_profile| {
// Check if the merchant_id of business profile is same as the current merchant_id
if business_profile.merchant_id.ne(merchant_id) {
- Err(errors::ApiErrorResponse::AccessForbidden)
+ Err(errors::ApiErrorResponse::AccessForbidden {
+ resource: business_profile.profile_id,
+ })
} else {
Ok(business_profile)
}
@@ -898,3 +944,84 @@ pub async fn validate_and_get_business_profile(
.transpose()
.into_report()
}
+
+fn connector_needs_business_sub_label(connector_name: &str) -> bool {
+ let connectors_list = [api_models::enums::Connector::Cybersource];
+ connectors_list
+ .map(|connector| connector.to_string())
+ .contains(&connector_name.to_string())
+}
+
+/// Create the connector label
+/// {connector_name}_{country}_{business_label}
+pub fn get_connector_label(
+ business_country: Option<api_models::enums::CountryAlpha2>,
+ business_label: Option<&String>,
+ business_sub_label: Option<&String>,
+ connector_name: &str,
+) -> Option<String> {
+ business_country
+ .zip(business_label)
+ .map(|(business_country, business_label)| {
+ let mut connector_label =
+ format!("{connector_name}_{business_country}_{business_label}");
+
+ // Business sub label is currently being used only for cybersource
+ // To ensure backwards compatibality, cybersource mca's created before this change
+ // will have the business_sub_label value as default.
+ //
+ // Even when creating the connector account, if no sub label is provided, default will be used
+ if connector_needs_business_sub_label(connector_name) {
+ if let Some(sub_label) = business_sub_label {
+ connector_label.push_str(&format!("_{sub_label}"));
+ } else {
+ connector_label.push_str("_default"); // For backwards compatibality
+ }
+ }
+
+ connector_label
+ })
+}
+
+/// If profile_id is not passed, use default profile if available, or
+/// If business_details (business_country and business_label) are passed, get the business_profile
+/// or return a `MissingRequiredField` error
+pub async fn get_profile_id_from_business_details(
+ business_country: Option<api_models::enums::CountryAlpha2>,
+ business_label: Option<&String>,
+ merchant_account: &domain::MerchantAccount,
+ request_profile_id: Option<&String>,
+ db: &dyn StorageInterface,
+) -> RouterResult<String> {
+ match request_profile_id.or(merchant_account.default_profile.as_ref()) {
+ Some(profile_id) => {
+ // Check whether this business profile belongs to the merchant
+ let _ = validate_and_get_business_profile(
+ db,
+ Some(profile_id),
+ &merchant_account.merchant_id,
+ )
+ .await?;
+ Ok(profile_id.clone())
+ }
+ None => match business_country.zip(business_label) {
+ Some((business_country, business_label)) => {
+ let profile_name = format!("{business_country}_{business_label}");
+ let business_profile = db
+ .find_business_profile_by_profile_name_merchant_id(
+ &profile_name,
+ &merchant_account.merchant_id,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::BusinessProfileNotFound {
+ id: profile_name,
+ })?;
+
+ Ok(business_profile.profile_id)
+ }
+ _ => Err(report!(errors::ApiErrorResponse::MissingRequiredField {
+ field_name: "profile_id or business_country, business_label"
+ })),
+ },
+ }
+}
diff --git a/crates/router/src/db/business_profile.rs b/crates/router/src/db/business_profile.rs
index dff3bac792..f29e0e9cec 100644
--- a/crates/router/src/db/business_profile.rs
+++ b/crates/router/src/db/business_profile.rs
@@ -20,6 +20,12 @@ pub trait BusinessProfileInterface {
profile_id: &str,
) -> CustomResult<business_profile::BusinessProfile, errors::StorageError>;
+ async fn find_business_profile_by_profile_name_merchant_id(
+ &self,
+ profile_name: &str,
+ merchant_id: &str,
+ ) -> CustomResult<business_profile::BusinessProfile, errors::StorageError>;
+
async fn update_business_profile_by_profile_id(
&self,
current_state: business_profile::BusinessProfile,
@@ -63,6 +69,22 @@ impl BusinessProfileInterface for Store {
.into_report()
}
+ async fn find_business_profile_by_profile_name_merchant_id(
+ &self,
+ profile_name: &str,
+ merchant_id: &str,
+ ) -> CustomResult<business_profile::BusinessProfile, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::business_profile::BusinessProfile::find_by_profile_name_merchant_id(
+ &conn,
+ profile_name,
+ merchant_id,
+ )
+ .await
+ .map_err(Into::into)
+ .into_report()
+ }
+
async fn update_business_profile_by_profile_id(
&self,
current_state: business_profile::BusinessProfile,
@@ -200,4 +222,12 @@ impl BusinessProfileInterface for MockDb {
Ok(business_profile_by_merchant_id)
}
+
+ async fn find_business_profile_by_profile_name_merchant_id(
+ &self,
+ _profile_name: &str,
+ _merchant_id: &str,
+ ) -> CustomResult<business_profile::BusinessProfile, errors::StorageError> {
+ Err(errors::StorageError::MockDbError)?
+ }
}
diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs
index 36c2e7c498..501a71bb9f 100644
--- a/crates/router/src/db/merchant_connector_account.rs
+++ b/crates/router/src/db/merchant_connector_account.rs
@@ -118,6 +118,13 @@ where
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError>;
+ async fn find_merchant_connector_account_by_profile_id_connector_name(
+ &self,
+ profile_id: &str,
+ connector_name: &str,
+ key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError>;
+
async fn find_merchant_connector_account_by_merchant_id_connector_name(
&self,
merchant_id: &str,
@@ -206,6 +213,51 @@ impl MerchantConnectorAccountInterface for Store {
}
}
+ async fn find_merchant_connector_account_by_profile_id_connector_name(
+ &self,
+ profile_id: &str,
+ connector_name: &str,
+ key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
+ let find_call = || async {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::MerchantConnectorAccount::find_by_profile_id_connector_name(
+ &conn,
+ profile_id,
+ connector_name,
+ )
+ .await
+ .map_err(Into::into)
+ .into_report()
+ };
+
+ #[cfg(not(feature = "accounts_cache"))]
+ {
+ find_call()
+ .await?
+ .convert(key_store.key.get_inner())
+ .await
+ .change_context(errors::StorageError::DeserializationFailed)
+ }
+
+ #[cfg(feature = "accounts_cache")]
+ {
+ super::cache::get_or_populate_in_memory(
+ self,
+ &format!("{}_{}", profile_id, connector_name),
+ find_call,
+ &cache::ACCOUNTS_CACHE,
+ )
+ .await
+ .async_and_then(|item| async {
+ item.convert(key_store.key.get_inner())
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ })
+ .await
+ }
+ }
+
async fn find_merchant_connector_account_by_merchant_id_connector_name(
&self,
merchant_id: &str,
@@ -329,7 +381,12 @@ impl MerchantConnectorAccountInterface for Store {
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
let _merchant_id = this.merchant_id.clone();
- let _merchant_connector_label = this.connector_label.clone();
+ let _profile_id = this
+ .profile_id
+ .clone()
+ .ok_or(errors::StorageError::ValueNotFound(
+ "profile_id".to_string(),
+ ))?;
let update_call = || async {
let conn = connection::pg_connection_write(self).await?;
@@ -352,9 +409,7 @@ impl MerchantConnectorAccountInterface for Store {
{
super::cache::publish_and_redact(
self,
- cache::CacheKind::Accounts(
- format!("{}_{}", _merchant_id, _merchant_connector_label).into(),
- ),
+ cache::CacheKind::Accounts(format!("{}_{}", _merchant_id, _profile_id).into()),
update_call,
)
.await
@@ -399,11 +454,13 @@ impl MerchantConnectorAccountInterface for Store {
.map_err(Into::into)
.into_report()?;
+ let _profile_id = mca.profile_id.ok_or(errors::StorageError::ValueNotFound(
+ "profile_id".to_string(),
+ ))?;
+
super::cache::publish_and_redact(
self,
- cache::CacheKind::Accounts(
- format!("{}_{}", mca.merchant_id, mca.connector_label).into(),
- ),
+ cache::CacheKind::Accounts(format!("{}_{}", mca.merchant_id, _profile_id).into()),
delete_call,
)
.await
@@ -430,7 +487,8 @@ impl MerchantConnectorAccountInterface for MockDb {
.await
.iter()
.find(|account| {
- account.merchant_id == merchant_id && account.connector_label == connector
+ account.merchant_id == merchant_id
+ && account.connector_label == Some(connector.to_string())
})
.cloned()
.async_map(|account| async {
@@ -496,6 +554,36 @@ impl MerchantConnectorAccountInterface for MockDb {
}
}
+ async fn find_merchant_connector_account_by_profile_id_connector_name(
+ &self,
+ profile_id: &str,
+ connector_name: &str,
+ key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
+ let maybe_mca = self
+ .merchant_connector_accounts
+ .lock()
+ .await
+ .iter()
+ .find(|account| {
+ account.profile_id.eq(&Some(profile_id.to_owned()))
+ && account.connector_name == connector_name
+ })
+ .cloned();
+
+ match maybe_mca {
+ Some(mca) => mca
+ .to_owned()
+ .convert(key_store.key.get_inner())
+ .await
+ .change_context(errors::StorageError::DecryptionError),
+ None => Err(errors::StorageError::ValueNotFound(
+ "cannot find merchant connector account".to_string(),
+ )
+ .into()),
+ }
+ }
+
async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id(
&self,
merchant_id: &str,
@@ -691,7 +779,7 @@ mod merchant_connector_account_cache_tests {
#[allow(clippy::unwrap_used)]
#[tokio::test]
- async fn test_connector_label_cache() {
+ async fn test_connector_profile_id_cache() {
let db = MockDb::new().await;
let redis_conn = db.get_redis_conn().unwrap();
@@ -704,6 +792,7 @@ mod merchant_connector_account_cache_tests {
let merchant_id = "test_merchant";
let connector_label = "stripe_USA";
let merchant_connector_id = "simple_merchant_connector_id";
+ let profile_id = "pro_max_ultra";
db.insert_merchant_key_store(
domain::MerchantKeyStore {
@@ -743,23 +832,24 @@ mod merchant_connector_account_cache_tests {
connector_type: ConnectorType::FinOperations,
metadata: None,
frm_configs: None,
- connector_label: connector_label.to_string(),
- business_country: CountryAlpha2::US,
- business_label: "cloth".to_string(),
+ connector_label: Some(connector_label.to_string()),
+ business_country: Some(CountryAlpha2::US),
+ business_label: Some("cloth".to_string()),
business_sub_label: None,
created_at: date_time::now(),
modified_at: date_time::now(),
connector_webhook_details: None,
- profile_id: None,
+ profile_id: Some(profile_id.to_string()),
};
- db.insert_merchant_connector_account(mca, &merchant_key)
+ db.insert_merchant_connector_account(mca.clone(), &merchant_key)
.await
.unwrap();
+
let find_call = || async {
- db.find_merchant_connector_account_by_merchant_id_connector_label(
- merchant_id,
- connector_label,
+ db.find_merchant_connector_account_by_profile_id_connector_name(
+ profile_id,
+ &mca.connector_name,
&merchant_key,
)
.await
@@ -770,7 +860,7 @@ mod merchant_connector_account_cache_tests {
};
let _: storage::MerchantConnectorAccount = cache::get_or_populate_in_memory(
&db,
- &format!("{}_{}", merchant_id, connector_label),
+ &format!("{}_{}", merchant_id, profile_id),
find_call,
&ACCOUNTS_CACHE,
)
diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs
index a0892abfcd..225b9bad82 100644
--- a/crates/router/src/routes/admin.rs
+++ b/crates/router/src/routes/admin.rs
@@ -402,7 +402,7 @@ pub async fn business_profile_create(
state.get_ref(),
&req,
payload,
- |state, _, req| create_business_profile(&*state.store, req, &merchant_id, None),
+ |state, _, req| create_business_profile(&*state.store, req, &merchant_id),
&auth::AdminApiAuth,
)
.await
diff --git a/crates/router/src/types/api/webhooks.rs b/crates/router/src/types/api/webhooks.rs
index 698353893f..d849f1f82e 100644
--- a/crates/router/src/types/api/webhooks.rs
+++ b/crates/router/src/types/api/webhooks.rs
@@ -90,7 +90,7 @@ pub trait IncomingWebhook: ConnectorCommon + Sync {
merchant_id, connector_name
);
let default_secret = "default_secret".to_string();
- let connector_label = utils::get_connector_label_using_object_reference_id(
+ let profile_id = utils::get_profile_id_using_object_reference_id(
db,
object_reference_id,
merchant_account,
@@ -98,11 +98,12 @@ pub trait IncomingWebhook: ConnectorCommon + Sync {
)
.await
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
- .attach_printable("Error while fetching connector_label")?;
+ .attach_printable("Error while fetching business_profile")?;
+
let merchant_connector_account_result = db
- .find_merchant_connector_account_by_merchant_id_connector_label(
- merchant_id,
- &connector_label,
+ .find_merchant_connector_account_by_profile_id_connector_name(
+ &profile_id,
+ &merchant_account.merchant_id,
key_store,
)
.await;
diff --git a/crates/router/src/types/domain/merchant_account.rs b/crates/router/src/types/domain/merchant_account.rs
index a5620724ac..30950f8c9c 100644
--- a/crates/router/src/types/domain/merchant_account.rs
+++ b/crates/router/src/types/domain/merchant_account.rs
@@ -75,6 +75,7 @@ pub enum MerchantAccountUpdate {
ReconUpdate {
recon_status: diesel_models::enums::ReconStatus,
},
+ UnsetDefaultProfile,
}
impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal {
@@ -130,6 +131,10 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal {
recon_status,
..Default::default()
},
+ MerchantAccountUpdate::UnsetDefaultProfile => Self {
+ default_profile: Some(None),
+ ..Default::default()
+ },
}
}
}
diff --git a/crates/router/src/types/domain/merchant_connector_account.rs b/crates/router/src/types/domain/merchant_connector_account.rs
index a013534926..8be60f6cb2 100644
--- a/crates/router/src/types/domain/merchant_connector_account.rs
+++ b/crates/router/src/types/domain/merchant_connector_account.rs
@@ -25,9 +25,9 @@ pub struct MerchantConnectorAccount {
pub connector_type: enums::ConnectorType,
pub metadata: Option<pii::SecretSerdeValue>,
pub frm_configs: Option<Vec<Secret<serde_json::Value>>>,
- pub connector_label: String,
- pub business_country: enums::CountryAlpha2,
- pub business_label: String,
+ pub connector_label: Option<String>,
+ pub business_country: Option<enums::CountryAlpha2>,
+ pub business_label: Option<String>,
pub business_sub_label: Option<String>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs
index a5aa35b35b..2452676378 100644
--- a/crates/router/src/utils.rs
+++ b/crates/router/src/utils.rs
@@ -283,37 +283,14 @@ pub async fn find_payment_intent_from_refund_id_type(
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
}
-pub async fn get_connector_label_using_object_reference_id(
+pub async fn get_profile_id_using_object_reference_id(
db: &dyn StorageInterface,
object_reference_id: webhooks::ObjectReferenceId,
merchant_account: &domain::MerchantAccount,
connector_name: &str,
) -> CustomResult<String, errors::ApiErrorResponse> {
- let mut primary_business_details = merchant_account
- .primary_business_details
- .clone()
- .parse_value::<Vec<api_models::admin::PrimaryBusinessDetails>>("PrimaryBusinessDetails")
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("failed to parse primary business details")?;
- //check if there is only one primary business details and get those details
- let (option_business_country, option_business_label) = match primary_business_details.pop() {
- Some(business_details) => {
- if primary_business_details.is_empty() {
- (
- Some(business_details.country),
- Some(business_details.business),
- )
- } else {
- (None, None)
- }
- }
- None => (None, None),
- };
- match (option_business_country, option_business_label) {
- (Some(business_country), Some(business_label)) => Ok(format!(
- "{connector_name}_{}_{}",
- business_country, business_label
- )),
+ match merchant_account.default_profile.as_ref() {
+ Some(profile_id) => Ok(profile_id.clone()),
_ => {
let payment_intent = match object_reference_id {
webhooks::ObjectReferenceId::PaymentId(payment_id_type) => {
@@ -330,10 +307,15 @@ pub async fn get_connector_label_using_object_reference_id(
.await?
}
};
- Ok(format!(
- "{connector_name}_{}_{}",
- payment_intent.business_country, payment_intent.business_label
- ))
+ let profile_id = payment_intent
+ .profile_id
+ .ok_or(errors::ApiErrorResponse::MissingRequiredField {
+ field_name: "business_profile",
+ })
+ .into_report()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("profile_id is not set in payment_intent")?;
+ Ok(profile_id)
}
}
}
diff --git a/migrations/2023-08-24-095037_add_profile_id_in_file_metadata/down.sql b/migrations/2023-08-24-095037_add_profile_id_in_file_metadata/down.sql
new file mode 100644
index 0000000000..93f8946110
--- /dev/null
+++ b/migrations/2023-08-24-095037_add_profile_id_in_file_metadata/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE file_metadata DROP COLUMN IF EXISTS profile_id;
diff --git a/migrations/2023-08-24-095037_add_profile_id_in_file_metadata/up.sql b/migrations/2023-08-24-095037_add_profile_id_in_file_metadata/up.sql
new file mode 100644
index 0000000000..1785f5b938
--- /dev/null
+++ b/migrations/2023-08-24-095037_add_profile_id_in_file_metadata/up.sql
@@ -0,0 +1,3 @@
+-- Your SQL goes here
+ALTER TABLE file_metadata
+ADD COLUMN IF NOT EXISTS profile_id VARCHAR(64);
diff --git a/migrations/2023-08-28-131238_make_business_details_optional/down.sql b/migrations/2023-08-28-131238_make_business_details_optional/down.sql
new file mode 100644
index 0000000000..092d7c5700
--- /dev/null
+++ b/migrations/2023-08-28-131238_make_business_details_optional/down.sql
@@ -0,0 +1,3 @@
+-- This file should undo anything in `up.sql`
+-- The changes cannot be reversed, once we move to business profiles, cannot revert back to business_labels
+SELECT 1;
diff --git a/migrations/2023-08-28-131238_make_business_details_optional/up.sql b/migrations/2023-08-28-131238_make_business_details_optional/up.sql
new file mode 100644
index 0000000000..6fd7b51432
--- /dev/null
+++ b/migrations/2023-08-28-131238_make_business_details_optional/up.sql
@@ -0,0 +1,21 @@
+-- Your SQL goes here
+ALTER TABLE payment_intent
+ALTER COLUMN business_country DROP NOT NULL;
+
+ALTER TABLE payment_intent
+ALTER COLUMN business_label DROP NOT NULL;
+
+ALTER TABLE merchant_connector_account
+ALTER COLUMN business_country DROP NOT NULL;
+
+ALTER TABLE merchant_connector_account
+ALTER COLUMN business_label DROP NOT NULL;
+
+ALTER TABLE merchant_connector_account
+ALTER COLUMN connector_label DROP NOT NULL;
+
+DROP INDEX IF EXISTS merchant_connector_account_merchant_id_connector_label_index;
+
+CREATE UNIQUE INDEX IF NOT EXISTS merchant_connector_account_profile_id_connector_id_index ON merchant_connector_account(profile_id, connector_name);
+
+CREATE UNIQUE INDEX IF NOT EXISTS business_profile_merchant_id_profile_name_index ON business_profile(merchant_id, profile_name);
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index b389c686f6..3f7ecae800 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -6383,9 +6383,7 @@
"required": [
"connector_type",
"connector_name",
- "connector_label",
- "business_country",
- "business_label"
+ "connector_label"
],
"properties": {
"connector_type": {
@@ -6482,10 +6480,16 @@
"nullable": true
},
"business_country": {
- "$ref": "#/components/schemas/CountryAlpha2"
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/CountryAlpha2"
+ }
+ ],
+ "nullable": true
},
"business_label": {
- "type": "string"
+ "type": "string",
+ "nullable": true
},
"business_sub_label": {
"type": "string",
@@ -6590,10 +6594,7 @@
"required": [
"connector_type",
"connector_name",
- "connector_label",
- "merchant_connector_id",
- "business_country",
- "business_label"
+ "merchant_connector_id"
],
"properties": {
"connector_type": {
@@ -6606,7 +6607,8 @@
},
"connector_label": {
"type": "string",
- "example": "stripe_US_travel"
+ "example": "stripe_US_travel",
+ "nullable": true
},
"merchant_connector_id": {
"type": "string",
@@ -6682,12 +6684,18 @@
"nullable": true
},
"business_country": {
- "$ref": "#/components/schemas/CountryAlpha2"
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/CountryAlpha2"
+ }
+ ],
+ "nullable": true
},
"business_label": {
"type": "string",
"description": "Business Type of the merchant",
- "example": "travel"
+ "example": "travel",
+ "nullable": true
},
"business_sub_label": {
"type": "string",
@@ -9041,8 +9049,6 @@
"amount",
"currency",
"payment_method",
- "business_country",
- "business_label",
"attempt_count"
],
"properties": {
@@ -9336,11 +9342,17 @@
"nullable": true
},
"business_country": {
- "$ref": "#/components/schemas/CountryAlpha2"
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/CountryAlpha2"
+ }
+ ],
+ "nullable": true
},
"business_label": {
"type": "string",
- "description": "The business label of merchant for this payment"
+ "description": "The business label of merchant for this payment",
+ "nullable": true
},
"business_sub_label": {
"type": "string",