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(payment_methods): add batch payment method data retrieval endpoint (#10663)
Kashifd241c0bdc722
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rsindex 886e91adcb..0e588d5637 100644--- a/crates/api_models/src/payment_methods.rs+++ b/crates/api_models/src/payment_methods.rs@@ -2865,6 +2865,31 @@ pub struct UpdatePaymentMethodRecord {pub card_expiry_year: Option<masking::Secret<String>>,}+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]+pub struct PaymentMethodsBatchRecord {+ pub payment_method_id: String,+ #[serde(skip_deserializing, default)]+ pub line_number: Option<i64>,+}++#[derive(Debug, serde::Serialize)]+pub struct PaymentMethodsBatchRetrieveResponse {+ pub payment_method_id: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub payment_method_type: Option<api_enums::PaymentMethod>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub payment_method_subtype: Option<api_enums::PaymentMethodType>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub payment_method_data: Option<PaymentMethodsData>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub error_message: Option<String>,+ pub line_number: Option<i64>,+}++impl common_utils::events::ApiEventMetric for PaymentMethodsBatchRecord {}++impl common_utils::events::ApiEventMetric for PaymentMethodsBatchRetrieveResponse {}+#[derive(Debug, serde::Serialize)]pub struct PaymentMethodUpdateResponse {pub payment_method_id: String,diff --git a/crates/diesel_models/src/query/payment_method.rs b/crates/diesel_models/src/query/payment_method.rsindex 72333d5f0f..8292d8d820 100644--- a/crates/diesel_models/src/query/payment_method.rs+++ b/crates/diesel_models/src/query/payment_method.rs@@ -106,6 +106,27 @@ impl PaymentMethod {.await}+ pub async fn find_by_merchant_id_payment_method_ids(+ conn: &PgPooledConn,+ merchant_id: &common_utils::id_type::MerchantId,+ payment_method_ids: &[String],+ limit: Option<i64>,+ ) -> StorageResult<Vec<Self>> {+ if payment_method_ids.is_empty() {+ return Ok(Vec::new());+ }+ generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(+ conn,+ dsl::merchant_id+ .eq(merchant_id.to_owned())+ .and(dsl::payment_method_id.eq_any(payment_method_ids.to_owned())),+ limit,+ None,+ Some(dsl::payment_method_id.asc()),+ )+ .await+ }+pub async fn get_count_by_customer_id_merchant_id_status(conn: &PgPooledConn,customer_id: &common_utils::id_type::CustomerId,diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rsindex 334fb77ff9..493a479dff 100644--- a/crates/hyperswitch_domain_models/src/payment_methods.rs+++ b/crates/hyperswitch_domain_models/src/payment_methods.rs@@ -874,6 +874,15 @@ pub trait PaymentMethodInterface {storage_scheme: MerchantStorageScheme,) -> CustomResult<PaymentMethod, Self::Error>;+ #[cfg(feature = "v1")]+ async fn find_payment_methods_by_merchant_id_payment_method_ids(+ &self,+ key_store: &MerchantKeyStore,+ merchant_id: &id_type::MerchantId,+ payment_method_ids: &[String],+ storage_scheme: MerchantStorageScheme,+ ) -> CustomResult<Vec<PaymentMethod>, Self::Error>;+#[cfg(feature = "v1")]async fn find_payment_method_by_customer_id_merchant_id_list(&self,diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rsindex 3ebac0ca81..38c4704f9a 100644--- a/crates/router/src/core/payment_methods.rs+++ b/crates/router/src/core/payment_methods.rs@@ -1,4 +1,6 @@pub mod access_token;+#[cfg(feature = "v1")]+pub mod batch_retrieve;pub mod cards;pub mod migration;pub mod network_tokenization;diff --git a/crates/router/src/core/payment_methods/batch_retrieve.rs b/crates/router/src/core/payment_methods/batch_retrieve.rsnew file mode 100644index 0000000000..59d84dd99a--- /dev/null+++ b/crates/router/src/core/payment_methods/batch_retrieve.rs@@ -0,0 +1,146 @@+use std::collections::{HashMap, HashSet};++use actix_multipart::form::{bytes::Bytes, text::Text, MultipartForm};+use api_models::payment_methods::{+ PaymentMethodsBatchRecord, PaymentMethodsBatchRetrieveResponse, PaymentMethodsData,+};+use common_utils::{ext_traits::ValueExt, id_type};+use error_stack::ResultExt;+use masking::ExposeInterface;+use router_env::logger;++use crate::{+ core::errors::{self, RouterResult},+ routes,+ types::domain,+};++#[derive(Debug, MultipartForm)]+pub struct PaymentMethodsBatchRetrieveForm {+ #[multipart(limit = "1MB")]+ pub file: Bytes,+ pub merchant_id: Text<id_type::MerchantId>,+}++pub fn parse_csv(data: &[u8]) -> csv::Result<Vec<PaymentMethodsBatchRecord>> {+ let mut csv_reader = csv::ReaderBuilder::new()+ .has_headers(true)+ .from_reader(data);+ let mut records = Vec::new();+ let mut id_counter = 0;+ for (line_number, result) in csv_reader+ .deserialize::<PaymentMethodsBatchRecord>()+ .enumerate()+ {+ match result {+ Ok(mut record) => {+ id_counter += 1;+ record.line_number = Some(id_counter);+ records.push(record);+ }+ Err(error) => {+ logger::error!("Error parsing line {}: {}", line_number + 1, error);+ }+ }+ }+ Ok(records)+}++pub fn get_payment_method_batch_records(+ form: PaymentMethodsBatchRetrieveForm,+) -> Result<(id_type::MerchantId, Vec<PaymentMethodsBatchRecord>), errors::ApiErrorResponse> {+ match parse_csv(form.file.data.as_ref()) {+ Ok(records) => {+ logger::info!("Parsed a total of {} records", records.len());+ Ok((form.merchant_id.0, records))+ }+ Err(error) => {+ logger::error!("Failed to parse CSV: {:?}", error);+ Err(errors::ApiErrorResponse::PreconditionFailed {+ message: error.to_string(),+ })+ }+ }+}++pub async fn retrieve_payment_method_data(+ state: &routes::SessionState,+ merchant_id: &id_type::MerchantId,+ platform: &domain::Platform,+ records: Vec<PaymentMethodsBatchRecord>,+) -> RouterResult<Vec<PaymentMethodsBatchRetrieveResponse>> {+ let storage_scheme = platform.get_provider().get_account().storage_scheme;+ let mut seen_ids = HashSet::new();+ let mut unique_ids = Vec::new();+ for record in &records {+ if seen_ids.insert(record.payment_method_id.clone()) {+ unique_ids.push(record.payment_method_id.clone());+ }+ }++ let payment_methods = if unique_ids.is_empty() {+ Vec::new()+ } else {+ state+ .store+ .find_payment_methods_by_merchant_id_payment_method_ids(+ platform.get_provider().get_key_store(),+ merchant_id,+ &unique_ids,+ storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)?+ };++ let pm_map = payment_methods+ .into_iter()+ .map(|pm| (pm.payment_method_id.clone(), pm))+ .collect::<HashMap<_, _>>();++ let responses = records+ .into_iter()+ .map(|record| {+ if let Some(payment_method) = pm_map.get(&record.payment_method_id) {+ let mut error_message = None;+ let payment_method_data = if let Some(raw_payment_method_data) =+ payment_method.payment_method_data.clone()+ {+ let value = raw_payment_method_data.into_inner().expose();+ match value.parse_value::<PaymentMethodsData>("PaymentMethodsData") {+ Ok(data) => Some(data),+ Err(err) => {+ logger::error!("Failed to deserialize payment_method_data: {:?}", err);+ error_message =+ Some("Failed to deserialize payment_method_data".to_string());+ None+ }+ }+ } else {+ error_message = Some("payment_method_data not found".to_string());+ None+ };++ PaymentMethodsBatchRetrieveResponse {+ payment_method_id: record.payment_method_id,+ payment_method_type: payment_method.get_payment_method_type(),+ payment_method_subtype: payment_method.get_payment_method_subtype(),+ payment_method_data,+ error_message,+ line_number: record.line_number,+ }+ } else {+ PaymentMethodsBatchRetrieveResponse {+ payment_method_id: record.payment_method_id,+ payment_method_type: None,+ payment_method_subtype: None,+ payment_method_data: None,+ error_message: Some("Payment method not found".to_string()),+ line_number: record.line_number,+ }+ }+ })+ .collect();++ Ok(responses)+}diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rsindex bee4fbf67a..bd81dd6cff 100644--- a/crates/router/src/db/kafka_store.rs+++ b/crates/router/src/db/kafka_store.rs@@ -2203,6 +2203,24 @@ impl PaymentMethodInterface for KafkaStore {.await}+ #[cfg(feature = "v1")]+ async fn find_payment_methods_by_merchant_id_payment_method_ids(+ &self,+ key_store: &domain::MerchantKeyStore,+ merchant_id: &id_type::MerchantId,+ payment_method_ids: &[String],+ storage_scheme: MerchantStorageScheme,+ ) -> CustomResult<Vec<domain::PaymentMethod>, errors::StorageError> {+ self.diesel_store+ .find_payment_methods_by_merchant_id_payment_method_ids(+ key_store,+ merchant_id,+ payment_method_ids,+ storage_scheme,+ )+ .await+ }+async fn insert_payment_method(&self,key_store: &domain::MerchantKeyStore,diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex dedce6c807..2fe88b4ab9 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -1640,6 +1640,10 @@ impl PaymentMethods {web::resource("/update-batch").route(web::post().to(payment_methods::update_payment_methods)),)+ .service(+ web::resource("/batch")+ .route(web::get().to(payment_methods::payment_methods_batch_retrieve_api)),+ ).service(web::resource("/tokenize-card").route(web::post().to(payment_methods::tokenize_card_api)),diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rsindex 881a153325..867fa9f96f 100644--- a/crates/router/src/routes/lock_utils.rs+++ b/crates/router/src/routes/lock_utils.rs@@ -125,6 +125,7 @@ impl From<Flow> for ApiIdentifier {Flow::PaymentMethodsCreate| Flow::PaymentMethodsMigrate| Flow::PaymentMethodsBatchUpdate+ | Flow::PaymentMethodsBatchRetrieve| Flow::PaymentMethodsList| Flow::CustomerPaymentMethodsList| Flow::GetPaymentMethodTokenDatadiff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rsindex f64fcd7b19..17c172a829 100644--- a/crates/router/src/routes/payment_methods.rs+++ b/crates/router/src/routes/payment_methods.rs@@ -1,3 +1,6 @@+#[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))]+use std::collections::HashMap;+use ::payment_methods::{controller::PaymentMethodsController,core::{migration, migration::payment_methods::migrate_payment_method},@@ -16,7 +19,10 @@ use router_env::{instrument, logger, tracing, Flow};use super::app::{AppState, SessionState};#[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))]-use crate::core::{customers, payment_methods::tokenize};+use crate::core::{+ customers,+ payment_methods::{batch_retrieve, tokenize},+};use crate::{core::{api_locking,@@ -351,7 +357,7 @@ pub async fn migrate_payment_methods(key_store,);- let mut mca_cache = std::collections::HashMap::new();+ let mut mca_cache = HashMap::new();let customers = Vec::<PaymentMethodCustomerMigrate>::foreign_try_from((&req,merchant_id.clone(),@@ -451,6 +457,74 @@ pub async fn update_payment_methods(.await}+#[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))]+#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsBatchRetrieve))]+pub async fn payment_methods_batch_retrieve_api(+ state: web::Data<AppState>,+ req: HttpRequest,+ MultipartForm(form): MultipartForm<batch_retrieve::PaymentMethodsBatchRetrieveForm>,+) -> HttpResponse {+ let flow = Flow::PaymentMethodsBatchRetrieve;+ let (merchant_id, records) = match batch_retrieve::get_payment_method_batch_records(form) {+ Ok(result) => result,+ Err(error) => return api::log_and_return_error_response(error.into()),+ };++ if records.is_empty() {+ return api::log_and_return_error_response(+ errors::ApiErrorResponse::InvalidRequestData {+ message: "No payment_method_ids provided".to_string(),+ }+ .into(),+ );+ }++ if records.len() > 200 {+ return api::log_and_return_error_response(+ errors::ApiErrorResponse::InvalidRequestData {+ message: "A maximum of 200 payment_method_ids are allowed per request".to_string(),+ }+ .into(),+ );+ }++ let payload_records = records.clone();+ Box::pin(api::server_wrap(+ flow,+ state,+ &req,+ payload_records,+ |state, _, _, _| {+ let merchant_id = merchant_id.clone();+ let records = records.clone();+ async move {+ let (key_store, merchant_account) =+ get_merchant_account(&state, &merchant_id).await?;++ let platform = domain::Platform::new(+ merchant_account.clone(),+ key_store.clone(),+ merchant_account,+ key_store,+ );++ let responses = batch_retrieve::retrieve_payment_method_data(+ &state,+ &merchant_id,+ &platform,+ records,+ )+ .await?;++ Ok(services::ApplicationResponse::Json(responses))+ }+ },+ &auth::AdminApiAuth,+ api_locking::LockAction::NotApplicable,+ ))+ .await+}+#[cfg(feature = "v1")]#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSave))]pub async fn save_payment_method_api(diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rsindex b5bddc2ec8..7741b18bff 100644--- a/crates/router_env/src/logger/types.rs+++ b/crates/router_env/src/logger/types.rs@@ -128,6 +128,8 @@ pub enum Flow {PaymentMethodsMigrate,/// Payment methods batch update flow.PaymentMethodsBatchUpdate,+ /// Payment methods batch retrieve flow.+ PaymentMethodsBatchRetrieve,/// Payment methods list flow.PaymentMethodsList,/// Payment method save flowdiff --git a/crates/storage_impl/src/payment_method.rs b/crates/storage_impl/src/payment_method.rsindex f2d3c43223..c3c03a0df8 100644--- a/crates/storage_impl/src/payment_method.rs+++ b/crates/storage_impl/src/payment_method.rs@@ -4,6 +4,9 @@ use crate::redis::kv_store::KvStorePartition;impl KvStorePartition for PaymentMethod {}+#[cfg(feature = "v1")]+use std::collections::HashSet;+use common_enums::enums::MerchantStorageScheme;use common_utils::{errors::CustomResult, id_type};#[cfg(feature = "v1")]@@ -92,6 +95,25 @@ impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> {.await}+ #[cfg(feature = "v1")]+ #[instrument(skip_all)]+ async fn find_payment_methods_by_merchant_id_payment_method_ids(+ &self,+ key_store: &MerchantKeyStore,+ merchant_id: &id_type::MerchantId,+ payment_method_ids: &[String],+ storage_scheme: MerchantStorageScheme,+ ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {+ self.router_store+ .find_payment_methods_by_merchant_id_payment_method_ids(+ key_store,+ merchant_id,+ payment_method_ids,+ storage_scheme,+ )+ .await+ }+// not supported in kv#[cfg(feature = "v1")]#[instrument(skip_all)]@@ -423,6 +445,28 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {.await}+ #[cfg(feature = "v1")]+ #[instrument(skip_all)]+ async fn find_payment_methods_by_merchant_id_payment_method_ids(+ &self,+ key_store: &MerchantKeyStore,+ merchant_id: &id_type::MerchantId,+ payment_method_ids: &[String],+ _storage_scheme: MerchantStorageScheme,+ ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {+ let conn = pg_connection_read(self).await?;+ self.find_resources(+ key_store,+ PaymentMethod::find_by_merchant_id_payment_method_ids(+ &conn,+ merchant_id,+ payment_method_ids,+ Some(200),+ ),+ )+ .await+ }+#[cfg(feature = "v1")]#[instrument(skip_all)]async fn get_payment_method_count_by_customer_id_merchant_id_status(@@ -711,6 +755,28 @@ impl PaymentMethodInterface for MockDb {.await}+ #[cfg(feature = "v1")]+ async fn find_payment_methods_by_merchant_id_payment_method_ids(+ &self,+ key_store: &MerchantKeyStore,+ merchant_id: &id_type::MerchantId,+ payment_method_ids: &[String],+ _storage_scheme: MerchantStorageScheme,+ ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {+ if payment_method_ids.is_empty() {+ return Ok(Vec::new());+ }+ let ids: HashSet<_> = payment_method_ids.iter().cloned().collect();+ let payment_methods = self.payment_methods.lock().await;+ self.get_resources(+ key_store,+ payment_methods,+ |pm| pm.merchant_id == *merchant_id && ids.contains(pm.get_id()),+ "cannot find payment method".to_string(),+ )+ .await+ }+#[cfg(feature = "v1")]async fn get_payment_method_count_by_customer_id_merchant_id_status(&self,