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(platform): implement provider and processor context to locker functions (#11860)
Ankit Kumar Guptaa61cbddfcf87
diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rsindex 46ac4778fe..b465bcf377 100644--- a/crates/api_models/src/events.rs+++ b/crates/api_models/src/events.rs@@ -5,7 +5,6 @@ pub mod customer;pub mod dispute;pub mod external_service_auth;pub mod gsm;-mod locker_migration;pub mod payment;#[cfg(feature = "payouts")]pub mod payouts;diff --git a/crates/api_models/src/events/locker_migration.rs b/crates/api_models/src/events/locker_migration.rsdeleted file mode 100644index db76a8f760..0000000000--- a/crates/api_models/src/events/locker_migration.rs+++ /dev/null@@ -1,9 +0,0 @@-use common_utils::events::ApiEventMetric;--use crate::locker_migration::MigrateCardResponse;--impl ApiEventMetric for MigrateCardResponse {- fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {- Some(common_utils::events::ApiEventsType::RustLocker)- }-}diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rsindex 57336e5f95..cea478f729 100644--- a/crates/api_models/src/lib.rs+++ b/crates/api_models/src/lib.rs@@ -24,7 +24,6 @@ pub mod feature_matrix;pub mod files;pub mod gsm;pub mod health_check;-pub mod locker_migration;pub mod mandates;pub mod merchant_connector_webhook_management;pub mod oidc;diff --git a/crates/api_models/src/locker_migration.rs b/crates/api_models/src/locker_migration.rsdeleted file mode 100644index 6e2881cd46..0000000000--- a/crates/api_models/src/locker_migration.rs+++ /dev/null@@ -1,8 +0,0 @@-#[derive(Debug, Clone, serde::Serialize)]-#[serde(rename_all = "camelCase")]-pub struct MigrateCardResponse {- pub status_message: String,- pub status_code: String,- pub customers_moved: usize,- pub cards_moved: usize,-}diff --git a/crates/router/src/core.rs b/crates/router/src/core.rsindex 55ec0f77be..b7e8a51d7b 100644--- a/crates/router/src/core.rs+++ b/crates/router/src/core.rs@@ -32,8 +32,6 @@ pub mod files;pub mod fraud_check;pub mod gsm;pub mod health_check;-#[cfg(feature = "v1")]-pub mod locker_migration;pub mod mandate;pub mod merchant_connector_webhook_management;pub mod metrics;diff --git a/crates/router/src/core/locker_migration.rs b/crates/router/src/core/locker_migration.rsdeleted file mode 100644index e50b423d16..0000000000--- a/crates/router/src/core/locker_migration.rs+++ /dev/null@@ -1,214 +0,0 @@-use ::payment_methods::controller::PaymentMethodsController;-use api_models::locker_migration::MigrateCardResponse;-use common_utils::{errors::CustomResult, id_type};-#[cfg(feature = "v1")]-use diesel_models::enums as storage_enums;-#[cfg(feature = "v1")]-use error_stack::FutureExt;-use error_stack::ResultExt;-#[cfg(feature = "v1")]-use futures::TryFutureExt;--#[cfg(feature = "v1")]-use super::{errors::StorageErrorExt, payment_methods::cards};-use crate::{errors, routes::SessionState, services, types::domain};-#[cfg(feature = "v1")]-use crate::{services::logger, types::api};--#[cfg(feature = "v2")]-pub async fn rust_locker_migration(- _state: SessionState,- _merchant_id: &id_type::MerchantId,-) -> CustomResult<services::ApplicationResponse<MigrateCardResponse>, errors::ApiErrorResponse> {- todo!()-}--#[cfg(feature = "v1")]-pub async fn rust_locker_migration(- state: SessionState,- merchant_id: &id_type::MerchantId,-) -> CustomResult<services::ApplicationResponse<MigrateCardResponse>, errors::ApiErrorResponse> {- use crate::db::customers::CustomerListConstraints;-- let db = state.store.as_ref();- let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- merchant_id,- &state.store.get_master_key().to_vec().into(),- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)?;-- let merchant_account = db- .find_merchant_account_by_merchant_id(merchant_id, &key_store)- .await- .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)- .change_context(errors::ApiErrorResponse::InternalServerError)?;-- // Handle cases where the number of customers is greater than the limit- let constraints = CustomerListConstraints {- limit: u16::MAX,- offset: None,- customer_id: None,- time_range: None,- };-- let domain_customers = db- .list_customers_by_merchant_id(merchant_id, &key_store, constraints)- .await- .change_context(errors::ApiErrorResponse::InternalServerError)?;-- let mut customers_moved = 0;- let mut cards_moved = 0;-- let platform = domain::Platform::new(- merchant_account.clone(),- key_store.clone(),- merchant_account.clone(),- key_store.clone(),- None,- );- for customer in domain_customers {- let result = Box::pin(- db.find_payment_method_by_customer_id_merchant_id_list(- &key_store,- &customer.customer_id,- merchant_id,- None,- )- .change_context(errors::ApiErrorResponse::InternalServerError)- .and_then(|pm| {- call_to_locker(&state, pm, &customer.customer_id, merchant_id, &platform)- }),- )- .await?;-- customers_moved += 1;- cards_moved += result;- }-- Ok(services::api::ApplicationResponse::Json(- MigrateCardResponse {- status_code: "200".to_string(),- status_message: "Card migration completed".to_string(),- customers_moved,- cards_moved,- },- ))-}--#[cfg(feature = "v1")]-pub async fn call_to_locker(- state: &SessionState,- payment_methods: Vec<domain::PaymentMethod>,- customer_id: &id_type::CustomerId,- merchant_id: &id_type::MerchantId,- platform: &domain::Platform,-) -> CustomResult<usize, errors::ApiErrorResponse> {- let mut cards_moved = 0;-- for pm in payment_methods.into_iter().filter(|pm| {- matches!(- pm.get_payment_method_type(),- Some(storage_enums::PaymentMethod::Card)- )- }) {- let card = cards::get_card_from_locker(- state,- customer_id,- merchant_id,- pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),- )- .await;-- let card = match card {- Ok(card) => card.get_card(),- Err(err) => {- logger::error!("Failed to fetch card from Basilisk HS locker : {:?}", err);- continue;- }- };-- let card_details = api::CardDetail {- card_number: card.card_number,- card_exp_month: card.card_exp_month,- card_exp_year: card.card_exp_year,- card_holder_name: card.name_on_card,- nick_name: card.nick_name.map(hyperswitch_masking::Secret::new),- card_cvc: None,- card_issuing_country: None,- card_issuing_country_code: None,- card_network: None,- card_issuer: None,- card_type: None,- };-- let pm_create = api::PaymentMethodCreate {- payment_method: pm.get_payment_method_type(),- payment_method_type: pm.get_payment_method_subtype(),- payment_method_issuer: pm.payment_method_issuer,- payment_method_issuer_code: pm.payment_method_issuer_code,- card: Some(card_details.clone()),- #[cfg(feature = "payouts")]- wallet: None,- #[cfg(feature = "payouts")]- bank_transfer: None,- #[cfg(feature = "payouts")]- bank_transfer_data: None,- metadata: pm.metadata,- customer_id: pm.customer_id,- card_network: card.card_brand,- client_secret: None,- payment_method_data: None,- billing: None,- connector_mandate_details: None,- network_transaction_id: None,- };-- let add_card_result = cards::PmCards{- state,- provider: platform.get_provider(),- }.add_card_hs(- pm_create,- &card_details,- customer_id,- Some(pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id)),-- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable(format!(- "Card migration failed for merchant_id: {merchant_id:?}, customer_id: {customer_id:?}, payment_method_id: {} ",- pm.payment_method_id- ));-- let (_add_card_rs_resp, _is_duplicate) = match add_card_result {- Ok(output) => output,- Err(err) => {- logger::error!("Failed to add card to Rust locker : {:?}", err);- continue;- }- };-- cards_moved += 1;-- logger::info!(- "Card migrated for merchant_id: {merchant_id:?}, customer_id: {customer_id:?}, payment_method_id: {} ",- pm.payment_method_id- );- }-- Ok(cards_moved)-}--#[cfg(feature = "v2")]-pub async fn call_to_locker(- _state: &SessionState,- _payment_methods: Vec<domain::PaymentMethod>,- _customer_id: &id_type::CustomerId,- _merchant_id: &id_type::MerchantId,- _platform: &domain::Platform,-) -> CustomResult<usize, errors::ApiErrorResponse> {- todo!()-}diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rsindex 1474433336..e2951e2708 100644--- a/crates/router/src/core/payment_methods/cards.rs+++ b/crates/router/src/core/payment_methods/cards.rs@@ -4184,7 +4184,7 @@ pub async fn list_payment_methods(let db = &*state.store;let payment_intent = if let Some(cs) = &req.client_secret {if cs.starts_with("pm_") {- validate_payment_method_and_client_secret(cs, db, &platform).await?;+ validate_payment_method_and_client_secret(cs, db, platform.get_provider()).await?;None} else {helpers::verify_payment_intent_time_and_client_secret(@@ -4648,7 +4648,7 @@ pub fn should_collect_shipping_or_billing_details_from_wallet_connector(async fn validate_payment_method_and_client_secret(cs: &String,db: &dyn db::StorageInterface,- platform: &domain::Platform,+ provider: &domain::Provider,) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> {let pm_vec = cs.split("_secret").collect::<Vec<&str>>();let pm_id = pm_vec@@ -4659,9 +4659,9 @@ async fn validate_payment_method_and_client_secret(let payment_method = db.find_payment_method(- platform.get_provider().get_key_store(),+ provider.get_key_store(),pm_id,- platform.get_provider().get_account().storage_scheme,+ provider.get_account().storage_scheme,).await.change_context(errors::ApiErrorResponse::PaymentMethodNotFound)diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rsindex 8ebac8c7f3..79faa62dd3 100644--- a/crates/router/src/core/payments/tokenization.rs+++ b/crates/router/src/core/payments/tokenization.rs@@ -55,7 +55,7 @@ use crate::{#[cfg(feature = "v1")]pub async fn save_network_token_details_in_nt_mapper(state: &SessionState,- platform: &domain::Platform,+ provider: &domain::Provider,customer_id: &id_type::CustomerId,payment_method_id: String,network_token_requestor_ref_id: String,@@ -64,7 +64,7 @@ pub async fn save_network_token_details_in_nt_mapper(//Insert the network token reference ID along with merchant id, customer id in CallbackMapper table for its respective webookslet callback_mapper_data = CallbackMapperData::NetworkTokenWebhook {- merchant_id: platform.get_processor().get_account().get_id().clone(),+ merchant_id: provider.get_account().get_id().clone(),customer_id: customer_id.to_owned(),payment_method_id: payment_method_id.clone(),};@@ -103,7 +103,7 @@ async fn save_in_locker(Box::pin(save_in_locker_external(state,- platform,+ platform.get_processor(),payment_method_request,card_detail,external_vault_details,@@ -112,7 +112,13 @@ async fn save_in_locker(}domain::ExternalVaultDetails::Skip => {// Use internal vault (locker)- save_in_locker_internal(state, platform, payment_method_request, card_detail).await+ save_in_locker_internal(+ state,+ platform.get_provider(),+ payment_method_request,+ card_detail,+ )+ .await}}}@@ -301,7 +307,7 @@ wherenetwork_token_resp,) = if !state.conf.locker.locker_enabled {let (res, dc) = skip_saving_card_in_locker(- platform,+ platform.get_provider(),payment_method_create_request.to_owned(),).await?;@@ -526,7 +532,7 @@ where//Insert the network token reference ID along with merchant id, customer id in CallbackMapper table for its respective webookssave_network_token_details_in_nt_mapper(state,- platform,+ platform.get_provider(),&customer_id,resp.payment_method_id.clone(),nt_ref_id,@@ -672,7 +678,7 @@ where//Insert the network token reference ID along with merchant id, customer id in CallbackMapper table for its respective webookssave_network_token_details_in_nt_mapper(state,- platform,+ platform.get_provider(),&customer_id,resp.payment_method_id.clone(),nt_ref_id.clone(),@@ -962,7 +968,7 @@ where//Insert the network token reference ID along with merchant id, customer id in CallbackMapper table for its respective webookssave_network_token_details_in_nt_mapper(state,- platform,+ platform.get_provider(),&customer_id,resp.payment_method_id.clone(),network_token_requestor_ref_id,@@ -1146,7 +1152,7 @@ pub async fn pre_payment_tokenization(#[cfg(feature = "v1")]async fn skip_saving_card_in_locker(- platform: &domain::Platform,+ provider: &domain::Provider,payment_method_request: api::PaymentMethodCreate,) -> RouterResult<(domain::PaymentMethodResponse,@@ -1190,7 +1196,7 @@ async fn skip_saving_card_in_locker(saved_to_locker: false,};let pm_resp = domain::PaymentMethodResponse {- merchant_id: platform.get_provider().get_account().get_id().to_owned(),+ merchant_id: provider.get_account().get_id().to_owned(),customer_id: Some(customer_id),payment_method_id,payment_method: payment_method_request.payment_method,@@ -1213,7 +1219,7 @@ async fn skip_saving_card_in_locker(None => {let pm_id = common_utils::generate_id(consts::ID_LENGTH, "pm");let payment_method_response = domain::PaymentMethodResponse {- merchant_id: platform.get_provider().get_account().get_id().to_owned(),+ merchant_id: provider.get_account().get_id().to_owned(),customer_id: Some(customer_id),payment_method_id: pm_id,payment_method: payment_method_request.payment_method,@@ -1249,7 +1255,7 @@ async fn skip_saving_card_in_locker(#[cfg(feature = "v1")]pub async fn save_in_locker_internal(state: &SessionState,- platform: &domain::Platform,+ provider: &domain::Provider,payment_method_request: api::PaymentMethodCreate,card_detail: Option<api::CardDetail>,) -> RouterResult<(@@ -1266,16 +1272,17 @@ pub async fn save_in_locker_internal(card_detail,payment_method_request.payment_method_data.clone(),) {- (_, Some(card), _) | (Some(card), _, _) => Box::pin(- PmCards {- state,- provider: platform.get_provider(),- }- .add_card_to_locker(payment_method_request, &card, &customer_id, None),- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Add Card Failed"),+ (_, Some(card), _) | (Some(card), _, _) => {+ Box::pin(PmCards { state, provider }.add_card_to_locker(+ payment_method_request,+ &card,+ &customer_id,+ None,+ ))+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Add Card Failed")+ }(None,@@ -1283,18 +1290,12 @@ pub async fn save_in_locker_internal(Some(api_models::payment_methods::PaymentMethodCreateData::BankDebit(bank_debit_create_data,)),- ) => Box::pin(- PmCards {- state,- provider: platform.get_provider(),- }- .add_bank_debit_to_locker(- payment_method_request,- bank_debit_create_data,- platform.get_provider().get_key_store(),- &customer_id,- ),- )+ ) => Box::pin(PmCards { state, provider }.add_bank_debit_to_locker(+ payment_method_request,+ bank_debit_create_data,+ provider.get_key_store(),+ &customer_id,+ )).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Add Bank Debit Failed"),@@ -1302,18 +1303,12 @@ pub async fn save_in_locker_internal(None,None,Some(api_models::payment_methods::PaymentMethodCreateData::Wallet(wallet_create_data)),- ) => Box::pin(- PmCards {- state,- provider: platform.get_provider(),- }- .add_wallet_to_locker(- payment_method_request,- wallet_create_data,- platform.get_provider().get_key_store(),- &customer_id,- ),- )+ ) => Box::pin(PmCards { state, provider }.add_wallet_to_locker(+ payment_method_request,+ wallet_create_data,+ provider.get_key_store(),+ &customer_id,+ )).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Add Wallet Failed"),@@ -1321,7 +1316,7 @@ pub async fn save_in_locker_internal(_ => {let pm_id = common_utils::generate_id(consts::ID_LENGTH, "pm");let payment_method_response = domain::PaymentMethodResponse {- merchant_id: platform.get_provider().get_account().get_id().clone(),+ merchant_id: provider.get_account().get_id().clone(),customer_id: Some(customer_id),payment_method_id: pm_id,payment_method: payment_method_request.payment_method,@@ -1346,7 +1341,7 @@ pub async fn save_in_locker_internal(#[cfg(feature = "v1")]pub async fn save_in_locker_external(state: &SessionState,- platform: &domain::Platform,+ processor: &domain::Processor,payment_method_request: api::PaymentMethodCreate,card_detail: Option<api::CardDetail>,external_vault_connector_details: &ExternalVaultConnectorDetails,@@ -1372,9 +1367,9 @@ pub async fn save_in_locker_external(let merchant_connector_account_details = state.store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(- platform.get_processor().get_account().get_id(),+ processor.get_account().get_id(),&external_vault_mca_id,- platform.get_processor().get_key_store(),+ processor.get_key_store(),).await.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {@@ -1385,7 +1380,7 @@ pub async fn save_in_locker_external(let vault_response = Box::pin(vault_payment_method_external_v1(state,&payment_method_custom_vaulting_data,- platform.get_processor().get_account(),+ processor.get_account(),merchant_connector_account_details,None,))@@ -1395,7 +1390,7 @@ pub async fn save_in_locker_external(let card_detail = CardDetailFromLocker::from(card);let pm_resp = domain::PaymentMethodResponse {- merchant_id: platform.get_processor().get_account().get_id().to_owned(),+ merchant_id: processor.get_account().get_id().to_owned(),customer_id: Some(customer_id),payment_method_id,payment_method: payment_method_request.payment_method,@@ -1418,7 +1413,7 @@ pub async fn save_in_locker_external(//Similar implementation is done for save in locker internallet pm_id = common_utils::generate_id(consts::ID_LENGTH, "pm");let payment_method_response = domain::PaymentMethodResponse {- merchant_id: platform.get_processor().get_account().get_id().to_owned(),+ merchant_id: processor.get_account().get_id().to_owned(),customer_id: Some(customer_id),payment_method_id: pm_id,payment_method: payment_method_request.payment_method,@@ -1468,7 +1463,7 @@ pub async fn save_network_token_in_locker(#[cfg(feature = "v1")]pub async fn save_network_token_in_locker(state: &SessionState,- platform: &domain::Platform,+ provider: &domain::Provider,card_data: &payment_method_data::Card,network_token_data: Option<api::CardDetail>,payment_method_request: api::PaymentMethodCreate,@@ -1488,18 +1483,12 @@ pub async fn save_network_token_in_locker(match network_token_data {Some(nt_data) => {- let (res, dc) = Box::pin(- PmCards {- state,- provider: platform.get_provider(),- }- .add_card_to_locker(- payment_method_request,- &nt_data,- &customer_id,- None,- ),- )+ let (res, dc) = Box::pin(PmCards { state, provider }.add_card_to_locker(+ payment_method_request,+ &nt_data,+ &customer_id,+ None,+ )).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Add Network Token Failed")?;@@ -1538,18 +1527,12 @@ pub async fn save_network_token_in_locker(card_type: None,};- let (res, dc) = Box::pin(- PmCards {- state,- provider: platform.get_provider(),- }- .add_card_to_locker(- payment_method_request,- &network_token_data,- &customer_id,- None,- ),- )+ let (res, dc) = Box::pin(PmCards { state, provider }.add_card_to_locker(+ payment_method_request,+ &network_token_data,+ &customer_id,+ None,+ )).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Add Network Token Failed")?;@@ -2012,7 +1995,7 @@ pub async fn save_card_and_network_token_in_locker(if payment_method_status == common_enums::PaymentMethodStatus::Active {let (res, dc) = Box::pin(save_in_locker_internal(state,- platform,+ platform.get_provider(),payment_method_create_request.to_owned(),Some(card_data),))@@ -2022,7 +2005,7 @@ pub async fn save_card_and_network_token_in_locker(let (network_token_resp, _dc, _) = Box::pin(save_network_token_in_locker(state,- platform,+ platform.get_provider(),&save_card_and_network_token_data.card_data,Some(network_token_data),payment_method_create_request.clone(),@@ -2057,7 +2040,7 @@ pub async fn save_card_and_network_token_in_locker(}let (res, dc) = Box::pin(save_in_locker_internal(state,- platform,+ platform.get_provider(),payment_method_create_request.to_owned(),Some(card_data),))@@ -2090,7 +2073,7 @@ pub async fn save_card_and_network_token_in_locker(network_token_requestor_ref_id,) = Box::pin(save_network_token_in_locker(state,- platform,+ platform.get_provider(),card,None,payment_method_create_request.clone(),@@ -2151,7 +2134,7 @@ async fn generate_network_token_and_update_payment_method(let (network_token_resp, _dc, network_token_requestor_ref_id) =Box::pin(save_network_token_in_locker(state,- platform,+ platform.get_provider(),card_data,None,payment_method_create_request.clone(),@@ -2217,7 +2200,7 @@ async fn generate_network_token_and_update_payment_method({save_network_token_details_in_nt_mapper(state,- platform,+ platform.get_provider(),&cust_id,pm_info.payment_method_id.clone(),nt_ref_id,diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rsindex 68780c7ce5..5229055977 100644--- a/crates/router/src/routes.rs+++ b/crates/router/src/routes.rs@@ -27,8 +27,6 @@ pub mod gsm;pub mod health;pub mod hypersense;pub mod lock_utils;-#[cfg(feature = "v1")]-pub mod locker_migration;pub mod mandates;pub mod metrics;pub mod oidc;diff --git a/crates/router/src/routes/locker_migration.rs b/crates/router/src/routes/locker_migration.rsdeleted file mode 100644index 6ebad77377..0000000000--- a/crates/router/src/routes/locker_migration.rs+++ /dev/null@@ -1,27 +0,0 @@-use actix_web::{web, HttpRequest, HttpResponse};-use router_env::Flow;--use super::AppState;-use crate::{- core::{api_locking, locker_migration},- services::{api, authentication as auth},-};--pub async fn rust_locker_migration(- state: web::Data<AppState>,- req: HttpRequest,- path: web::Path<common_utils::id_type::MerchantId>,-) -> HttpResponse {- let flow = Flow::RustLockerMigration;- let merchant_id = path.into_inner();- Box::pin(api::server_wrap(- flow,- state,- &req,- &merchant_id,- |state, _, _, _| locker_migration::rust_locker_migration(state, &merchant_id),- &auth::AdminApiAuth,- api_locking::LockAction::NotApplicable,- ))- .await-}