repo
stringclasses
1 value
instance_id
stringlengths
24
24
problem_statement
stringlengths
24
8.41k
patch
stringlengths
0
367k
test_patch
stringclasses
1 value
created_at
stringdate
2023-04-18 16:43:29
2025-10-07 09:18:54
hints_text
stringlengths
57
132k
version
stringclasses
8 values
base_commit
stringlengths
40
40
environment_setup_commit
stringlengths
40
40
juspay/hyperswitch
juspay__hyperswitch-8389
Bug: [FEATURE] Kv Redis feature for V2 models ### Feature Description Extend kv support for v2 models ### Possible Implementation Use existing construct to extend to v2 models ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/diesel_models/src/kv.rs b/crates/diesel_models/src/kv.rs index 6c0666e5903..ed984649e92 100644 --- a/crates/diesel_models/src/kv.rs +++ b/crates/diesel_models/src/kv.rs @@ -126,12 +126,7 @@ impl DBOperation { )), #[cfg(feature = "v2")] Updateable::PaymentAttemptUpdate(a) => DBResult::PaymentAttempt(Box::new( - a.orig - .update_with_attempt_id( - conn, - PaymentAttemptUpdateInternal::from(a.update_data), - ) - .await?, + a.orig.update_with_attempt_id(conn, a.update_data).await?, )), #[cfg(feature = "v1")] Updateable::RefundUpdate(a) => { @@ -263,12 +258,20 @@ pub struct PaymentIntentUpdateMems { pub update_data: PaymentIntentUpdateInternal, } +#[cfg(feature = "v1")] #[derive(Debug, Serialize, Deserialize)] pub struct PaymentAttemptUpdateMems { pub orig: PaymentAttempt, pub update_data: PaymentAttemptUpdate, } +#[cfg(feature = "v2")] +#[derive(Debug, Serialize, Deserialize)] +pub struct PaymentAttemptUpdateMems { + pub orig: PaymentAttempt, + pub update_data: PaymentAttemptUpdateInternal, +} + #[derive(Debug, Serialize, Deserialize)] pub struct RefundUpdateMems { pub orig: Refund, diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index 95fb600adc4..0afea0574a7 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -833,7 +833,7 @@ pub enum PaymentAttemptUpdate { // TODO: uncomment fields as and when required #[cfg(feature = "v2")] -#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] +#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = payment_attempt)] pub struct PaymentAttemptUpdateInternal { pub status: Option<storage_enums::AttemptStatus>, @@ -881,6 +881,112 @@ pub struct PaymentAttemptUpdateInternal { pub connector_request_reference_id: Option<String>, } +#[cfg(feature = "v2")] +impl PaymentAttemptUpdateInternal { + pub fn apply_changeset(self, source: PaymentAttempt) -> PaymentAttempt { + let Self { + status, + authentication_type, + error_message, + connector_payment_id, + modified_at, + browser_info, + error_code, + connector_metadata, + error_reason, + amount_capturable, + amount_to_capture, + updated_by, + merchant_connector_id, + connector, + redirection_data, + unified_code, + unified_message, + connector_token_details, + feature_metadata, + network_decline_code, + network_advice_code, + network_error_message, + payment_method_id, + connector_request_reference_id, + } = self; + + PaymentAttempt { + payment_id: source.payment_id, + merchant_id: source.merchant_id, + status: status.unwrap_or(source.status), + connector: connector.or(source.connector), + error_message: error_message.or(source.error_message), + surcharge_amount: source.surcharge_amount, + payment_method_id: payment_method_id.or(source.payment_method_id), + authentication_type: authentication_type.unwrap_or(source.authentication_type), + created_at: source.created_at, + modified_at: common_utils::date_time::now(), + last_synced: source.last_synced, + cancellation_reason: source.cancellation_reason, + amount_to_capture: amount_to_capture.or(source.amount_to_capture), + browser_info: browser_info + .and_then(|val| { + serde_json::from_value::<common_utils::types::BrowserInformation>(val).ok() + }) + .or(source.browser_info), + error_code: error_code.or(source.error_code), + payment_token: source.payment_token, + connector_metadata: connector_metadata.or(source.connector_metadata), + payment_experience: source.payment_experience, + payment_method_data: source.payment_method_data, + preprocessing_step_id: source.preprocessing_step_id, + error_reason: error_reason.or(source.error_reason), + multiple_capture_count: source.multiple_capture_count, + connector_response_reference_id: source.connector_response_reference_id, + amount_capturable: amount_capturable.unwrap_or(source.amount_capturable), + updated_by, + merchant_connector_id: merchant_connector_id.or(source.merchant_connector_id), + encoded_data: source.encoded_data, + unified_code: unified_code.flatten().or(source.unified_code), + unified_message: unified_message.flatten().or(source.unified_message), + net_amount: source.net_amount, + external_three_ds_authentication_attempted: source + .external_three_ds_authentication_attempted, + authentication_connector: source.authentication_connector, + authentication_id: source.authentication_id, + fingerprint_id: source.fingerprint_id, + client_source: source.client_source, + client_version: source.client_version, + customer_acceptance: source.customer_acceptance, + profile_id: source.profile_id, + organization_id: source.organization_id, + card_network: source.card_network, + shipping_cost: source.shipping_cost, + order_tax_amount: source.order_tax_amount, + request_extended_authorization: source.request_extended_authorization, + extended_authorization_applied: source.extended_authorization_applied, + capture_before: source.capture_before, + card_discovery: source.card_discovery, + charges: source.charges, + processor_merchant_id: source.processor_merchant_id, + created_by: source.created_by, + payment_method_type_v2: source.payment_method_type_v2, + connector_payment_id: source.connector_payment_id, + payment_method_subtype: source.payment_method_subtype, + routing_result: source.routing_result, + authentication_applied: source.authentication_applied, + external_reference_id: source.external_reference_id, + tax_on_surcharge: source.tax_on_surcharge, + payment_method_billing_address: source.payment_method_billing_address, + redirection_data: redirection_data.or(source.redirection_data), + connector_payment_data: source.connector_payment_data, + connector_token_details: connector_token_details.or(source.connector_token_details), + id: source.id, + feature_metadata: feature_metadata.or(source.feature_metadata), + network_advice_code: network_advice_code.or(source.network_advice_code), + network_decline_code: network_decline_code.or(source.network_decline_code), + network_error_message: network_error_message.or(source.network_error_message), + connector_request_reference_id: connector_request_reference_id + .or(source.connector_request_reference_id), + } + } +} #[cfg(feature = "v1")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = payment_attempt)] diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index ea0a9cead20..bcaefa512db 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -632,6 +632,122 @@ pub struct PaymentIntentUpdateInternal { pub is_iframe_redirection_enabled: Option<bool>, } +#[cfg(feature = "v2")] +impl PaymentIntentUpdateInternal { + pub fn apply_changeset(self, source: PaymentIntent) -> PaymentIntent { + let Self { + status, + prerouting_algorithm, + amount_captured, + modified_at: _, // This will be ignored from self + active_attempt_id, + amount, + currency, + shipping_cost, + tax_details, + skip_external_tax_calculation, + surcharge_applicable, + surcharge_amount, + tax_on_surcharge, + routing_algorithm_id, + capture_method, + authentication_type, + billing_address, + shipping_address, + customer_present, + description, + return_url, + setup_future_usage, + apply_mit_exemption, + statement_descriptor, + order_details, + allowed_payment_method_types, + metadata, + connector_metadata, + feature_metadata, + payment_link_config, + request_incremental_authorization, + session_expiry, + frm_metadata, + request_external_three_ds_authentication, + updated_by, + force_3ds_challenge, + is_iframe_redirection_enabled, + } = self; + + PaymentIntent { + status: status.unwrap_or(source.status), + prerouting_algorithm: prerouting_algorithm.or(source.prerouting_algorithm), + amount_captured: amount_captured.or(source.amount_captured), + modified_at: common_utils::date_time::now(), + active_attempt_id: match active_attempt_id { + Some(v_option) => v_option, + None => source.active_attempt_id, + }, + amount: amount.unwrap_or(source.amount), + currency: currency.unwrap_or(source.currency), + shipping_cost: shipping_cost.or(source.shipping_cost), + tax_details: tax_details.or(source.tax_details), + skip_external_tax_calculation: skip_external_tax_calculation + .or(source.skip_external_tax_calculation), + surcharge_applicable: surcharge_applicable.or(source.surcharge_applicable), + surcharge_amount: surcharge_amount.or(source.surcharge_amount), + tax_on_surcharge: tax_on_surcharge.or(source.tax_on_surcharge), + routing_algorithm_id: routing_algorithm_id.or(source.routing_algorithm_id), + capture_method: capture_method.or(source.capture_method), + authentication_type: authentication_type.or(source.authentication_type), + billing_address: billing_address.or(source.billing_address), + shipping_address: shipping_address.or(source.shipping_address), + customer_present: customer_present.or(source.customer_present), + description: description.or(source.description), + return_url: return_url.or(source.return_url), + setup_future_usage: setup_future_usage.or(source.setup_future_usage), + apply_mit_exemption: apply_mit_exemption.or(source.apply_mit_exemption), + statement_descriptor: statement_descriptor.or(source.statement_descriptor), + order_details: order_details.or(source.order_details), + allowed_payment_method_types: allowed_payment_method_types + .or(source.allowed_payment_method_types), + metadata: metadata.or(source.metadata), + connector_metadata: connector_metadata.or(source.connector_metadata), + feature_metadata: feature_metadata.or(source.feature_metadata), + payment_link_config: payment_link_config.or(source.payment_link_config), + request_incremental_authorization: request_incremental_authorization + .or(source.request_incremental_authorization), + session_expiry: session_expiry.unwrap_or(source.session_expiry), + frm_metadata: frm_metadata.or(source.frm_metadata), + request_external_three_ds_authentication: request_external_three_ds_authentication + .or(source.request_external_three_ds_authentication), + updated_by, + force_3ds_challenge: force_3ds_challenge.or(source.force_3ds_challenge), + is_iframe_redirection_enabled: is_iframe_redirection_enabled + .or(source.is_iframe_redirection_enabled), + + // Fields from source + merchant_id: source.merchant_id, + customer_id: source.customer_id, + created_at: source.created_at, + last_synced: source.last_synced, + attempt_count: source.attempt_count, + profile_id: source.profile_id, + payment_link_id: source.payment_link_id, + authorization_count: source.authorization_count, + customer_details: source.customer_details, + organization_id: source.organization_id, + request_extended_authorization: source.request_extended_authorization, + psd2_sca_exemption_type: source.psd2_sca_exemption_type, + split_payments: source.split_payments, + platform_merchant_id: source.platform_merchant_id, + force_3ds_challenge_trigger: source.force_3ds_challenge_trigger, + processor_merchant_id: source.processor_merchant_id, + created_by: source.created_by, + merchant_reference_id: source.merchant_reference_id, + frm_merchant_decision: source.frm_merchant_decision, + enable_payment_link: source.enable_payment_link, + id: source.id, + } + } +} + #[cfg(feature = "v1")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = payment_intent)] diff --git a/crates/drainer/Cargo.toml b/crates/drainer/Cargo.toml index 1a02f9f3d95..800622cf36a 100644 --- a/crates/drainer/Cargo.toml +++ b/crates/drainer/Cargo.toml @@ -11,6 +11,7 @@ license.workspace = true release = ["vergen", "external_services/aws_kms"] vergen = ["router_env/vergen"] v1 = ["diesel_models/v1", "hyperswitch_interfaces/v1", "common_utils/v1"] +v2 = ["diesel_models/v2", "hyperswitch_interfaces/v2", "common_utils/v2"] [dependencies] actix-web = "4.11.0" diff --git a/crates/hyperswitch_interfaces/Cargo.toml b/crates/hyperswitch_interfaces/Cargo.toml index 04cb644a1d7..6b216d5c86f 100644 --- a/crates/hyperswitch_interfaces/Cargo.toml +++ b/crates/hyperswitch_interfaces/Cargo.toml @@ -10,7 +10,7 @@ license.workspace = true default = ["dummy_connector", "frm", "payouts"] dummy_connector = [] v1 = ["hyperswitch_domain_models/v1", "api_models/v1", "common_utils/v1"] -v2 = [] +v2 = ["api_models/v2", "common_utils/v2", "hyperswitch_domain_models/v2"] payouts = ["hyperswitch_domain_models/payouts"] frm = ["hyperswitch_domain_models/frm"] revenue_recovery = [] diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index ed51b12ff00..6bcb17ad1a5 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -116,7 +116,7 @@ pub fn mk_app( > { let mut server_app = get_application_builder(request_body_limit, state.conf.cors.clone()); - #[cfg(all(feature = "dummy_connector", feature = "v1"))] + #[cfg(feature = "dummy_connector")] { use routes::DummyConnector; server_app = server_app.service(DummyConnector::server(state.clone())); diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index d3ffb715b73..20de3c492e7 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -915,6 +915,7 @@ pub async fn connector_delete( /// Merchant Account - Toggle KV /// /// Toggle KV mode for the Merchant Account +#[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn merchant_account_toggle_kv( state: web::Data<AppState>, @@ -938,6 +939,29 @@ pub async fn merchant_account_toggle_kv( .await } +#[cfg(feature = "v2")] +#[instrument(skip_all)] +pub async fn merchant_account_toggle_kv( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<common_utils::id_type::MerchantId>, + json_payload: web::Json<admin::ToggleKVRequest>, +) -> HttpResponse { + let flow = Flow::ConfigKeyUpdate; + let mut payload = json_payload.into_inner(); + payload.merchant_id = path.into_inner(); + + api::server_wrap( + flow, + state, + &req, + payload, + |state, _, payload, _| kv_for_merchant(state, payload.merchant_id, payload.kv_enabled), + &auth::V2AdminApiAuth, + api_locking::LockAction::NotApplicable, + ) + .await +} /// Merchant Account - Transfer Keys /// /// Transfer Merchant Encryption key to keymanager @@ -965,6 +989,7 @@ pub async fn merchant_account_toggle_all_kv( /// Merchant Account - KV Status /// /// Toggle KV mode for the Merchant Account +#[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn merchant_account_kv_status( state: web::Data<AppState>, @@ -986,6 +1011,27 @@ pub async fn merchant_account_kv_status( .await } +#[cfg(feature = "v2")] +#[instrument(skip_all)] +pub async fn merchant_account_kv_status( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<common_utils::id_type::MerchantId>, +) -> HttpResponse { + let flow = Flow::ConfigKeyFetch; + let merchant_id = path.into_inner(); + + api::server_wrap( + flow, + state, + &req, + merchant_id, + |state, _, req, _| check_merchant_account_kv_status(state, req), + &auth::V2AdminApiAuth, + api_locking::LockAction::NotApplicable, + ) + .await +} /// Merchant Account - KV Status /// /// Toggle KV mode for the Merchant Account diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 8656d3f2890..cabcc8d1507 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -600,6 +600,22 @@ impl DummyConnector { } } +#[cfg(all(feature = "dummy_connector", feature = "v2"))] +impl DummyConnector { + pub fn server(state: AppState) -> Scope { + let mut routes_with_restricted_access = web::scope(""); + #[cfg(not(feature = "external_access_dc"))] + { + routes_with_restricted_access = + routes_with_restricted_access.guard(actix_web::guard::Host("localhost")); + } + routes_with_restricted_access = routes_with_restricted_access + .service(web::resource("/payment").route(web::post().to(dummy_connector_payment))); + web::scope("/dummy-connector") + .app_data(web::Data::new(state)) + .service(routes_with_restricted_access) + } +} pub struct Payments; #[cfg(all(any(feature = "olap", feature = "oltp"), feature = "v2"))] @@ -1556,6 +1572,11 @@ impl MerchantAccount { ) .service( web::resource("/profiles").route(web::get().to(profiles::profiles_list)), + ) + .service( + web::resource("/kv") + .route(web::post().to(admin::merchant_account_toggle_kv)) + .route(web::get().to(admin::merchant_account_kv_status)), ), ) } diff --git a/crates/router/src/routes/dummy_connector.rs b/crates/router/src/routes/dummy_connector.rs index 5d425c675a5..c0a7bc9f7fc 100644 --- a/crates/router/src/routes/dummy_connector.rs +++ b/crates/router/src/routes/dummy_connector.rs @@ -61,7 +61,7 @@ pub async fn dummy_connector_complete_payment( .await } -#[cfg(all(feature = "dummy_connector", feature = "v1"))] +#[cfg(feature = "dummy_connector")] #[instrument(skip_all, fields(flow = ?types::Flow::DummyPaymentCreate))] pub async fn dummy_connector_payment( state: web::Data<app::AppState>, @@ -82,7 +82,7 @@ pub async fn dummy_connector_payment( .await } -#[cfg(all(feature = "dummy_connector", feature = "v1"))] +#[cfg(feature = "dummy_connector")] #[instrument(skip_all, fields(flow = ?types::Flow::DummyPaymentRetrieve))] pub async fn dummy_connector_payment_data( state: web::Data<app::AppState>, diff --git a/crates/router/src/routes/dummy_connector/core.rs b/crates/router/src/routes/dummy_connector/core.rs index cafb6b58bca..0d7fb9627cc 100644 --- a/crates/router/src/routes/dummy_connector/core.rs +++ b/crates/router/src/routes/dummy_connector/core.rs @@ -9,7 +9,7 @@ use crate::{ utils::OptionExt, }; -#[cfg(all(feature = "dummy_connector", feature = "v1"))] +#[cfg(feature = "dummy_connector")] pub async fn payment( state: SessionState, req: types::DummyConnectorPaymentRequest, diff --git a/crates/storage_impl/src/customers.rs b/crates/storage_impl/src/customers.rs index bedbcadd6a8..53056a137c1 100644 --- a/crates/storage_impl/src/customers.rs +++ b/crates/storage_impl/src/customers.rs @@ -23,6 +23,32 @@ use crate::{ impl KvStorePartition for customers::Customer {} +#[cfg(feature = "v2")] +mod label { + use common_utils::id_type; + + pub(super) const MODEL_NAME: &str = "customer_v2"; + pub(super) const CLUSTER_LABEL: &str = "cust"; + + pub(super) fn get_global_id_label(global_customer_id: &id_type::GlobalCustomerId) -> String { + format!( + "customer_global_id_{}", + global_customer_id.get_string_repr() + ) + } + + pub(super) fn get_merchant_scoped_id_label( + merchant_id: &id_type::MerchantId, + merchant_reference_id: &id_type::CustomerId, + ) -> String { + format!( + "customer_mid_{}_mrefid_{}", + merchant_id.get_string_repr(), + merchant_reference_id.get_string_repr() + ) + } +} + #[async_trait::async_trait] impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterStore<T> { type Error = StorageError; @@ -283,22 +309,32 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterSt .construct_new() .await .change_context(StorageError::EncryptionError)?; - let storage_scheme = Box::pin(decide_storage_scheme::<_, customers::Customer>( + + let decided_storage_scheme = Box::pin(decide_storage_scheme::<_, customers::Customer>( self, storage_scheme, Op::Insert, )) .await; - new_customer.update_storage_scheme(storage_scheme); + new_customer.update_storage_scheme(decided_storage_scheme); + + let mut reverse_lookups = Vec::new(); + + if let Some(ref merchant_ref_id) = new_customer.merchant_reference_id { + let reverse_lookup_merchant_scoped_id = + label::get_merchant_scoped_id_label(&new_customer.merchant_id, merchant_ref_id); + reverse_lookups.push(reverse_lookup_merchant_scoped_id); + } + self.insert_resource( state, key_store, - storage_scheme, + decided_storage_scheme, new_customer.clone().insert(&conn), new_customer.clone().into(), kv_router_store::InsertResourceParams { insertable: kv::Insertable::Customer(new_customer.clone()), - reverse_lookups: vec![], + reverse_lookups, identifier, key, resource_type: "customer", diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs index 814314f4351..156ebee2dea 100644 --- a/crates/storage_impl/src/lib.rs +++ b/crates/storage_impl/src/lib.rs @@ -378,6 +378,16 @@ impl UniqueConstraints for diesel_models::PaymentAttempt { } } +#[cfg(feature = "v2")] +impl UniqueConstraints for diesel_models::PaymentAttempt { + fn unique_constraints(&self) -> Vec<String> { + vec![format!("pa_{}", self.id.get_string_repr())] + } + fn table_name(&self) -> &str { + "PaymentAttempt" + } +} + #[cfg(feature = "v1")] impl UniqueConstraints for diesel_models::Refund { fn unique_constraints(&self) -> Vec<String> { diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index 8eb8222afbf..78531b78ad6 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -6,16 +6,17 @@ use common_utils::{ fallback_reverse_lookup_not_found, types::{ConnectorTransactionId, ConnectorTransactionIdTrait, CreatedBy}, }; +#[cfg(feature = "v1")] +use diesel_models::payment_attempt::PaymentAttemptNew as DieselPaymentAttemptNew; use diesel_models::{ enums::{ MandateAmountData as DieselMandateAmountData, MandateDataType as DieselMandateType, MandateDetails as DieselMandateDetails, MerchantStorageScheme, }, + kv, payment_attempt::PaymentAttempt as DieselPaymentAttempt, reverse_lookup::{ReverseLookup, ReverseLookupNew}, }; -#[cfg(feature = "v1")] -use diesel_models::{kv, payment_attempt::PaymentAttemptNew as DieselPaymentAttemptNew}; use error_stack::ResultExt; #[cfg(feature = "v1")] use hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptNew; @@ -32,22 +33,21 @@ use hyperswitch_domain_models::{ use hyperswitch_domain_models::{ payments::payment_attempt::PaymentListFilters, payments::PaymentIntent, }; -#[cfg(feature = "v1")] +#[cfg(feature = "v2")] +use label::*; use redis_interface::HsetnxReply; use router_env::{instrument, tracing}; +#[cfg(feature = "v2")] +use crate::kv_router_store::{FilterResourceParams, FindResourceBy, UpdateResourceParams}; use crate::{ diesel_error_to_data_error, errors, + errors::RedisErrorExt, kv_router_store::KVRouterStore, lookup::ReverseLookupInterface, - utils::{pg_connection_read, pg_connection_write}, - DataModelExt, DatabaseStore, RouterStore, -}; -#[cfg(feature = "v1")] -use crate::{ - errors::RedisErrorExt, redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey}, - utils::try_redis_get_else_try_database_get, + utils::{pg_connection_read, pg_connection_write, try_redis_get_else_try_database_get}, + DataModelExt, DatabaseStore, RouterStore, }; #[async_trait::async_trait] @@ -747,15 +747,98 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { payment_attempt: PaymentAttempt, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError> { - // Ignoring storage scheme for v2 implementation - self.router_store - .insert_payment_attempt( - key_manager_state, - merchant_key_store, - payment_attempt, - storage_scheme, - ) - .await + let decided_storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>( + self, + storage_scheme, + Op::Insert, + )) + .await; + + match decided_storage_scheme { + MerchantStorageScheme::PostgresOnly => { + self.router_store + .insert_payment_attempt( + key_manager_state, + merchant_key_store, + payment_attempt, + decided_storage_scheme, + ) + .await + } + MerchantStorageScheme::RedisKv => { + let key = PartitionKey::GlobalPaymentId { + id: &payment_attempt.payment_id, + }; + let key_str = key.to_string(); + let field = format!( + "{}_{}", + label::CLUSTER_LABEL, + payment_attempt.id.get_string_repr() + ); + + let diesel_payment_attempt_new = payment_attempt + .clone() + .construct_new() + .await + .change_context(errors::StorageError::EncryptionError)?; + + let diesel_payment_attempt_for_redis: DieselPaymentAttempt = + Conversion::convert(payment_attempt.clone()) + .await + .change_context(errors::StorageError::EncryptionError)?; + + let redis_entry = kv::TypedSql { + op: kv::DBOperation::Insert { + insertable: Box::new(kv::Insertable::PaymentAttempt(Box::new( + diesel_payment_attempt_new.clone(), + ))), + }, + }; + + let reverse_lookup_attempt_id = ReverseLookupNew { + lookup_id: label::get_global_id_label(&payment_attempt.id), + pk_id: key_str.clone(), + sk_id: field.clone(), + source: "payment_attempt".to_string(), + updated_by: decided_storage_scheme.to_string(), + }; + self.insert_reverse_lookup(reverse_lookup_attempt_id, decided_storage_scheme) + .await?; + + if let Some(ref conn_txn_id_val) = payment_attempt.connector_payment_id { + let reverse_lookup_conn_txn_id = ReverseLookupNew { + lookup_id: label::get_profile_id_connector_transaction_label( + payment_attempt.profile_id.get_string_repr(), + conn_txn_id_val, + ), + pk_id: key_str.clone(), + sk_id: field.clone(), + source: "payment_attempt".to_string(), + updated_by: decided_storage_scheme.to_string(), + }; + self.insert_reverse_lookup(reverse_lookup_conn_txn_id, decided_storage_scheme) + .await?; + } + + match Box::pin(kv_wrapper::<DieselPaymentAttempt, _, _>( + self, + KvOperation::HSetNx(&field, &diesel_payment_attempt_for_redis, redis_entry), + key, + )) + .await + .map_err(|err| err.to_redis_failed_response(&key_str))? + .try_into_hsetnx() + { + Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue { + entity: "payment_attempt", + key: Some(payment_attempt.id.get_string_repr().to_owned()), + } + .into()), + Ok(HsetnxReply::KeySet) => Ok(payment_attempt), + Err(error) => Err(error.change_context(errors::StorageError::KVError)), + } + } + } } #[cfg(feature = "v1")] @@ -889,19 +972,48 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, this: PaymentAttempt, - payment_attempt: PaymentAttemptUpdate, + payment_attempt_update: PaymentAttemptUpdate, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError> { - // Ignoring storage scheme for v2 implementation - self.router_store - .update_payment_attempt( - key_manager_state, - merchant_key_store, - this, - payment_attempt, - storage_scheme, - ) + let payment_attempt = Conversion::convert(this.clone()) .await + .change_context(errors::StorageError::DecryptionError)?; + + let key = PartitionKey::GlobalPaymentId { + id: &this.payment_id, + }; + + let field = format!("{}_{}", label::CLUSTER_LABEL, this.id.get_string_repr()); + let conn = pg_connection_write(self).await?; + + let payment_attempt_internal = + diesel_models::PaymentAttemptUpdateInternal::from(payment_attempt_update); + let updated_payment_attempt = payment_attempt_internal + .clone() + .apply_changeset(payment_attempt.clone()); + + let updated_by = updated_payment_attempt.updated_by.to_owned(); + let updated_payment_attempt_with_id = payment_attempt + .clone() + .update_with_attempt_id(&conn, payment_attempt_internal.clone()); + + Box::pin(self.update_resource( + key_manager_state, + merchant_key_store, + storage_scheme, + updated_payment_attempt_with_id, + updated_payment_attempt, + UpdateResourceParams { + updateable: kv::Updateable::PaymentAttemptUpdate(Box::new( + kv::PaymentAttemptUpdateMems { + orig: payment_attempt, + update_data: payment_attempt_internal, + }, + )), + operation: Op::Update(key.clone(), &field, Some(updated_by.as_str())), + }, + )) + .await } #[cfg(feature = "v1")] @@ -1095,15 +1207,69 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { payment_id: &common_utils::id_type::GlobalPaymentId, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError> { - // Ignoring storage scheme for v2 implementation - self.router_store - .find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id( - key_manager_state, - merchant_key_store, - payment_id, - storage_scheme, - ) - .await + let database_call = || { + self.router_store + .find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id( + key_manager_state, + merchant_key_store, + payment_id, + storage_scheme, + ) + }; + + let decided_storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>( + self, + storage_scheme, + Op::Find, + )) + .await; + + match decided_storage_scheme { + MerchantStorageScheme::PostgresOnly => database_call().await, + MerchantStorageScheme::RedisKv => { + let key = PartitionKey::GlobalPaymentId { id: payment_id }; + + let redis_fut = async { + let kv_result = kv_wrapper::<DieselPaymentAttempt, _, _>( + self, + KvOperation::<DieselPaymentAttempt>::Scan("pa_*"), + key.clone(), + ) + .await? + .try_into_scan(); + + let payment_attempt = kv_result.and_then(|mut payment_attempts| { + payment_attempts.sort_by(|a, b| b.modified_at.cmp(&a.modified_at)); + payment_attempts + .iter() + .find(|&pa| { + pa.status == diesel_models::enums::AttemptStatus::Charged + || pa.status + == diesel_models::enums::AttemptStatus::PartialCharged + }) + .cloned() + .ok_or(error_stack::report!( + redis_interface::errors::RedisError::NotFound + )) + })?; + let merchant_id = payment_attempt.merchant_id.clone(); + PaymentAttempt::convert_back( + key_manager_state, + payment_attempt, + merchant_key_store.key.get_inner(), + merchant_id.into(), + ) + .await + .change_context(redis_interface::errors::RedisError::UnknownResult) + }; + + Box::pin(try_redis_get_else_try_database_get( + redis_fut, + database_call, + )) + .await + } + } } #[cfg(feature = "v2")] @@ -1115,16 +1281,22 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { connector_transaction_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentAttempt, errors::StorageError> { - // Ignoring storage scheme for v2 implementation - self.router_store - .find_payment_attempt_by_profile_id_connector_transaction_id( - key_manager_state, - merchant_key_store, + let conn = pg_connection_read(self).await?; + self.find_resource_by_id( + key_manager_state, + merchant_key_store, + storage_scheme, + DieselPaymentAttempt::find_by_profile_id_connector_transaction_id( + &conn, profile_id, connector_transaction_id, - storage_scheme, - ) - .await + ), + FindResourceBy::LookupId(label::get_profile_id_connector_transaction_label( + profile_id.get_string_repr(), + connector_transaction_id, + )), + ) + .await } #[instrument(skip_all)] @@ -1329,15 +1501,15 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { attempt_id: &common_utils::id_type::GlobalAttemptId, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError> { - // Ignoring storage scheme for v2 implementation - self.router_store - .find_payment_attempt_by_id( - key_manager_state, - merchant_key_store, - attempt_id, - storage_scheme, - ) - .await + let conn = pg_connection_read(self).await?; + self.find_resource_by_id( + key_manager_state, + merchant_key_store, + storage_scheme, + DieselPaymentAttempt::find_by_id(&conn, attempt_id), + FindResourceBy::LookupId(label::get_global_id_label(attempt_id)), + ) + .await } #[cfg(feature = "v2")] @@ -1349,14 +1521,20 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentAttempt>, errors::StorageError> { - self.router_store - .find_payment_attempts_by_payment_intent_id( - key_manager_state, - payment_id, - merchant_key_store, - storage_scheme, - ) - .await + let conn = pg_connection_read(self).await?; + self.filter_resources( + key_manager_state, + merchant_key_store, + storage_scheme, + DieselPaymentAttempt::find_by_payment_id(&conn, payment_id), + |_| true, + FilterResourceParams { + key: PartitionKey::GlobalPaymentId { id: payment_id }, + pattern: "pa_*", + limit: None, + }, + ) + .await } #[cfg(feature = "v1")] @@ -2036,3 +2214,25 @@ async fn add_preprocessing_id_to_reverse_lookup<T: DatabaseStore>( .insert_reverse_lookup(reverse_lookup_new, storage_scheme) .await } + +#[cfg(feature = "v2")] +mod label { + pub(super) const MODEL_NAME: &str = "payment_attempt_v2"; + pub(super) const CLUSTER_LABEL: &str = "pa"; + + pub(super) fn get_profile_id_connector_transaction_label( + profile_id: &str, + connector_transaction_id: &str, + ) -> String { + format!( + "profile_{}_conn_txn_{}", + profile_id, connector_transaction_id + ) + } + + pub(super) fn get_global_id_label( + attempt_id: &common_utils::id_type::GlobalAttemptId, + ) -> String { + format!("attempt_global_id_{}", attempt_id.get_string_repr()) + } +} diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs index 17156855e13..d054a4b1650 100644 --- a/crates/storage_impl/src/payments/payment_intent.rs +++ b/crates/storage_impl/src/payments/payment_intent.rs @@ -2,13 +2,22 @@ use api_models::payments::{AmountFilter, Order, SortBy, SortOn}; #[cfg(feature = "olap")] use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl}; -#[cfg(feature = "v1")] -use common_utils::ext_traits::Encode; -use common_utils::{ext_traits::AsyncExt, types::keymanager::KeyManagerState}; +#[cfg(feature = "v2")] +use common_utils::fallback_reverse_lookup_not_found; +use common_utils::{ + ext_traits::{AsyncExt, Encode}, + types::keymanager::KeyManagerState, +}; #[cfg(feature = "olap")] use diesel::{associations::HasTable, ExpressionMethods, JoinOnDsl, QueryDsl}; +#[cfg(feature = "v1")] +use diesel_models::payment_intent::PaymentIntentUpdate as DieselPaymentIntentUpdate; +#[cfg(feature = "v2")] +use diesel_models::payment_intent::PaymentIntentUpdateInternal; #[cfg(feature = "olap")] use diesel_models::query::generics::db_metrics; +#[cfg(feature = "v2")] +use diesel_models::reverse_lookup::ReverseLookupNew; #[cfg(all(feature = "v1", feature = "olap"))] use diesel_models::schema::{ payment_attempt::{self as payment_attempt_schema, dsl as pa_dsl}, @@ -20,10 +29,8 @@ use diesel_models::schema_v2::{ payment_intent::dsl as pi_dsl, }; use diesel_models::{ - enums::MerchantStorageScheme, payment_intent::PaymentIntent as DieselPaymentIntent, + enums::MerchantStorageScheme, kv, payment_intent::PaymentIntent as DieselPaymentIntent, }; -#[cfg(feature = "v1")] -use diesel_models::{kv, payment_intent::PaymentIntentUpdate as DieselPaymentIntentUpdate}; use error_stack::ResultExt; #[cfg(feature = "olap")] use hyperswitch_domain_models::payments::{ @@ -37,7 +44,6 @@ use hyperswitch_domain_models::{ PaymentIntent, }, }; -#[cfg(feature = "v1")] use redis_interface::HsetnxReply; #[cfg(feature = "olap")] use router_env::logger; @@ -47,17 +53,14 @@ use router_env::{instrument, tracing}; use crate::connection; use crate::{ diesel_error_to_data_error, - errors::StorageError, + errors::{RedisErrorExt, StorageError}, kv_router_store::KVRouterStore, - utils::{pg_connection_read, pg_connection_write}, - DatabaseStore, -}; -#[cfg(feature = "v1")] -use crate::{ - errors::RedisErrorExt, redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey}, - utils, + utils::{self, pg_connection_read, pg_connection_write}, + DatabaseStore, }; +#[cfg(feature = "v2")] +use crate::{errors, lookup::ReverseLookupInterface}; #[async_trait::async_trait] impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { @@ -163,7 +166,68 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { } MerchantStorageScheme::RedisKv => { - todo!("Implement payment intent insert for kv") + let id = payment_intent.id.clone(); + let key = PartitionKey::GlobalPaymentId { id: &id }; + let field = format!("pi_{}", id.get_string_repr()); + let key_str = key.to_string(); + + let new_payment_intent = payment_intent + .clone() + .construct_new() + .await + .change_context(StorageError::EncryptionError)?; + + let redis_entry = kv::TypedSql { + op: kv::DBOperation::Insert { + insertable: Box::new(kv::Insertable::PaymentIntent(Box::new( + new_payment_intent, + ))), + }, + }; + + let diesel_payment_intent = payment_intent + .clone() + .convert() + .await + .change_context(StorageError::EncryptionError)?; + + if let Some(merchant_reference_id) = &payment_intent.merchant_reference_id { + let reverse_lookup = ReverseLookupNew { + lookup_id: format!( + "pi_merchant_reference_{}_{}", + payment_intent.profile_id.get_string_repr(), + merchant_reference_id.get_string_repr() + ), + pk_id: key_str.clone(), + sk_id: field.clone(), + source: "payment_intent".to_string(), + updated_by: storage_scheme.to_string(), + }; + self.insert_reverse_lookup(reverse_lookup, storage_scheme) + .await?; + } + + match Box::pin(kv_wrapper::<DieselPaymentIntent, _, _>( + self, + KvOperation::<DieselPaymentIntent>::HSetNx( + &field, + &diesel_payment_intent, + redis_entry, + ), + key, + )) + .await + .map_err(|err| err.to_redis_failed_response(&key_str))? + .try_into_hsetnx() + { + Ok(HsetnxReply::KeyNotSet) => Err(StorageError::DuplicateValue { + entity: "payment_intent", + key: Some(key_str), + } + .into()), + Ok(HsetnxReply::KeySet) => Ok(payment_intent), + Err(error) => Err(error.change_context(StorageError::KVError)), + } } } } @@ -300,7 +364,59 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { .await } MerchantStorageScheme::RedisKv => { - todo!() + let id = this.id.clone(); + let merchant_id = this.merchant_id.clone(); + let key = PartitionKey::GlobalPaymentId { id: &id }; + let field = format!("pi_{}", id.get_string_repr()); + let key_str = key.to_string(); + + let diesel_intent_update = + PaymentIntentUpdateInternal::try_from(payment_intent_update) + .change_context(StorageError::DeserializationFailed)?; + let origin_diesel_intent = this + .convert() + .await + .change_context(StorageError::EncryptionError)?; + + let diesel_intent = diesel_intent_update + .clone() + .apply_changeset(origin_diesel_intent.clone()); + + let redis_value = diesel_intent + .encode_to_string_of_json() + .change_context(StorageError::SerializationFailed)?; + + let redis_entry = kv::TypedSql { + op: kv::DBOperation::Update { + updatable: Box::new(kv::Updateable::PaymentIntentUpdate(Box::new( + kv::PaymentIntentUpdateMems { + orig: origin_diesel_intent, + update_data: diesel_intent_update, + }, + ))), + }, + }; + + Box::pin(kv_wrapper::<(), _, _>( + self, + KvOperation::<DieselPaymentIntent>::Hset((&field, redis_value), redis_entry), + key, + )) + .await + .map_err(|err| err.to_redis_failed_response(&key_str))? + .try_into_hset() + .change_context(StorageError::KVError)?; + + let payment_intent = PaymentIntent::convert_back( + state, + diesel_intent, + merchant_key_store.key.get_inner(), + merchant_id.into(), + ) + .await + .change_context(StorageError::DecryptionError)?; + + Ok(payment_intent) } } } @@ -372,18 +488,50 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { state: &KeyManagerState, id: &common_utils::id_type::GlobalPaymentId, merchant_key_store: &MerchantKeyStore, - _storage_scheme: MerchantStorageScheme, + storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { - let conn: bb8::PooledConnection< - '_, - async_bb8_diesel::ConnectionManager<diesel::PgConnection>, - > = pg_connection_read(self).await?; - let diesel_payment_intent = DieselPaymentIntent::find_by_global_id(&conn, id) - .await - .map_err(|er| { - let new_err = diesel_error_to_data_error(*er.current_context()); - er.change_context(new_err) - })?; + let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentIntent>( + self, + storage_scheme, + Op::Find, + )) + .await; + + let database_call = || async { + let conn: bb8::PooledConnection< + '_, + async_bb8_diesel::ConnectionManager<diesel::PgConnection>, + > = pg_connection_read(self).await?; + + DieselPaymentIntent::find_by_global_id(&conn, id) + .await + .map_err(|er| { + let new_err = diesel_error_to_data_error(*er.current_context()); + er.change_context(new_err) + }) + }; + + let diesel_payment_intent = match storage_scheme { + MerchantStorageScheme::PostgresOnly => database_call().await, + MerchantStorageScheme::RedisKv => { + let key = PartitionKey::GlobalPaymentId { id }; + let field = format!("pi_{}", id.get_string_repr()); + + Box::pin(utils::try_redis_get_else_try_database_get( + async { + Box::pin(kv_wrapper::<DieselPaymentIntent, _, _>( + self, + KvOperation::<DieselPaymentIntent>::HGet(&field), + key, + )) + .await? + .try_into_hget() + }, + database_call, + )) + .await + } + }?; let merchant_id = diesel_payment_intent.merchant_id.clone(); @@ -391,7 +539,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { state, diesel_payment_intent, merchant_key_store.key.get_inner(), - merchant_id.to_owned().into(), + merchant_id.into(), ) .await .change_context(StorageError::DecryptionError) @@ -523,7 +671,68 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { .await } MerchantStorageScheme::RedisKv => { - todo!() + let lookup_id = format!( + "pi_merchant_reference_{}_{}", + profile_id.get_string_repr(), + merchant_reference_id.get_string_repr() + ); + + let lookup = fallback_reverse_lookup_not_found!( + self.get_lookup_by_lookup_id(&lookup_id, *storage_scheme) + .await, + self.router_store + .find_payment_intent_by_merchant_reference_id_profile_id( + state, + merchant_reference_id, + profile_id, + merchant_key_store, + storage_scheme, + ) + .await + ); + + let key = PartitionKey::CombinationKey { + combination: &lookup.pk_id, + }; + + let database_call = || async { + let conn = pg_connection_read(self).await?; + DieselPaymentIntent::find_by_merchant_reference_id_profile_id( + &conn, + merchant_reference_id, + profile_id, + ) + .await + .map_err(|er| { + let new_err = diesel_error_to_data_error(*er.current_context()); + er.change_context(new_err) + }) + }; + + let diesel_payment_intent = Box::pin(utils::try_redis_get_else_try_database_get( + async { + Box::pin(kv_wrapper::<DieselPaymentIntent, _, _>( + self, + KvOperation::<DieselPaymentIntent>::HGet(&lookup.sk_id), + key, + )) + .await? + .try_into_hget() + }, + database_call, + )) + .await?; + + let merchant_id = diesel_payment_intent.merchant_id.clone(); + + PaymentIntent::convert_back( + state, + diesel_payment_intent, + merchant_key_store.key.get_inner(), + merchant_id.into(), + ) + .await + .change_context(StorageError::DecryptionError) } } } @@ -607,9 +816,8 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, StorageError> { let conn = pg_connection_write(self).await?; - let diesel_payment_intent_update = - diesel_models::PaymentIntentUpdateInternal::try_from(payment_intent) - .change_context(StorageError::DeserializationFailed)?; + let diesel_payment_intent_update = PaymentIntentUpdateInternal::try_from(payment_intent) + .change_context(StorageError::DeserializationFailed)?; let diesel_payment_intent = this .convert() .await diff --git a/crates/storage_impl/src/redis/kv_store.rs b/crates/storage_impl/src/redis/kv_store.rs index f09506bc76b..fd583f500ed 100644 --- a/crates/storage_impl/src/redis/kv_store.rs +++ b/crates/storage_impl/src/redis/kv_store.rs @@ -55,6 +55,10 @@ pub enum PartitionKey<'a> { GlobalId { id: &'a str, }, + #[cfg(feature = "v2")] + GlobalPaymentId { + id: &'a common_utils::id_type::GlobalPaymentId, + }, } // PartitionKey::MerchantIdPaymentId {merchant_id, payment_id} impl std::fmt::Display for PartitionKey<'_> { @@ -108,7 +112,11 @@ impl std::fmt::Display for PartitionKey<'_> { )), #[cfg(feature = "v2")] - PartitionKey::GlobalId { id } => f.write_str(&format!("cust_{id}",)), + PartitionKey::GlobalId { id } => f.write_str(&format!("global_cust_{id}",)), + #[cfg(feature = "v2")] + PartitionKey::GlobalPaymentId { id } => { + f.write_str(&format!("global_payment_{}", id.get_string_repr())) + } } } }
2025-06-02T04:50:28Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description #8389 - Added Kv Redis support to - payment_intent V2, payment_attempt V2 models - Added enable Kv route for v2 merchant-account added enable kv api for v2 merchant account ` curl --location 'https://<host>/v2/merchant-accounts/:mid/kv' \ --header 'Authorization: admin-api-key=***' \ --header 'x-organization-id:***' \ --header 'Content-Type: application/json' \ --data '{"kv_enabled" : true}' ` ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Locally tested kv writes and drainer functionality ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
c5c0e677f2a2d43170a66330c98e0ebc4d771717
c5c0e677f2a2d43170a66330c98e0ebc4d771717
juspay/hyperswitch
juspay__hyperswitch-8379
Bug: [FEATURE] Add v2 kafka events for payment_intent, payment_attempt and refund
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 7b14351a49a..ca382fa1479 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -5560,25 +5560,24 @@ impl From<&PaymentsRequest> for PaymentsCreateIntentRequest { billing: request.billing.clone(), shipping: request.shipping.clone(), customer_id: request.customer_id.clone(), - customer_present: request.customer_present.clone(), + customer_present: request.customer_present, description: request.description.clone(), return_url: request.return_url.clone(), setup_future_usage: request.setup_future_usage, - apply_mit_exemption: request.apply_mit_exemption.clone(), + apply_mit_exemption: request.apply_mit_exemption, statement_descriptor: request.statement_descriptor.clone(), order_details: request.order_details.clone(), allowed_payment_method_types: request.allowed_payment_method_types.clone(), metadata: request.metadata.clone(), connector_metadata: request.connector_metadata.clone(), feature_metadata: request.feature_metadata.clone(), - payment_link_enabled: request.payment_link_enabled.clone(), + payment_link_enabled: request.payment_link_enabled, payment_link_config: request.payment_link_config.clone(), request_incremental_authorization: request.request_incremental_authorization, session_expiry: request.session_expiry, frm_metadata: request.frm_metadata.clone(), request_external_three_ds_authentication: request - .request_external_three_ds_authentication - .clone(), + .request_external_three_ds_authentication, force_3ds_challenge: request.force_3ds_challenge, merchant_connector_details: request.merchant_connector_details.clone(), } diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 568fa5959eb..641dc83291c 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1679,6 +1679,16 @@ pub enum FutureUsage { OnSession, } +impl FutureUsage { + /// Indicates whether the payment method should be saved for future use or not + pub fn is_off_session(self) -> bool { + match self { + Self::OffSession => true, + Self::OnSession => false, + } + } +} + #[derive( Clone, Copy, @@ -7975,7 +7985,9 @@ pub enum SuccessBasedRoutingConclusiveState { } /// Whether 3ds authentication is requested or not -#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] +#[derive( + Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, +)] pub enum External3dsAuthenticationRequest { /// Request for 3ds authentication Enable, @@ -7985,7 +7997,9 @@ pub enum External3dsAuthenticationRequest { } /// Whether payment link is requested to be enabled or not for this transaction -#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] +#[derive( + Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, +)] pub enum EnablePaymentLinkRequest { /// Request for enabling payment link Enable, @@ -7994,7 +8008,9 @@ pub enum EnablePaymentLinkRequest { Skip, } -#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] +#[derive( + Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, +)] pub enum MitExemptionRequest { /// Request for applying MIT exemption Apply, @@ -8004,7 +8020,9 @@ pub enum MitExemptionRequest { } /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. -#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] +#[derive( + Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema, +)] #[serde(rename_all = "snake_case")] pub enum PresenceOfCustomerDuringPayment { /// Customer is present during the payment. This is the default value diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index 8c892dcc08f..eb5c0a467c5 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -289,7 +289,7 @@ impl AmountDetails { } /// Get the action to whether calculate external tax or not as a boolean value - fn get_external_tax_action_as_bool(&self) -> bool { + pub fn get_external_tax_action_as_bool(&self) -> bool { self.skip_external_tax_calculation.as_bool() } diff --git a/crates/masking/src/secret.rs b/crates/masking/src/secret.rs index f2f519dd3ed..889c666f801 100644 --- a/crates/masking/src/secret.rs +++ b/crates/masking/src/secret.rs @@ -85,6 +85,14 @@ where { StrongSecret::new(self.inner_secret) } + + /// Convert to [`Secret`] with a reference to the inner secret + pub fn as_ref(&self) -> Secret<&SecretValue, MaskingStrategy> + where + MaskingStrategy: for<'a> Strategy<&'a SecretValue>, + { + Secret::new(self.peek()) + } } impl<SecretValue, MaskingStrategy> PeekInterface<SecretValue> diff --git a/crates/masking/src/serde.rs b/crates/masking/src/serde.rs index ecb92086a63..463c0ebc369 100644 --- a/crates/masking/src/serde.rs +++ b/crates/masking/src/serde.rs @@ -31,6 +31,8 @@ impl SerializableSecret for url::Url {} #[cfg(feature = "time")] impl SerializableSecret for time::Date {} +impl<T: SerializableSecret> SerializableSecret for &T {} + impl<'de, T, I> Deserialize<'de> for Secret<T, I> where T: Clone + de::DeserializeOwned + Sized, diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 7094c73be5a..4ded67d612e 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -361,7 +361,7 @@ pub async fn construct_payment_router_data_for_authorize<'a>( // TODO: Create unified address address: payment_data.payment_address.clone(), auth_type: payment_data.payment_attempt.authentication_type, - connector_meta_data: None, + connector_meta_data: merchant_connector_account.get_metadata(), connector_wallets_details: None, request, response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()), @@ -1791,11 +1791,11 @@ where .map(|shipping| shipping.into_inner()) .map(From::from), customer_id: payment_intent.customer_id.clone(), - customer_present: payment_intent.customer_present.clone(), + customer_present: payment_intent.customer_present, description: payment_intent.description.clone(), return_url: payment_intent.return_url.clone(), setup_future_usage: payment_intent.setup_future_usage, - apply_mit_exemption: payment_intent.apply_mit_exemption.clone(), + apply_mit_exemption: payment_intent.apply_mit_exemption, statement_descriptor: payment_intent.statement_descriptor.clone(), order_details: payment_intent.order_details.clone().map(|order_details| { order_details @@ -1810,7 +1810,7 @@ where .feature_metadata .clone() .map(|feature_metadata| feature_metadata.convert_back()), - payment_link_enabled: payment_intent.enable_payment_link.clone(), + payment_link_enabled: payment_intent.enable_payment_link, payment_link_config: payment_intent .payment_link_config .clone() @@ -1819,8 +1819,7 @@ where expires_on: payment_intent.session_expiry, frm_metadata: payment_intent.frm_metadata.clone(), request_external_three_ds_authentication: payment_intent - .request_external_three_ds_authentication - .clone(), + .request_external_three_ds_authentication, }, vec![], ))) diff --git a/crates/router/src/services/kafka/payment_attempt.rs b/crates/router/src/services/kafka/payment_attempt.rs index 6232bbcbf07..f2c18ae9302 100644 --- a/crates/router/src/services/kafka/payment_attempt.rs +++ b/crates/router/src/services/kafka/payment_attempt.rs @@ -1,11 +1,22 @@ -// use diesel_models::enums::MandateDetails; +#[cfg(feature = "v2")] +use common_types::payments; +#[cfg(feature = "v2")] +use common_utils::types; use common_utils::{id_type, types::MinorUnit}; use diesel_models::enums as storage_enums; +#[cfg(feature = "v2")] +use diesel_models::payment_attempt; +#[cfg(feature = "v2")] +use hyperswitch_domain_models::{ + address, payments::payment_attempt::PaymentAttemptFeatureMetadata, + router_response_types::RedirectForm, +}; use hyperswitch_domain_models::{ mandates::MandateDetails, payments::payment_attempt::PaymentAttempt, }; use time::OffsetDateTime; +#[cfg(feature = "v1")] #[derive(serde::Serialize, Debug)] pub struct KafkaPaymentAttempt<'a> { pub payment_id: &'a id_type::PaymentId, @@ -123,68 +134,242 @@ impl<'a> KafkaPaymentAttempt<'a> { } } +#[cfg(feature = "v2")] +#[derive(serde::Serialize, Debug)] +pub struct KafkaPaymentAttempt<'a> { + pub payment_id: &'a id_type::GlobalPaymentId, + pub merchant_id: &'a id_type::MerchantId, + pub attempt_id: &'a id_type::GlobalAttemptId, + pub status: storage_enums::AttemptStatus, + pub amount: MinorUnit, + pub connector: Option<&'a String>, + pub error_message: Option<&'a String>, + pub surcharge_amount: Option<MinorUnit>, + pub tax_amount: Option<MinorUnit>, + pub payment_method_id: Option<&'a id_type::GlobalPaymentMethodId>, + pub payment_method: storage_enums::PaymentMethod, + pub connector_transaction_id: Option<&'a String>, + pub authentication_type: storage_enums::AuthenticationType, + #[serde(with = "time::serde::timestamp")] + pub created_at: OffsetDateTime, + #[serde(with = "time::serde::timestamp")] + pub modified_at: OffsetDateTime, + #[serde(default, with = "time::serde::timestamp::option")] + pub last_synced: Option<OffsetDateTime>, + pub cancellation_reason: Option<&'a String>, + pub amount_to_capture: Option<MinorUnit>, + pub browser_info: Option<&'a types::BrowserInformation>, + pub error_code: Option<&'a String>, + pub connector_metadata: Option<String>, + // TODO: These types should implement copy ideally + pub payment_experience: Option<&'a storage_enums::PaymentExperience>, + pub payment_method_type: &'a storage_enums::PaymentMethodType, + pub payment_method_data: Option<String>, + pub error_reason: Option<&'a String>, + pub multiple_capture_count: Option<i16>, + pub amount_capturable: MinorUnit, + pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>, + pub net_amount: MinorUnit, + pub unified_code: Option<&'a String>, + pub unified_message: Option<&'a String>, + pub client_source: Option<&'a String>, + pub client_version: Option<&'a String>, + pub profile_id: &'a id_type::ProfileId, + pub organization_id: &'a id_type::OrganizationId, + pub card_network: Option<String>, + pub card_discovery: Option<String>, + + pub connector_payment_id: Option<types::ConnectorTransactionId>, + pub payment_token: Option<String>, + pub preprocessing_step_id: Option<String>, + pub connector_response_reference_id: Option<String>, + pub updated_by: &'a String, + pub encoded_data: Option<&'a masking::Secret<String>>, + pub external_three_ds_authentication_attempted: Option<bool>, + pub authentication_connector: Option<String>, + pub authentication_id: Option<String>, + pub fingerprint_id: Option<String>, + pub customer_acceptance: Option<&'a masking::Secret<serde_json::Value>>, + pub shipping_cost: Option<MinorUnit>, + pub order_tax_amount: Option<MinorUnit>, + pub charges: Option<payments::ConnectorChargeResponseData>, + pub processor_merchant_id: &'a id_type::MerchantId, + pub created_by: Option<&'a types::CreatedBy>, + pub payment_method_type_v2: storage_enums::PaymentMethod, + pub payment_method_subtype: storage_enums::PaymentMethodType, + pub routing_result: Option<serde_json::Value>, + pub authentication_applied: Option<common_enums::AuthenticationType>, + pub external_reference_id: Option<String>, + pub tax_on_surcharge: Option<MinorUnit>, + pub payment_method_billing_address: Option<masking::Secret<&'a address::Address>>, // adjusted from Encryption + pub redirection_data: Option<&'a RedirectForm>, + pub connector_payment_data: Option<String>, + pub connector_token_details: Option<&'a payment_attempt::ConnectorTokenDetails>, + pub feature_metadata: Option<&'a PaymentAttemptFeatureMetadata>, + pub network_advice_code: Option<String>, + pub network_decline_code: Option<String>, + pub network_error_message: Option<String>, + pub connector_request_reference_id: Option<String>, +} + #[cfg(feature = "v2")] impl<'a> KafkaPaymentAttempt<'a> { pub fn from_storage(attempt: &'a PaymentAttempt) -> Self { - todo!() - // Self { - // payment_id: &attempt.payment_id, - // merchant_id: &attempt.merchant_id, - // attempt_id: &attempt.attempt_id, - // status: attempt.status, - // amount: attempt.amount, - // currency: attempt.currency, - // save_to_locker: attempt.save_to_locker, - // connector: attempt.connector.as_ref(), - // error_message: attempt.error_message.as_ref(), - // offer_amount: attempt.offer_amount, - // surcharge_amount: attempt.surcharge_amount, - // tax_amount: attempt.tax_amount, - // payment_method_id: attempt.payment_method_id.as_ref(), - // payment_method: attempt.payment_method, - // connector_transaction_id: attempt.connector_transaction_id.as_ref(), - // capture_method: attempt.capture_method, - // capture_on: attempt.capture_on.map(|i| i.assume_utc()), - // confirm: attempt.confirm, - // authentication_type: attempt.authentication_type, - // created_at: attempt.created_at.assume_utc(), - // modified_at: attempt.modified_at.assume_utc(), - // last_synced: attempt.last_synced.map(|i| i.assume_utc()), - // cancellation_reason: attempt.cancellation_reason.as_ref(), - // amount_to_capture: attempt.amount_to_capture, - // mandate_id: attempt.mandate_id.as_ref(), - // browser_info: attempt.browser_info.as_ref().map(|v| v.to_string()), - // error_code: attempt.error_code.as_ref(), - // connector_metadata: attempt.connector_metadata.as_ref().map(|v| v.to_string()), - // payment_experience: attempt.payment_experience.as_ref(), - // payment_method_type: attempt.payment_method_type.as_ref(), - // payment_method_data: attempt.payment_method_data.as_ref().map(|v| v.to_string()), - // error_reason: attempt.error_reason.as_ref(), - // multiple_capture_count: attempt.multiple_capture_count, - // amount_capturable: attempt.amount_capturable, - // merchant_connector_id: attempt.merchant_connector_id.as_ref(), - // net_amount: attempt.net_amount, - // unified_code: attempt.unified_code.as_ref(), - // unified_message: attempt.unified_message.as_ref(), - // mandate_data: attempt.mandate_data.as_ref(), - // client_source: attempt.client_source.as_ref(), - // client_version: attempt.client_version.as_ref(), - // profile_id: &attempt.profile_id, - // organization_id: &attempt.organization_id, - // card_network: attempt - // .payment_method_data - // .as_ref() - // .and_then(|data| data.as_object()) - // .and_then(|pm| pm.get("card")) - // .and_then(|data| data.as_object()) - // .and_then(|card| card.get("card_network")) - // .and_then(|network| network.as_str()) - // .map(|network| network.to_string()), - // } + use masking::PeekInterface; + let PaymentAttempt { + payment_id, + merchant_id, + amount_details, + status, + connector, + error, + authentication_type, + created_at, + modified_at, + last_synced, + cancellation_reason, + browser_info, + payment_token, + connector_metadata, + payment_experience, + payment_method_data, + routing_result, + preprocessing_step_id, + multiple_capture_count, + connector_response_reference_id, + updated_by, + redirection_data, + encoded_data, + merchant_connector_id, + external_three_ds_authentication_attempted, + authentication_connector, + authentication_id, + fingerprint_id, + client_source, + client_version, + customer_acceptance, + profile_id, + organization_id, + payment_method_type, + payment_method_id, + connector_payment_id, + payment_method_subtype, + authentication_applied, + external_reference_id, + payment_method_billing_address, + id, + connector_token_details, + card_discovery, + charges, + feature_metadata, + processor_merchant_id, + created_by, + connector_request_reference_id, + } = attempt; + + let (connector_payment_id, connector_payment_data) = connector_payment_id + .clone() + .map(types::ConnectorTransactionId::form_id_and_data) + .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) + .unwrap_or((None, None)); + + Self { + payment_id, + merchant_id, + attempt_id: id, + status: *status, + amount: amount_details.get_net_amount(), + connector: connector.as_ref(), + error_message: error.as_ref().map(|error_details| &error_details.message), + surcharge_amount: amount_details.get_surcharge_amount(), + tax_amount: amount_details.get_tax_on_surcharge(), + payment_method_id: payment_method_id.as_ref(), + payment_method: *payment_method_type, + connector_transaction_id: connector_response_reference_id.as_ref(), + authentication_type: *authentication_type, + created_at: created_at.assume_utc(), + modified_at: modified_at.assume_utc(), + last_synced: last_synced.map(|i| i.assume_utc()), + cancellation_reason: cancellation_reason.as_ref(), + amount_to_capture: amount_details.get_amount_to_capture(), + browser_info: browser_info.as_ref(), + error_code: error.as_ref().map(|error_details| &error_details.code), + connector_metadata: connector_metadata.as_ref().map(|v| v.peek().to_string()), + payment_experience: payment_experience.as_ref(), + payment_method_type: payment_method_subtype, + payment_method_data: payment_method_data.as_ref().map(|v| v.peek().to_string()), + error_reason: error + .as_ref() + .and_then(|error_details| error_details.reason.as_ref()), + multiple_capture_count: *multiple_capture_count, + amount_capturable: amount_details.get_amount_capturable(), + merchant_connector_id: merchant_connector_id.as_ref(), + net_amount: amount_details.get_net_amount(), + unified_code: error + .as_ref() + .and_then(|error_details| error_details.unified_code.as_ref()), + unified_message: error + .as_ref() + .and_then(|error_details| error_details.unified_message.as_ref()), + client_source: client_source.as_ref(), + client_version: client_version.as_ref(), + profile_id, + organization_id, + card_network: payment_method_data + .as_ref() + .map(|data| data.peek()) + .and_then(|data| data.as_object()) + .and_then(|pm| pm.get("card")) + .and_then(|data| data.as_object()) + .and_then(|card| card.get("card_network")) + .and_then(|network| network.as_str()) + .map(|network| network.to_string()), + card_discovery: card_discovery.map(|discovery| discovery.to_string()), + payment_token: payment_token.clone(), + preprocessing_step_id: preprocessing_step_id.clone(), + connector_response_reference_id: connector_response_reference_id.clone(), + updated_by, + encoded_data: encoded_data.as_ref(), + external_three_ds_authentication_attempted: *external_three_ds_authentication_attempted, + authentication_connector: authentication_connector.clone(), + authentication_id: authentication_id.clone(), + fingerprint_id: fingerprint_id.clone(), + customer_acceptance: customer_acceptance.as_ref(), + shipping_cost: amount_details.get_shipping_cost(), + order_tax_amount: amount_details.get_order_tax_amount(), + charges: charges.clone(), + processor_merchant_id, + created_by: created_by.as_ref(), + payment_method_type_v2: *payment_method_type, + connector_payment_id: connector_payment_id.as_ref().cloned(), + payment_method_subtype: *payment_method_subtype, + routing_result: routing_result.clone(), + authentication_applied: *authentication_applied, + external_reference_id: external_reference_id.clone(), + tax_on_surcharge: amount_details.get_tax_on_surcharge(), + payment_method_billing_address: payment_method_billing_address + .as_ref() + .map(|v| masking::Secret::new(v.get_inner())), + redirection_data: redirection_data.as_ref(), + connector_payment_data, + connector_token_details: connector_token_details.as_ref(), + feature_metadata: feature_metadata.as_ref(), + network_advice_code: error + .as_ref() + .and_then(|details| details.network_advice_code.clone()), + network_decline_code: error + .as_ref() + .and_then(|details| details.network_decline_code.clone()), + network_error_message: error + .as_ref() + .and_then(|details| details.network_error_message.clone()), + connector_request_reference_id: connector_request_reference_id.clone(), + } } } impl super::KafkaMessage for KafkaPaymentAttempt<'_> { + #[cfg(feature = "v1")] fn key(&self) -> String { format!( "{}_{}_{}", @@ -193,6 +378,15 @@ impl super::KafkaMessage for KafkaPaymentAttempt<'_> { self.attempt_id ) } + #[cfg(feature = "v2")] + fn key(&self) -> String { + format!( + "{}_{}_{}", + self.merchant_id.get_string_repr(), + self.payment_id.get_string_repr(), + self.attempt_id.get_string_repr() + ) + } fn event_type(&self) -> crate::events::EventType { crate::events::EventType::PaymentAttempt diff --git a/crates/router/src/services/kafka/payment_attempt_event.rs b/crates/router/src/services/kafka/payment_attempt_event.rs index f3fcd701846..e06f4e014dd 100644 --- a/crates/router/src/services/kafka/payment_attempt_event.rs +++ b/crates/router/src/services/kafka/payment_attempt_event.rs @@ -1,11 +1,22 @@ -// use diesel_models::enums::MandateDetails; +#[cfg(feature = "v2")] +use common_types::payments; +#[cfg(feature = "v2")] +use common_utils::types; use common_utils::{id_type, types::MinorUnit}; use diesel_models::enums as storage_enums; +#[cfg(feature = "v2")] +use diesel_models::payment_attempt; +#[cfg(feature = "v2")] +use hyperswitch_domain_models::{ + address, payments::payment_attempt::PaymentAttemptFeatureMetadata, + router_response_types::RedirectForm, +}; use hyperswitch_domain_models::{ mandates::MandateDetails, payments::payment_attempt::PaymentAttempt, }; use time::OffsetDateTime; +#[cfg(feature = "v1")] #[serde_with::skip_serializing_none] #[derive(serde::Serialize, Debug)] pub struct KafkaPaymentAttemptEvent<'a> { @@ -124,68 +135,243 @@ impl<'a> KafkaPaymentAttemptEvent<'a> { } } +#[cfg(feature = "v2")] +#[serde_with::skip_serializing_none] +#[derive(serde::Serialize, Debug)] +pub struct KafkaPaymentAttemptEvent<'a> { + pub payment_id: &'a id_type::GlobalPaymentId, + pub merchant_id: &'a id_type::MerchantId, + pub attempt_id: &'a id_type::GlobalAttemptId, + pub status: storage_enums::AttemptStatus, + pub amount: MinorUnit, + pub connector: Option<&'a String>, + pub error_message: Option<&'a String>, + pub surcharge_amount: Option<MinorUnit>, + pub tax_amount: Option<MinorUnit>, + pub payment_method_id: Option<&'a id_type::GlobalPaymentMethodId>, + pub payment_method: storage_enums::PaymentMethod, + pub connector_transaction_id: Option<&'a String>, + pub authentication_type: storage_enums::AuthenticationType, + #[serde(with = "time::serde::timestamp")] + pub created_at: OffsetDateTime, + #[serde(with = "time::serde::timestamp")] + pub modified_at: OffsetDateTime, + #[serde(default, with = "time::serde::timestamp::option")] + pub last_synced: Option<OffsetDateTime>, + pub cancellation_reason: Option<&'a String>, + pub amount_to_capture: Option<MinorUnit>, + pub browser_info: Option<&'a types::BrowserInformation>, + pub error_code: Option<&'a String>, + pub connector_metadata: Option<String>, + // TODO: These types should implement copy ideally + pub payment_experience: Option<&'a storage_enums::PaymentExperience>, + pub payment_method_type: &'a storage_enums::PaymentMethodType, + pub payment_method_data: Option<String>, + pub error_reason: Option<&'a String>, + pub multiple_capture_count: Option<i16>, + pub amount_capturable: MinorUnit, + pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>, + pub net_amount: MinorUnit, + pub unified_code: Option<&'a String>, + pub unified_message: Option<&'a String>, + pub client_source: Option<&'a String>, + pub client_version: Option<&'a String>, + pub profile_id: &'a id_type::ProfileId, + pub organization_id: &'a id_type::OrganizationId, + pub card_network: Option<String>, + pub card_discovery: Option<String>, + + pub connector_payment_id: Option<types::ConnectorTransactionId>, + pub payment_token: Option<String>, + pub preprocessing_step_id: Option<String>, + pub connector_response_reference_id: Option<String>, + pub updated_by: &'a String, + pub encoded_data: Option<&'a masking::Secret<String>>, + pub external_three_ds_authentication_attempted: Option<bool>, + pub authentication_connector: Option<String>, + pub authentication_id: Option<String>, + pub fingerprint_id: Option<String>, + pub customer_acceptance: Option<&'a masking::Secret<serde_json::Value>>, + pub shipping_cost: Option<MinorUnit>, + pub order_tax_amount: Option<MinorUnit>, + pub charges: Option<payments::ConnectorChargeResponseData>, + pub processor_merchant_id: &'a id_type::MerchantId, + pub created_by: Option<&'a types::CreatedBy>, + pub payment_method_type_v2: storage_enums::PaymentMethod, + pub payment_method_subtype: storage_enums::PaymentMethodType, + pub routing_result: Option<serde_json::Value>, + pub authentication_applied: Option<common_enums::AuthenticationType>, + pub external_reference_id: Option<String>, + pub tax_on_surcharge: Option<MinorUnit>, + pub payment_method_billing_address: Option<masking::Secret<&'a address::Address>>, // adjusted from Encryption + pub redirection_data: Option<&'a RedirectForm>, + pub connector_payment_data: Option<String>, + pub connector_token_details: Option<&'a payment_attempt::ConnectorTokenDetails>, + pub feature_metadata: Option<&'a PaymentAttemptFeatureMetadata>, + pub network_advice_code: Option<String>, + pub network_decline_code: Option<String>, + pub network_error_message: Option<String>, + pub connector_request_reference_id: Option<String>, +} + #[cfg(feature = "v2")] impl<'a> KafkaPaymentAttemptEvent<'a> { pub fn from_storage(attempt: &'a PaymentAttempt) -> Self { - todo!() - // Self { - // payment_id: &attempt.payment_id, - // merchant_id: &attempt.merchant_id, - // attempt_id: &attempt.attempt_id, - // status: attempt.status, - // amount: attempt.amount, - // currency: attempt.currency, - // save_to_locker: attempt.save_to_locker, - // connector: attempt.connector.as_ref(), - // error_message: attempt.error_message.as_ref(), - // offer_amount: attempt.offer_amount, - // surcharge_amount: attempt.surcharge_amount, - // tax_amount: attempt.tax_amount, - // payment_method_id: attempt.payment_method_id.as_ref(), - // payment_method: attempt.payment_method, - // connector_transaction_id: attempt.connector_transaction_id.as_ref(), - // capture_method: attempt.capture_method, - // capture_on: attempt.capture_on.map(|i| i.assume_utc()), - // confirm: attempt.confirm, - // authentication_type: attempt.authentication_type, - // created_at: attempt.created_at.assume_utc(), - // modified_at: attempt.modified_at.assume_utc(), - // last_synced: attempt.last_synced.map(|i| i.assume_utc()), - // cancellation_reason: attempt.cancellation_reason.as_ref(), - // amount_to_capture: attempt.amount_to_capture, - // mandate_id: attempt.mandate_id.as_ref(), - // browser_info: attempt.browser_info.as_ref().map(|v| v.to_string()), - // error_code: attempt.error_code.as_ref(), - // connector_metadata: attempt.connector_metadata.as_ref().map(|v| v.to_string()), - // payment_experience: attempt.payment_experience.as_ref(), - // payment_method_type: attempt.payment_method_type.as_ref(), - // payment_method_data: attempt.payment_method_data.as_ref().map(|v| v.to_string()), - // error_reason: attempt.error_reason.as_ref(), - // multiple_capture_count: attempt.multiple_capture_count, - // amount_capturable: attempt.amount_capturable, - // merchant_connector_id: attempt.merchant_connector_id.as_ref(), - // net_amount: attempt.net_amount, - // unified_code: attempt.unified_code.as_ref(), - // unified_message: attempt.unified_message.as_ref(), - // mandate_data: attempt.mandate_data.as_ref(), - // client_source: attempt.client_source.as_ref(), - // client_version: attempt.client_version.as_ref(), - // profile_id: &attempt.profile_id, - // organization_id: &attempt.organization_id, - // card_network: attempt - // .payment_method_data - // .as_ref() - // .and_then(|data| data.as_object()) - // .and_then(|pm| pm.get("card")) - // .and_then(|data| data.as_object()) - // .and_then(|card| card.get("card_network")) - // .and_then(|network| network.as_str()) - // .map(|network| network.to_string()), - // } + use masking::PeekInterface; + let PaymentAttempt { + payment_id, + merchant_id, + amount_details, + status, + connector, + error, + authentication_type, + created_at, + modified_at, + last_synced, + cancellation_reason, + browser_info, + payment_token, + connector_metadata, + payment_experience, + payment_method_data, + routing_result, + preprocessing_step_id, + multiple_capture_count, + connector_response_reference_id, + updated_by, + redirection_data, + encoded_data, + merchant_connector_id, + external_three_ds_authentication_attempted, + authentication_connector, + authentication_id, + fingerprint_id, + client_source, + client_version, + customer_acceptance, + profile_id, + organization_id, + payment_method_type, + payment_method_id, + connector_payment_id, + payment_method_subtype, + authentication_applied, + external_reference_id, + payment_method_billing_address, + id, + connector_token_details, + card_discovery, + charges, + feature_metadata, + processor_merchant_id, + created_by, + connector_request_reference_id, + } = attempt; + + let (connector_payment_id, connector_payment_data) = connector_payment_id + .clone() + .map(types::ConnectorTransactionId::form_id_and_data) + .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) + .unwrap_or((None, None)); + + Self { + payment_id, + merchant_id, + attempt_id: id, + status: *status, + amount: amount_details.get_net_amount(), + connector: connector.as_ref(), + error_message: error.as_ref().map(|error_details| &error_details.message), + surcharge_amount: amount_details.get_surcharge_amount(), + tax_amount: amount_details.get_tax_on_surcharge(), + payment_method_id: payment_method_id.as_ref(), + payment_method: *payment_method_type, + connector_transaction_id: connector_response_reference_id.as_ref(), + authentication_type: *authentication_type, + created_at: created_at.assume_utc(), + modified_at: modified_at.assume_utc(), + last_synced: last_synced.map(|i| i.assume_utc()), + cancellation_reason: cancellation_reason.as_ref(), + amount_to_capture: amount_details.get_amount_to_capture(), + browser_info: browser_info.as_ref(), + error_code: error.as_ref().map(|error_details| &error_details.code), + connector_metadata: connector_metadata.as_ref().map(|v| v.peek().to_string()), + payment_experience: payment_experience.as_ref(), + payment_method_type: payment_method_subtype, + payment_method_data: payment_method_data.as_ref().map(|v| v.peek().to_string()), + error_reason: error + .as_ref() + .and_then(|error_details| error_details.reason.as_ref()), + multiple_capture_count: *multiple_capture_count, + amount_capturable: amount_details.get_amount_capturable(), + merchant_connector_id: merchant_connector_id.as_ref(), + net_amount: amount_details.get_net_amount(), + unified_code: error + .as_ref() + .and_then(|error_details| error_details.unified_code.as_ref()), + unified_message: error + .as_ref() + .and_then(|error_details| error_details.unified_message.as_ref()), + client_source: client_source.as_ref(), + client_version: client_version.as_ref(), + profile_id, + organization_id, + card_network: payment_method_data + .as_ref() + .map(|data| data.peek()) + .and_then(|data| data.as_object()) + .and_then(|pm| pm.get("card")) + .and_then(|data| data.as_object()) + .and_then(|card| card.get("card_network")) + .and_then(|network| network.as_str()) + .map(|network| network.to_string()), + card_discovery: card_discovery.map(|discovery| discovery.to_string()), + payment_token: payment_token.clone(), + preprocessing_step_id: preprocessing_step_id.clone(), + connector_response_reference_id: connector_response_reference_id.clone(), + updated_by, + encoded_data: encoded_data.as_ref(), + external_three_ds_authentication_attempted: *external_three_ds_authentication_attempted, + authentication_connector: authentication_connector.clone(), + authentication_id: authentication_id.clone(), + fingerprint_id: fingerprint_id.clone(), + customer_acceptance: customer_acceptance.as_ref(), + shipping_cost: amount_details.get_shipping_cost(), + order_tax_amount: amount_details.get_order_tax_amount(), + charges: charges.clone(), + processor_merchant_id, + created_by: created_by.as_ref(), + payment_method_type_v2: *payment_method_type, + connector_payment_id: connector_payment_id.as_ref().cloned(), + payment_method_subtype: *payment_method_subtype, + routing_result: routing_result.clone(), + authentication_applied: *authentication_applied, + external_reference_id: external_reference_id.clone(), + tax_on_surcharge: amount_details.get_tax_on_surcharge(), + payment_method_billing_address: payment_method_billing_address + .as_ref() + .map(|v| masking::Secret::new(v.get_inner())), + redirection_data: redirection_data.as_ref(), + connector_payment_data, + connector_token_details: connector_token_details.as_ref(), + feature_metadata: feature_metadata.as_ref(), + network_advice_code: error + .as_ref() + .and_then(|details| details.network_advice_code.clone()), + network_decline_code: error + .as_ref() + .and_then(|details| details.network_decline_code.clone()), + network_error_message: error + .as_ref() + .and_then(|details| details.network_error_message.clone()), + connector_request_reference_id: connector_request_reference_id.clone(), + } } } impl super::KafkaMessage for KafkaPaymentAttemptEvent<'_> { + #[cfg(feature = "v1")] fn key(&self) -> String { format!( "{}_{}_{}", @@ -194,6 +380,15 @@ impl super::KafkaMessage for KafkaPaymentAttemptEvent<'_> { self.attempt_id ) } + #[cfg(feature = "v2")] + fn key(&self) -> String { + format!( + "{}_{}_{}", + self.merchant_id.get_string_repr(), + self.payment_id.get_string_repr(), + self.attempt_id.get_string_repr() + ) + } fn event_type(&self) -> crate::events::EventType { crate::events::EventType::PaymentAttempt diff --git a/crates/router/src/services/kafka/payment_intent.rs b/crates/router/src/services/kafka/payment_intent.rs index b438a07b9ca..f0b4438bd2e 100644 --- a/crates/router/src/services/kafka/payment_intent.rs +++ b/crates/router/src/services/kafka/payment_intent.rs @@ -1,6 +1,20 @@ -use common_utils::{crypto::Encryptable, hashing::HashedString, id_type, pii, types::MinorUnit}; +#[cfg(feature = "v2")] +use ::common_types::{payments, primitive_wrappers::RequestExtendedAuthorizationBool}; +#[cfg(feature = "v2")] +use common_enums; +#[cfg(feature = "v2")] +use common_enums::RequestIncrementalAuthorization; +use common_utils::{ + crypto::Encryptable, hashing::HashedString, id_type, pii, types as common_types, +}; use diesel_models::enums as storage_enums; +#[cfg(feature = "v2")] +use diesel_models::{types as diesel_types, PaymentLinkConfigRequestForPayments}; +#[cfg(feature = "v2")] +use diesel_models::{types::OrderDetailsWithAmount, TaxDetails}; use hyperswitch_domain_models::payments::PaymentIntent; +#[cfg(feature = "v2")] +use hyperswitch_domain_models::{address, routing}; use masking::{PeekInterface, Secret}; use serde_json::Value; use time::OffsetDateTime; @@ -11,9 +25,9 @@ pub struct KafkaPaymentIntent<'a> { pub payment_id: &'a id_type::PaymentId, pub merchant_id: &'a id_type::MerchantId, pub status: storage_enums::IntentStatus, - pub amount: MinorUnit, + pub amount: common_types::MinorUnit, pub currency: Option<storage_enums::Currency>, - pub amount_captured: Option<MinorUnit>, + pub amount_captured: Option<common_types::MinorUnit>, pub customer_id: Option<&'a id_type::CustomerId>, pub description: Option<&'a String>, pub return_url: Option<&'a String>, @@ -46,41 +60,6 @@ pub struct KafkaPaymentIntent<'a> { infra_values: Option<Value>, } -#[cfg(feature = "v2")] -#[derive(serde::Serialize, Debug)] -pub struct KafkaPaymentIntent<'a> { - pub id: &'a id_type::PaymentId, - pub merchant_id: &'a id_type::MerchantId, - pub status: storage_enums::IntentStatus, - pub amount: MinorUnit, - pub currency: storage_enums::Currency, - pub amount_captured: Option<MinorUnit>, - pub customer_id: Option<&'a id_type::CustomerId>, - pub description: Option<&'a String>, - pub return_url: Option<&'a String>, - pub metadata: Option<String>, - pub statement_descriptor: Option<&'a String>, - #[serde(with = "time::serde::timestamp")] - pub created_at: OffsetDateTime, - #[serde(with = "time::serde::timestamp")] - pub modified_at: OffsetDateTime, - #[serde(default, with = "time::serde::timestamp::option")] - pub last_synced: Option<OffsetDateTime>, - pub setup_future_usage: Option<storage_enums::FutureUsage>, - pub off_session: Option<bool>, - pub client_secret: Option<&'a String>, - pub active_attempt_id: String, - pub attempt_count: i16, - pub profile_id: &'a id_type::ProfileId, - pub payment_confirm_source: Option<storage_enums::PaymentSource>, - pub billing_details: Option<Encryptable<Secret<Value>>>, - pub shipping_details: Option<Encryptable<Secret<Value>>>, - pub customer_email: Option<HashedString<pii::EmailStrategy>>, - pub feature_metadata: Option<&'a Value>, - pub merchant_order_reference_id: Option<&'a String>, - pub organization_id: &'a id_type::OrganizationId, -} - #[cfg(feature = "v1")] impl<'a> KafkaPaymentIntent<'a> { pub fn from_storage(intent: &'a PaymentIntent, infra_values: Option<Value>) -> Self { @@ -128,46 +107,204 @@ impl<'a> KafkaPaymentIntent<'a> { } } +#[cfg(feature = "v2")] +#[derive(serde::Serialize, Debug)] +pub struct KafkaPaymentIntent<'a> { + pub payment_id: &'a id_type::GlobalPaymentId, + pub merchant_id: &'a id_type::MerchantId, + pub status: storage_enums::IntentStatus, + pub amount: common_types::MinorUnit, + pub currency: storage_enums::Currency, + pub amount_captured: Option<common_types::MinorUnit>, + pub customer_id: Option<&'a id_type::GlobalCustomerId>, + pub description: Option<&'a common_types::Description>, + pub return_url: Option<&'a common_types::Url>, + pub metadata: Option<&'a Secret<Value>>, + pub statement_descriptor: Option<&'a common_types::StatementDescriptor>, + #[serde(with = "time::serde::timestamp")] + pub created_at: OffsetDateTime, + #[serde(with = "time::serde::timestamp")] + pub modified_at: OffsetDateTime, + #[serde(default, with = "time::serde::timestamp::option")] + pub last_synced: Option<OffsetDateTime>, + pub setup_future_usage: storage_enums::FutureUsage, + pub off_session: bool, + pub active_attempt_id: Option<&'a id_type::GlobalAttemptId>, + pub attempt_count: i16, + pub profile_id: &'a id_type::ProfileId, + pub customer_email: Option<HashedString<pii::EmailStrategy>>, + pub feature_metadata: Option<&'a diesel_types::FeatureMetadata>, + pub organization_id: &'a id_type::OrganizationId, + pub order_details: Option<&'a Vec<Secret<OrderDetailsWithAmount>>>, + + pub allowed_payment_method_types: Option<&'a Vec<common_enums::PaymentMethodType>>, + pub connector_metadata: Option<&'a Secret<Value>>, + pub payment_link_id: Option<&'a String>, + pub updated_by: &'a String, + pub surcharge_applicable: Option<bool>, + pub request_incremental_authorization: RequestIncrementalAuthorization, + pub authorization_count: Option<i32>, + #[serde(with = "time::serde::timestamp")] + pub session_expiry: OffsetDateTime, + pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest, + pub frm_metadata: Option<Secret<&'a Value>>, + pub customer_details: Option<Secret<&'a Value>>, + pub shipping_cost: Option<common_types::MinorUnit>, + pub tax_details: Option<TaxDetails>, + pub skip_external_tax_calculation: bool, + pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, + pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>, + pub split_payments: Option<&'a payments::SplitPaymentsRequest>, + pub platform_merchant_id: Option<&'a id_type::MerchantId>, + pub force_3ds_challenge: Option<bool>, + pub force_3ds_challenge_trigger: Option<bool>, + pub processor_merchant_id: &'a id_type::MerchantId, + pub created_by: Option<&'a common_types::CreatedBy>, + pub is_iframe_redirection_enabled: Option<bool>, + pub merchant_reference_id: Option<&'a id_type::PaymentReferenceId>, + pub capture_method: storage_enums::CaptureMethod, + pub authentication_type: Option<common_enums::AuthenticationType>, + pub prerouting_algorithm: Option<&'a routing::PaymentRoutingInfo>, + pub surcharge_amount: Option<common_types::MinorUnit>, + pub billing_address: Option<Secret<&'a address::Address>>, + pub shipping_address: Option<Secret<&'a address::Address>>, + pub tax_on_surcharge: Option<common_types::MinorUnit>, + pub frm_merchant_decision: Option<common_enums::MerchantDecision>, + pub enable_payment_link: common_enums::EnablePaymentLinkRequest, + pub apply_mit_exemption: common_enums::MitExemptionRequest, + pub customer_present: common_enums::PresenceOfCustomerDuringPayment, + pub routing_algorithm_id: Option<&'a id_type::RoutingId>, + pub payment_link_config: Option<&'a PaymentLinkConfigRequestForPayments>, + + #[serde(flatten)] + infra_values: Option<Value>, +} + #[cfg(feature = "v2")] impl<'a> KafkaPaymentIntent<'a> { pub fn from_storage(intent: &'a PaymentIntent, infra_values: Option<Value>) -> Self { - // Self { - // id: &intent.id, - // merchant_id: &intent.merchant_id, - // status: intent.status, - // amount: intent.amount, - // currency: intent.currency, - // amount_captured: intent.amount_captured, - // customer_id: intent.customer_id.as_ref(), - // description: intent.description.as_ref(), - // return_url: intent.return_url.as_ref(), - // metadata: intent.metadata.as_ref().map(|x| x.to_string()), - // statement_descriptor: intent.statement_descriptor.as_ref(), - // created_at: intent.created_at.assume_utc(), - // modified_at: intent.modified_at.assume_utc(), - // last_synced: intent.last_synced.map(|i| i.assume_utc()), - // setup_future_usage: intent.setup_future_usage, - // off_session: intent.off_session, - // client_secret: intent.client_secret.as_ref(), - // active_attempt_id: intent.active_attempt.get_id(), - // attempt_count: intent.attempt_count, - // profile_id: &intent.profile_id, - // payment_confirm_source: intent.payment_confirm_source, - // // TODO: use typed information here to avoid PII logging - // billing_details: None, - // shipping_details: None, - // customer_email: intent - // .customer_details - // .as_ref() - // .and_then(|value| value.get_inner().peek().as_object()) - // .and_then(|obj| obj.get("email")) - // .and_then(|email| email.as_str()) - // .map(|email| HashedString::from(Secret::new(email.to_string()))), - // feature_metadata: intent.feature_metadata.as_ref(), - // merchant_order_reference_id: intent.merchant_order_reference_id.as_ref(), - // organization_id: &intent.organization_id, - // } - todo!() + let PaymentIntent { + id, + merchant_id, + status, + amount_details, + amount_captured, + customer_id, + description, + return_url, + metadata, + statement_descriptor, + created_at, + modified_at, + last_synced, + setup_future_usage, + active_attempt_id, + order_details, + allowed_payment_method_types, + connector_metadata, + feature_metadata, + attempt_count, + profile_id, + payment_link_id, + frm_merchant_decision, + updated_by, + request_incremental_authorization, + authorization_count, + session_expiry, + request_external_three_ds_authentication, + frm_metadata, + customer_details, + merchant_reference_id, + billing_address, + shipping_address, + capture_method, + authentication_type, + prerouting_algorithm, + organization_id, + enable_payment_link, + apply_mit_exemption, + customer_present, + payment_link_config, + routing_algorithm_id, + split_payments, + force_3ds_challenge, + force_3ds_challenge_trigger, + processor_merchant_id, + created_by, + is_iframe_redirection_enabled, + } = intent; + + Self { + payment_id: id, + merchant_id, + status: *status, + amount: amount_details.order_amount, + currency: amount_details.currency, + amount_captured: *amount_captured, + customer_id: customer_id.as_ref(), + description: description.as_ref(), + return_url: return_url.as_ref(), + metadata: metadata.as_ref(), + statement_descriptor: statement_descriptor.as_ref(), + created_at: created_at.assume_utc(), + modified_at: modified_at.assume_utc(), + last_synced: last_synced.map(|t| t.assume_utc()), + setup_future_usage: *setup_future_usage, + off_session: setup_future_usage.is_off_session(), + active_attempt_id: active_attempt_id.as_ref(), + attempt_count: *attempt_count, + profile_id, + customer_email: None, + feature_metadata: feature_metadata.as_ref(), + organization_id, + order_details: order_details.as_ref(), + allowed_payment_method_types: allowed_payment_method_types.as_ref(), + connector_metadata: connector_metadata.as_ref(), + payment_link_id: payment_link_id.as_ref(), + updated_by, + surcharge_applicable: None, + request_incremental_authorization: *request_incremental_authorization, + authorization_count: *authorization_count, + session_expiry: session_expiry.assume_utc(), + request_external_three_ds_authentication: *request_external_three_ds_authentication, + frm_metadata: frm_metadata + .as_ref() + .map(|frm_metadata| frm_metadata.as_ref()), + customer_details: customer_details + .as_ref() + .map(|customer_details| customer_details.get_inner().as_ref()), + shipping_cost: amount_details.shipping_cost, + tax_details: amount_details.tax_details.clone(), + skip_external_tax_calculation: amount_details.get_external_tax_action_as_bool(), + request_extended_authorization: None, + psd2_sca_exemption_type: None, + split_payments: split_payments.as_ref(), + platform_merchant_id: None, + force_3ds_challenge: *force_3ds_challenge, + force_3ds_challenge_trigger: *force_3ds_challenge_trigger, + processor_merchant_id, + created_by: created_by.as_ref(), + is_iframe_redirection_enabled: *is_iframe_redirection_enabled, + merchant_reference_id: merchant_reference_id.as_ref(), + billing_address: billing_address + .as_ref() + .map(|billing_address| Secret::new(billing_address.get_inner())), + shipping_address: shipping_address + .as_ref() + .map(|shipping_address| Secret::new(shipping_address.get_inner())), + capture_method: *capture_method, + authentication_type: *authentication_type, + prerouting_algorithm: prerouting_algorithm.as_ref(), + surcharge_amount: amount_details.surcharge_amount, + tax_on_surcharge: amount_details.tax_on_surcharge, + frm_merchant_decision: *frm_merchant_decision, + enable_payment_link: *enable_payment_link, + apply_mit_exemption: *apply_mit_exemption, + customer_present: *customer_present, + routing_algorithm_id: routing_algorithm_id.as_ref(), + payment_link_config: payment_link_config.as_ref(), + infra_values, + } } } @@ -178,8 +315,8 @@ impl KafkaPaymentIntent<'_> { } #[cfg(feature = "v2")] - fn get_id(&self) -> &id_type::PaymentId { - self.id + fn get_id(&self) -> &id_type::GlobalPaymentId { + self.payment_id } } diff --git a/crates/router/src/services/kafka/payment_intent_event.rs b/crates/router/src/services/kafka/payment_intent_event.rs index b7715a591ef..f7d1bca5b32 100644 --- a/crates/router/src/services/kafka/payment_intent_event.rs +++ b/crates/router/src/services/kafka/payment_intent_event.rs @@ -1,6 +1,18 @@ -use common_utils::{crypto::Encryptable, hashing::HashedString, id_type, pii, types::MinorUnit}; +#[cfg(feature = "v2")] +use ::common_types::{payments, primitive_wrappers::RequestExtendedAuthorizationBool}; +#[cfg(feature = "v2")] +use common_enums::{self, RequestIncrementalAuthorization}; +use common_utils::{ + crypto::Encryptable, hashing::HashedString, id_type, pii, types as common_types, +}; use diesel_models::enums as storage_enums; +#[cfg(feature = "v2")] +use diesel_models::{types as diesel_types, PaymentLinkConfigRequestForPayments}; +#[cfg(feature = "v2")] +use diesel_models::{types::OrderDetailsWithAmount, TaxDetails}; use hyperswitch_domain_models::payments::PaymentIntent; +#[cfg(feature = "v2")] +use hyperswitch_domain_models::{address, routing}; use masking::{PeekInterface, Secret}; use serde_json::Value; use time::OffsetDateTime; @@ -12,9 +24,9 @@ pub struct KafkaPaymentIntentEvent<'a> { pub payment_id: &'a id_type::PaymentId, pub merchant_id: &'a id_type::MerchantId, pub status: storage_enums::IntentStatus, - pub amount: MinorUnit, + pub amount: common_types::MinorUnit, pub currency: Option<storage_enums::Currency>, - pub amount_captured: Option<MinorUnit>, + pub amount_captured: Option<common_types::MinorUnit>, pub customer_id: Option<&'a id_type::CustomerId>, pub description: Option<&'a String>, pub return_url: Option<&'a String>, @@ -51,36 +63,74 @@ pub struct KafkaPaymentIntentEvent<'a> { #[serde_with::skip_serializing_none] #[derive(serde::Serialize, Debug)] pub struct KafkaPaymentIntentEvent<'a> { - pub id: &'a id_type::PaymentId, + pub payment_id: &'a id_type::GlobalPaymentId, pub merchant_id: &'a id_type::MerchantId, pub status: storage_enums::IntentStatus, - pub amount: MinorUnit, + pub amount: common_types::MinorUnit, pub currency: storage_enums::Currency, - pub amount_captured: Option<MinorUnit>, - pub customer_id: Option<&'a id_type::CustomerId>, - pub description: Option<&'a String>, - pub return_url: Option<&'a String>, - pub metadata: Option<String>, - pub statement_descriptor: Option<&'a String>, - #[serde(with = "time::serde::timestamp::nanoseconds")] + pub amount_captured: Option<common_types::MinorUnit>, + pub customer_id: Option<&'a id_type::GlobalCustomerId>, + pub description: Option<&'a common_types::Description>, + pub return_url: Option<&'a common_types::Url>, + pub metadata: Option<&'a Secret<Value>>, + pub statement_descriptor: Option<&'a common_types::StatementDescriptor>, + #[serde(with = "time::serde::timestamp")] pub created_at: OffsetDateTime, - #[serde(with = "time::serde::timestamp::nanoseconds")] + #[serde(with = "time::serde::timestamp")] pub modified_at: OffsetDateTime, - #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] + #[serde(default, with = "time::serde::timestamp::option")] pub last_synced: Option<OffsetDateTime>, - pub setup_future_usage: Option<storage_enums::FutureUsage>, - pub off_session: Option<bool>, - pub client_secret: Option<&'a String>, - pub active_attempt_id: String, + pub setup_future_usage: storage_enums::FutureUsage, + pub off_session: bool, + pub active_attempt_id: Option<&'a id_type::GlobalAttemptId>, pub attempt_count: i16, pub profile_id: &'a id_type::ProfileId, - pub payment_confirm_source: Option<storage_enums::PaymentSource>, - pub billing_details: Option<Encryptable<Secret<Value>>>, - pub shipping_details: Option<Encryptable<Secret<Value>>>, pub customer_email: Option<HashedString<pii::EmailStrategy>>, - pub feature_metadata: Option<&'a Value>, - pub merchant_order_reference_id: Option<&'a String>, + pub feature_metadata: Option<&'a diesel_types::FeatureMetadata>, pub organization_id: &'a id_type::OrganizationId, + pub order_details: Option<&'a Vec<Secret<OrderDetailsWithAmount>>>, + + pub allowed_payment_method_types: Option<&'a Vec<common_enums::PaymentMethodType>>, + pub connector_metadata: Option<&'a Secret<Value>>, + pub payment_link_id: Option<&'a String>, + pub updated_by: &'a String, + pub surcharge_applicable: Option<bool>, + pub request_incremental_authorization: RequestIncrementalAuthorization, + pub authorization_count: Option<i32>, + #[serde(with = "time::serde::timestamp")] + pub session_expiry: OffsetDateTime, + pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest, + pub frm_metadata: Option<Secret<&'a Value>>, + pub customer_details: Option<Secret<&'a Value>>, + pub shipping_cost: Option<common_types::MinorUnit>, + pub tax_details: Option<TaxDetails>, + pub skip_external_tax_calculation: bool, + pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, + pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>, + pub split_payments: Option<&'a payments::SplitPaymentsRequest>, + pub platform_merchant_id: Option<&'a id_type::MerchantId>, + pub force_3ds_challenge: Option<bool>, + pub force_3ds_challenge_trigger: Option<bool>, + pub processor_merchant_id: &'a id_type::MerchantId, + pub created_by: Option<&'a common_types::CreatedBy>, + pub is_iframe_redirection_enabled: Option<bool>, + pub merchant_reference_id: Option<&'a id_type::PaymentReferenceId>, + pub capture_method: storage_enums::CaptureMethod, + pub authentication_type: Option<common_enums::AuthenticationType>, + pub prerouting_algorithm: Option<&'a routing::PaymentRoutingInfo>, + pub surcharge_amount: Option<common_types::MinorUnit>, + pub billing_address: Option<Secret<&'a address::Address>>, + pub shipping_address: Option<Secret<&'a address::Address>>, + pub tax_on_surcharge: Option<common_types::MinorUnit>, + pub frm_merchant_decision: Option<common_enums::MerchantDecision>, + pub enable_payment_link: common_enums::EnablePaymentLinkRequest, + pub apply_mit_exemption: common_enums::MitExemptionRequest, + pub customer_present: common_enums::PresenceOfCustomerDuringPayment, + pub routing_algorithm_id: Option<&'a id_type::RoutingId>, + pub payment_link_config: Option<&'a PaymentLinkConfigRequestForPayments>, + + #[serde(flatten)] + infra_values: Option<Value>, } impl KafkaPaymentIntentEvent<'_> { @@ -90,8 +140,8 @@ impl KafkaPaymentIntentEvent<'_> { } #[cfg(feature = "v2")] - pub fn get_id(&self) -> &id_type::PaymentId { - self.id + pub fn get_id(&self) -> &id_type::GlobalPaymentId { + self.payment_id } } @@ -145,43 +195,128 @@ impl<'a> KafkaPaymentIntentEvent<'a> { #[cfg(feature = "v2")] impl<'a> KafkaPaymentIntentEvent<'a> { pub fn from_storage(intent: &'a PaymentIntent, infra_values: Option<Value>) -> Self { - // Self { - // id: &intent.id, - // merchant_id: &intent.merchant_id, - // status: intent.status, - // amount: intent.amount, - // currency: intent.currency, - // amount_captured: intent.amount_captured, - // customer_id: intent.customer_id.as_ref(), - // description: intent.description.as_ref(), - // return_url: intent.return_url.as_ref(), - // metadata: intent.metadata.as_ref().map(|x| x.to_string()), - // statement_descriptor: intent.statement_descriptor.as_ref(), - // created_at: intent.created_at.assume_utc(), - // modified_at: intent.modified_at.assume_utc(), - // last_synced: intent.last_synced.map(|i| i.assume_utc()), - // setup_future_usage: intent.setup_future_usage, - // off_session: intent.off_session, - // client_secret: intent.client_secret.as_ref(), - // active_attempt_id: intent.active_attempt.get_id(), - // attempt_count: intent.attempt_count, - // profile_id: &intent.profile_id, - // payment_confirm_source: intent.payment_confirm_source, - // // TODO: use typed information here to avoid PII logging - // billing_details: None, - // shipping_details: None, - // customer_email: intent - // .customer_details - // .as_ref() - // .and_then(|value| value.get_inner().peek().as_object()) - // .and_then(|obj| obj.get("email")) - // .and_then(|email| email.as_str()) - // .map(|email| HashedString::from(Secret::new(email.to_string()))), - // feature_metadata: intent.feature_metadata.as_ref(), - // merchant_order_reference_id: intent.merchant_order_reference_id.as_ref(), - // organization_id: &intent.organization_id, - // } - todo!() + let PaymentIntent { + id, + merchant_id, + status, + amount_details, + amount_captured, + customer_id, + description, + return_url, + metadata, + statement_descriptor, + created_at, + modified_at, + last_synced, + setup_future_usage, + active_attempt_id, + order_details, + allowed_payment_method_types, + connector_metadata, + feature_metadata, + attempt_count, + profile_id, + payment_link_id, + frm_merchant_decision, + updated_by, + request_incremental_authorization, + authorization_count, + session_expiry, + request_external_three_ds_authentication, + frm_metadata, + customer_details, + merchant_reference_id, + billing_address, + shipping_address, + capture_method, + authentication_type, + prerouting_algorithm, + organization_id, + enable_payment_link, + apply_mit_exemption, + customer_present, + payment_link_config, + routing_algorithm_id, + split_payments, + force_3ds_challenge, + force_3ds_challenge_trigger, + processor_merchant_id, + created_by, + is_iframe_redirection_enabled, + } = intent; + + Self { + payment_id: id, + merchant_id, + status: *status, + amount: amount_details.order_amount, + currency: amount_details.currency, + amount_captured: *amount_captured, + customer_id: customer_id.as_ref(), + description: description.as_ref(), + return_url: return_url.as_ref(), + metadata: metadata.as_ref(), + statement_descriptor: statement_descriptor.as_ref(), + created_at: created_at.assume_utc(), + modified_at: modified_at.assume_utc(), + last_synced: last_synced.map(|t| t.assume_utc()), + setup_future_usage: *setup_future_usage, + off_session: setup_future_usage.is_off_session(), + active_attempt_id: active_attempt_id.as_ref(), + attempt_count: *attempt_count, + profile_id, + customer_email: None, + feature_metadata: feature_metadata.as_ref(), + organization_id, + order_details: order_details.as_ref(), + allowed_payment_method_types: allowed_payment_method_types.as_ref(), + connector_metadata: connector_metadata.as_ref(), + payment_link_id: payment_link_id.as_ref(), + updated_by, + surcharge_applicable: None, + request_incremental_authorization: *request_incremental_authorization, + authorization_count: *authorization_count, + session_expiry: session_expiry.assume_utc(), + request_external_three_ds_authentication: *request_external_three_ds_authentication, + frm_metadata: frm_metadata + .as_ref() + .map(|frm_metadata| frm_metadata.as_ref()), + customer_details: customer_details + .as_ref() + .map(|customer_details| customer_details.get_inner().as_ref()), + shipping_cost: amount_details.shipping_cost, + tax_details: amount_details.tax_details.clone(), + skip_external_tax_calculation: amount_details.get_external_tax_action_as_bool(), + request_extended_authorization: None, + psd2_sca_exemption_type: None, + split_payments: split_payments.as_ref(), + platform_merchant_id: None, + force_3ds_challenge: *force_3ds_challenge, + force_3ds_challenge_trigger: *force_3ds_challenge_trigger, + processor_merchant_id, + created_by: created_by.as_ref(), + is_iframe_redirection_enabled: *is_iframe_redirection_enabled, + merchant_reference_id: merchant_reference_id.as_ref(), + billing_address: billing_address + .as_ref() + .map(|billing_address| Secret::new(billing_address.get_inner())), + shipping_address: shipping_address + .as_ref() + .map(|shipping_address| Secret::new(shipping_address.get_inner())), + capture_method: *capture_method, + authentication_type: *authentication_type, + prerouting_algorithm: prerouting_algorithm.as_ref(), + surcharge_amount: amount_details.surcharge_amount, + tax_on_surcharge: amount_details.tax_on_surcharge, + frm_merchant_decision: *frm_merchant_decision, + enable_payment_link: *enable_payment_link, + apply_mit_exemption: *apply_mit_exemption, + customer_present: *customer_present, + routing_algorithm_id: routing_algorithm_id.as_ref(), + payment_link_config: payment_link_config.as_ref(), + infra_values, + } } } diff --git a/crates/router/src/services/kafka/refund.rs b/crates/router/src/services/kafka/refund.rs index 19635b2d8c2..4e10ac4ee36 100644 --- a/crates/router/src/services/kafka/refund.rs +++ b/crates/router/src/services/kafka/refund.rs @@ -1,3 +1,7 @@ +#[cfg(feature = "v2")] +use common_utils::pii; +#[cfg(feature = "v2")] +use common_utils::types::{self, ChargeRefunds}; use common_utils::{ id_type, types::{ConnectorTransactionIdTrait, MinorUnit}, @@ -73,13 +77,13 @@ impl<'a> KafkaRefund<'a> { #[cfg(feature = "v2")] #[derive(serde::Serialize, Debug)] pub struct KafkaRefund<'a> { - pub id: &'a id_type::GlobalRefundId, + pub refund_id: &'a id_type::GlobalRefundId, pub merchant_reference_id: &'a id_type::RefundReferenceId, pub payment_id: &'a id_type::GlobalPaymentId, pub merchant_id: &'a id_type::MerchantId, - pub connector_transaction_id: &'a String, + pub connector_transaction_id: &'a types::ConnectorTransactionId, pub connector: &'a String, - pub connector_refund_id: Option<&'a String>, + pub connector_refund_id: Option<&'a types::ConnectorTransactionId>, pub external_reference_id: Option<&'a String>, pub refund_type: &'a storage_enums::RefundType, pub total_amount: &'a MinorUnit, @@ -99,42 +103,101 @@ pub struct KafkaRefund<'a> { pub refund_error_code: Option<&'a String>, pub profile_id: Option<&'a id_type::ProfileId>, pub organization_id: &'a id_type::OrganizationId, + + pub metadata: Option<&'a pii::SecretSerdeValue>, + pub updated_by: &'a String, + pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>, + pub charges: Option<&'a ChargeRefunds>, + pub connector_refund_data: Option<&'a String>, + pub connector_transaction_data: Option<&'a String>, + pub split_refunds: Option<&'a common_types::refunds::SplitRefund>, + pub unified_code: Option<&'a String>, + pub unified_message: Option<&'a String>, + pub processor_refund_data: Option<&'a String>, + pub processor_transaction_data: Option<&'a String>, } #[cfg(feature = "v2")] impl<'a> KafkaRefund<'a> { pub fn from_storage(refund: &'a Refund) -> Self { + let Refund { + payment_id, + merchant_id, + connector_transaction_id, + connector, + connector_refund_id, + external_reference_id, + refund_type, + total_amount, + currency, + refund_amount, + refund_status, + sent_to_gateway, + refund_error_message, + metadata, + refund_arn, + created_at, + modified_at, + description, + attempt_id, + refund_reason, + refund_error_code, + profile_id, + updated_by, + charges, + organization_id, + split_refunds, + unified_code, + unified_message, + processor_refund_data, + processor_transaction_data, + id, + merchant_reference_id, + connector_id, + } = refund; + Self { - id: &refund.id, - merchant_reference_id: &refund.merchant_reference_id, - payment_id: &refund.payment_id, - merchant_id: &refund.merchant_id, - connector_transaction_id: refund.get_connector_transaction_id(), - connector: &refund.connector, - connector_refund_id: refund.get_optional_connector_refund_id(), - external_reference_id: refund.external_reference_id.as_ref(), - refund_type: &refund.refund_type, - total_amount: &refund.total_amount, - currency: &refund.currency, - refund_amount: &refund.refund_amount, - refund_status: &refund.refund_status, - sent_to_gateway: &refund.sent_to_gateway, - refund_error_message: refund.refund_error_message.as_ref(), - refund_arn: refund.refund_arn.as_ref(), - created_at: refund.created_at.assume_utc(), - modified_at: refund.modified_at.assume_utc(), - description: refund.description.as_ref(), - attempt_id: &refund.attempt_id, - refund_reason: refund.refund_reason.as_ref(), - refund_error_code: refund.refund_error_code.as_ref(), - profile_id: refund.profile_id.as_ref(), - organization_id: &refund.organization_id, + refund_id: id, + merchant_reference_id, + payment_id, + merchant_id, + connector_transaction_id, + connector, + connector_refund_id: connector_refund_id.as_ref(), + external_reference_id: external_reference_id.as_ref(), + refund_type, + total_amount, + currency, + refund_amount, + refund_status, + sent_to_gateway, + refund_error_message: refund_error_message.as_ref(), + refund_arn: refund_arn.as_ref(), + created_at: created_at.assume_utc(), + modified_at: modified_at.assume_utc(), + description: description.as_ref(), + attempt_id, + refund_reason: refund_reason.as_ref(), + refund_error_code: refund_error_code.as_ref(), + profile_id: profile_id.as_ref(), + organization_id, + metadata: metadata.as_ref(), + updated_by, + merchant_connector_id: connector_id.as_ref(), + charges: charges.as_ref(), + connector_refund_data: processor_refund_data.as_ref(), + connector_transaction_data: processor_transaction_data.as_ref(), + split_refunds: split_refunds.as_ref(), + unified_code: unified_code.as_ref(), + unified_message: unified_message.as_ref(), + processor_refund_data: processor_refund_data.as_ref(), + processor_transaction_data: processor_transaction_data.as_ref(), } } } -#[cfg(feature = "v1")] impl super::KafkaMessage for KafkaRefund<'_> { + #[cfg(feature = "v1")] fn key(&self) -> String { format!( "{}_{}_{}_{}", @@ -144,14 +207,7 @@ impl super::KafkaMessage for KafkaRefund<'_> { self.refund_id ) } - - fn event_type(&self) -> events::EventType { - events::EventType::Refund - } -} - -#[cfg(feature = "v2")] -impl super::KafkaMessage for KafkaRefund<'_> { + #[cfg(feature = "v2")] fn key(&self) -> String { format!( "{}_{}_{}_{}", diff --git a/crates/router/src/services/kafka/refund_event.rs b/crates/router/src/services/kafka/refund_event.rs index 34ed0b85c55..18cc0445cc9 100644 --- a/crates/router/src/services/kafka/refund_event.rs +++ b/crates/router/src/services/kafka/refund_event.rs @@ -1,3 +1,7 @@ +#[cfg(feature = "v2")] +use common_utils::pii; +#[cfg(feature = "v2")] +use common_utils::types::{self, ChargeRefunds}; use common_utils::{ id_type, types::{ConnectorTransactionIdTrait, MinorUnit}, @@ -75,13 +79,13 @@ impl<'a> KafkaRefundEvent<'a> { #[serde_with::skip_serializing_none] #[derive(serde::Serialize, Debug)] pub struct KafkaRefundEvent<'a> { - pub id: &'a id_type::GlobalRefundId, + pub refund_id: &'a id_type::GlobalRefundId, pub merchant_reference_id: &'a id_type::RefundReferenceId, pub payment_id: &'a id_type::GlobalPaymentId, pub merchant_id: &'a id_type::MerchantId, - pub connector_transaction_id: &'a String, + pub connector_transaction_id: &'a types::ConnectorTransactionId, pub connector: &'a String, - pub connector_refund_id: Option<&'a String>, + pub connector_refund_id: Option<&'a types::ConnectorTransactionId>, pub external_reference_id: Option<&'a String>, pub refund_type: &'a storage_enums::RefundType, pub total_amount: &'a MinorUnit, @@ -91,9 +95,9 @@ pub struct KafkaRefundEvent<'a> { pub sent_to_gateway: &'a bool, pub refund_error_message: Option<&'a String>, pub refund_arn: Option<&'a String>, - #[serde(default, with = "time::serde::timestamp::nanoseconds")] + #[serde(default, with = "time::serde::timestamp")] pub created_at: OffsetDateTime, - #[serde(default, with = "time::serde::timestamp::nanoseconds")] + #[serde(default, with = "time::serde::timestamp")] pub modified_at: OffsetDateTime, pub description: Option<&'a String>, pub attempt_id: &'a id_type::GlobalAttemptId, @@ -101,36 +105,95 @@ pub struct KafkaRefundEvent<'a> { pub refund_error_code: Option<&'a String>, pub profile_id: Option<&'a id_type::ProfileId>, pub organization_id: &'a id_type::OrganizationId, + + pub metadata: Option<&'a pii::SecretSerdeValue>, + pub updated_by: &'a String, + pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>, + pub charges: Option<&'a ChargeRefunds>, + pub connector_refund_data: Option<&'a String>, + pub connector_transaction_data: Option<&'a String>, + pub split_refunds: Option<&'a common_types::refunds::SplitRefund>, + pub unified_code: Option<&'a String>, + pub unified_message: Option<&'a String>, + pub processor_refund_data: Option<&'a String>, + pub processor_transaction_data: Option<&'a String>, } #[cfg(feature = "v2")] impl<'a> KafkaRefundEvent<'a> { pub fn from_storage(refund: &'a Refund) -> Self { + let Refund { + payment_id, + merchant_id, + connector_transaction_id, + connector, + connector_refund_id, + external_reference_id, + refund_type, + total_amount, + currency, + refund_amount, + refund_status, + sent_to_gateway, + refund_error_message, + metadata, + refund_arn, + created_at, + modified_at, + description, + attempt_id, + refund_reason, + refund_error_code, + profile_id, + updated_by, + charges, + organization_id, + split_refunds, + unified_code, + unified_message, + processor_refund_data, + processor_transaction_data, + id, + merchant_reference_id, + connector_id, + } = refund; + Self { - id: &refund.id, - merchant_reference_id: &refund.merchant_reference_id, - payment_id: &refund.payment_id, - merchant_id: &refund.merchant_id, - connector_transaction_id: refund.get_connector_transaction_id(), - connector: &refund.connector, - connector_refund_id: refund.get_optional_connector_refund_id(), - external_reference_id: refund.external_reference_id.as_ref(), - refund_type: &refund.refund_type, - total_amount: &refund.total_amount, - currency: &refund.currency, - refund_amount: &refund.refund_amount, - refund_status: &refund.refund_status, - sent_to_gateway: &refund.sent_to_gateway, - refund_error_message: refund.refund_error_message.as_ref(), - refund_arn: refund.refund_arn.as_ref(), - created_at: refund.created_at.assume_utc(), - modified_at: refund.modified_at.assume_utc(), - description: refund.description.as_ref(), - attempt_id: &refund.attempt_id, - refund_reason: refund.refund_reason.as_ref(), - refund_error_code: refund.refund_error_code.as_ref(), - profile_id: refund.profile_id.as_ref(), - organization_id: &refund.organization_id, + refund_id: id, + merchant_reference_id, + payment_id, + merchant_id, + connector_transaction_id, + connector, + connector_refund_id: connector_refund_id.as_ref(), + external_reference_id: external_reference_id.as_ref(), + refund_type, + total_amount, + currency, + refund_amount, + refund_status, + sent_to_gateway, + refund_error_message: refund_error_message.as_ref(), + refund_arn: refund_arn.as_ref(), + created_at: created_at.assume_utc(), + modified_at: modified_at.assume_utc(), + description: description.as_ref(), + attempt_id, + refund_reason: refund_reason.as_ref(), + refund_error_code: refund_error_code.as_ref(), + profile_id: profile_id.as_ref(), + organization_id, + metadata: metadata.as_ref(), + updated_by, + merchant_connector_id: connector_id.as_ref(), + charges: charges.as_ref(), + connector_refund_data: processor_refund_data.as_ref(), + connector_transaction_data: processor_transaction_data.as_ref(), + split_refunds: split_refunds.as_ref(), + unified_code: unified_code.as_ref(), + unified_message: unified_message.as_ref(), + processor_refund_data: processor_refund_data.as_ref(), + processor_transaction_data: processor_transaction_data.as_ref(), } } }
2025-06-12T06:01:54Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Added payment_intent payment_attempt and refund kafka events for v2 Other changes: * populate connector_metadata in AuthorizaRouterData in v2. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Made a payment and refund and verified if proper events are logged into Kafka. <img width="1728" alt="Screenshot 2025-06-12 at 9 48 33 AM" src="https://github.com/user-attachments/assets/91286bfd-8c83-4cb4-85cb-a672efb81daa" /> <img width="1728" alt="Screenshot 2025-06-12 at 9 48 18 AM" src="https://github.com/user-attachments/assets/2fe52584-a28d-44b7-acfb-936805775fab" /> <img width="1728" alt="Screenshot 2025-06-12 at 9 48 52 AM" src="https://github.com/user-attachments/assets/2c3b085a-7b87-41e1-80e1-28266a091fb6" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
7b2919b46fda92aad14980280bc46c2c23d81086
7b2919b46fda92aad14980280bc46c2c23d81086
juspay/hyperswitch
juspay__hyperswitch-8377
Bug: feat(router): Add v2 endpoint to list payment attempts by intent_id In payment flows that involve retries—such as smart , cascading retires —a single payment intent may result in multiple attempts. Previously, there was no clean way to retrieve all these attempts together. ### API Flow: Adds a new endpoint: GET /v2/payments/{intent_id}/attempts Validates the request and ensures merchant authorization Retrieves all associated payment attempts linked to that intent_id
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index 0304eaf3b0c..b213d96accd 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -15511,6 +15511,31 @@ } } }, + "PaymentAttemptListRequest": { + "type": "object", + "required": [ + "payment_intent_id" + ], + "properties": { + "payment_intent_id": { + "type": "string" + } + } + }, + "PaymentAttemptListResponse": { + "type": "object", + "required": [ + "payment_attempt_list" + ], + "properties": { + "payment_attempt_list": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PaymentAttemptResponse" + } + } + } + }, "PaymentAttemptRecordResponse": { "type": "object", "required": [ diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs index ef55763b0af..ec4c8667f45 100644 --- a/crates/api_models/src/events/payment.rs +++ b/crates/api_models/src/events/payment.rs @@ -2,8 +2,8 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; #[cfg(feature = "v2")] use super::{ - PaymentStartRedirectionRequest, PaymentsCreateIntentRequest, PaymentsGetIntentRequest, - PaymentsIntentResponse, PaymentsRequest, + PaymentAttemptListRequest, PaymentAttemptListResponse, PaymentStartRedirectionRequest, + PaymentsCreateIntentRequest, PaymentsGetIntentRequest, PaymentsIntentResponse, PaymentsRequest, }; #[cfg(feature = "v2")] use crate::payment_methods::PaymentMethodListResponseForSession; @@ -185,6 +185,22 @@ impl ApiEventMetric for PaymentsGetIntentRequest { } } +#[cfg(feature = "v2")] +impl ApiEventMetric for PaymentAttemptListRequest { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Payment { + payment_id: self.payment_intent_id.clone(), + }) + } +} + +#[cfg(feature = "v2")] +impl ApiEventMetric for PaymentAttemptListResponse { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + None + } +} + #[cfg(feature = "v2")] impl ApiEventMetric for PaymentsIntentResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index ca382fa1479..cb5480ed1f4 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -290,7 +290,18 @@ pub struct MerchantConnectorDetails { }"#)] pub merchant_connector_creds: pii::SecretSerdeValue, } +#[cfg(feature = "v2")] +#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] +pub struct PaymentAttemptListRequest { + #[schema(value_type = String)] + pub payment_intent_id: id_type::GlobalPaymentId, +} +#[cfg(feature = "v2")] +#[derive(Debug, serde::Serialize, Clone, ToSchema)] +pub struct PaymentAttemptListResponse { + pub payment_attempt_list: Vec<PaymentAttemptResponse>, +} #[cfg(feature = "v2")] impl PaymentsCreateIntentRequest { pub fn get_feature_metadata_as_value( diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index eb5c0a467c5..99ce4ca17f3 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -845,6 +845,16 @@ where pub connector_customer_id: Option<String>, } +#[cfg(feature = "v2")] +#[derive(Clone)] +pub struct PaymentAttemptListData<F> +where + F: Clone, +{ + pub flow: PhantomData<F>, + pub payment_attempt_list: Vec<PaymentAttempt>, +} + // TODO: Check if this can be merged with existing payment data #[cfg(feature = "v2")] #[derive(Clone, Debug)] diff --git a/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs b/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs index f139249f62a..660c9fae4e2 100644 --- a/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs +++ b/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs @@ -76,3 +76,6 @@ pub struct UpdateMetadata; #[derive(Debug, Clone)] pub struct CreateOrder; + +#[derive(Debug, Clone)] +pub struct PaymentGetListAttempts; diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 822397767cf..43bf1159e7d 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -432,6 +432,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::PaymentsCreateIntentRequest, api_models::payments::PaymentsUpdateIntentRequest, api_models::payments::PaymentsIntentResponse, + api_models::payments::PaymentAttemptListRequest, + api_models::payments::PaymentAttemptListResponse, api_models::payments::PazeWalletData, api_models::payments::AmountDetails, api_models::payments::AmountDetailsUpdate, diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 854af3f8333..59de54f41fa 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -45,7 +45,8 @@ use futures::future::join_all; use helpers::{decrypt_paze_token, ApplePayData}; #[cfg(feature = "v2")] use hyperswitch_domain_models::payments::{ - PaymentCaptureData, PaymentConfirmData, PaymentIntentData, PaymentStatusData, + PaymentAttemptListData, PaymentCaptureData, PaymentConfirmData, PaymentIntentData, + PaymentStatusData, }; #[cfg(feature = "v2")] use hyperswitch_domain_models::router_response_types::RedirectForm; @@ -1410,6 +1411,83 @@ where Ok((payment_data, req, customer)) } +#[cfg(feature = "v2")] +#[allow(clippy::too_many_arguments, clippy::type_complexity)] +#[instrument(skip_all, fields(payment_id, merchant_id))] +pub async fn payments_attempt_operation_core<F, Req, Op, D>( + state: &SessionState, + req_state: ReqState, + merchant_context: domain::MerchantContext, + profile: domain::Profile, + operation: Op, + req: Req, + payment_id: id_type::GlobalPaymentId, + header_payload: HeaderPayload, +) -> RouterResult<(D, Req, Option<domain::Customer>)> +where + F: Send + Clone + Sync, + Req: Clone, + Op: Operation<F, Req, Data = D> + Send + Sync, + D: OperationSessionGetters<F> + Send + Sync + Clone, +{ + let operation: BoxedOperation<'_, F, Req, D> = Box::new(operation); + + tracing::Span::current().record( + "merchant_id", + merchant_context + .get_merchant_account() + .get_id() + .get_string_repr(), + ); + + let _validate_result = operation + .to_validate_request()? + .validate_request(&req, &merchant_context)?; + + tracing::Span::current().record("global_payment_id", payment_id.get_string_repr()); + + let operations::GetTrackerResponse { mut payment_data } = operation + .to_get_tracker()? + .get_trackers( + state, + &payment_id, + &req, + &merchant_context, + &profile, + &header_payload, + ) + .await?; + + let (_operation, customer) = operation + .to_domain()? + .get_customer_details( + state, + &mut payment_data, + merchant_context.get_merchant_key_store(), + merchant_context.get_merchant_account().storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound) + .attach_printable("Failed while fetching/creating customer")?; + + let (_operation, payment_data) = operation + .to_update_tracker()? + .update_trackers( + state, + req_state, + payment_data, + customer.clone(), + merchant_context.get_merchant_account().storage_scheme, + None, + merchant_context.get_merchant_key_store(), + None, + header_payload, + ) + .await?; + + Ok((payment_data, req, customer)) +} + #[instrument(skip_all)] #[cfg(feature = "v1")] pub async fn call_decision_manager<F, D>( @@ -2089,6 +2167,50 @@ where ) } +#[cfg(feature = "v2")] +#[allow(clippy::too_many_arguments)] +pub async fn payments_list_attempts_using_payment_intent_id<F, Res, Req, Op, D>( + state: SessionState, + req_state: ReqState, + merchant_context: domain::MerchantContext, + profile: domain::Profile, + operation: Op, + req: Req, + payment_id: id_type::GlobalPaymentId, + header_payload: HeaderPayload, +) -> RouterResponse<Res> +where + F: Send + Clone + Sync, + Op: Operation<F, Req, Data = D> + Send + Sync + Clone, + Req: Debug + Clone, + D: OperationSessionGetters<F> + Send + Sync + Clone, + Res: transformers::ToResponse<F, D, Op>, +{ + let (payment_data, _req, customer) = payments_attempt_operation_core::<_, _, _, _>( + &state, + req_state, + merchant_context.clone(), + profile, + operation.clone(), + req, + payment_id, + header_payload.clone(), + ) + .await?; + + Res::generate_response( + payment_data, + customer, + &state.base_url, + operation, + &state.conf.connector_request_reference_id_config, + None, + None, + header_payload.x_hs_latency, + &merchant_context, + ) +} + #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] pub async fn payments_get_intent_using_merchant_reference( @@ -8716,6 +8838,8 @@ impl<F: Clone> PaymentMethodChecker<F> for PaymentData<F> { pub trait OperationSessionGetters<F> { fn get_payment_attempt(&self) -> &storage::PaymentAttempt; + #[cfg(feature = "v2")] + fn list_payments_attempts(&self) -> &Vec<storage::PaymentAttempt>; fn get_payment_intent(&self) -> &storage::PaymentIntent; #[cfg(feature = "v2")] fn get_client_secret(&self) -> &Option<Secret<String>>; @@ -9147,6 +9271,10 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentIntentData<F> { fn get_payment_attempt(&self) -> &storage::PaymentAttempt { todo!() } + #[cfg(feature = "v2")] + fn list_payments_attempts(&self) -> &Vec<storage::PaymentAttempt> { + todo!() + } fn get_client_secret(&self) -> &Option<Secret<String>> { &self.client_secret @@ -9429,6 +9557,10 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentConfirmData<F> { fn get_payment_attempt(&self) -> &storage::PaymentAttempt { &self.payment_attempt } + #[cfg(feature = "v2")] + fn list_payments_attempts(&self) -> &Vec<storage::PaymentAttempt> { + todo!() + } fn get_client_secret(&self) -> &Option<Secret<String>> { todo!() } @@ -9715,6 +9847,10 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentStatusData<F> { fn get_payment_attempt(&self) -> &storage::PaymentAttempt { &self.payment_attempt } + #[cfg(feature = "v2")] + fn list_payments_attempts(&self) -> &Vec<storage::PaymentAttempt> { + todo!() + } fn get_client_secret(&self) -> &Option<Secret<String>> { todo!() } @@ -9996,6 +10132,10 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentCaptureData<F> { fn get_payment_attempt(&self) -> &storage::PaymentAttempt { &self.payment_attempt } + #[cfg(feature = "v2")] + fn list_payments_attempts(&self) -> &Vec<storage::PaymentAttempt> { + todo!() + } fn get_client_secret(&self) -> &Option<Secret<String>> { todo!() } @@ -10271,3 +10411,172 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentCaptureData<F> { todo!() } } + +#[cfg(feature = "v2")] +impl<F: Clone> OperationSessionGetters<F> for PaymentAttemptListData<F> { + #[track_caller] + fn get_payment_attempt(&self) -> &storage::PaymentAttempt { + todo!() + } + #[cfg(feature = "v2")] + fn list_payments_attempts(&self) -> &Vec<storage::PaymentAttempt> { + &self.payment_attempt_list + } + fn get_client_secret(&self) -> &Option<Secret<String>> { + todo!() + } + fn get_payment_intent(&self) -> &storage::PaymentIntent { + todo!() + } + + fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod> { + todo!() + } + + fn get_mandate_id(&self) -> Option<&payments_api::MandateIds> { + todo!() + } + + // what is this address find out and not required remove this + fn get_address(&self) -> &PaymentAddress { + todo!() + } + + fn get_creds_identifier(&self) -> Option<&str> { + None + } + + fn get_token(&self) -> Option<&str> { + todo!() + } + + fn get_multiple_capture_data(&self) -> Option<&types::MultipleCaptureData> { + todo!() + } + + fn get_payment_link_data(&self) -> Option<api_models::payments::PaymentLinkResponse> { + todo!() + } + + fn get_ephemeral_key(&self) -> Option<ephemeral_key::EphemeralKey> { + todo!() + } + + fn get_setup_mandate(&self) -> Option<&MandateData> { + todo!() + } + + fn get_poll_config(&self) -> Option<router_types::PollConfig> { + todo!() + } + + fn get_authentication( + &self, + ) -> Option<&hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore> + { + todo!() + } + + fn get_frm_message(&self) -> Option<FraudCheck> { + todo!() + } + + fn get_refunds(&self) -> Vec<storage::Refund> { + todo!() + } + + fn get_disputes(&self) -> Vec<storage::Dispute> { + todo!() + } + + fn get_authorizations(&self) -> Vec<diesel_models::authorization::Authorization> { + todo!() + } + + fn get_attempts(&self) -> Option<Vec<storage::PaymentAttempt>> { + todo!() + } + + fn get_recurring_details(&self) -> Option<&RecurringDetails> { + todo!() + } + + fn get_payment_intent_profile_id(&self) -> Option<&id_type::ProfileId> { + todo!() + } + + fn get_currency(&self) -> storage_enums::Currency { + todo!() + } + + fn get_amount(&self) -> api::Amount { + todo!() + } + + fn get_payment_attempt_connector(&self) -> Option<&str> { + todo!() + } + + fn get_merchant_connector_id_in_attempt(&self) -> Option<id_type::MerchantConnectorAccountId> { + todo!() + } + + fn get_connector_customer_id(&self) -> Option<String> { + todo!() + } + + fn get_billing_address(&self) -> Option<hyperswitch_domain_models::address::Address> { + todo!() + } + + fn get_payment_method_data(&self) -> Option<&domain::PaymentMethodData> { + todo!() + } + + fn get_sessions_token(&self) -> Vec<api::SessionToken> { + todo!() + } + + fn get_token_data(&self) -> Option<&storage::PaymentTokenData> { + todo!() + } + + fn get_mandate_connector(&self) -> Option<&MandateConnectorDetails> { + todo!() + } + + fn get_force_sync(&self) -> Option<bool> { + todo!() + } + + fn get_capture_method(&self) -> Option<enums::CaptureMethod> { + todo!() + } + + #[cfg(feature = "v2")] + fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt> { + todo!() + } + + fn get_all_keys_required(&self) -> Option<bool> { + todo!(); + } + + fn get_whole_connector_response(&self) -> Option<String> { + todo!(); + } + fn get_pre_routing_result( + &self, + ) -> Option<HashMap<enums::PaymentMethodType, domain::PreRoutingConnectorChoice>> { + None + } + fn get_merchant_connector_details( + &self, + ) -> Option<api_models::payments::MerchantConnectorDetails> { + todo!() + } + + fn get_optional_external_vault_session_details(&self) -> Option<api::VaultSessionDetails> { + todo!() + } +} diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs index 223ab65d0fb..fb42b2016cd 100644 --- a/crates/router/src/core/payments/operations.rs +++ b/crates/router/src/core/payments/operations.rs @@ -32,19 +32,20 @@ pub mod payments_incremental_authorization; #[cfg(feature = "v1")] pub mod tax_calculation; +#[cfg(feature = "v2")] +pub mod payment_attempt_list; #[cfg(feature = "v2")] pub mod payment_attempt_record; #[cfg(feature = "v2")] pub mod payment_confirm_intent; -#[cfg(feature = "v2")] -pub mod proxy_payments_intent; - #[cfg(feature = "v2")] pub mod payment_create_intent; #[cfg(feature = "v2")] pub mod payment_get_intent; #[cfg(feature = "v2")] pub mod payment_update_intent; +#[cfg(feature = "v2")] +pub mod proxy_payments_intent; #[cfg(feature = "v2")] pub mod payment_get; @@ -59,6 +60,8 @@ use async_trait::async_trait; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; +#[cfg(feature = "v2")] +pub use self::payment_attempt_list::PaymentGetListAttempts; #[cfg(feature = "v2")] pub use self::payment_get::PaymentGet; #[cfg(feature = "v2")] diff --git a/crates/router/src/core/payments/operations/payment_attempt_list.rs b/crates/router/src/core/payments/operations/payment_attempt_list.rs new file mode 100644 index 00000000000..3d651b8c9e9 --- /dev/null +++ b/crates/router/src/core/payments/operations/payment_attempt_list.rs @@ -0,0 +1,224 @@ +use std::marker::PhantomData; + +#[cfg(feature = "v2")] +use api_models::{enums::FrmSuggestion, payments::PaymentAttemptListRequest}; +use async_trait::async_trait; +use common_utils::errors::CustomResult; +use router_env::{instrument, tracing}; + +use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; +use crate::{ + core::{ + errors::{self, RouterResult}, + payments::{self, operations}, + }, + db::errors::StorageErrorExt, + routes::{app::ReqState, SessionState}, + types::{ + api, domain, + storage::{self, enums}, + }, +}; + +#[derive(Debug, Clone, Copy)] +pub struct PaymentGetListAttempts; + +impl<F: Send + Clone + Sync> Operation<F, PaymentAttemptListRequest> for &PaymentGetListAttempts { + type Data = payments::PaymentAttemptListData<F>; + fn to_validate_request( + &self, + ) -> RouterResult<&(dyn ValidateRequest<F, PaymentAttemptListRequest, Self::Data> + Send + Sync)> + { + Ok(*self) + } + fn to_get_tracker( + &self, + ) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentAttemptListRequest> + Send + Sync)> + { + Ok(*self) + } + fn to_domain(&self) -> RouterResult<&(dyn Domain<F, PaymentAttemptListRequest, Self::Data>)> { + Ok(*self) + } + fn to_update_tracker( + &self, + ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentAttemptListRequest> + Send + Sync)> + { + Ok(*self) + } +} + +impl<F: Send + Clone + Sync> Operation<F, PaymentAttemptListRequest> for PaymentGetListAttempts { + type Data = payments::PaymentAttemptListData<F>; + fn to_validate_request( + &self, + ) -> RouterResult<&(dyn ValidateRequest<F, PaymentAttemptListRequest, Self::Data> + Send + Sync)> + { + Ok(self) + } + fn to_get_tracker( + &self, + ) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentAttemptListRequest> + Send + Sync)> + { + Ok(self) + } + fn to_domain(&self) -> RouterResult<&(dyn Domain<F, PaymentAttemptListRequest, Self::Data>)> { + Ok(self) + } + fn to_update_tracker( + &self, + ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentAttemptListRequest> + Send + Sync)> + { + Ok(self) + } +} + +type PaymentAttemptsListOperation<'b, F> = + BoxedOperation<'b, F, PaymentAttemptListRequest, payments::PaymentAttemptListData<F>>; + +#[async_trait] +impl<F: Send + Clone + Sync> + GetTracker<F, payments::PaymentAttemptListData<F>, PaymentAttemptListRequest> + for PaymentGetListAttempts +{ + #[instrument(skip_all)] + async fn get_trackers<'a>( + &'a self, + state: &'a SessionState, + _payment_id: &common_utils::id_type::GlobalPaymentId, + request: &PaymentAttemptListRequest, + merchant_context: &domain::MerchantContext, + _profile: &domain::Profile, + _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, + ) -> RouterResult<operations::GetTrackerResponse<payments::PaymentAttemptListData<F>>> { + let db = &*state.store; + let key_manager_state = &state.into(); + let storage_scheme = merchant_context.get_merchant_account().storage_scheme; + let payment_attempt_list = db + .find_payment_attempts_by_payment_intent_id( + key_manager_state, + &request.payment_intent_id, + merchant_context.get_merchant_key_store(), + storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + + let payment_data = payments::PaymentAttemptListData { + flow: PhantomData, + payment_attempt_list, + }; + + let get_trackers_response = operations::GetTrackerResponse { payment_data }; + + Ok(get_trackers_response) + } +} + +#[async_trait] +impl<F: Clone + Sync> + UpdateTracker<F, payments::PaymentAttemptListData<F>, PaymentAttemptListRequest> + for PaymentGetListAttempts +{ + #[instrument(skip_all)] + async fn update_trackers<'b>( + &'b self, + _state: &'b SessionState, + _req_state: ReqState, + payment_data: payments::PaymentAttemptListData<F>, + _customer: Option<domain::Customer>, + _storage_scheme: enums::MerchantStorageScheme, + _updated_customer: Option<storage::CustomerUpdate>, + _key_store: &domain::MerchantKeyStore, + _frm_suggestion: Option<FrmSuggestion>, + _header_payload: hyperswitch_domain_models::payments::HeaderPayload, + ) -> RouterResult<( + PaymentAttemptsListOperation<'b, F>, + payments::PaymentAttemptListData<F>, + )> + where + F: 'b + Send, + { + Ok((Box::new(self), payment_data)) + } +} + +impl<F: Send + Clone + Sync> + ValidateRequest<F, PaymentAttemptListRequest, payments::PaymentAttemptListData<F>> + for PaymentGetListAttempts +{ + #[instrument(skip_all)] + fn validate_request<'a, 'b>( + &'b self, + _request: &PaymentAttemptListRequest, + merchant_context: &'a domain::MerchantContext, + ) -> RouterResult<operations::ValidateResult> { + Ok(operations::ValidateResult { + merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), + storage_scheme: merchant_context.get_merchant_account().storage_scheme, + requeue: false, + }) + } +} + +#[async_trait] +impl<F: Clone + Send + Sync> + Domain<F, PaymentAttemptListRequest, payments::PaymentAttemptListData<F>> + for PaymentGetListAttempts +{ + #[instrument(skip_all)] + async fn get_customer_details<'a>( + &'a self, + _state: &SessionState, + _payment_data: &mut payments::PaymentAttemptListData<F>, + _merchant_key_store: &domain::MerchantKeyStore, + _storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult< + ( + BoxedOperation<'a, F, PaymentAttemptListRequest, payments::PaymentAttemptListData<F>>, + Option<domain::Customer>, + ), + errors::StorageError, + > { + Ok((Box::new(self), None)) + } + + #[instrument(skip_all)] + async fn make_pm_data<'a>( + &'a self, + _state: &'a SessionState, + _payment_data: &mut payments::PaymentAttemptListData<F>, + _storage_scheme: enums::MerchantStorageScheme, + _merchant_key_store: &domain::MerchantKeyStore, + _customer: &Option<domain::Customer>, + _business_profile: &domain::Profile, + _should_retry_with_pan: bool, + ) -> RouterResult<( + PaymentAttemptsListOperation<'a, F>, + Option<domain::PaymentMethodData>, + Option<String>, + )> { + Ok((Box::new(self), None, None)) + } + + #[instrument(skip_all)] + async fn perform_routing<'a>( + &'a self, + _merchant_context: &domain::MerchantContext, + _business_profile: &domain::Profile, + _state: &SessionState, + _payment_data: &mut payments::PaymentAttemptListData<F>, + ) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse> { + Ok(api::ConnectorCallType::Skip) + } + + #[instrument(skip_all)] + async fn guard_payment_against_blocklist<'a>( + &'a self, + _state: &SessionState, + _merchant_context: &domain::MerchantContext, + _payment_data: &mut payments::PaymentAttemptListData<F>, + ) -> CustomResult<bool, errors::ApiErrorResponse> { + Ok(false) + } +} diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 4ded67d612e..5d40a603cbb 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -1826,6 +1826,38 @@ where } } +#[cfg(feature = "v2")] +impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentAttemptListResponse +where + F: Clone, + Op: Debug, + D: OperationSessionGetters<F>, +{ + #[allow(clippy::too_many_arguments)] + fn generate_response( + payment_data: D, + _customer: Option<domain::Customer>, + _base_url: &str, + _operation: Op, + _connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig, + _connector_http_status_code: Option<u16>, + _external_latency: Option<u128>, + _is_latency_header_enabled: Option<bool>, + _merchant_context: &domain::MerchantContext, + ) -> RouterResponse<Self> { + Ok(services::ApplicationResponse::JsonWithHeaders(( + Self { + payment_attempt_list: payment_data + .list_payments_attempts() + .iter() + .map(api_models::payments::PaymentAttemptResponse::foreign_from) + .collect(), + }, + vec![], + ))) + } +} + #[cfg(feature = "v2")] impl<F> GenerateResponse<api_models::payments::PaymentsResponse> for hyperswitch_domain_models::payments::PaymentConfirmData<F> diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 020fea804fd..bbb17589162 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -639,6 +639,10 @@ impl Payments { web::resource("/confirm-intent") .route(web::post().to(payments::payment_confirm_intent)), ) + .service( + web::resource("/list_attempts") + .route(web::get().to(payments::list_payment_attempts)), + ) .service( web::resource("/proxy-confirm-intent") .route(web::post().to(payments::proxy_confirm_intent)), diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 73f98ebc2a5..039986f1f4a 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -161,7 +161,8 @@ impl From<Flow> for ApiIdentifier { | Flow::PaymentsCreateAndConfirmIntent | Flow::PaymentStartRedirection | Flow::ProxyConfirmIntent - | Flow::PaymentsRetrieveUsingMerchantReferenceId => Self::Payments, + | Flow::PaymentsRetrieveUsingMerchantReferenceId + | Flow::PaymentAttemptsList => Self::Payments, Flow::PayoutsCreate | Flow::PayoutsRetrieve diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index ae2fcf2cf12..020a1fbf713 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -247,6 +247,71 @@ pub async fn payments_get_intent( .await } +#[cfg(feature = "v2")] +#[instrument(skip_all, fields(flow = ?Flow::PaymentAttemptsList, payment_id,))] +pub async fn list_payment_attempts( + state: web::Data<app::AppState>, + req: actix_web::HttpRequest, + path: web::Path<common_utils::id_type::GlobalPaymentId>, +) -> impl Responder { + let flow = Flow::PaymentAttemptsList; + let payment_intent_id = path.into_inner(); + + let payload = api_models::payments::PaymentAttemptListRequest { + payment_intent_id: payment_intent_id.clone(), + }; + + let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { + Ok(headers) => headers, + Err(err) => { + return api::log_and_return_error_response(err); + } + }; + + Box::pin(api::server_wrap( + flow, + state, + &req, + payload.clone(), + |session_state, auth, req_payload, req_state| { + let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( + domain::Context(auth.merchant_account, auth.key_store), + )); + + payments::payments_list_attempts_using_payment_intent_id::< + payments::operations::PaymentGetListAttempts, + api_models::payments::PaymentAttemptListResponse, + api_models::payments::PaymentAttemptListRequest, + payments::operations::payment_attempt_list::PaymentGetListAttempts, + hyperswitch_domain_models::payments::PaymentAttemptListData< + payments::operations::PaymentGetListAttempts, + >, + >( + session_state, + req_state, + merchant_context, + auth.profile, + payments::operations::PaymentGetListAttempts, + payload.clone(), + req_payload.payment_intent_id, + header_payload.clone(), + ) + }, + auth::auth_type( + &auth::V2ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: false, + }, + &auth::JWTAuth { + permission: Permission::ProfilePaymentRead, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} + #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsCreateAndConfirmIntent, payment_id))] pub async fn payments_create_and_confirm_intent( diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs index 7728945fe62..725a821eba1 100644 --- a/crates/router/src/types/api/payments.rs +++ b/crates/router/src/types/api/payments.rs @@ -1,11 +1,11 @@ -#[cfg(feature = "v1")] +#[cfg(feature = "v2")] pub use api_models::payments::{ - PaymentListFilterConstraints, PaymentListResponse, PaymentListResponseV2, + PaymentAttemptListRequest, PaymentAttemptListResponse, PaymentsConfirmIntentRequest, + PaymentsCreateIntentRequest, PaymentsIntentResponse, PaymentsUpdateIntentRequest, }; -#[cfg(feature = "v2")] +#[cfg(feature = "v1")] pub use api_models::payments::{ - PaymentsConfirmIntentRequest, PaymentsCreateIntentRequest, PaymentsIntentResponse, - PaymentsUpdateIntentRequest, + PaymentListFilterConstraints, PaymentListResponse, PaymentListResponseV2, }; pub use api_models::{ feature_matrix::{ diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index e353d2b28f4..cf176e1562e 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -180,6 +180,8 @@ pub enum Flow { PaymentsConfirmIntent, /// Payments create and confirm intent flow PaymentsCreateAndConfirmIntent, + /// Payment attempt list flow + PaymentAttemptsList, #[cfg(feature = "payouts")] /// Payouts create flow PayoutsCreate,
2025-06-17T15:08:52Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR introduces an API to list all payment attempts associated with a given intent_id. #### Why this is needed: In payment flows that involve retries—such as smart , cascading retires —a single payment intent may result in multiple attempts. Previously, there was no clean way to retrieve all these attempts together. #### Implemented API Flow: - Adds a new endpoint: GET /v2/payments/{intent_id}/list_attempts - Validates the request and ensures merchant authorization - Retrieves all associated payment attempts linked to that intent_id ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> I inserted two payment attempts for a payment intent as part of testing. ### Curl ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_01978809316e7850b05ab92288ed7746/list_attempts' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_pF6sS2TBfhg0Vdp6N04E' \ --header 'api-key: dev_bzJEoDI7SlTyV0M7Vq6VdtCtbKGwOPphw39wD1mYdu8rY3GoydtnymDbkkMxDopB' \ --header 'Authorization: api-key=dev_bzJEoDI7SlTyV0M7Vq6VdtCtbKGwOPphw39wD1mYdu8rY3GoydtnymDbkkMxDopB' ``` ### Response ``` { "payment_attempts": [ { "id": "12345_att_01975ae7bf32760282f479794fbf810c", "status": "failure", "amount": { "net_amount": 10000, "amount_to_capture": null, "surcharge_amount": null, "tax_on_surcharge": null, "amount_capturable": 10000, "shipping_cost": null, "order_tax_amount": null }, "connector": "stripe", "error": null, "authentication_type": "no_three_ds", "created_at": "2025-06-17T13:50:49.173Z", "modified_at": "2025-06-17T13:50:49.173Z", "cancellation_reason": null, "payment_token": null, "connector_metadata": null, "payment_experience": null, "payment_method_type": "card", "connector_reference_id": null, "payment_method_subtype": "credit", "connector_payment_id": { "TxnId": "ch_3RYW3N06IkU6uKNZ01mrX2tD" }, "payment_method_id": null, "client_source": null, "client_version": null, "feature_metadata": { "revenue_recovery": { "attempt_triggered_by": "external" } } }, { "id": "12345_att_01975ae7bf32760282f479794fbf810d", "status": "failure", "amount": { "net_amount": 10000, "amount_to_capture": null, "surcharge_amount": null, "tax_on_surcharge": null, "amount_capturable": 10000, "shipping_cost": null, "order_tax_amount": null }, "connector": "stripe", "error": null, "authentication_type": "no_three_ds", "created_at": "2025-06-17T13:51:16.812Z", "modified_at": "2025-06-17T13:51:16.812Z", "cancellation_reason": null, "payment_token": null, "connector_metadata": null, "payment_experience": null, "payment_method_type": "card", "connector_reference_id": null, "payment_method_subtype": "credit", "connector_payment_id": { "TxnId": "ch_3RYW3N06IkU6uKNZ01mrX2tD" }, "payment_method_id": null, "client_source": null, "client_version": null, "feature_metadata": { "revenue_recovery": { "attempt_triggered_by": "external" } } } ] } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
305ca9bda9d3c5bf3cc97458b7ed07b79e894154
305ca9bda9d3c5bf3cc97458b7ed07b79e894154
juspay/hyperswitch
juspay__hyperswitch-8356
Bug: Create a profile level config to switch between routing engine Hyperswitch already has support to handle euclid rules, whereas the same support has been added in [decision engine](https://github.com/juspay/decision-engine) as part of the routing unification. To migrate hyperswitch merchants to start using the decision engine results, we need this switch to migrate them slowly.
diff --git a/crates/api_models/src/open_router.rs b/crates/api_models/src/open_router.rs index af91ece3f12..bec1f14fef6 100644 --- a/crates/api_models/src/open_router.rs +++ b/crates/api_models/src/open_router.rs @@ -186,6 +186,19 @@ pub struct DecisionEngineConfigSetupRequest { pub config: DecisionEngineConfigVariant, } +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct GetDecisionEngineConfigRequest { + pub merchant_id: String, + pub config: DecisionEngineDynamicAlgorithmType, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub enum DecisionEngineDynamicAlgorithmType { + SuccessRate, + Elimination, +} + #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(tag = "type", content = "data")] #[serde(rename_all = "camelCase")] diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index 3e312769e07..a8f7315be40 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -1409,6 +1409,7 @@ pub struct RuleMigrationResponse { pub profile_id: common_utils::id_type::ProfileId, pub euclid_algorithm_id: common_utils::id_type::RoutingId, pub decision_engine_algorithm_id: String, + pub is_active_rule: bool, } #[derive(Debug, serde::Serialize)] @@ -1423,11 +1424,23 @@ impl RuleMigrationResponse { profile_id: common_utils::id_type::ProfileId, euclid_algorithm_id: common_utils::id_type::RoutingId, decision_engine_algorithm_id: String, + is_active_rule: bool, ) -> Self { Self { profile_id, euclid_algorithm_id, decision_engine_algorithm_id, + is_active_rule, } } } + +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString)] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum RoutingResultSource { + /// External Decision Engine + DecisionEngine, + /// Inbuilt Hyperswitch Routing Engine + HyperswitchRouting, +} diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs index 93ed2af4945..1b1b87b6b50 100644 --- a/crates/hyperswitch_domain_models/src/business_profile.rs +++ b/crates/hyperswitch_domain_models/src/business_profile.rs @@ -5,7 +5,7 @@ use common_utils::{ date_time, encryption::Encryption, errors::{CustomResult, ValidationError}, - ext_traits::OptionExt, + ext_traits::{OptionExt, ValueExt}, pii, type_name, types::keymanager, }; @@ -20,8 +20,10 @@ use diesel_models::business_profile::{ use error_stack::ResultExt; use masking::{ExposeInterface, PeekInterface, Secret}; -use crate::type_encryption::{crypto_operation, AsyncLift, CryptoOperation}; - +use crate::{ + errors::api_error_response, + type_encryption::{crypto_operation, AsyncLift, CryptoOperation}, +}; #[cfg(feature = "v1")] #[derive(Clone, Debug)] pub struct Profile { @@ -1194,6 +1196,61 @@ impl Profile { pub fn is_vault_sdk_enabled(&self) -> bool { self.external_vault_connector_details.is_some() } + + #[cfg(feature = "v1")] + pub fn get_payment_routing_algorithm( + &self, + ) -> CustomResult< + Option<api_models::routing::RoutingAlgorithmRef>, + api_error_response::ApiErrorResponse, + > { + self.routing_algorithm + .clone() + .map(|val| { + val.parse_value::<api_models::routing::RoutingAlgorithmRef>("RoutingAlgorithmRef") + }) + .transpose() + .change_context(api_error_response::ApiErrorResponse::InternalServerError) + .attach_printable("unable to deserialize routing algorithm ref from merchant account") + } + + #[cfg(feature = "v1")] + pub fn get_payout_routing_algorithm( + &self, + ) -> CustomResult< + Option<api_models::routing::RoutingAlgorithmRef>, + api_error_response::ApiErrorResponse, + > { + self.payout_routing_algorithm + .clone() + .map(|val| { + val.parse_value::<api_models::routing::RoutingAlgorithmRef>("RoutingAlgorithmRef") + }) + .transpose() + .change_context(api_error_response::ApiErrorResponse::InternalServerError) + .attach_printable( + "unable to deserialize payout routing algorithm ref from merchant account", + ) + } + + #[cfg(feature = "v1")] + pub fn get_frm_routing_algorithm( + &self, + ) -> CustomResult< + Option<api_models::routing::RoutingAlgorithmRef>, + api_error_response::ApiErrorResponse, + > { + self.frm_routing_algorithm + .clone() + .map(|val| { + val.parse_value::<api_models::routing::RoutingAlgorithmRef>("RoutingAlgorithmRef") + }) + .transpose() + .change_context(api_error_response::ApiErrorResponse::InternalServerError) + .attach_printable( + "unable to deserialize frm routing algorithm ref from merchant account", + ) + } } #[cfg(feature = "v2")] diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 53a657c2e6c..2ab004cccd1 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -460,76 +460,72 @@ pub async fn perform_static_routing_v1( ) .await?; - Ok(match cached_algorithm.as_ref() { - CachedAlgorithm::Single(conn) => vec![(**conn).clone()], + let backend_input = match transaction_data { + routing::TransactionData::Payment(payment_data) => make_dsl_input(payment_data)?, + #[cfg(feature = "payouts")] + routing::TransactionData::Payout(payout_data) => make_dsl_input_for_payouts(payout_data)?, + }; - CachedAlgorithm::Priority(plist) => plist.clone(), + let payment_id = match transaction_data { + routing::TransactionData::Payment(payment_data) => payment_data + .payment_attempt + .payment_id + .clone() + .get_string_repr() + .to_string(), + #[cfg(feature = "payouts")] + routing::TransactionData::Payout(payout_data) => { + payout_data.payout_attempt.payout_id.clone() + } + }; + + let routing_events_wrapper = utils::RoutingEventsWrapper::new( + state.tenant.tenant_id.clone(), + state.request_id, + payment_id, + business_profile.get_id().to_owned(), + business_profile.merchant_id.to_owned(), + "DecisionEngine: Euclid Static Routing".to_string(), + None, + true, + false, + ); + let de_euclid_connectors = perform_decision_euclid_routing( + state, + backend_input.clone(), + business_profile.get_id().get_string_repr().to_string(), + routing_events_wrapper + ) + .await + .map_err(|e| + // errors are ignored as this is just for diff checking as of now (optional flow). + logger::error!(decision_engine_euclid_evaluate_error=?e, "decision_engine_euclid: error in evaluation of rule") + ).unwrap_or_default(); + + let routable_connectors = match cached_algorithm.as_ref() { + CachedAlgorithm::Single(conn) => vec![(**conn).clone()], + CachedAlgorithm::Priority(plist) => plist.clone(), CachedAlgorithm::VolumeSplit(splits) => perform_volume_split(splits.to_vec()) .change_context(errors::RoutingError::ConnectorSelectionFailed)?, - CachedAlgorithm::Advanced(interpreter) => { - let backend_input = match transaction_data { - routing::TransactionData::Payment(payment_data) => make_dsl_input(payment_data)?, - #[cfg(feature = "payouts")] - routing::TransactionData::Payout(payout_data) => { - make_dsl_input_for_payouts(payout_data)? - } - }; - - let payment_id = match transaction_data { - routing::TransactionData::Payment(payment_data) => payment_data - .payment_attempt - .payment_id - .clone() - .get_string_repr() - .to_string(), - #[cfg(feature = "payouts")] - routing::TransactionData::Payout(payout_data) => { - payout_data.payout_attempt.payout_id.clone() - } - }; + execute_dsl_and_get_connector_v1(backend_input, interpreter)? + } + }; - let routing_events_wrapper = utils::RoutingEventsWrapper::new( - state.tenant.tenant_id.clone(), - state.request_id, - payment_id, - business_profile.get_id().to_owned(), - business_profile.merchant_id.to_owned(), - "DecisionEngine: Euclid Static Routing".to_string(), - None, - true, - false, - ); + utils::compare_and_log_result( + de_euclid_connectors.clone(), + routable_connectors.clone(), + "evaluate_routing".to_string(), + ); - let de_euclid_connectors = perform_decision_euclid_routing( - state, - backend_input.clone(), - business_profile.get_id().get_string_repr().to_string(), - routing_events_wrapper - ) - .await - .map_err(|e| - // errors are ignored as this is just for diff checking as of now (optional flow). - logger::error!(decision_engine_euclid_evaluate_error=?e, "decision_engine_euclid: error in evaluation of rule") - ).unwrap_or_default(); - let routable_connectors = execute_dsl_and_get_connector_v1(backend_input, interpreter)?; - let connectors = routable_connectors - .iter() - .map(|c| c.connector.to_string()) - .collect::<Vec<String>>(); - let de_connectors = de_euclid_connectors - .iter() - .map(|c| c.gateway_name.to_string()) - .collect::<Vec<String>>(); - utils::compare_and_log_result( - de_connectors, - connectors, - "evaluate_routing".to_string(), - ); - routable_connectors - } - }) + Ok(utils::select_routing_result( + state, + business_profile, + routable_connectors, + de_euclid_connectors, + ) + .await) } async fn ensure_algorithm_cached_v1( diff --git a/crates/router/src/core/payments/routing/utils.rs b/crates/router/src/core/payments/routing/utils.rs index d49aada7076..4296fea819f 100644 --- a/crates/router/src/core/payments/routing/utils.rs +++ b/crates/router/src/core/payments/routing/utils.rs @@ -1,19 +1,26 @@ -use std::{ - collections::{HashMap, HashSet}, - str::FromStr, -}; +use std::collections::{HashMap, HashSet}; use api_models::{ - open_router as or_types, routing as api_routing, - routing::{ConnectorSelection, RoutableConnectorChoice}, + open_router as or_types, + routing::{ + self as api_routing, ConnectorSelection, ConnectorVolumeSplit, RoutableConnectorChoice, + }, }; use async_trait::async_trait; -use common_utils::{ext_traits::BytesExt, id_type}; +use common_enums::TransactionType; +use common_utils::{ + ext_traits::{BytesExt, StringExt}, + id_type, +}; use diesel_models::{enums, routing_algorithm}; use error_stack::ResultExt; -use euclid::{backend::BackendInput, frontend::ast}; +use euclid::{ + backend::BackendInput, + frontend::ast::{self}, +}; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use external_services::grpc_client::dynamic_routing as ir_client; +use hyperswitch_domain_models::business_profile; use hyperswitch_interfaces::events::routing_api_logs as routing_events; use router_env::tracing_actix_web::RequestId; use serde::{Deserialize, Serialize}; @@ -40,17 +47,6 @@ pub trait DecisionEngineApiHandler { where Req: Serialize + Send + Sync + 'static + Clone, Res: Serialize + serde::de::DeserializeOwned + Send + 'static + std::fmt::Debug + Clone; - - async fn send_decision_engine_request_without_response_parsing<Req>( - state: &SessionState, - http_method: services::Method, - path: &str, - request_body: Option<Req>, - timeout: Option<u64>, - events_wrapper: Option<RoutingEventsWrapper<Req>>, - ) -> RoutingResult<()> - where - Req: Serialize + Send + Sync + 'static + Clone; } // Struct to implement the DecisionEngineApiHandler trait @@ -71,7 +67,7 @@ pub async fn build_and_send_decision_engine_http_request<Req, Res, ErrRes>( ) -> RoutingResult<RoutingEventsResponse<Res>> where Req: Serialize + Send + Sync + 'static + Clone, - Res: Serialize + serde::de::DeserializeOwned + std::fmt::Debug + Clone, + Res: Serialize + serde::de::DeserializeOwned + std::fmt::Debug + Clone + 'static, ErrRes: serde::de::DeserializeOwned + std::fmt::Debug + Clone + DecisionEngineErrorsInterface, { let decision_engine_base_url = &state.conf.open_router.url; @@ -109,6 +105,15 @@ where let resp = should_parse_response .then(|| { + if std::any::TypeId::of::<Res>() == std::any::TypeId::of::<String>() + && resp.response.is_empty() + { + return serde_json::from_str::<Res>("\"\"").change_context( + errors::RoutingError::OpenRouterError( + "Failed to parse empty response as String".into(), + ), + ); + } let response_type: Res = resp .response .parse_struct(std::any::type_name::<Res>()) @@ -209,35 +214,6 @@ impl DecisionEngineApiHandler for EuclidApiClient { logger::debug!(parsed_response = ?parsed_response, response_type = %std::any::type_name::<Res>(), euclid_request_path = %path, "decision_engine_euclid: Successfully parsed response from Euclid API"); Ok(event_response) } - - async fn send_decision_engine_request_without_response_parsing<Req>( - state: &SessionState, - http_method: services::Method, - path: &str, - request_body: Option<Req>, - timeout: Option<u64>, - events_wrapper: Option<RoutingEventsWrapper<Req>>, - ) -> RoutingResult<()> - where - Req: Serialize + Send + Sync + 'static + Clone, - { - let event_response = - build_and_send_decision_engine_http_request::<Req, (), DeErrorResponse>( - state, - http_method, - path, - request_body, - timeout, - "not parsing response", - events_wrapper, - ) - .await?; - - let response = event_response.response; - - logger::debug!(euclid_response = ?response, euclid_request_path = %path, "decision_engine_routing: Received raw response from Euclid API"); - Ok(()) - } } #[async_trait] @@ -275,35 +251,6 @@ impl DecisionEngineApiHandler for ConfigApiClient { logger::debug!(parsed_response = ?parsed_response, response_type = %std::any::type_name::<Res>(), decision_engine_request_path = %path, "decision_engine_config: Successfully parsed response from Decision Engine config API"); Ok(events_response) } - - async fn send_decision_engine_request_without_response_parsing<Req>( - state: &SessionState, - http_method: services::Method, - path: &str, - request_body: Option<Req>, - timeout: Option<u64>, - events_wrapper: Option<RoutingEventsWrapper<Req>>, - ) -> RoutingResult<()> - where - Req: Serialize + Send + Sync + 'static + Clone, - { - let event_response = - build_and_send_decision_engine_http_request::<Req, (), DeErrorResponse>( - state, - http_method, - path, - request_body, - timeout, - "not parsing response", - events_wrapper, - ) - .await?; - - let response = event_response.response; - - logger::debug!(decision_engine_response = ?response, decision_engine_request_path = %path, "decision_engine_config: Received raw response from Decision Engine config API"); - Ok(()) - } } #[async_trait] @@ -342,35 +289,6 @@ impl DecisionEngineApiHandler for SRApiClient { logger::debug!(parsed_response = ?parsed_response, response_type = %std::any::type_name::<Res>(), decision_engine_request_path = %path, "decision_engine_config: Successfully parsed response from Decision Engine config API"); Ok(events_response) } - - async fn send_decision_engine_request_without_response_parsing<Req>( - state: &SessionState, - http_method: services::Method, - path: &str, - request_body: Option<Req>, - timeout: Option<u64>, - events_wrapper: Option<RoutingEventsWrapper<Req>>, - ) -> RoutingResult<()> - where - Req: Serialize + Send + Sync + 'static + Clone, - { - let event_response = - build_and_send_decision_engine_http_request::<Req, (), or_types::ErrorResponse>( - state, - http_method, - path, - request_body, - timeout, - "not parsing response", - events_wrapper, - ) - .await?; - - let response = event_response.response; - - logger::debug!(decision_engine_response = ?response, decision_engine_request_path = %path, "decision_engine_config: Received raw response from Decision Engine config API"); - Ok(()) - } } const EUCLID_API_TIMEOUT: u64 = 5; @@ -380,7 +298,7 @@ pub async fn perform_decision_euclid_routing( input: BackendInput, created_by: String, events_wrapper: RoutingEventsWrapper<RoutingEvaluateRequest>, -) -> RoutingResult<Vec<ConnectorInfo>> { +) -> RoutingResult<Vec<RoutableConnectorChoice>> { logger::debug!("decision_engine_euclid: evaluate api call for euclid routing evaluation"); let mut events_wrapper = events_wrapper; @@ -413,47 +331,8 @@ pub async fn perform_decision_euclid_routing( status_code: 500, })?; - let connector_info = euclid_response.evaluated_output.clone(); - let mut routable_connectors = Vec::new(); - for conn in &connector_info { - let connector = common_enums::RoutableConnectors::from_str(conn.gateway_name.as_str()) - .change_context(errors::RoutingError::GenericConversionError { - from: "String".to_string(), - to: "RoutableConnectors".to_string(), - }) - .attach_printable( - "decision_engine_euclid: unable to convert String to RoutableConnectors", - ) - .ok(); - let mca_id = conn - .gateway_id - .as_ref() - .map(|id| { - id_type::MerchantConnectorAccountId::wrap(id.to_string()) - .change_context(errors::RoutingError::GenericConversionError { - from: "String".to_string(), - to: "MerchantConnectorAccountId".to_string(), - }) - .attach_printable( - "decision_engine_euclid: unable to convert MerchantConnectorAccountId from string", - ) - }) - .transpose() - .ok() - .flatten(); - - if let Some(conn) = connector { - let connector = RoutableConnectorChoice { - choice_kind: api_routing::RoutableChoiceKind::FullStruct, - connector: conn, - merchant_connector_id: mca_id, - }; - routable_connectors.push(connector); - } - } - routing_event.set_routing_approach(RoutingApproach::StaticRouting.to_string()); - routing_event.set_routable_connectors(routable_connectors); + routing_event.set_routable_connectors(euclid_response.evaluated_output.clone()); state.event_handler.log_event(&routing_event); // Need to log euclid response event here @@ -498,7 +377,7 @@ pub async fn link_de_euclid_routing_algorithm( ) -> RoutingResult<()> { logger::debug!("decision_engine_euclid: link api call for euclid routing algorithm"); - EuclidApiClient::send_decision_engine_request_without_response_parsing( + EuclidApiClient::send_decision_engine_request::<_, String>( state, services::Method::Post, "routing/activate", @@ -542,6 +421,31 @@ pub async fn list_de_euclid_routing_algorithms( .collect::<Vec<_>>()) } +pub async fn list_de_euclid_active_routing_algorithm( + state: &SessionState, + created_by: String, +) -> RoutingResult<Vec<api_routing::RoutingDictionaryRecord>> { + logger::debug!("decision_engine_euclid: list api call for euclid active routing algorithm"); + let response: Vec<RoutingAlgorithmRecord> = EuclidApiClient::send_decision_engine_request( + state, + services::Method::Post, + format!("routing/list/active/{created_by}").as_str(), + None::<()>, + Some(EUCLID_API_TIMEOUT), + None, + ) + .await? + .response + .ok_or(errors::RoutingError::OpenRouterError( + "Response from decision engine API is empty".to_string(), + ))?; + + Ok(response + .into_iter() + .map(|record| routing_algorithm::RoutingProfileMetadata::from(record).foreign_into()) + .collect()) +} + pub fn compare_and_log_result<T: RoutingEq<T> + Serialize>( de_result: Vec<T>, result: Vec<T>, @@ -566,7 +470,8 @@ pub trait RoutingEq<T> { impl RoutingEq<Self> for api_routing::RoutingDictionaryRecord { fn is_equal(a: &Self, b: &Self) -> bool { - a.name == b.name + a.id == b.id + && a.name == b.name && a.profile_id == b.profile_id && a.description == b.description && a.kind == b.kind @@ -580,6 +485,14 @@ impl RoutingEq<Self> for String { } } +impl RoutingEq<Self> for RoutableConnectorChoice { + fn is_equal(a: &Self, b: &Self) -> bool { + a.connector.eq(&b.connector) + && a.choice_kind.eq(&b.choice_kind) + && a.merchant_connector_id.eq(&b.merchant_connector_id) + } +} + pub fn to_json_string<T: Serialize>(value: &T) -> String { serde_json::to_string(value) .map_err(|_| errors::RoutingError::GenericConversionError { @@ -772,8 +685,30 @@ pub struct RoutingEvaluateRequest { pub struct RoutingEvaluateResponse { pub status: String, pub output: serde_json::Value, - pub evaluated_output: Vec<ConnectorInfo>, - pub eligible_connectors: Vec<ConnectorInfo>, + #[serde(deserialize_with = "deserialize_connector_choices")] + pub evaluated_output: Vec<RoutableConnectorChoice>, + #[serde(deserialize_with = "deserialize_connector_choices")] + pub eligible_connectors: Vec<RoutableConnectorChoice>, +} + +/// Routable Connector chosen for a payment +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct DeRoutableConnectorChoice { + pub gateway_name: common_enums::RoutableConnectors, + pub gateway_id: Option<id_type::MerchantConnectorAccountId>, +} + +fn deserialize_connector_choices<'de, D>( + deserializer: D, +) -> Result<Vec<RoutableConnectorChoice>, D::Error> +where + D: serde::Deserializer<'de>, +{ + let infos = Vec::<DeRoutableConnectorChoice>::deserialize(deserializer)?; + Ok(infos + .into_iter() + .map(RoutableConnectorChoice::from) + .collect()) } #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] @@ -794,12 +729,24 @@ pub enum ValueType { MetadataVariant(MetadataValue), /// Represents a arbitrary String value StrValue(String), + /// Represents a global reference, which is a reference to a global variable GlobalRef(String), + /// Represents an array of numbers. This is basically used for + /// "one of the given numbers" operations + /// eg: payment.method.amount = (1, 2, 3) + NumberArray(Vec<u64>), + /// Similar to NumberArray but for enum variants + /// eg: payment.method.cardtype = (debit, credit) + EnumVariantArray(Vec<String>), + /// Like a number array but can include comparisons. Useful for + /// conditions like "500 < amount < 1000" + /// eg: payment.amount = (> 500, < 1000) + NumberComparisonArray(Vec<NumberComparison>), } pub type Metadata = HashMap<String, serde_json::Value>; /// Represents a number comparison for "NumberComparisonArrayValue" -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct NumberComparison { pub comparison_type: ComparisonType, @@ -917,9 +864,20 @@ impl ConnectorInfo { } } +impl From<DeRoutableConnectorChoice> for RoutableConnectorChoice { + fn from(choice: DeRoutableConnectorChoice) -> Self { + Self { + choice_kind: api_routing::RoutableChoiceKind::FullStruct, + connector: choice.gateway_name, + merchant_connector_id: choice.gateway_id, + } + } +} + #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Output { + Single(ConnectorInfo), Priority(Vec<ConnectorInfo>), VolumeSplit(Vec<VolumeSplit<ConnectorInfo>>), VolumeSplitPriority(Vec<VolumeSplit<Vec<ConnectorInfo>>>), @@ -949,12 +907,73 @@ pub struct RoutingRule { pub description: Option<String>, pub metadata: Option<RoutingMetadata>, pub created_by: String, + #[serde(default)] + pub algorithm_for: AlgorithmType, pub algorithm: StaticRoutingAlgorithm, } +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize, strum::Display)] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum AlgorithmType { + #[default] + Payment, + Payout, + ThreeDsAuthentication, +} + +impl From<TransactionType> for AlgorithmType { + fn from(transaction_type: TransactionType) -> Self { + match transaction_type { + TransactionType::Payment => Self::Payment, + TransactionType::Payout => Self::Payout, + TransactionType::ThreeDsAuthentication => Self::ThreeDsAuthentication, + } + } +} + +impl From<RoutableConnectorChoice> for ConnectorInfo { + fn from(c: RoutableConnectorChoice) -> Self { + Self { + gateway_name: c.connector.to_string(), + gateway_id: c + .merchant_connector_id + .map(|mca_id| mca_id.get_string_repr().to_string()), + } + } +} + +impl From<Box<RoutableConnectorChoice>> for ConnectorInfo { + fn from(c: Box<RoutableConnectorChoice>) -> Self { + Self { + gateway_name: c.connector.to_string(), + gateway_id: c + .merchant_connector_id + .map(|mca_id| mca_id.get_string_repr().to_string()), + } + } +} + +impl From<ConnectorVolumeSplit> for VolumeSplit<ConnectorInfo> { + fn from(v: ConnectorVolumeSplit) -> Self { + Self { + split: v.split, + output: ConnectorInfo { + gateway_name: v.connector.connector.to_string(), + gateway_id: v + .connector + .merchant_connector_id + .map(|mca_id| mca_id.get_string_repr().to_string()), + }, + } + } +} #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] pub enum StaticRoutingAlgorithm { + Single(Box<ConnectorInfo>), + Priority(Vec<ConnectorInfo>), + VolumeSplit(Vec<VolumeSplit<ConnectorInfo>>), Advanced(Program), } @@ -962,7 +981,6 @@ pub enum StaticRoutingAlgorithm { #[serde(rename_all = "snake_case")] pub struct RoutingMetadata { pub kind: enums::RoutingAlgorithmKind, - pub algorithm_for: enums::TransactionType, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] @@ -981,7 +999,8 @@ pub struct RoutingAlgorithmRecord { pub name: String, pub description: Option<String>, pub created_by: id_type::ProfileId, - pub algorithm_data: Program, + pub algorithm_data: StaticRoutingAlgorithm, + pub algorithm_for: TransactionType, pub metadata: Option<RoutingMetadata>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, @@ -989,12 +1008,11 @@ pub struct RoutingAlgorithmRecord { impl From<RoutingAlgorithmRecord> for routing_algorithm::RoutingProfileMetadata { fn from(record: RoutingAlgorithmRecord) -> Self { - let (kind, algorithm_for) = match record.metadata { - Some(metadata) => (metadata.kind, metadata.algorithm_for), - None => ( - enums::RoutingAlgorithmKind::Advanced, - enums::TransactionType::default(), - ), + let kind = match record.algorithm_data { + StaticRoutingAlgorithm::Single(_) => enums::RoutingAlgorithmKind::Single, + StaticRoutingAlgorithm::Priority(_) => enums::RoutingAlgorithmKind::Priority, + StaticRoutingAlgorithm::VolumeSplit(_) => enums::RoutingAlgorithmKind::VolumeSplit, + StaticRoutingAlgorithm::Advanced(_) => enums::RoutingAlgorithmKind::Advanced, }; Self { profile_id: record.created_by, @@ -1004,7 +1022,7 @@ impl From<RoutingAlgorithmRecord> for routing_algorithm::RoutingProfileMetadata kind, created_at: record.created_at, modified_at: record.modified_at, - algorithm_for, + algorithm_for: record.algorithm_for, } } } @@ -1106,8 +1124,20 @@ fn convert_value(v: ast::ValueType) -> RoutingResult<ValueType> { value: m.value, })), StrValue(s) => Ok(ValueType::StrValue(s)), - _ => Err(error_stack::Report::new( - errors::RoutingError::InvalidRoutingAlgorithmStructure, + + NumberArray(arr) => Ok(ValueType::NumberArray( + arr.into_iter() + .map(|n| n.get_amount_as_i64().try_into().unwrap_or_default()) + .collect(), + )), + EnumVariantArray(arr) => Ok(ValueType::EnumVariantArray(arr)), + NumberComparisonArray(arr) => Ok(ValueType::NumberComparisonArray( + arr.into_iter() + .map(|nc| NumberComparison { + comparison_type: convert_comparison_type(nc.comparison_type), + number: nc.number.get_amount_as_i64().try_into().unwrap_or_default(), + }) + .collect(), )), } } @@ -1136,6 +1166,29 @@ fn stringify_choice(c: RoutableConnectorChoice) -> ConnectorInfo { ) } +pub async fn select_routing_result<T>( + state: &SessionState, + business_profile: &business_profile::Profile, + hyperswitch_result: T, + de_result: T, +) -> T { + let routing_result_source: Option<api_routing::RoutingResultSource> = state + .store + .find_config_by_key(&format!( + "routing_result_source_{0}", + business_profile.get_id().get_string_repr() + )) + .await + .map(|c| c.config.parse_enum("RoutingResultSource").ok()) + .unwrap_or(None); //Ignore errors so that we can use the hyperswitch result as a fallback + if let Some(api_routing::RoutingResultSource::DecisionEngine) = routing_result_source { + logger::debug!(business_profile_id=?business_profile.get_id(), "Using Decision Engine routing result"); + de_result + } else { + logger::debug!(business_profile_id=?business_profile.get_id(), "Using Hyperswitch routing result"); + hyperswitch_result + } +} pub trait DecisionEngineErrorsInterface { fn get_error_message(&self) -> String; fn get_error_code(&self) -> String; diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs index 1ab333ef139..b52fc966721 100644 --- a/crates/router/src/core/routing.rs +++ b/crates/router/src/core/routing.rs @@ -25,8 +25,6 @@ use external_services::grpc_client::dynamic_routing::{ use helpers::update_decision_engine_dynamic_routing_setup; use hyperswitch_domain_models::{mandates, payment_address}; use payment_methods::helpers::StorageErrorExt; -#[cfg(all(feature = "v1", feature = "dynamic_routing"))] -use router_env::logger; use rustc_hash::FxHashSet; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use storage_impl::redis::cache; @@ -167,7 +165,7 @@ pub async fn retrieve_merchant_routing_dictionary( routing_metadata, ); - let result = routing_metadata + let mut result = routing_metadata .into_iter() .map(ForeignInto::foreign_into) .collect::<Vec<_>>(); @@ -175,7 +173,7 @@ pub async fn retrieve_merchant_routing_dictionary( if let Some(profile_ids) = profile_id_list { let mut de_result: Vec<routing_types::RoutingDictionaryRecord> = vec![]; // DE_TODO: need to replace this with batch API call to reduce the number of network calls - for profile_id in profile_ids { + for profile_id in &profile_ids { let list_request = ListRountingAlgorithmsRequest { created_by: profile_id.get_string_repr().to_string(), }; @@ -186,8 +184,32 @@ pub async fn retrieve_merchant_routing_dictionary( }) .ok() // Avoid throwing error if Decision Engine is not available or other errors .map(|mut de_routing| de_result.append(&mut de_routing)); + // filter de_result based on transaction type + de_result.retain(|record| record.algorithm_for == Some(transaction_type)); + // append dynamic routing algorithms to de_result + de_result.append( + &mut result + .clone() + .into_iter() + .filter(|record: &routing_types::RoutingDictionaryRecord| { + record.kind == routing_types::RoutingAlgorithmKind::Dynamic + }) + .collect::<Vec<_>>(), + ); } - compare_and_log_result(de_result, result.clone(), "list_routing".to_string()); + compare_and_log_result( + de_result.clone(), + result.clone(), + "list_routing".to_string(), + ); + result = build_list_routing_result( + &state, + merchant_context, + &result, + &de_result, + profile_ids.clone(), + ) + .await?; } metrics::ROUTING_MERCHANT_DICTIONARY_RETRIEVE_SUCCESS_RESPONSE.add(1, &[]); @@ -196,6 +218,47 @@ pub async fn retrieve_merchant_routing_dictionary( )) } +async fn build_list_routing_result( + state: &SessionState, + merchant_context: domain::MerchantContext, + hs_results: &[routing_types::RoutingDictionaryRecord], + de_results: &[routing_types::RoutingDictionaryRecord], + profile_ids: Vec<common_utils::id_type::ProfileId>, +) -> RouterResult<Vec<routing_types::RoutingDictionaryRecord>> { + let db = state.store.as_ref(); + let key_manager_state = &state.into(); + let mut list_result: Vec<routing_types::RoutingDictionaryRecord> = vec![]; + for profile_id in profile_ids.iter() { + let by_profile = + |rec: &&routing_types::RoutingDictionaryRecord| &rec.profile_id == profile_id; + let de_result_for_profile = de_results.iter().filter(by_profile).cloned().collect(); + let hs_result_for_profile = hs_results.iter().filter(by_profile).cloned().collect(); + let business_profile = core_utils::validate_and_get_business_profile( + db, + key_manager_state, + merchant_context.get_merchant_key_store(), + Some(profile_id), + merchant_context.get_merchant_account().get_id(), + ) + .await? + .get_required_value("Profile") + .change_context(errors::ApiErrorResponse::ProfileNotFound { + id: profile_id.get_string_repr().to_owned(), + })?; + + list_result.append( + &mut select_routing_result( + state, + &business_profile, + hs_result_for_profile, + de_result_for_profile, + ) + .await, + ); + } + Ok(list_result) +} + #[cfg(feature = "v2")] pub async fn create_routing_algorithm_under_profile( state: SessionState, @@ -280,8 +343,6 @@ pub async fn create_routing_algorithm_under_profile( ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { use api_models::routing::StaticRoutingAlgorithm as EuclidAlgorithm; - use crate::services::logger; - metrics::ROUTING_CREATE_REQUEST_RECEIVED.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); @@ -344,61 +405,84 @@ pub async fn create_routing_algorithm_under_profile( let mut decision_engine_routing_id: Option<String> = None; - if let Some(EuclidAlgorithm::Advanced(program)) = request.algorithm.clone() { - match program.try_into() { - Ok(internal_program) => { - let routing_rule = RoutingRule { - rule_id: None, - name: name.clone(), - description: Some(description.clone()), - created_by: profile_id.get_string_repr().to_string(), - algorithm: internal_program, - metadata: Some(RoutingMetadata { - kind: algorithm.get_kind().foreign_into(), - algorithm_for: transaction_type.to_owned(), - }), - }; - - match create_de_euclid_routing_algo(&state, &routing_rule).await { - Ok(id) => { - decision_engine_routing_id = Some(id); - } - Err(e) - if matches!( - e.current_context(), - errors::RoutingError::DecisionEngineValidationError(_) - ) => + if let Some(euclid_algorithm) = request.algorithm.clone() { + let maybe_static_algorithm: Option<StaticRoutingAlgorithm> = match euclid_algorithm { + EuclidAlgorithm::Advanced(program) => match program.try_into() { + Ok(internal_program) => Some(StaticRoutingAlgorithm::Advanced(internal_program)), + Err(e) => { + router_env::logger::error!(decision_engine_error = ?e, "decision_engine_euclid"); + None + } + }, + EuclidAlgorithm::Single(conn) => { + Some(StaticRoutingAlgorithm::Single(Box::new(conn.into()))) + } + EuclidAlgorithm::Priority(connectors) => { + let converted: Vec<ConnectorInfo> = + connectors.into_iter().map(Into::into).collect(); + Some(StaticRoutingAlgorithm::Priority(converted)) + } + EuclidAlgorithm::VolumeSplit(splits) => { + let converted: Vec<VolumeSplit<ConnectorInfo>> = + splits.into_iter().map(Into::into).collect(); + Some(StaticRoutingAlgorithm::VolumeSplit(converted)) + } + EuclidAlgorithm::ThreeDsDecisionRule(_) => { + router_env::logger::error!( + "decision_engine_euclid: ThreeDsDecisionRules are not yet implemented" + ); + None + } + }; + + if let Some(static_algorithm) = maybe_static_algorithm { + let routing_rule = RoutingRule { + rule_id: Some(algorithm_id.clone().get_string_repr().to_owned()), + name: name.clone(), + description: Some(description.clone()), + created_by: profile_id.get_string_repr().to_string(), + algorithm: static_algorithm, + algorithm_for: transaction_type.into(), + metadata: Some(RoutingMetadata { + kind: algorithm.get_kind().foreign_into(), + }), + }; + + match create_de_euclid_routing_algo(&state, &routing_rule).await { + Ok(id) => { + decision_engine_routing_id = Some(id); + } + Err(e) + if matches!( + e.current_context(), + errors::RoutingError::DecisionEngineValidationError(_) + ) => + { + if let errors::RoutingError::DecisionEngineValidationError(msg) = + e.current_context() { - if let errors::RoutingError::DecisionEngineValidationError(msg) = - e.current_context() - { - logger::error!( - decision_engine_euclid_error = ?msg, - decision_engine_euclid_request = ?routing_rule, - "failed to create rule in decision_engine with validation error" - ); - } - } - Err(e) => { - logger::error!( - decision_engine_euclid_error = ?e, + router_env::logger::error!( + decision_engine_euclid_error = ?msg, decision_engine_euclid_request = ?routing_rule, - "failed to create rule in decision_engine" + "failed to create rule in decision_engine with validation error" ); } } + Err(e) => { + router_env::logger::error!( + decision_engine_euclid_error = ?e, + decision_engine_euclid_request = ?routing_rule, + "failed to create rule in decision_engine" + ); + } } - Err(e) => { - // errors are ignored as this is just for diff checking as of now (optional flow). - logger::error!(decision_engine_error=?e, "decision_engine_euclid"); - } - }; + } } if decision_engine_routing_id.is_some() { - logger::info!(routing_flow=?"create_euclid_routing_algorithm", is_equal=?"true", "decision_engine_euclid"); + router_env::logger::info!(routing_flow=?"create_euclid_routing_algorithm", is_equal=?"true", "decision_engine_euclid"); } else { - logger::info!(routing_flow=?"create_euclid_routing_algorithm", is_equal=?"false", "decision_engine_euclid"); + router_env::logger::info!(routing_flow=?"create_euclid_routing_algorithm", is_equal=?"false", "decision_engine_euclid"); } let timestamp = common_utils::date_time::now(); @@ -1276,7 +1360,23 @@ pub async fn retrieve_linked_routing_config( ) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; - active_algorithms.push(record.foreign_into()); + let hs_records: Vec<routing_types::RoutingDictionaryRecord> = + vec![record.foreign_into()]; + let de_records = retrieve_decision_engine_active_rules( + &state, + &transaction_type, + profile_id.clone(), + hs_records.clone(), + ) + .await; + compare_and_log_result( + de_records.clone(), + hs_records.clone(), + "list_active_routing".to_string(), + ); + active_algorithms.append( + &mut select_routing_result(&state, &business_profile, hs_records, de_records).await, + ); } // Handle dynamic routing algorithms @@ -1319,7 +1419,9 @@ pub async fn retrieve_linked_routing_config( ) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; - active_algorithms.push(record.foreign_into()); + if record.algorithm_for == transaction_type { + active_algorithms.push(record.foreign_into()); + } } } @@ -1328,6 +1430,32 @@ pub async fn retrieve_linked_routing_config( routing_types::LinkedRoutingConfigRetrieveResponse::ProfileBased(active_algorithms), )) } + +pub async fn retrieve_decision_engine_active_rules( + state: &SessionState, + transaction_type: &enums::TransactionType, + profile_id: common_utils::id_type::ProfileId, + hs_records: Vec<routing_types::RoutingDictionaryRecord>, +) -> Vec<routing_types::RoutingDictionaryRecord> { + let mut de_records = + list_de_euclid_active_routing_algorithm(state, profile_id.get_string_repr().to_owned()) + .await + .map_err(|e| { + router_env::logger::error!(?e, "Failed to list DE Euclid active routing algorithm"); + }) + .ok() // Avoid throwing error if Decision Engine is not available or other errors thrown + .unwrap_or_default(); + // Use Hs records to list the dynamic algorithms as DE is not supporting dynamic algorithms in HS standard + let mut dynamic_algos = hs_records + .into_iter() + .filter(|record| record.kind == routing_types::RoutingAlgorithmKind::Dynamic) + .collect::<Vec<_>>(); + de_records.append(&mut dynamic_algos); + de_records + .into_iter() + .filter(|r| r.algorithm_for == Some(*transaction_type)) + .collect::<Vec<_>>() +} // List all the default fallback algorithms under all the profile under a merchant pub async fn retrieve_default_routing_config_for_profiles( state: SessionState, @@ -1707,7 +1835,7 @@ pub async fn success_based_routing_update_configs( cache_entries_to_redact, ) .await - .map_err(|e| logger::error!("unable to publish into the redact channel for evicting the success based routing config cache {e:?}")); + .map_err(|e| router_env::logger::error!("unable to publish into the redact channel for evicting the success based routing config cache {e:?}")); let new_record = record.foreign_into(); @@ -1811,7 +1939,7 @@ pub async fn elimination_routing_update_configs( cache_entries_to_redact, ) .await - .map_err(|e| logger::error!("unable to publish into the redact channel for evicting the elimination routing config cache {e:?}")).ok(); + .map_err(|e| router_env::logger::error!("unable to publish into the redact channel for evicting the elimination routing config cache {e:?}")).ok(); let new_record = record.foreign_into(); @@ -2148,7 +2276,7 @@ pub async fn contract_based_routing_update_configs( cache_entries_to_redact, ) .await - .map_err(|e| logger::error!("unable to publish into the redact channel for evicting the contract based routing config cache {e:?}")); + .map_err(|e| router_env::logger::error!("unable to publish into the redact channel for evicting the contract based routing config cache {e:?}")); let new_record = record.foreign_into(); @@ -2324,15 +2452,13 @@ pub async fn migrate_rules_for_profile( ) -> RouterResult<routing_types::RuleMigrationResult> { use api_models::routing::StaticRoutingAlgorithm as EuclidAlgorithm; - use crate::services::logger; - let profile_id = query_params.profile_id.clone(); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let merchant_key_store = merchant_context.get_merchant_key_store(); let merchant_id = merchant_context.get_merchant_account().get_id(); - core_utils::validate_and_get_business_profile( + let business_profile = core_utils::validate_and_get_business_profile( db, key_manager_state, merchant_key_store, @@ -2345,7 +2471,29 @@ pub async fn migrate_rules_for_profile( id: profile_id.get_string_repr().to_owned(), })?; - let routing_metadatas: Vec<diesel_models::routing_algorithm::RoutingProfileMetadata> = state + #[cfg(feature = "v1")] + let active_payment_routing_ids: Vec<Option<common_utils::id_type::RoutingId>> = vec![ + business_profile + .get_payment_routing_algorithm() + .attach_printable("Failed to get payment routing algorithm")? + .unwrap_or_default() + .algorithm_id, + business_profile + .get_payout_routing_algorithm() + .attach_printable("Failed to get payout routing algorithm")? + .unwrap_or_default() + .algorithm_id, + business_profile + .get_frm_routing_algorithm() + .attach_printable("Failed to get frm routing algorithm")? + .unwrap_or_default() + .algorithm_id, + ]; + + #[cfg(feature = "v2")] + let active_payment_routing_ids = [business_profile.routing_algorithm_id.clone()]; + + let routing_metadatas = state .store .list_routing_algorithm_metadata_by_profile_id( &profile_id, @@ -2358,111 +2506,119 @@ pub async fn migrate_rules_for_profile( let mut response_list = Vec::new(); let mut error_list = Vec::new(); - for routing_metadata in routing_metadatas - .into_iter() - .filter(|algo| algo.metadata_is_advanced_rule_for_payments()) - { - match db - .find_routing_algorithm_by_profile_id_algorithm_id( - &profile_id, - &routing_metadata.algorithm_id, - ) + let mut push_error = |algorithm_id, msg: String| { + error_list.push(RuleMigrationError { + profile_id: profile_id.clone(), + algorithm_id, + error: msg, + }); + }; + + for routing_metadata in routing_metadatas { + let algorithm_id = routing_metadata.algorithm_id.clone(); + let algorithm = match db + .find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algorithm_id) .await { - Ok(algorithm) => { - let parsed_result = algorithm - .algorithm_data - .parse_value::<EuclidAlgorithm>("EuclidAlgorithm"); - - match parsed_result { - Ok(EuclidAlgorithm::Advanced(program)) => match program.try_into() { - Ok(internal_program) => { - let routing_rule = RoutingRule { - rule_id: Some( - algorithm.algorithm_id.clone().get_string_repr().to_string(), - ), - name: algorithm.name.clone(), - description: algorithm.description.clone(), - created_by: profile_id.get_string_repr().to_string(), - algorithm: StaticRoutingAlgorithm::Advanced(internal_program), - metadata: None, - }; - - let result = create_de_euclid_routing_algo(&state, &routing_rule).await; - - match result { - Ok(decision_engine_routing_id) => { - let response = RuleMigrationResponse { - profile_id: profile_id.clone(), - euclid_algorithm_id: algorithm.algorithm_id.clone(), - decision_engine_algorithm_id: decision_engine_routing_id, - }; - response_list.push(response); - } - Err(err) => { - logger::error!( - decision_engine_rule_migration_error = ?err, - algorithm_id = ?algorithm.algorithm_id, - "Failed to insert into decision engine" - ); - error_list.push(RuleMigrationError { - profile_id: profile_id.clone(), - algorithm_id: algorithm.algorithm_id.clone(), - error: format!("Insertion error: {:?}", err), - }); - } - } - } - Err(e) => { - logger::error!( - decision_engine_rule_migration_error = ?e, - algorithm_id = ?algorithm.algorithm_id, - "Failed to convert program" - ); - error_list.push(RuleMigrationError { - profile_id: profile_id.clone(), - algorithm_id: algorithm.algorithm_id.clone(), - error: format!("Program conversion error: {:?}", e), - }); - } - }, - Err(e) => { - logger::error!( - decision_engine_rule_migration_error = ?e, - algorithm_id = ?algorithm.algorithm_id, - "Failed to parse EuclidAlgorithm" - ); - error_list.push(RuleMigrationError { - profile_id: profile_id.clone(), - algorithm_id: algorithm.algorithm_id.clone(), - error: format!("JSON parse error: {:?}", e), - }); - } - _ => { - logger::info!( - "decision_engine_rule_migration_error: Skipping non-advanced algorithm {:?}", - algorithm.algorithm_id - ); - error_list.push(RuleMigrationError { - profile_id: profile_id.clone(), - algorithm_id: algorithm.algorithm_id.clone(), - error: "Not an advanced algorithm".to_string(), - }); - } + Ok(algo) => algo, + Err(e) => { + router_env::logger::error!(?e, ?algorithm_id, "Failed to fetch routing algorithm"); + push_error(algorithm_id, format!("Fetch error: {:?}", e)); + continue; + } + }; + + let parsed_result = algorithm + .algorithm_data + .parse_value::<EuclidAlgorithm>("EuclidAlgorithm"); + + let maybe_static_algorithm: Option<StaticRoutingAlgorithm> = match parsed_result { + Ok(EuclidAlgorithm::Advanced(program)) => match program.try_into() { + Ok(ip) => Some(StaticRoutingAlgorithm::Advanced(ip)), + Err(e) => { + router_env::logger::error!( + ?e, + ?algorithm_id, + "Failed to convert advanced program" + ); + push_error(algorithm_id.clone(), format!("Conversion error: {:?}", e)); + None } + }, + Ok(EuclidAlgorithm::Single(conn)) => { + Some(StaticRoutingAlgorithm::Single(Box::new(conn.into()))) } - Err(e) => { - logger::error!( - decision_engine_rule_migration_error = ?e, - algorithm_id = ?routing_metadata.algorithm_id, - "Failed to fetch routing algorithm" + Ok(EuclidAlgorithm::Priority(connectors)) => Some(StaticRoutingAlgorithm::Priority( + connectors.into_iter().map(Into::into).collect(), + )), + Ok(EuclidAlgorithm::VolumeSplit(splits)) => Some(StaticRoutingAlgorithm::VolumeSplit( + splits.into_iter().map(Into::into).collect(), + )), + Ok(EuclidAlgorithm::ThreeDsDecisionRule(_)) => { + router_env::logger::info!( + ?algorithm_id, + "Skipping 3DS rule migration (not supported yet)" ); - error_list.push(RuleMigrationError { + push_error(algorithm_id.clone(), "3DS migration not implemented".into()); + None + } + Err(e) => { + router_env::logger::error!(?e, ?algorithm_id, "Failed to parse algorithm"); + push_error(algorithm_id.clone(), format!("Parse error: {:?}", e)); + None + } + }; + + let Some(static_algorithm) = maybe_static_algorithm else { + continue; + }; + + let routing_rule = RoutingRule { + rule_id: Some(algorithm.algorithm_id.clone().get_string_repr().to_string()), + name: algorithm.name.clone(), + description: algorithm.description.clone(), + created_by: profile_id.get_string_repr().to_string(), + algorithm: static_algorithm, + algorithm_for: algorithm.algorithm_for.into(), + metadata: Some(RoutingMetadata { + kind: algorithm.kind, + }), + }; + + match create_de_euclid_routing_algo(&state, &routing_rule).await { + Ok(decision_engine_routing_id) => { + let mut is_active_rule = false; + if active_payment_routing_ids.contains(&Some(algorithm.algorithm_id.clone())) { + link_de_euclid_routing_algorithm( + &state, + ActivateRoutingConfigRequest { + created_by: profile_id.get_string_repr().to_string(), + routing_algorithm_id: decision_engine_routing_id.clone(), + }, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to link active routing algorithm")?; + is_active_rule = true; + } + response_list.push(RuleMigrationResponse { profile_id: profile_id.clone(), - algorithm_id: routing_metadata.algorithm_id.clone(), - error: format!("Fetch error: {:?}", e), + euclid_algorithm_id: algorithm.algorithm_id.clone(), + decision_engine_algorithm_id: decision_engine_routing_id, + is_active_rule, }); } + Err(err) => { + router_env::logger::error!( + decision_engine_rule_migration_error = ?err, + algorithm_id = ?algorithm.algorithm_id, + "Failed to insert into decision engine" + ); + push_error( + algorithm.algorithm_id.clone(), + format!("Insertion error: {:?}", err), + ); + } } } diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 666d0020260..e73c9c5bc75 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -72,6 +72,7 @@ pub const CONTRACT_BASED_DYNAMIC_ROUTING_ALGORITHM: &str = pub const DECISION_ENGINE_RULE_CREATE_ENDPOINT: &str = "rule/create"; pub const DECISION_ENGINE_RULE_UPDATE_ENDPOINT: &str = "rule/update"; +pub const DECISION_ENGINE_RULE_GET_ENDPOINT: &str = "rule/get"; pub const DECISION_ENGINE_RULE_DELETE_ENDPOINT: &str = "rule/delete"; pub const DECISION_ENGINE_MERCHANT_BASE_ENDPOINT: &str = "merchant-account"; pub const DECISION_ENGINE_MERCHANT_CREATE_ENDPOINT: &str = "merchant-account/create"; @@ -2433,6 +2434,37 @@ pub async fn update_decision_engine_dynamic_routing_setup( Ok(()) } +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +pub async fn get_decision_engine_active_dynamic_routing_algorithm( + state: &SessionState, + profile_id: &id_type::ProfileId, + dynamic_routing_type: open_router::DecisionEngineDynamicAlgorithmType, +) -> RouterResult<Option<open_router::DecisionEngineConfigSetupRequest>> { + logger::debug!( + "decision_engine_euclid: GET api call for decision active {:?} routing algorithm", + dynamic_routing_type + ); + let request = open_router::GetDecisionEngineConfigRequest { + merchant_id: profile_id.get_string_repr().to_owned(), + config: dynamic_routing_type, + }; + let response: Option<open_router::DecisionEngineConfigSetupRequest> = + routing_utils::ConfigApiClient::send_decision_engine_request( + state, + services::Method::Post, + DECISION_ENGINE_RULE_GET_ENDPOINT, + Some(request), + None, + None, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get active dynamic algorithm from decision engine")? + .response; + + Ok(response) +} + #[cfg(all(feature = "dynamic_routing", feature = "v1"))] #[instrument(skip_all)] pub async fn disable_decision_engine_dynamic_routing_setup( @@ -2545,11 +2577,11 @@ pub async fn delete_decision_engine_merchant( DECISION_ENGINE_MERCHANT_BASE_ENDPOINT, profile_id.get_string_repr() ); - routing_utils::ConfigApiClient::send_decision_engine_request_without_response_parsing::<()>( + routing_utils::ConfigApiClient::send_decision_engine_request::<_, String>( state, services::Method::Delete, &path, - None, + None::<id_type::ProfileId>, None, None, )
2025-06-16T07:49:21Z
- [ ] Bugfix - [ ] New feature - [X] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This pull request introduces a new field, `routing_result_source`, across various structs and enums in the codebase to specify the source of routing decision results. This field allows for flexibility in choosing between Hyperswitch's inbuilt routing engine and an external decision engine. The changes span multiple modules, including API models, database models, and domain models. Also, while creating the routing rule decision engine rule_id will be prefilled with the hyperswitch rule_id, so both systems will have the same id ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Add profile-level config to choose between Hyperswitch routing result and Decision engine routing result ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create a merchant account, API key, profile, connector <details> <summary>2. Create Routing Rule </summary> Request curl --location 'http://localhost:8080/routing' \ --header 'X-Profile-Id: pro_Wt98jyZeU8jaQ3cr9zDP' \ --header 'api-key: dev_yUplJwLqvtAJiqOMmiamv78Xj9k1DkaEK3kxRExy4baMX4tsSVpEm55eTohlaifG' \ --data '{ "name": "Rule Based Routing-2025-05-07", "description": "This is a rule based routing created at Wed, 07 May 2025 13:03:39 GMT", "profile_id": "pro_Wt98jyZeU8jaQ3cr9zDP", "algorithm": { "type": "advanced", "data": { "defaultSelection": { "type": "priority", "data": [] }, "metadata": {}, "rules": [ { "name": "rule_1", "connectorSelection": { "type": "priority", "data": [ { "connector": "cybersource", "merchant_connector_id": "mca_EU1XaLVDXZumYK8r3ft7" } ] }, "statements": [ { "condition": [ { "lhs": "billing_country", "comparison": "equal", "value": { "type": "enum_variant", "value": "India" }, "metadata": {} } ], "nested": null } ] } ] } } }' Response { "id": "routing_rFQyeEY3ujqyjtjJIlDB", "profile_id": "pro_Wt98jyZeU8jaQ3cr9zDP", "name": "Rule Based Routing-2025-05-07", "kind": "advanced", "description": "This is a rule based routing created at Wed, 07 May 2025 13:03:39 GMT", "created_at": 1750082560, "modified_at": 1750082560, "algorithm_for": "payment", "decision_engine_routing_id": "routing_rFQyeEY3ujqyjtjJIlDB" } </details> <details> <summary>3. List Routing Rules </summary> Request curl --location 'http://localhost:8080/configs/' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "key": "routing_result_source_pro_Wt98jyZeU8jaQ3cr9zDP", "value": "decision_engine" }' Response { key: "routing_result_source_pro_Wt98jyZeU8jaQ3cr9zDP", value: "decision_engine" } Rules are getting fetched from hyperswitch <img width="1324" alt="Screenshot 2025-06-16 at 7 35 55 PM" src="https://github.com/user-attachments/assets/2b655974-444f-4bf4-8b14-2f6f0b10f055" /> </details> <details> <summary>4. Change Profile config to use decision engine result directly </summary> Request curl --location 'http://localhost:8080/account/merchant_1750082519/business_profile/pro_Wt98jyZeU8jaQ3cr9zDP' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_j1154b6pVqBwC32eFEcQDZDIBKGGEBT3zh3VMi3cWUpFcurnQqBD2SDLXmFbaJem' \ --data '{ "dynamic_routing_algorithm": { "routing_result_source": "decision_engine" } }' Response { "merchant_id": "merchant_1750082519", "profile_id": "pro_Wt98jyZeU8jaQ3cr9zDP", "profile_name": "1750082525", "return_url": "https://google.com/success", "enable_payment_response_hash": true, "payment_response_hash_key": "MkZkTPS7BIusBLHYEmQCKB0FaGiTkTsASUBTQCfuEuGwCRrN9zso4M0qIOKValbF", "redirect_to_merchant_with_http_post": false, "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "webhook_url": null, "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "metadata": null, "routing_algorithm": null, "intent_fulfillment_time": 900, "frm_routing_algorithm": null, "payout_routing_algorithm": null, "applepay_verified_domains": null, "session_expiry": 900, "payment_link_config": null, "authentication_connector_details": null, "use_billing_as_payment_method_billing": true, "extended_card_info_config": null, "collect_shipping_details_from_wallet_connector": false, "collect_billing_details_from_wallet_connector": false, "always_collect_shipping_details_from_wallet_connector": false, "always_collect_billing_details_from_wallet_connector": false, "is_connector_agnostic_mit_enabled": false, "payout_link_config": null, "outgoing_webhook_custom_http_headers": null, "tax_connector_id": null, "is_tax_connector_enabled": false, "is_network_tokenization_enabled": false, "is_auto_retries_enabled": false, "max_auto_retries_enabled": null, "always_request_extended_authorization": null, "is_click_to_pay_enabled": false, "authentication_product_ids": null, "card_testing_guard_config": { "card_ip_blocking_status": "disabled", "card_ip_blocking_threshold": 3, "guest_user_card_blocking_status": "disabled", "guest_user_card_blocking_threshold": 10, "customer_id_blocking_status": "disabled", "customer_id_blocking_threshold": 5, "card_testing_guard_expiry": 3600 }, "is_clear_pan_retries_enabled": false, "force_3ds_challenge": false, "is_debit_routing_enabled": false, "merchant_business_country": null, "is_pre_network_tokenization_enabled": false, "acquirer_configs": null, "is_iframe_redirection_enabled": null, "merchant_category_code": null } </details> <details> <summary>5. List Routing Rules again</summary> This time result from the decision engine should be used to return results Request curl --location 'http://localhost:8080/routing/list/profile?limit=100' \ --header 'sec-ch-ua-platform: "macOS"' \ --header 'Referer: https://app.hyperswitch.io/dashboard/routing' \ --header 'sec-ch-ua: "Chromium";v="136", "Google Chrome";v="136", "Not.A/Brand";v="99"' \ --header 'X-Profile-Id: pro_Wt98jyZeU8jaQ3cr9zDP' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'api-key: dev_yUplJwLqvtAJiqOMmiamv78Xj9k1DkaEK3kxRExy4baMX4tsSVpEm55eTohlaifG' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36' \ --header 'Content-Type: application/json' Response [ { "id": "routing_rFQyeEY3ujqyjtjJIlDB", "profile_id": "pro_Wt98jyZeU8jaQ3cr9zDP", "name": "Rule Based Routing-2025-05-07", "kind": "advanced", "description": "This is a rule based routing created at Wed, 07 May 2025 13:03:39 GMT", "created_at": 1750082560, "modified_at": 1750082560, "algorithm_for": "payment", "decision_engine_routing_id": null } ] <img width="1320" alt="Screenshot 2025-06-16 at 7 37 57 PM" src="https://github.com/user-attachments/assets/df30369e-30b8-4565-ab29-c5289305409e" /> </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
c99ec73885e0c64552f01826b20a1af7a934a65c
c99ec73885e0c64552f01826b20a1af7a934a65c
juspay/hyperswitch
juspay__hyperswitch-8378
Bug: [FEATURE] allow configuring outgoing webhooks for different status as a part of payment and refund flows ### Feature Description This feature allows merchants to configure different states for triggered the outgoing webhooks during payment and refund flows. Currently, outgoing webhooks are triggered for predefined status for both payments and refunds - which are common for all the merchants. ### Possible Implementation Allow defining the different payment and refund states which are eligible for triggering outgoing webhooks during the payment and refund flows. This config can be set at business profile level. For payment and refund flows (different from the incoming webhook flow) - This config will be used for checking if the current payment status is eligible for triggering an outgoing webhook - By default, the current states will be kept as is (in code) for triggering the outgoing webhook ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json index 6045147a050..b4f09cd1f2f 100644 --- a/api-reference/v1/openapi_spec_v1.json +++ b/api-reference/v1/openapi_spec_v1.json @@ -30652,6 +30652,10 @@ }, "WebhookDetails": { "type": "object", + "required": [ + "payment_statuses_enabled", + "refund_statuses_enabled" + ], "properties": { "webhook_version": { "type": "string", @@ -30697,6 +30701,42 @@ "description": "If this property is true, a webhook message is posted whenever a payment fails", "example": true, "nullable": true + }, + "payment_statuses_enabled": { + "type": "array", + "items": { + "$ref": "#/components/schemas/IntentStatus" + }, + "description": "List of payment statuses that triggers a webhook for payment intents", + "example": [ + "succeeded", + "failed", + "partially_captured", + "requires_merchant_action" + ] + }, + "refund_statuses_enabled": { + "type": "array", + "items": { + "$ref": "#/components/schemas/IntentStatus" + }, + "description": "List of refund statuses that triggers a webhook for refunds", + "example": [ + "success", + "failure" + ] + }, + "payout_statuses_enabled": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PayoutStatus" + }, + "description": "List of payout statuses that triggers a webhook for payouts", + "example": [ + "success", + "failed" + ], + "nullable": true } }, "additionalProperties": false diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index 65d1b847f3d..1f0611e1cfc 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -25623,6 +25623,10 @@ }, "WebhookDetails": { "type": "object", + "required": [ + "payment_statuses_enabled", + "refund_statuses_enabled" + ], "properties": { "webhook_version": { "type": "string", @@ -25668,6 +25672,42 @@ "description": "If this property is true, a webhook message is posted whenever a payment fails", "example": true, "nullable": true + }, + "payment_statuses_enabled": { + "type": "array", + "items": { + "$ref": "#/components/schemas/IntentStatus" + }, + "description": "List of payment statuses that triggers a webhook for payment intents", + "example": [ + "succeeded", + "failed", + "partially_captured", + "requires_merchant_action" + ] + }, + "refund_statuses_enabled": { + "type": "array", + "items": { + "$ref": "#/components/schemas/IntentStatus" + }, + "description": "List of refund statuses that triggers a webhook for refunds", + "example": [ + "success", + "failure" + ] + }, + "payout_statuses_enabled": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PayoutStatus" + }, + "description": "List of payout statuses that triggers a webhook for payouts", + "example": [ + "success", + "failed" + ], + "nullable": true } }, "additionalProperties": false diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index f12e6d5bd4a..00fccd4ed45 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -702,6 +702,58 @@ pub struct WebhookDetails { /// If this property is true, a webhook message is posted whenever a payment fails #[schema(example = true)] pub payment_failed_enabled: Option<bool>, + + /// List of payment statuses that triggers a webhook for payment intents + #[schema(value_type = Vec<IntentStatus>, example = json!(["succeeded", "failed", "partially_captured", "requires_merchant_action"]))] + pub payment_statuses_enabled: Option<Vec<api_enums::IntentStatus>>, + + /// List of refund statuses that triggers a webhook for refunds + #[schema(value_type = Vec<IntentStatus>, example = json!(["success", "failure"]))] + pub refund_statuses_enabled: Option<Vec<api_enums::RefundStatus>>, + + /// List of payout statuses that triggers a webhook for payouts + #[cfg(feature = "payouts")] + #[schema(value_type = Option<Vec<PayoutStatus>>, example = json!(["success", "failed"]))] + pub payout_statuses_enabled: Option<Vec<api_enums::PayoutStatus>>, +} + +impl WebhookDetails { + fn validate_statuses<T>(statuses: &[T], status_type_name: &str) -> Result<(), String> + where + T: strum::IntoEnumIterator + Copy + PartialEq + std::fmt::Debug, + T: Into<Option<api_enums::EventType>>, + { + let valid_statuses: Vec<T> = T::iter().filter(|s| (*s).into().is_some()).collect(); + + for status in statuses { + if !valid_statuses.contains(status) { + return Err(format!( + "Invalid {} webhook status provided: {:?}", + status_type_name, status + )); + } + } + Ok(()) + } + + pub fn validate(&self) -> Result<(), String> { + if let Some(payment_statuses) = &self.payment_statuses_enabled { + Self::validate_statuses(payment_statuses, "payment")?; + } + + if let Some(refund_statuses) = &self.refund_statuses_enabled { + Self::validate_statuses(refund_statuses, "refund")?; + } + + #[cfg(feature = "payouts")] + { + if let Some(payout_statuses) = &self.payout_statuses_enabled { + Self::validate_statuses(payout_statuses, "payout")?; + } + } + + Ok(()) + } } #[derive(Debug, Serialize, ToSchema)] diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 641dc83291c..e33e7b0a376 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -2292,6 +2292,7 @@ pub enum FrmTransactionType { serde::Deserialize, serde::Serialize, strum::Display, + strum::EnumIter, strum::EnumString, ToSchema, )] @@ -6959,6 +6960,7 @@ pub enum BrazilStatesAbbreviation { serde::Deserialize, serde::Serialize, strum::Display, + strum::EnumIter, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] diff --git a/crates/common_enums/src/transformers.rs b/crates/common_enums/src/transformers.rs index 0ea21f5943c..fb4555dea92 100644 --- a/crates/common_enums/src/transformers.rs +++ b/crates/common_enums/src/transformers.rs @@ -2,9 +2,11 @@ use std::fmt::{Display, Formatter}; use serde::{Deserialize, Serialize}; +#[cfg(feature = "payouts")] +use crate::enums::PayoutStatus; use crate::enums::{ - AttemptStatus, Country, CountryAlpha2, CountryAlpha3, IntentStatus, PaymentMethod, - PaymentMethodType, + AttemptStatus, Country, CountryAlpha2, CountryAlpha3, DisputeStatus, EventType, IntentStatus, + MandateStatus, PaymentMethod, PaymentMethodType, RefundStatus, }; impl Display for NumericCountryCodeParseError { @@ -2119,6 +2121,82 @@ impl From<AttemptStatus> for IntentStatus { } } +impl From<IntentStatus> for Option<EventType> { + fn from(value: IntentStatus) -> Self { + match value { + IntentStatus::Succeeded => Some(EventType::PaymentSucceeded), + IntentStatus::Failed => Some(EventType::PaymentFailed), + IntentStatus::Processing => Some(EventType::PaymentProcessing), + IntentStatus::RequiresMerchantAction + | IntentStatus::RequiresCustomerAction + | IntentStatus::Conflicted => Some(EventType::ActionRequired), + IntentStatus::Cancelled => Some(EventType::PaymentCancelled), + IntentStatus::PartiallyCaptured | IntentStatus::PartiallyCapturedAndCapturable => { + Some(EventType::PaymentCaptured) + } + IntentStatus::RequiresCapture => Some(EventType::PaymentAuthorized), + IntentStatus::RequiresPaymentMethod | IntentStatus::RequiresConfirmation => None, + } + } +} + +impl From<RefundStatus> for Option<EventType> { + fn from(value: RefundStatus) -> Self { + match value { + RefundStatus::Success => Some(EventType::RefundSucceeded), + RefundStatus::Failure => Some(EventType::RefundFailed), + RefundStatus::ManualReview + | RefundStatus::Pending + | RefundStatus::TransactionFailure => None, + } + } +} + +#[cfg(feature = "payouts")] +impl From<PayoutStatus> for Option<EventType> { + fn from(value: PayoutStatus) -> Self { + match value { + PayoutStatus::Success => Some(EventType::PayoutSuccess), + PayoutStatus::Failed => Some(EventType::PayoutFailed), + PayoutStatus::Cancelled => Some(EventType::PayoutCancelled), + PayoutStatus::Initiated => Some(EventType::PayoutInitiated), + PayoutStatus::Expired => Some(EventType::PayoutExpired), + PayoutStatus::Reversed => Some(EventType::PayoutReversed), + PayoutStatus::Ineligible + | PayoutStatus::Pending + | PayoutStatus::RequiresCreation + | PayoutStatus::RequiresFulfillment + | PayoutStatus::RequiresPayoutMethodData + | PayoutStatus::RequiresVendorAccountCreation + | PayoutStatus::RequiresConfirmation => None, + } + } +} + +impl From<DisputeStatus> for EventType { + fn from(value: DisputeStatus) -> Self { + match value { + DisputeStatus::DisputeOpened => Self::DisputeOpened, + DisputeStatus::DisputeExpired => Self::DisputeExpired, + DisputeStatus::DisputeAccepted => Self::DisputeAccepted, + DisputeStatus::DisputeCancelled => Self::DisputeCancelled, + DisputeStatus::DisputeChallenged => Self::DisputeChallenged, + DisputeStatus::DisputeWon => Self::DisputeWon, + DisputeStatus::DisputeLost => Self::DisputeLost, + } + } +} + +impl From<MandateStatus> for Option<EventType> { + fn from(value: MandateStatus) -> Self { + match value { + MandateStatus::Active => Some(EventType::MandateActive), + MandateStatus::Revoked => Some(EventType::MandateRevoked), + MandateStatus::Inactive | MandateStatus::Pending => None, + } + } +} + #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] diff --git a/crates/common_types/src/consts.rs b/crates/common_types/src/consts.rs index 3550333443f..1ceb9999086 100644 --- a/crates/common_types/src/consts.rs +++ b/crates/common_types/src/consts.rs @@ -7,3 +7,26 @@ pub const API_VERSION: common_enums::ApiVersion = common_enums::ApiVersion::V1; /// API version #[cfg(feature = "v2")] pub const API_VERSION: common_enums::ApiVersion = common_enums::ApiVersion::V2; + +/// Default payment intent statuses that trigger a webhook +pub const DEFAULT_PAYMENT_WEBHOOK_TRIGGER_STATUSES: &[common_enums::IntentStatus] = &[ + common_enums::IntentStatus::Succeeded, + common_enums::IntentStatus::Failed, + common_enums::IntentStatus::PartiallyCaptured, + common_enums::IntentStatus::RequiresMerchantAction, +]; + +/// Default refund statuses that trigger a webhook +pub const DEFAULT_REFUND_WEBHOOK_TRIGGER_STATUSES: &[common_enums::RefundStatus] = &[ + common_enums::RefundStatus::Success, + common_enums::RefundStatus::Failure, + common_enums::RefundStatus::TransactionFailure, +]; + +/// Default payout statuses that trigger a webhook +pub const DEFAULT_PAYOUT_WEBHOOK_TRIGGER_STATUSES: &[common_enums::PayoutStatus] = &[ + common_enums::PayoutStatus::Success, + common_enums::PayoutStatus::Failed, + common_enums::PayoutStatus::Initiated, + common_enums::PayoutStatus::Pending, +]; diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs index e2543e3b431..2c887e7f7cb 100644 --- a/crates/diesel_models/src/business_profile.rs +++ b/crates/diesel_models/src/business_profile.rs @@ -747,6 +747,9 @@ pub struct WebhookDetails { pub payment_created_enabled: Option<bool>, pub payment_succeeded_enabled: Option<bool>, pub payment_failed_enabled: Option<bool>, + pub payment_statuses_enabled: Option<Vec<common_enums::IntentStatus>>, + pub refund_statuses_enabled: Option<Vec<common_enums::RefundStatus>>, + pub payout_statuses_enabled: Option<Vec<common_enums::PayoutStatus>>, } common_utils::impl_to_sql_from_sql_json!(WebhookDetails); diff --git a/crates/euclid_wasm/Cargo.toml b/crates/euclid_wasm/Cargo.toml index bf530143006..f8c9bbce62b 100644 --- a/crates/euclid_wasm/Cargo.toml +++ b/crates/euclid_wasm/Cargo.toml @@ -15,8 +15,8 @@ release = ["payouts"] dummy_connector = ["kgraph_utils/dummy_connector", "connector_configs/dummy_connector"] production = ["connector_configs/production"] sandbox = ["connector_configs/sandbox"] -payouts = ["api_models/payouts", "euclid/payouts"] -v1 = ["api_models/v1", "kgraph_utils/v1"] +payouts = ["api_models/payouts", "common_enums/payouts", "euclid/payouts"] +v1 = ["api_models/v1", "kgraph_utils/v1", "payouts"] v2 = [] [dependencies] diff --git a/crates/euclid_wasm/src/lib.rs b/crates/euclid_wasm/src/lib.rs index 25d1da385ad..c0e58520c71 100644 --- a/crates/euclid_wasm/src/lib.rs +++ b/crates/euclid_wasm/src/lib.rs @@ -34,7 +34,12 @@ use wasm_bindgen::prelude::*; use crate::utils::JsResultExt; type JsResult = Result<JsValue, JsValue>; use api_models::payment_methods::CountryCodeWithName; -use common_enums::{CountryAlpha2, MerchantCategoryCode, MerchantCategoryCodeWithName}; +#[cfg(feature = "payouts")] +use common_enums::PayoutStatus; +use common_enums::{ + CountryAlpha2, DisputeStatus, EventClass, EventType, IntentStatus, MandateStatus, + MerchantCategoryCode, MerchantCategoryCodeWithName, RefundStatus, +}; use strum::IntoEnumIterator; struct SeedData { @@ -472,3 +477,42 @@ pub fn get_payout_description_category() -> JsResult { Ok(serde_wasm_bindgen::to_value(&category)?) } + +#[wasm_bindgen(js_name = getValidWebhookStatus)] +pub fn get_valid_webhook_status(key: &str) -> JsResult { + let event_class = EventClass::from_str(key) + .map_err(|_| "Invalid webhook event type received".to_string()) + .err_to_js()?; + + match event_class { + EventClass::Payments => { + let statuses: Vec<IntentStatus> = IntentStatus::iter() + .filter(|intent_status| Into::<Option<EventType>>::into(*intent_status).is_some()) + .collect(); + Ok(serde_wasm_bindgen::to_value(&statuses)?) + } + EventClass::Refunds => { + let statuses: Vec<RefundStatus> = RefundStatus::iter() + .filter(|status| Into::<Option<EventType>>::into(*status).is_some()) + .collect(); + Ok(serde_wasm_bindgen::to_value(&statuses)?) + } + EventClass::Disputes => { + let statuses: Vec<DisputeStatus> = DisputeStatus::iter().collect(); + Ok(serde_wasm_bindgen::to_value(&statuses)?) + } + EventClass::Mandates => { + let statuses: Vec<MandateStatus> = MandateStatus::iter() + .filter(|status| Into::<Option<EventType>>::into(*status).is_some()) + .collect(); + Ok(serde_wasm_bindgen::to_value(&statuses)?) + } + #[cfg(feature = "payouts")] + EventClass::Payouts => { + let statuses: Vec<PayoutStatus> = PayoutStatus::iter() + .filter(|status| Into::<Option<EventType>>::into(*status).is_some()) + .collect(); + Ok(serde_wasm_bindgen::to_value(&statuses)?) + } + } +} diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs index 8f239ef62e0..c386693a222 100644 --- a/crates/hyperswitch_domain_models/src/business_profile.rs +++ b/crates/hyperswitch_domain_models/src/business_profile.rs @@ -1,3 +1,5 @@ +use std::borrow::Cow; + use common_enums::enums as api_enums; use common_types::primitive_wrappers; use common_utils::{ @@ -1251,6 +1253,39 @@ impl Profile { "unable to deserialize frm routing algorithm ref from merchant account", ) } + + pub fn get_payment_webhook_statuses(&self) -> Cow<'_, [common_enums::IntentStatus]> { + self.webhook_details + .as_ref() + .and_then(|details| details.payment_statuses_enabled.as_ref()) + .filter(|statuses_vec| !statuses_vec.is_empty()) + .map(|statuses_vec| Cow::Borrowed(statuses_vec.as_slice())) + .unwrap_or_else(|| { + Cow::Borrowed(common_types::consts::DEFAULT_PAYMENT_WEBHOOK_TRIGGER_STATUSES) + }) + } + + pub fn get_refund_webhook_statuses(&self) -> Cow<'_, [common_enums::RefundStatus]> { + self.webhook_details + .as_ref() + .and_then(|details| details.refund_statuses_enabled.as_ref()) + .filter(|statuses_vec| !statuses_vec.is_empty()) + .map(|statuses_vec| Cow::Borrowed(statuses_vec.as_slice())) + .unwrap_or_else(|| { + Cow::Borrowed(common_types::consts::DEFAULT_REFUND_WEBHOOK_TRIGGER_STATUSES) + }) + } + + pub fn get_payout_webhook_statuses(&self) -> Cow<'_, [common_enums::PayoutStatus]> { + self.webhook_details + .as_ref() + .and_then(|details| details.payout_statuses_enabled.as_ref()) + .filter(|statuses_vec| !statuses_vec.is_empty()) + .map(|statuses_vec| Cow::Borrowed(statuses_vec.as_slice())) + .unwrap_or_else(|| { + Cow::Borrowed(common_types::consts::DEFAULT_PAYOUT_WEBHOOK_TRIGGER_STATUSES) + }) + } } #[cfg(feature = "v2")] diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index cbb9957115b..495bea84eac 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -363,7 +363,7 @@ pub async fn payouts_create_core( .await? }; - response_handler(&state, &merchant_context, &payout_data).await + trigger_webhook_and_handle_response(&state, &merchant_context, &payout_data).await } #[instrument(skip_all)] @@ -426,7 +426,7 @@ pub async fn payouts_confirm_core( ) .await?; - response_handler(&state, &merchant_context, &payout_data).await + trigger_webhook_and_handle_response(&state, &merchant_context, &payout_data).await } pub async fn payouts_update_core( @@ -498,7 +498,7 @@ pub async fn payouts_update_core( .await?; } - response_handler(&state, &merchant_context, &payout_data).await + trigger_webhook_and_handle_response(&state, &merchant_context, &payout_data).await } #[cfg(all(feature = "payouts", feature = "v1"))] @@ -541,7 +541,9 @@ pub async fn payouts_retrieve_core( .await?; } - response_handler(&state, &merchant_context, &payout_data).await + Ok(services::ApplicationResponse::Json( + response_handler(&state, &merchant_context, &payout_data).await?, + )) } #[instrument(skip_all)] @@ -632,7 +634,9 @@ pub async fn payouts_cancel_core( .attach_printable("Payout cancellation failed for given Payout request")?; } - response_handler(&state, &merchant_context, &payout_data).await + Ok(services::ApplicationResponse::Json( + response_handler(&state, &merchant_context, &payout_data).await?, + )) } #[instrument(skip_all)] @@ -722,7 +726,7 @@ pub async fn payouts_fulfill_core( })); } - response_handler(&state, &merchant_context, &payout_data).await + trigger_webhook_and_handle_response(&state, &merchant_context, &payout_data).await } #[cfg(all(feature = "olap", feature = "v2"))] @@ -2481,11 +2485,21 @@ pub async fn fulfill_payout( Ok(()) } -pub async fn response_handler( +pub async fn trigger_webhook_and_handle_response( state: &SessionState, merchant_context: &domain::MerchantContext, payout_data: &PayoutData, ) -> RouterResponse<payouts::PayoutCreateResponse> { + let response = response_handler(state, merchant_context, payout_data).await?; + utils::trigger_payouts_webhook(state, merchant_context, &response).await?; + Ok(services::ApplicationResponse::Json(response)) +} + +pub async fn response_handler( + state: &SessionState, + merchant_context: &domain::MerchantContext, + payout_data: &PayoutData, +) -> RouterResult<payouts::PayoutCreateResponse> { let payout_attempt = payout_data.payout_attempt.to_owned(); let payouts = payout_data.payouts.to_owned(); @@ -2574,7 +2588,8 @@ pub async fn response_handler( .attach_printable("Failed to parse payout link's URL")?, payout_method_id, }; - Ok(services::ApplicationResponse::Json(response)) + + Ok(response) } #[cfg(feature = "v2")] diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs index 3f95d61bfb7..cf841e98b5d 100644 --- a/crates/router/src/core/webhooks/incoming.rs +++ b/crates/router/src/core/webhooks/incoming.rs @@ -727,7 +727,7 @@ async fn payments_incoming_webhook_flow( let status = payments_response.status; - let event_type: Option<enums::EventType> = payments_response.status.foreign_into(); + let event_type: Option<enums::EventType> = payments_response.status.into(); // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook if let Some(outgoing_event_type) = event_type { @@ -847,20 +847,13 @@ async fn payouts_incoming_webhook_flow( ) })?; - let event_type: Option<enums::EventType> = updated_payout_attempt.status.foreign_into(); + let event_type: Option<enums::EventType> = updated_payout_attempt.status.into(); // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook if let Some(outgoing_event_type) = event_type { - let router_response = + let payout_create_response = payouts::response_handler(&state, &merchant_context, &payout_data).await?; - let payout_create_response: payout_models::PayoutCreateResponse = match router_response - { - services::ApplicationResponse::Json(response) => response, - _ => Err(errors::ApiErrorResponse::WebhookResourceNotFound) - .attach_printable("Failed to fetch the payout create response")?, - }; - Box::pin(super::create_event_and_trigger_outgoing_webhook( state, merchant_context, @@ -1055,7 +1048,7 @@ async fn refunds_incoming_webhook_flow( .await .attach_printable_lazy(|| format!("Failed while updating refund: refund_id: {refund_id}"))? }; - let event_type: Option<enums::EventType> = updated_refund.refund_status.foreign_into(); + let event_type: Option<enums::EventType> = updated_refund.refund_status.into(); // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook if let Some(outgoing_event_type) = event_type { @@ -1367,8 +1360,7 @@ async fn external_authentication_incoming_webhook_flow( let payment_id = payments_response.payment_id.clone(); let status = payments_response.status; - let event_type: Option<enums::EventType> = - payments_response.status.foreign_into(); + let event_type: Option<enums::EventType> = payments_response.status.into(); // Set poll_id as completed in redis to allow the fetch status of poll through retrieve_poll_status api from client let poll_id = core_utils::get_poll_id( merchant_context.get_merchant_account().get_id(), @@ -1486,7 +1478,7 @@ async fn mandates_incoming_webhook_flow( ) .await?, ); - let event_type: Option<enums::EventType> = updated_mandate.mandate_status.foreign_into(); + let event_type: Option<enums::EventType> = updated_mandate.mandate_status.into(); if let Some(outgoing_event_type) = event_type { Box::pin(super::create_event_and_trigger_outgoing_webhook( state, @@ -1589,7 +1581,7 @@ async fn frm_incoming_webhook_flow( services::ApplicationResponse::JsonWithHeaders((payments_response, _)) => { let payment_id = payments_response.payment_id.clone(); let status = payments_response.status; - let event_type: Option<enums::EventType> = payments_response.status.foreign_into(); + let event_type: Option<enums::EventType> = payments_response.status.into(); if let Some(outgoing_event_type) = event_type { let primary_object_created_at = payments_response.created; Box::pin(super::create_event_and_trigger_outgoing_webhook( @@ -1663,7 +1655,7 @@ async fn disputes_incoming_webhook_flow( ) .await?; let disputes_response = Box::new(dispute_object.clone().foreign_into()); - let event_type: enums::EventType = dispute_object.dispute_status.foreign_into(); + let event_type: enums::EventType = dispute_object.dispute_status.into(); Box::pin(super::create_event_and_trigger_outgoing_webhook( state, @@ -1745,7 +1737,7 @@ async fn bank_transfer_webhook_flow( services::ApplicationResponse::JsonWithHeaders((payments_response, _)) => { let payment_id = payments_response.payment_id.clone(); - let event_type: Option<enums::EventType> = payments_response.status.foreign_into(); + let event_type: Option<enums::EventType> = payments_response.status.into(); let status = payments_response.status; // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook diff --git a/crates/router/src/core/webhooks/incoming_v2.rs b/crates/router/src/core/webhooks/incoming_v2.rs index c6ff1e73abc..0cf8b2bfe7b 100644 --- a/crates/router/src/core/webhooks/incoming_v2.rs +++ b/crates/router/src/core/webhooks/incoming_v2.rs @@ -535,7 +535,7 @@ async fn payments_incoming_webhook_flow( let status = payments_response.status; - let event_type: Option<enums::EventType> = payments_response.status.foreign_into(); + let event_type: Option<enums::EventType> = payments_response.status.into(); // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook if let Some(outgoing_event_type) = event_type { diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index d3ffb715b73..89fe95268ee 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -3,7 +3,7 @@ use router_env::{instrument, tracing, Flow}; use super::app::AppState; use crate::{ - core::{admin::*, api_locking}, + core::{admin::*, api_locking, errors}, services::{api, authentication as auth, authorization::permissions::Permission}, types::{api::admin, domain}, }; @@ -186,11 +186,25 @@ pub async fn merchant_account_create( json_payload: web::Json<admin::MerchantAccountCreate>, ) -> HttpResponse { let flow = Flow::MerchantsAccountCreate; + let payload = json_payload.into_inner(); + if let Err(api_error) = payload + .webhook_details + .as_ref() + .map(|details| { + details + .validate() + .map_err(|message| errors::ApiErrorResponse::InvalidRequestData { message }) + }) + .transpose() + { + return api::log_and_return_error_response(api_error.into()); + } + Box::pin(api::server_wrap( flow, state, &req, - json_payload.into_inner(), + payload, |state, auth, req, _| create_merchant_account(state, req, auth), &auth::PlatformOrgAdminAuth { is_admin_auth_allowed: true, diff --git a/crates/router/src/routes/profiles.rs b/crates/router/src/routes/profiles.rs index caa06c97b74..a854a68a2a3 100644 --- a/crates/router/src/routes/profiles.rs +++ b/crates/router/src/routes/profiles.rs @@ -3,7 +3,7 @@ use router_env::{instrument, tracing, Flow}; use super::app::AppState; use crate::{ - core::{admin::*, api_locking}, + core::{admin::*, api_locking, errors}, services::{api, authentication as auth, authorization::permissions}, types::{api::admin, domain}, }; @@ -19,6 +19,18 @@ pub async fn profile_create( let flow = Flow::ProfileCreate; let payload = json_payload.into_inner(); let merchant_id = path.into_inner(); + if let Err(api_error) = payload + .webhook_details + .as_ref() + .map(|details| { + details + .validate() + .map_err(|message| errors::ApiErrorResponse::InvalidRequestData { message }) + }) + .transpose() + { + return api::log_and_return_error_response(api_error.into()); + } Box::pin(api::server_wrap( flow, @@ -53,6 +65,18 @@ pub async fn profile_create( ) -> HttpResponse { let flow = Flow::ProfileCreate; let payload = json_payload.into_inner(); + if let Err(api_error) = payload + .webhook_details + .as_ref() + .map(|details| { + details + .validate() + .map_err(|message| errors::ApiErrorResponse::InvalidRequestData { message }) + }) + .transpose() + { + return api::log_and_return_error_response(api_error.into()); + } Box::pin(api::server_wrap( flow, @@ -158,12 +182,25 @@ pub async fn profile_update( ) -> HttpResponse { let flow = Flow::ProfileUpdate; let (merchant_id, profile_id) = path.into_inner(); + let payload = json_payload.into_inner(); + if let Err(api_error) = payload + .webhook_details + .as_ref() + .map(|details| { + details + .validate() + .map_err(|message| errors::ApiErrorResponse::InvalidRequestData { message }) + }) + .transpose() + { + return api::log_and_return_error_response(api_error.into()); + } Box::pin(api::server_wrap( flow, state, &req, - json_payload.into_inner(), + payload, |state, auth_data, req, _| update_profile(state, &profile_id, auth_data.key_store, req), auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())), @@ -189,12 +226,25 @@ pub async fn profile_update( ) -> HttpResponse { let flow = Flow::ProfileUpdate; let profile_id = path.into_inner(); + let payload = json_payload.into_inner(); + if let Err(api_error) = payload + .webhook_details + .as_ref() + .map(|details| { + details + .validate() + .map_err(|message| errors::ApiErrorResponse::InvalidRequestData { message }) + }) + .transpose() + { + return api::log_and_return_error_response(api_error.into()); + } Box::pin(api::server_wrap( flow, state, &req, - json_payload.into_inner(), + payload, |state, auth::AuthenticationDataWithoutProfile { key_store, .. }, req, _| { update_profile(state, &profile_id, key_store, req) }, diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 2e64b10c284..ea7f0990649 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -461,31 +461,6 @@ impl ForeignFrom<payments::MandateAmountData> for storage_enums::MandateAmountDa } } -impl ForeignFrom<api_enums::IntentStatus> for Option<storage_enums::EventType> { - fn foreign_from(value: api_enums::IntentStatus) -> Self { - match value { - api_enums::IntentStatus::Succeeded => Some(storage_enums::EventType::PaymentSucceeded), - api_enums::IntentStatus::Failed => Some(storage_enums::EventType::PaymentFailed), - api_enums::IntentStatus::Processing => { - Some(storage_enums::EventType::PaymentProcessing) - } - api_enums::IntentStatus::RequiresMerchantAction - | api_enums::IntentStatus::RequiresCustomerAction - | api_enums::IntentStatus::Conflicted => Some(storage_enums::EventType::ActionRequired), - api_enums::IntentStatus::Cancelled => Some(storage_enums::EventType::PaymentCancelled), - api_enums::IntentStatus::PartiallyCaptured - | api_enums::IntentStatus::PartiallyCapturedAndCapturable => { - Some(storage_enums::EventType::PaymentCaptured) - } - api_enums::IntentStatus::RequiresCapture => { - Some(storage_enums::EventType::PaymentAuthorized) - } - api_enums::IntentStatus::RequiresPaymentMethod - | api_enums::IntentStatus::RequiresConfirmation => None, - } - } -} - impl ForeignFrom<api_enums::PaymentMethodType> for api_enums::PaymentMethod { fn foreign_from(payment_method_type: api_enums::PaymentMethodType) -> Self { match payment_method_type { @@ -632,66 +607,6 @@ impl ForeignTryFrom<payments::PaymentMethodData> for api_enums::PaymentMethod { } } -impl ForeignFrom<storage_enums::RefundStatus> for Option<storage_enums::EventType> { - fn foreign_from(value: storage_enums::RefundStatus) -> Self { - match value { - storage_enums::RefundStatus::Success => Some(storage_enums::EventType::RefundSucceeded), - storage_enums::RefundStatus::Failure => Some(storage_enums::EventType::RefundFailed), - api_enums::RefundStatus::ManualReview - | api_enums::RefundStatus::Pending - | api_enums::RefundStatus::TransactionFailure => None, - } - } -} - -impl ForeignFrom<storage_enums::PayoutStatus> for Option<storage_enums::EventType> { - fn foreign_from(value: storage_enums::PayoutStatus) -> Self { - match value { - storage_enums::PayoutStatus::Success => Some(storage_enums::EventType::PayoutSuccess), - storage_enums::PayoutStatus::Failed => Some(storage_enums::EventType::PayoutFailed), - storage_enums::PayoutStatus::Cancelled => { - Some(storage_enums::EventType::PayoutCancelled) - } - storage_enums::PayoutStatus::Initiated => { - Some(storage_enums::EventType::PayoutInitiated) - } - storage_enums::PayoutStatus::Expired => Some(storage_enums::EventType::PayoutExpired), - storage_enums::PayoutStatus::Reversed => Some(storage_enums::EventType::PayoutReversed), - storage_enums::PayoutStatus::Ineligible - | storage_enums::PayoutStatus::Pending - | storage_enums::PayoutStatus::RequiresCreation - | storage_enums::PayoutStatus::RequiresFulfillment - | storage_enums::PayoutStatus::RequiresPayoutMethodData - | storage_enums::PayoutStatus::RequiresVendorAccountCreation - | storage_enums::PayoutStatus::RequiresConfirmation => None, - } - } -} - -impl ForeignFrom<storage_enums::DisputeStatus> for storage_enums::EventType { - fn foreign_from(value: storage_enums::DisputeStatus) -> Self { - match value { - storage_enums::DisputeStatus::DisputeOpened => Self::DisputeOpened, - storage_enums::DisputeStatus::DisputeExpired => Self::DisputeExpired, - storage_enums::DisputeStatus::DisputeAccepted => Self::DisputeAccepted, - storage_enums::DisputeStatus::DisputeCancelled => Self::DisputeCancelled, - storage_enums::DisputeStatus::DisputeChallenged => Self::DisputeChallenged, - storage_enums::DisputeStatus::DisputeWon => Self::DisputeWon, - storage_enums::DisputeStatus::DisputeLost => Self::DisputeLost, - } - } -} - -impl ForeignFrom<storage_enums::MandateStatus> for Option<storage_enums::EventType> { - fn foreign_from(value: storage_enums::MandateStatus) -> Self { - match value { - storage_enums::MandateStatus::Active => Some(storage_enums::EventType::MandateActive), - storage_enums::MandateStatus::Revoked => Some(storage_enums::EventType::MandateRevoked), - storage_enums::MandateStatus::Inactive | storage_enums::MandateStatus::Pending => None, - } - } -} - impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for storage_enums::RefundStatus { type Error = errors::ValidationError; @@ -2153,8 +2068,11 @@ impl ForeignFrom<api_models::admin::WebhookDetails> webhook_password: item.webhook_password, webhook_url: item.webhook_url, payment_created_enabled: item.payment_created_enabled, - payment_succeeded_enabled: item.payment_succeeded_enabled, payment_failed_enabled: item.payment_failed_enabled, + payment_succeeded_enabled: item.payment_succeeded_enabled, + payment_statuses_enabled: item.payment_statuses_enabled, + refund_statuses_enabled: item.refund_statuses_enabled, + payout_statuses_enabled: item.payout_statuses_enabled, } } } @@ -2169,8 +2087,11 @@ impl ForeignFrom<diesel_models::business_profile::WebhookDetails> webhook_password: item.webhook_password, webhook_url: item.webhook_url, payment_created_enabled: item.payment_created_enabled, - payment_succeeded_enabled: item.payment_succeeded_enabled, payment_failed_enabled: item.payment_failed_enabled, + payment_succeeded_enabled: item.payment_succeeded_enabled, + payment_statuses_enabled: item.payment_statuses_enabled, + refund_statuses_enabled: item.refund_statuses_enabled, + payout_statuses_enabled: item.payout_statuses_enabled, } } } diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index 6861e4d1df3..7da042a4882 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -55,10 +55,7 @@ use crate::{ logger, routes::{metrics, SessionState}, services::{self, authentication::get_header_value_by_key}, - types::{ - self, domain, - transformers::{ForeignFrom, ForeignInto}, - }, + types::{self, domain, transformers::ForeignInto}, }; #[cfg(feature = "v1")] use crate::{core::webhooks as webhooks_core, types::storage}; @@ -1154,25 +1151,21 @@ where D: payments_core::OperationSessionGetters<F>, { let status = payment_data.get_payment_intent().status; - let payment_id = payment_data.get_payment_intent().get_id().to_owned(); - - let captures = payment_data - .get_multiple_capture_data() - .map(|multiple_capture_data| { - multiple_capture_data - .get_all_captures() - .into_iter() - .cloned() - .collect() - }); - - if matches!( - status, - enums::IntentStatus::Succeeded - | enums::IntentStatus::Failed - | enums::IntentStatus::PartiallyCaptured - | enums::IntentStatus::RequiresMerchantAction - ) { + let should_trigger_webhook = business_profile + .get_payment_webhook_statuses() + .contains(&status); + + if should_trigger_webhook { + let captures = payment_data + .get_multiple_capture_data() + .map(|multiple_capture_data| { + multiple_capture_data + .get_all_captures() + .into_iter() + .cloned() + .collect() + }); + let payment_id = payment_data.get_payment_intent().get_id().to_owned(); let payments_response = crate::core::payments::transformers::payments_to_payments_response( payment_data, captures, @@ -1186,7 +1179,7 @@ where None, )?; - let event_type = ForeignFrom::foreign_from(status); + let event_type = status.into(); if let services::ApplicationResponse::JsonWithHeaders((payments_response_json, _)) = payments_response @@ -1248,27 +1241,28 @@ pub async fn trigger_refund_outgoing_webhook( profile_id: id_type::ProfileId, ) -> RouterResult<()> { let refund_status = refund.refund_status; - if matches!( - refund_status, - enums::RefundStatus::Success - | enums::RefundStatus::Failure - | enums::RefundStatus::TransactionFailure - ) { - let event_type = ForeignFrom::foreign_from(refund_status); + + let key_manager_state = &(state).into(); + let business_profile = state + .store + .find_business_profile_by_profile_id( + key_manager_state, + merchant_context.get_merchant_key_store(), + &profile_id, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { + id: profile_id.get_string_repr().to_owned(), + })?; + + let should_trigger_webhook = business_profile + .get_refund_webhook_statuses() + .contains(&refund_status); + + if should_trigger_webhook { + let event_type = refund_status.into(); let refund_response: api_models::refunds::RefundResponse = refund.clone().foreign_into(); - let key_manager_state = &(state).into(); let refund_id = refund_response.refund_id.clone(); - let business_profile = state - .store - .find_business_profile_by_profile_id( - key_manager_state, - merchant_context.get_merchant_key_store(), - &profile_id, - ) - .await - .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { - id: profile_id.get_string_repr().to_owned(), - })?; let cloned_state = state.clone(); let cloned_merchant_context = merchant_context.clone(); let primary_object_created_at = refund_response.created_at; @@ -1315,3 +1309,72 @@ pub fn get_locale_from_header(headers: &actix_web::http::header::HeaderMap) -> S .map(|val| val.to_string()) .unwrap_or(common_utils::consts::DEFAULT_LOCALE.to_string()) } + +#[cfg(all(feature = "payouts", feature = "v1"))] +pub async fn trigger_payouts_webhook( + state: &SessionState, + merchant_context: &domain::MerchantContext, + payout_response: &api_models::payouts::PayoutCreateResponse, +) -> RouterResult<()> { + let key_manager_state = &(state).into(); + let profile_id = &payout_response.profile_id; + let business_profile = state + .store + .find_business_profile_by_profile_id( + key_manager_state, + merchant_context.get_merchant_key_store(), + profile_id, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { + id: profile_id.get_string_repr().to_owned(), + })?; + + let status = &payout_response.status; + let should_trigger_webhook = business_profile + .get_payout_webhook_statuses() + .contains(status); + + if should_trigger_webhook { + let event_type = (*status).into(); + if let Some(event_type) = event_type { + let cloned_merchant_context = merchant_context.clone(); + let cloned_state = state.clone(); + let cloned_response = payout_response.clone(); + + // This spawns this futures in a background thread, the exception inside this future won't affect + // the current thread and the lifecycle of spawn thread is not handled by runtime. + // So when server shutdown won't wait for this thread's completion. + tokio::spawn( + async move { + let primary_object_created_at = cloned_response.created; + Box::pin(webhooks_core::create_event_and_trigger_outgoing_webhook( + cloned_state, + cloned_merchant_context, + business_profile, + event_type, + diesel_models::enums::EventClass::Payouts, + cloned_response.payout_id.clone(), + diesel_models::enums::EventObjectType::PayoutDetails, + webhooks::OutgoingWebhookContent::PayoutDetails(Box::new(cloned_response)), + primary_object_created_at, + )) + .await + } + .in_current_span(), + ); + } else { + logger::warn!("Outgoing webhook not sent because of missing event type status mapping"); + } + } + Ok(()) +} + +#[cfg(all(feature = "payouts", feature = "v2"))] +pub async fn trigger_payouts_webhook( + state: &SessionState, + merchant_context: &domain::MerchantContext, + payout_response: &api_models::payouts::PayoutCreateResponse, +) -> RouterResult<()> { + todo!() +} diff --git a/crates/router/src/workflows/outgoing_webhook_retry.rs b/crates/router/src/workflows/outgoing_webhook_retry.rs index d525763529e..8a04094f31d 100644 --- a/crates/router/src/workflows/outgoing_webhook_retry.rs +++ b/crates/router/src/workflows/outgoing_webhook_retry.rs @@ -438,7 +438,7 @@ async fn get_outgoing_webhook_content_and_event_type( }) } }?; - let event_type = Option::<EventType>::foreign_from(payments_response.status); + let event_type: Option<EventType> = payments_response.status.into(); logger::debug!(current_resource_status=%payments_response.status); Ok(( @@ -462,7 +462,7 @@ async fn get_outgoing_webhook_content_and_event_type( request, )) .await?; - let event_type = Option::<EventType>::foreign_from(refund.refund_status); + let event_type: Option<EventType> = refund.refund_status.into(); logger::debug!(current_resource_status=%refund.refund_status); let refund_response = RefundResponse::foreign_from(refund); @@ -495,7 +495,7 @@ async fn get_outgoing_webhook_content_and_event_type( } } .map(Box::new)?; - let event_type = Some(EventType::foreign_from(dispute_response.dispute_status)); + let event_type = Some(EventType::from(dispute_response.dispute_status)); logger::debug!(current_resource_status=%dispute_response.dispute_status); Ok(( @@ -527,7 +527,7 @@ async fn get_outgoing_webhook_content_and_event_type( } } .map(Box::new)?; - let event_type = Option::<EventType>::foreign_from(mandate_response.status); + let event_type: Option<EventType> = mandate_response.status.into(); logger::debug!(current_resource_status=%mandate_response.status); Ok(( @@ -551,17 +551,10 @@ async fn get_outgoing_webhook_content_and_event_type( )) .await?; - let router_response = + let payout_create_response = payouts::response_handler(&state, &merchant_context, &payout_data).await?; - let payout_create_response: payout_models::PayoutCreateResponse = match router_response - { - ApplicationResponse::Json(response) => response, - _ => Err(errors::ApiErrorResponse::WebhookResourceNotFound) - .attach_printable("Failed to fetch the payout create response")?, - }; - - let event_type = Option::<EventType>::foreign_from(payout_data.payout_attempt.status); + let event_type: Option<EventType> = payout_data.payout_attempt.status.into(); logger::debug!(current_resource_status=%payout_data.payout_attempt.status); Ok(( diff --git a/crates/router/tests/utils.rs b/crates/router/tests/utils.rs index eb8ed7090df..20b83f47483 100644 --- a/crates/router/tests/utils.rs +++ b/crates/router/tests/utils.rs @@ -220,9 +220,6 @@ fn mk_merchant_account(merchant_id: Option<String>) -> Value { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", - "payment_created_enabled": true, - "payment_succeeded_enabled": true, - "payment_failed_enabled": true }, "routing_algorithm": { "type": "single", diff --git a/loadtest/k6/helper/setup.js b/loadtest/k6/helper/setup.js index 79e0146329e..18f10242a60 100644 --- a/loadtest/k6/helper/setup.js +++ b/loadtest/k6/helper/setup.js @@ -34,10 +34,7 @@ export function setup_merchant_apikey() { "webhook_details":{ "webhook_version":"1.0.1", "webhook_username":"wh_store", - "webhook_password":"pwd_wh@101", - "payment_created_enabled":true, - "payment_succeeded_enabled":true, - "payment_failed_enabled":true + "webhook_password":"pwd_wh@101" }, "routing_algorithm": { "type": "single", @@ -126,10 +123,7 @@ export function setup_merchant_apikey() { "webhook_details":{ "webhook_version":"1.0.1", "webhook_username":"wh_store", - "webhook_password":"pwd_wh@101", - "payment_created_enabled":true, - "payment_succeeded_enabled":true, - "payment_failed_enabled":true + "webhook_password":"pwd_wh@101" }, "routing_algorithm": { "type": "single",
2025-06-23T10:41:00Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This pull request introduces validation for webhook status configurations at the business profile level. Specifically, the following changes have been made: 1. **WebhookDetails Validation:** * Added a `validate()` method to the `WebhookDetails` struct in `crates/api_models/src/admin.rs`. * This method ensures that any statuses provided in `payment_statuses_enabled`, `refund_statuses_enabled`, and `payout_statuses_enabled` are valid and correspond to triggerable event types. 2. **API Handler Integration:** * Updated the API route handlers in `crates/router/src/routes/profiles.rs` for merchant account creation, merchant account updates, profile creation and profile updates. * These handlers now invoke the `WebhookDetails::validate()` method if `webhook_details` are present in the request payload. * If validation fails (i.e., an invalid status is provided), the API will return an `ApiErrorResponse::InvalidRequestData` with a descriptive message. 3. **Core flows - payments, refunds and payouts** * Added logic for checking if the resource status is eligible for triggering an outgoing webhook in the payment, refund and payout flows. * If statuses configured are empty in profile, it uses a default list for checking the eligibility. 4. **WASM functionalities** * Added functionality in WASM crate for fetching a list of valid webhook statuses which can be used to render on HyperSwitch dashboard for configurations. This ensures that only valid webhook configurations are accepted and stored, improving the robustness of the outgoing webhook system. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Allows merchants to configure different statuses for triggering outgoing webhooks. ## How did you test it? I. New behavior <details> <summary>1. Create Merchant Account with custom `webhook_details`</summary> cURL curl --location --request POST 'http://localhost:8080/accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data-raw '{"merchant_id":"merchant_1750673206","locker_id":"m0010","merchant_name":"NewAge Retailer","merchant_details":{"primary_contact_person":"John Test","primary_email":"[email protected]","primary_phone":"sunt laborum","secondary_contact_person":"John Test2","secondary_email":"[email protected]","secondary_phone":"cillum do dolor id","website":"https://www.example.com","about_business":"Online Retail with a wide selection of organic products for North America","address":{"line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"California","zip":"94122","country":"US"}},"return_url":"https://google.com/success","webhook_details":{"webhook_url":"https://webhook.site/ede0ddc6-5583-4a92-80e3-d513028c4fe2","webhook_version":"1.0.1","webhook_username":"random","webhook_password":"pass","payment_statuses_enabled":["requires_customer_action","failed"],"payout_statuses_enabled":["failed"],"refund_statuses_enabled":["success"]},"sub_merchants_enabled":false,"metadata":{"city":"NY","unit":"245"},"primary_business_details":[{"country":"IN","business":"default"}]}' Response {"merchant_id":"merchant_1750673203","merchant_name":"NewAge Retailer","return_url":"https://google.com/success","enable_payment_response_hash":true,"payment_response_hash_key":"pv3MWoTzwpOnCUWo8rkeBATn5QiaJ2MKtpKe9anxnqC2dt53I0pK6lH0yy50j1zT","redirect_to_merchant_with_http_post":false,"merchant_details":{"primary_contact_person":"John Test","primary_phone":"sunt laborum","primary_email":"[email protected]","secondary_contact_person":"John Test2","secondary_phone":"cillum do dolor id","secondary_email":"[email protected]","website":"https://www.example.com","about_business":"Online Retail with a wide selection of organic products for North America","address":{"city":"San Fransico","country":"US","line1":null,"line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"California","first_name":null,"last_name":null}},"webhook_details":{"webhook_version":"1.0.1","webhook_username":"random","webhook_password":"pass","webhook_url":"https://webhook.site/ede0ddc6-5583-4a92-80e3-d513028c4fe2","payment_statuses_enabled":["requires_customer_action","failed"],"refund_statuses_enabled":["success"],"payout_statuses_enabled":["failed"]},"payout_routing_algorithm":null,"sub_merchants_enabled":false,"parent_merchant_id":null,"publishable_key":"pk_dev_fdfb25c3c2294cf49aa1bb361afb1100","metadata":{"city":"NY","unit":"245","compatible_connector":null},"locker_id":"m0010","primary_business_details":[{"country":"IN","business":"default"}],"frm_routing_algorithm":null,"organization_id":"org_II9RJV4U9ZcIloWWrNbR","is_recon_enabled":false,"default_profile":"pro_65qra6NQYjw2UP9vperw","recon_status":"not_requested","pm_collect_link_config":null,"product_type":"orchestration","merchant_account_type":"standard"} Expectation - Only valid status can be specified for triggering webhooks across payments, refunds and payouts </details> <details> <summary>2. Create a payment</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_1MDGBqiM9KD4GY0mu6QfjecN40bJrnJWFDyGxxTdaGKKXt6xH3Jbrr59B0Ua4NPK' \ --data-raw '{"amount":4500,"currency":"EUR","confirm":true,"profile_id":"pro_pNXZoICIkiLUZEYSrKfX","capture_method":"manual","capture_on":"2022-09-10T10:11:12Z","authentication_type":"three_ds","setup_future_usage":"off_session","connector":["adyen"],"customer_id":"cus_zhY6PdgnyRlXLVGzqkvM","email":"[email protected]","return_url":"https://google.com","payment_method":"card","payment_method_type":"debit","payment_method_data":{"card":{"card_number":"4111112014267661","card_exp_month":"12","card_exp_year":"2030","card_cvc":"737"}},"billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"California","zip":"94122","country":"IT","first_name":"joseph","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"metadata":{"Force-PSP":"Adyen","udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"browser_info":{"user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"en-US","color_depth":32,"screen_height":1117,"screen_width":1728,"time_zone":-330,"java_enabled":true,"java_script_enabled":true,"ip_address":"127.0.0.1"},"customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"connector_metadata":{"adyen":{"testing":{}}},"session_expiry":60}' Response {"payment_id":"pay_iApiXN3tqc2yW1XBP0Ua","merchant_id":"merchant_1750673324","status":"requires_capture","amount":4500,"net_amount":4500,"shipping_cost":null,"amount_capturable":4500,"amount_received":null,"connector":"adyen","client_secret":"pay_iApiXN3tqc2yW1XBP0Ua_secret_AgBcvgc6zoSu2Qr2sq96","created":"2025-06-23T10:08:56.548Z","currency":"EUR","customer_id":"cus_zhY6PdgnyRlXLVGzqkvM","customer":{"id":"cus_zhY6PdgnyRlXLVGzqkvM","name":"John Nether","email":"[email protected]","phone":"6168205362","phone_country_code":"+1"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":"manual","payment_method":"card","payment_method_data":{"card":{"last4":"7661","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"411111","card_extended_bin":null,"card_exp_month":"12","card_exp_year":"2030","card_holder_name":null,"payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"IT","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"California","first_name":"joseph","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"order_details":null,"email":"[email protected]","name":"John Nether","phone":"6168205362","return_url":"https://google.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"debit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_zhY6PdgnyRlXLVGzqkvM","created_at":1750673336,"expires":1750676936,"secret":"epk_0e045ee6e8b3409da23d14233314639d"},"manual_retry_allowed":false,"connector_transaction_id":"GZD3LFQ2BDDHL975","frm_message":null,"metadata":{"udf1":"value1","Force-PSP":"Adyen","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":{"apple_pay":null,"airwallex":null,"noon":null,"braintree":null,"adyen":{"testing":{"holder_name":null}}},"feature_metadata":null,"reference_id":"pay_iApiXN3tqc2yW1XBP0Ua_1","payment_link":null,"profile_id":"pro_pNXZoICIkiLUZEYSrKfX","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_9dLJtXqFTDdVt4fwwLL4","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-06-23T10:09:56.548Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":32,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_method_id":"pm_4eqrT6kM50j4XdLyX6YK","payment_method_status":"active","updated":"2025-06-23T10:08:57.185Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":"JVZJSSRZPLSMC375","card_discovery":"manual","force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null,"is_iframe_redirection_enabled":null,"whole_connector_response":null} Expectation - A payment webhook must be triggered since the status reaches `requires_capture` which was configured for triggering webhooks </details> <details> <summary>3. Update an existing profile</summary> cURL curl --location --request POST 'http://localhost:8080/account/merchant_1750673423/business_profile/pro_vjiSMmVIZdLWNbPBnGXP' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_WWRksDrZIVkWppHEPz4MWFccxq9ZMEoGHTWRw1euMjstZC3XD51mGBc5NjMLVAwx' \ --data '{"webhook_details":{"webhook_url":"https://webhook.site/ede0ddc6-5583-4a92-80e3-d513028c4fe2","webhook_version":"1.0.1","webhook_username":"random","webhook_password":"pass","payment_statuses_enabled":["requires_capture","failed"],"payout_statuses_enabled":["failed"],"refund_statuses_enabled":["success"]}}' Response {"merchant_id":"merchant_1750673423","profile_id":"pro_vjiSMmVIZdLWNbPBnGXP","profile_name":"IN_default","return_url":"https://google.com/success","enable_payment_response_hash":true,"payment_response_hash_key":"EPy4DzeilG41Sz0g2krFOfbz9jI49AnrsljEPFkIqRhHn96Hh70NcvvrsXMsuiR9","redirect_to_merchant_with_http_post":false,"webhook_details":{"webhook_version":"1.0.1","webhook_username":"random","webhook_password":"pass","webhook_url":"https://webhook.site/ede0ddc6-5583-4a92-80e3-d513028c4fe2","payment_statuses_enabled":["requires_capture","failed"],"refund_statuses_enabled":["success"],"payout_statuses_enabled":["failed"]},"metadata":null,"routing_algorithm":null,"intent_fulfillment_time":900,"frm_routing_algorithm":null,"payout_routing_algorithm":null,"applepay_verified_domains":["gdpp-dev.zurich.com"],"session_expiry":900,"payment_link_config":{"domain_name":null,"theme":"#E1E1E1","logo":"https://hyperswitch.io/favicon.ico","seller_name":null,"sdk_layout":null,"display_sdk_only":null,"enabled_saved_payment_method":true,"hide_card_nickname_field":null,"show_card_form_by_default":null,"transaction_details":null,"background_image":null,"details_layout":null,"payment_button_text":null,"custom_message_for_card_terms":"","payment_button_colour":null,"skip_status_screen":null,"payment_button_text_colour":null,"background_colour":null,"sdk_ui_rules":null,"payment_link_ui_rules":null,"enable_button_only_on_form_ready":null,"payment_form_header_text":null,"payment_form_label_type":null,"show_card_terms":"always","is_setup_mandate_flow":null,"color_icon_card_cvc_error":null,"business_specific_configs":{"mendix":{"theme":null,"logo":"https://hyperswitch.io/favicon.ico","seller_name":null,"sdk_layout":null,"display_sdk_only":true,"enabled_saved_payment_method":null,"hide_card_nickname_field":null,"show_card_form_by_default":null,"transaction_details":null,"background_image":null,"details_layout":null,"payment_button_text":"Validate Card","custom_message_for_card_terms":null,"payment_button_colour":null,"skip_status_screen":null,"payment_button_text_colour":null,"background_colour":null,"sdk_ui_rules":{".Input--invalid":{"color":"#545454"},".w-full.relative.flex.flex-row.my-4":{"display":"none"},".Tab":{"display":"none"},".InputLogo":{"color":"#545454"},".Error":{"paddingLeft":"0px","opacity":"1","color":"#CB4B40","display":"block","fontSize":"12px","marginTop":"4px"},".Label":{"left":"0px","fontWeight":"300","color":"#2167AE","fontSize":"12px","bottom":"5px","marginLeft":"0px","opacity":"1","fontFamily":"'zurich-sans-Medium', sans-serif"},".InputLogo--empty":{"color":"#979797"},".flex.flex-col.gap-2.h-auto.w-full":{"display":"none"},".Input":{"paddingBottom":"2px","fontWeight":"400","boxSizing":"border-box","height":"56px","width":"100%","paddingLeft":"0px","backgroundColor":"white","display":"block","border":"none","fontSize":"18px","color":"#23366F","borderRadius":"0px","boxShadow":"none","borderBottom":"1px solid #2167AE","fontFamily":"'zurich-sans-Medium', sans-serif"},".Input:focus":{"outline":"none","borderBottom":"1px solid #2167AE","backgroundColor":"white"},".Label--floating":{"opacity":"1"},".Input:focus + .Label":{"opacity":"0 !important"},".PaymentLabel":{"color":"#545454","fontSize":"24px"},".Input--empty":{"backgroundColor":"white","boxShadow":"none","borderBottom":"1px solid #2167AE"},".TabHeader":{"display":"none"},".InputLogo--invalid":{"color":"#CB4B40"},".Input::placeholder":{"fontFamily":"'zurich-sans-light', sans-serif","fontSize":"18px","paddingLeft":"0px","color":"#C0C0C0"}},"payment_link_ui_rules":{"#submit.processing":{"paddingLeft":"50px !important","paddingRight":"50px !important"},"#submit":{"padding":"13px 20px","marginTop":"24px","width":"max-content !important","borderRadius":"50px !important","backgroundColor":"#2167AE !important","height":"max-content !important","fontSize":"14px !important"}},"enable_button_only_on_form_ready":true,"payment_form_header_text":null,"payment_form_label_type":null,"show_card_terms":null,"is_setup_mandate_flow":null,"color_icon_card_cvc_error":"#CB4B40"},"omnium":{"theme":null,"logo":"https://hyperswitch.io/favicon.ico","seller_name":null,"sdk_layout":null,"display_sdk_only":true,"enabled_saved_payment_method":true,"hide_card_nickname_field":null,"show_card_form_by_default":null,"transaction_details":null,"background_image":null,"details_layout":null,"payment_button_text":"Save Card","custom_message_for_card_terms":null,"payment_button_colour":"#c2c2c2","skip_status_screen":null,"payment_button_text_colour":null,"background_colour":null,"sdk_ui_rules":{".Input:not(.Input--empty) + .Label":{"opacity":"0 !important"},".Error":{"marginTop":"4px","display":"block","opacity":"1","fontSize":"12px","paddingLeft":"0px","color":"#CB4B40"},".Label--invalid":{"color":"#CB4B40 !important","opacity":"1 !important"},".InputLogo--empty":{"color":"#979797"},".Tab":{"display":"none"},".TabHeader":{"display":"none"},".InputLogo":{"color":"#545454"},".w-full.relative.flex.flex-row.my-4":{"display":"none"},".Input:focus":{"border":"none !important","outline":"none","borderBottom":"1px solid #C2C2C2 !important","backgroundColor":"white","color":"#C2C2C2"},".Label":{"marginLeft":"0px","bottom":"5px","pointerEvents":"none","left":"0px","color":"#C2C2C2","opacity":"1","fontSize":"14px"},".Input--invalid":{"color":"#CB4B40"},".Input::placeholder":{"color":"#C2C2C2","paddingLeft":"0px"},".Input":{"width":"100%","fontSize":"14px","fontFamily":"'Open Sans', sans-serif","padding":"0","boxSizing":"border-box","borderRadius":"0px","backgroundColor":"white","display":"block","borderBottom":"1px solid #C2C2C2 !important","border":"none !important","boxShadow":"none","color":"#C2C2C2"},".PaymentLabel":{"fontSize":"24px","color":"#545454"},".InputLogo--invalid":{"color":"#CB4B40"},".flex.flex-col.gap-2.h-auto.w-full":{"display":"none"},".Input--empty":{"color":"#C2C2C2","backgroundColor":"white"},".Input:focus + .Label":{"color":"transparent"}},"payment_link_ui_rules":{"#submit":{"height":"25px !important","width":"max-content !important","backgroundColour":"#c2c2c2 !important","padding":"0 8px","color":"#ffffff !important","margin":"0 0 4px auto","fontSize":"13px !important","border":"1px solid #c2c2c2 !important","borderRadius":"0 !important"},"#submit.not-ready":{"border":"1px solid #c2c2c2 !important","backgroundColor":"#ffffff !important","color":"#c2c2c2 !important"},"#submit-spinner":{"borderBottomColor":"#c2c2c2 !important","width":"20px !important","border":"2px solid #fff !important","height":"20px !important"}},"enable_button_only_on_form_ready":true,"payment_form_header_text":null,"payment_form_label_type":"floating","show_card_terms":null,"is_setup_mandate_flow":null,"color_icon_card_cvc_error":"#CB4B40"},"zproject":{"theme":null,"logo":"https://hyperswitch.io/favicon.ico","seller_name":null,"sdk_layout":null,"display_sdk_only":true,"enabled_saved_payment_method":null,"hide_card_nickname_field":null,"show_card_form_by_default":null,"transaction_details":null,"background_image":null,"details_layout":null,"payment_button_text":"Validate Card","custom_message_for_card_terms":null,"payment_button_colour":null,"skip_status_screen":null,"payment_button_text_colour":null,"background_colour":null,"sdk_ui_rules":{".Label":{"marginLeft":"0px","left":"0px","color":"#5495CF !important","fontFamily":"'zurich-sans-light', sans-serif","fontWeight":"400","fontSize":"14px","bottom":"5px","opacity":"1 !important"},".InputLogo":{"color":"#545454"},".PaymentLabel":{"fontSize":"24px","color":"#545454 !important"},".w-full.relative.flex.flex-row.my-4":{"display":"none"},".Input, .Input:focus, .Input--invalid, .Input--empty":{"height":"56px","fontSize":"18px","paddingLeft":"0px !important","borderBottom":"1px solid #5495CF","boxShadow":"none","width":"100%","display":"block","borderRadius":"0px","border":"none","boxSizing":"border-box","color":"#000000","paddingBottom":"2px !important","backgroundColor":"white !important","fontFamily":"'zurich-sans-Medium', sans-serif","fontWeight":"400"},".Input::placeholder":{"color":"#C0C0C0","fontSize":"14px","paddingLeft":"0px !important","fontFamily":"'zurich-sans-light', sans-serif"},".Tab":{"display":"none"},".InputLogo--invalid":{"color":"#CB4B40"},".Input--invalid":{"color":"#545454 !important"},".InputLogo--empty":{"color":"#979797"},".Error":{"fontSize":"12px","color":"#CB4B40 !important","marginTop":"4px","opacity":"1 !important","paddingLeft":"0px","display":"block"},".TabHeader":{"display":"none"},".Input:focus + .Label":{"opacity":"0 !important"},".flex.flex-col.gap-2.h-auto.w-full":{"display":"none"},".Label--floating":{"opacity":"1 !important"}},"payment_link_ui_rules":{"#submit":{"padding":"13px 20px","fontSize":"14px !important","borderRadius":"50px !important","height":"max-content !important","backgroundColor":"#5495CF !important","marginTop":"24px","width":"max-content !important"},"#submit.processing":{"paddingRight":"50px !important","paddingLeft":"50px !important"}},"enable_button_only_on_form_ready":true,"payment_form_header_text":null,"payment_form_label_type":null,"show_card_terms":null,"is_setup_mandate_flow":null,"color_icon_card_cvc_error":"#CB4B40"},"illustrator":{"theme":null,"logo":"https://hyperswitch.io/favicon.ico","seller_name":null,"sdk_layout":null,"display_sdk_only":true,"enabled_saved_payment_method":null,"hide_card_nickname_field":null,"show_card_form_by_default":null,"transaction_details":null,"background_image":null,"details_layout":null,"payment_button_text":"Save Card","custom_message_for_card_terms":null,"payment_button_colour":null,"skip_status_screen":null,"payment_button_text_colour":null,"background_colour":null,"sdk_ui_rules":{".Label--floating,":{"opacity":"1 !important"},".Label--invalid, .Error":{"opacity":"1 !important","color":"#f00 !important"},".InputLogo--empty":{"color":"#979797"},".TabHeader":{"display":"none"},".Input, .Input:focus, .Input--invalid, .Input--empty":{"width":"100%","fontFamily":"'Open Sans', sans-serif","paddingBottom":"2px !important","paddingLeft":"0px !important","height":"56px","fontWeight":"400","boxSizing":"border-box","color":"#494949","borderBottom":"1px solid #C2C2C2","borderRadius":"0px","backgroundColor":"white !important","display":"block","border":"none","fontSize":"14px","boxShadow":"none"},".InputLogo":{"color":"#545454"},".flex.flex-col.gap-2.h-auto.w-full":{"display":"none"},".Input::placeholder":{"color":"#979797","paddingLeft":"0px !important"},".Input--invalid":{"color":"#545454 !important","borderBottom":"1px solid #f00 !important"},".PaymentLabel":{"color":"#545454 !important","fontSize":"24px"},".w-full.relative.flex.flex-row.my-4":{"display":"none"},".Input:focus + .Label":{"opacity":"0 !important"},".Error":{"marginTop":"4px","fontSize":"12px","paddingLeft":"0px","color":"#f00 !important","display":"block","opacity":"1 !important"},".InputLogo--invalid":{"color":"#CB4B40"},".Tab":{"display":"none"},".Label":{"color":"#FF0022","left":"0px","opacity":"1 !important","marginLeft":"0px","bottom":"5px"}},"payment_link_ui_rules":{"#submit":{"margin":"0 4px 0 auto","fontSize":"13px !important","width":"max-content !important","borderRadius":"0 !important","border":"1px solid #b2b2b2 !important","backgroundColor":"#b2b2b2 !important","height":"25px !important","padding":"0 8px","color":"#ffffff !important"},"#submit.not-ready":{"color":"#b2b2b2 !important","border":"1px solid #b2b2b2 !important","backgroundColor":"#ffffff !important"},"#submit-spinner":{"height":"20px !important","width":"20px !important","borderBottomColor":"#c2c2c2 !important","border":"2px solid #fff !important"}},"enable_button_only_on_form_ready":true,"payment_form_header_text":null,"payment_form_label_type":null,"show_card_terms":null,"is_setup_mandate_flow":null,"color_icon_card_cvc_error":"#CB4B40"},"spain":{"theme":"#2167AE","logo":null,"seller_name":null,"sdk_layout":null,"display_sdk_only":true,"enabled_saved_payment_method":null,"hide_card_nickname_field":true,"show_card_form_by_default":null,"transaction_details":null,"background_image":null,"details_layout":null,"payment_button_text":null,"custom_message_for_card_terms":null,"payment_button_colour":null,"skip_status_screen":null,"payment_button_text_colour":null,"background_colour":null,"sdk_ui_rules":{".InputLogo":{"color":"#23366F"},".InputLogo--invalid":{"color":"#CB4B40"},".Input, .Input:focus, .Input--empty":{"color":"#23366F"},".Label--floating":{"opacity":"1 !important"},".Input, .Input:focus, .Input--invalid, .Input--empty":{"backgroundColor":"rgb(231, 234, 235) !important","paddingLeft":"22px !important","border":"none","boxShadow":"none","borderRadius":"28px","fontSize":"20px","height":"56px","paddingBottom":"2px !important"},".Label":{"color":"#2167AE","opacity":"1 !important","bottom":"5px","marginLeft":"22px"},".Label--invalid, .Input--invalid, .Error":{"color":"#CB4B40 !important","opacity":"1 !important"},".PaymentLabel":{"color":"#23366F !important","fontSize":"24px"},".InputLogo--empty":{"color":"#979797"},".Input--invalid":{"border":"2px solid #CB4B40 !important"}},"payment_link_ui_rules":{"#submit":{"height":"max-content","padding":"14px 20px","fontSize":"20px","marginTop":"48px","borderRadius":"50px"},"#submit.not-ready":{"backgroundColor":"#A6ADAF !important"},"#submit.processing":{"paddingRight":"50px !important","paddingLeft":"50px !important"}},"enable_button_only_on_form_ready":true,"payment_form_header_text":null,"payment_form_label_type":"floating","show_card_terms":"never","is_setup_mandate_flow":null,"color_icon_card_cvc_error":null}},"allowed_domains":["http://localhost:5500","localhost:5500","*","localhost:5501","http://localhost:5501"],"branding_visibility":false},"authentication_connector_details":null,"use_billing_as_payment_method_billing":true,"extended_card_info_config":null,"collect_shipping_details_from_wallet_connector":false,"collect_billing_details_from_wallet_connector":false,"always_collect_shipping_details_from_wallet_connector":false,"always_collect_billing_details_from_wallet_connector":false,"is_connector_agnostic_mit_enabled":true,"payout_link_config":null,"outgoing_webhook_custom_http_headers":null,"tax_connector_id":null,"is_tax_connector_enabled":false,"is_network_tokenization_enabled":true,"is_auto_retries_enabled":false,"max_auto_retries_enabled":null,"always_request_extended_authorization":null,"is_click_to_pay_enabled":false,"authentication_product_ids":null,"card_testing_guard_config":{"card_ip_blocking_status":"disabled","card_ip_blocking_threshold":3,"guest_user_card_blocking_status":"disabled","guest_user_card_blocking_threshold":10,"customer_id_blocking_status":"disabled","customer_id_blocking_threshold":5,"card_testing_guard_expiry":3600},"is_clear_pan_retries_enabled":false,"force_3ds_challenge":false,"is_debit_routing_enabled":false,"merchant_business_country":null,"is_pre_network_tokenization_enabled":false,"acquirer_configs":null,"is_iframe_redirection_enabled":null,"merchant_category_code":null} Expectation - Only valid status can be specified for triggering webhooks across payments, refunds and payouts </details> II. Existing behavior <details> <summary>1. Create Merchant account without specifying custom status list for triggering webhooks</summary> cURL curl --location --request POST 'http://localhost:8080/accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data-raw '{"merchant_id":"merchant_1750673427","locker_id":"m0010","merchant_name":"NewAge Retailer","merchant_details":{"primary_contact_person":"John Test","primary_email":"[email protected]","primary_phone":"sunt laborum","secondary_contact_person":"John Test2","secondary_email":"[email protected]","secondary_phone":"cillum do dolor id","website":"https://www.example.com","about_business":"Online Retail with a wide selection of organic products for North America","address":{"line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"California","zip":"94122","country":"US"}},"return_url":"https://google.com/success","webhook_details":{"webhook_url":"https://webhook.site/ede0ddc6-5583-4a92-80e3-d513028c4fe2","webhook_version":"1.0.1","webhook_username":"random","webhook_password":"pass"},"sub_merchants_enabled":false,"metadata":{"city":"NY","unit":"245"},"primary_business_details":[{"country":"IN","business":"default"}]}' Response {"merchant_id":"merchant_1750673423","merchant_name":"NewAge Retailer","return_url":"https://google.com/success","enable_payment_response_hash":true,"payment_response_hash_key":"EPy4DzeilG41Sz0g2krFOfbz9jI49AnrsljEPFkIqRhHn96Hh70NcvvrsXMsuiR9","redirect_to_merchant_with_http_post":false,"merchant_details":{"primary_contact_person":"John Test","primary_phone":"sunt laborum","primary_email":"[email protected]","secondary_contact_person":"John Test2","secondary_phone":"cillum do dolor id","secondary_email":"[email protected]","website":"https://www.example.com","about_business":"Online Retail with a wide selection of organic products for North America","address":{"city":"San Fransico","country":"US","line1":null,"line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"California","first_name":null,"last_name":null}},"webhook_details":{"webhook_version":"1.0.1","webhook_username":"random","webhook_password":"pass","webhook_url":"https://webhook.site/ede0ddc6-5583-4a92-80e3-d513028c4fe2","payment_statuses_enabled":null,"refund_statuses_enabled":null,"payout_statuses_enabled":null},"payout_routing_algorithm":null,"sub_merchants_enabled":false,"parent_merchant_id":null,"publishable_key":"pk_dev_429522d9b95049bb9f077fdbbf270d2c","metadata":{"city":"NY","unit":"245","compatible_connector":null},"locker_id":"m0010","primary_business_details":[{"country":"IN","business":"default"}],"frm_routing_algorithm":null,"organization_id":"org_wpDh2xmA3WgSWCi8Lzik","is_recon_enabled":false,"default_profile":"pro_vjiSMmVIZdLWNbPBnGXP","recon_status":"not_requested","pm_collect_link_config":null,"product_type":"orchestration","merchant_account_type":"standard"} </details> <details> <summary>2. Create a payment</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_WWRksDrZIVkWppHEPz4MWFccxq9ZMEoGHTWRw1euMjstZC3XD51mGBc5NjMLVAwx' \ --data-raw '{"amount":4500,"currency":"EUR","confirm":true,"profile_id":"pro_vjiSMmVIZdLWNbPBnGXP","capture_method":"manual","capture_on":"2022-09-10T10:11:12Z","authentication_type":"three_ds","setup_future_usage":"off_session","connector":["adyen"],"customer_id":"cus_zhY6PdgnyRlXLVGzqkvM","email":"[email protected]","return_url":"https://google.com","payment_method":"card","payment_method_type":"debit","payment_method_data":{"card":{"card_number":"4111112014267661","card_exp_month":"12","card_exp_year":"2030","card_cvc":"737"}},"billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"California","zip":"94122","country":"IT","first_name":"joseph","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"metadata":{"Force-PSP":"Adyen","udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"browser_info":{"user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"en-US","color_depth":32,"screen_height":1117,"screen_width":1728,"time_zone":-330,"java_enabled":true,"java_script_enabled":true,"ip_address":"127.0.0.1"},"customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"connector_metadata":{"adyen":{"testing":{}}},"session_expiry":60}' Response {"payment_id":"pay_g0OJdggJBGyoEzizQvs5","merchant_id":"merchant_1750673423","status":"requires_capture","amount":4500,"net_amount":4500,"shipping_cost":null,"amount_capturable":4500,"amount_received":null,"connector":"adyen","client_secret":"pay_g0OJdggJBGyoEzizQvs5_secret_hfNsAK9g7dE6py1TIyMV","created":"2025-06-23T10:11:45.123Z","currency":"EUR","customer_id":"cus_zhY6PdgnyRlXLVGzqkvM","customer":{"id":"cus_zhY6PdgnyRlXLVGzqkvM","name":null,"email":"[email protected]","phone":null,"phone_country_code":null},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":"manual","payment_method":"card","payment_method_data":{"card":{"last4":"7661","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"411111","card_extended_bin":null,"card_exp_month":"12","card_exp_year":"2030","card_holder_name":null,"payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"IT","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"California","first_name":"joseph","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":"[email protected]"},"order_details":null,"email":"[email protected]","name":null,"phone":null,"return_url":"https://google.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"debit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_zhY6PdgnyRlXLVGzqkvM","created_at":1750673505,"expires":1750677105,"secret":"epk_f3de069957be49b9b927d52fd2c01192"},"manual_retry_allowed":false,"connector_transaction_id":"NJHLXGQ2BDDHL975","frm_message":null,"metadata":{"udf1":"value1","Force-PSP":"Adyen","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":{"apple_pay":null,"airwallex":null,"noon":null,"braintree":null,"adyen":{"testing":{"holder_name":null}}},"feature_metadata":null,"reference_id":"pay_g0OJdggJBGyoEzizQvs5_1","payment_link":null,"profile_id":"pro_vjiSMmVIZdLWNbPBnGXP","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_q5cJJsbcZBqqwUZURC49","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-06-23T10:12:45.123Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":32,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_method_id":"pm_kWp3mS4JxBegRLBnls36","payment_method_status":"active","updated":"2025-06-23T10:11:46.750Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":"WCLS4TMLJZ545G75","card_discovery":"manual","force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null,"is_iframe_redirection_enabled":null,"whole_connector_response":null} Expectation - Webhook must not be triggered as payment status `requires_capture` is not configured for triggering webhooks by default </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
6fd7626c99e006bb7dcac864c30299bb8ef1d742
6fd7626c99e006bb7dcac864c30299bb8ef1d742
juspay/hyperswitch
juspay__hyperswitch-8343
Bug: Fix(CI): Update api-reference path in `pr_labeler` PR #8333 modified the `api-reference` folder structure. Need to update it in `pr_labeler` job
2025-06-13T10:24:29Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> - Updated OpenAPI spec path in `pr_labeler` CI job - Modified `CODEOWNERS` file to remove deleted folder ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #8343 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
07c93f183b13b0bfd2fbcdede33906852b0fca79
07c93f183b13b0bfd2fbcdede33906852b0fca79
juspay/hyperswitch
juspay__hyperswitch-8371
Bug: [REFACTOR]: Move Dummy connector Movement of dummy connector form `router` crate to `hyperswitch_connectors` crate
diff --git a/crates/hyperswitch_connectors/Cargo.toml b/crates/hyperswitch_connectors/Cargo.toml index 9233aa9bc5f..9e4996d14cd 100644 --- a/crates/hyperswitch_connectors/Cargo.toml +++ b/crates/hyperswitch_connectors/Cargo.toml @@ -11,6 +11,11 @@ payouts = ["hyperswitch_domain_models/payouts", "api_models/payouts", "hyperswit v1 = ["api_models/v1", "hyperswitch_domain_models/v1", "common_utils/v1"] v2 = ["api_models/v2", "hyperswitch_domain_models/v2", "common_utils/v2", "hyperswitch_interfaces/v2"] revenue_recovery = ["hyperswitch_interfaces/revenue_recovery", "hyperswitch_domain_models/revenue_recovery"] +default = ["dummy_connector"] +dummy_connector = [ + "hyperswitch_interfaces/dummy_connector", + "hyperswitch_domain_models/dummy_connector", +] [dependencies] actix-web = "4.11.0" diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs index b603923d985..15dc705db50 100644 --- a/crates/hyperswitch_connectors/src/connectors.rs +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -26,6 +26,8 @@ pub mod datatrans; pub mod deutschebank; pub mod digitalvirgo; pub mod dlocal; +#[cfg(feature = "dummy_connector")] +pub mod dummyconnector; pub mod ebanx; pub mod elavon; pub mod facilitapay; @@ -103,6 +105,8 @@ pub mod worldpayxml; pub mod xendit; pub mod zen; pub mod zsl; +#[cfg(feature = "dummy_connector")] +pub use self::dummyconnector::DummyConnector; pub use self::{ aci::Aci, adyen::Adyen, adyenplatform::Adyenplatform, airwallex::Airwallex, amazonpay::Amazonpay, archipel::Archipel, authorizedotnet::Authorizedotnet, bambora::Bambora, diff --git a/crates/hyperswitch_connectors/src/connectors/dummyconnector.rs b/crates/hyperswitch_connectors/src/connectors/dummyconnector.rs new file mode 100644 index 00000000000..c86ca3cb219 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/dummyconnector.rs @@ -0,0 +1,627 @@ +pub mod transformers; + +use std::fmt::Debug; + +use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId}; +use common_enums::{CaptureMethod, PaymentMethod, PaymentMethodType}; +use common_utils::{ + consts as common_consts, + errors::CustomResult, + ext_traits::BytesExt, + request::{Method, Request, RequestBuilder, RequestContent}, +}; +use error_stack::{report, ResultExt}; +use hyperswitch_domain_models::{ + router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, + router_flow_types::{ + AccessTokenAuth, Authorize, Capture, Execute, PSync, PaymentMethodToken, RSync, Session, + SetupMandate, Void, + }, + router_request_types::{ + AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, + RefundsData, SetupMandateRequestData, + }, + router_response_types::{PaymentsResponseData, RefundsResponseData}, + types::{ + PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, + RefundSyncRouterData, RefundsRouterData, + }, +}; +use hyperswitch_interfaces::{ + api::{ + ConnectorAccessToken, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, + ConnectorSpecifications, ConnectorValidation, MandateSetup, Payment, PaymentAuthorize, + PaymentCapture, PaymentSession, PaymentSync, PaymentToken, PaymentVoid, Refund, + RefundExecute, RefundSync, + }, + configs::Connectors, + errors::ConnectorError, + events::connector_api_logs::ConnectorEvent, + types::{ + PaymentsAuthorizeType, PaymentsCaptureType, PaymentsSyncType, RefundExecuteType, + RefundSyncType, Response, + }, + webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, +}; +use masking::{Mask as _, Maskable}; + +use crate::{ + constants::headers, + types::ResponseRouterData, + utils::{construct_not_supported_error_report, RefundsRequestData as _}, +}; + +#[derive(Debug, Clone)] +pub struct DummyConnector<const T: u8>; + +impl<const T: u8> Payment for DummyConnector<T> {} +impl<const T: u8> PaymentSession for DummyConnector<T> {} +impl<const T: u8> ConnectorAccessToken for DummyConnector<T> {} +impl<const T: u8> MandateSetup for DummyConnector<T> {} +impl<const T: u8> PaymentAuthorize for DummyConnector<T> {} +impl<const T: u8> PaymentSync for DummyConnector<T> {} +impl<const T: u8> PaymentCapture for DummyConnector<T> {} +impl<const T: u8> PaymentVoid for DummyConnector<T> {} +impl<const T: u8> Refund for DummyConnector<T> {} +impl<const T: u8> RefundExecute for DummyConnector<T> {} +impl<const T: u8> RefundSync for DummyConnector<T> {} +impl<const T: u8> PaymentToken for DummyConnector<T> {} + +impl<const T: u8> + ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for DummyConnector<T> +{ + // Not Implemented (R) +} + +impl<const T: u8, Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> + for DummyConnector<T> +where + Self: ConnectorIntegration<Flow, Request, Response>, +{ + fn build_headers( + &self, + req: &RouterData<Flow, Request, Response>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + let mut header = vec![ + ( + headers::CONTENT_TYPE.to_string(), + PaymentsAuthorizeType::get_content_type(self) + .to_string() + .into(), + ), + ( + common_consts::TENANT_HEADER.to_string(), + req.tenant_id.get_string_repr().to_string().into(), + ), + ]; + let mut api_key = self.get_auth_header(&req.connector_auth_type)?; + header.append(&mut api_key); + Ok(header) + } +} + +impl<const T: u8> ConnectorCommon for DummyConnector<T> { + fn id(&self) -> &'static str { + Into::<transformers::DummyConnectors>::into(T).get_dummy_connector_id() + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { + connectors.dummyconnector.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + let auth = transformers::DummyConnectorAuthType::try_from(auth_type) + .change_context(ConnectorError::FailedToObtainAuthType)?; + Ok(vec![( + headers::AUTHORIZATION.to_string(), + auth.api_key.into_masked(), + )]) + } + + fn build_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, ConnectorError> { + let response: transformers::DummyConnectorErrorResponse = res + .response + .parse_struct("DummyConnectorErrorResponse") + .change_context(ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + + Ok(ErrorResponse { + status_code: res.status_code, + code: response.error.code, + message: response.error.message, + reason: response.error.reason, + attempt_status: None, + connector_transaction_id: None, + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + }) + } +} + +impl<const T: u8> ConnectorValidation for DummyConnector<T> { + fn validate_connector_against_payment_request( + &self, + capture_method: Option<CaptureMethod>, + _payment_method: PaymentMethod, + _pmt: Option<PaymentMethodType>, + ) -> CustomResult<(), ConnectorError> { + let capture_method = capture_method.unwrap_or_default(); + match capture_method { + CaptureMethod::Automatic + | CaptureMethod::Manual + | CaptureMethod::SequentialAutomatic => Ok(()), + CaptureMethod::ManualMultiple | CaptureMethod::Scheduled => Err( + construct_not_supported_error_report(capture_method, self.id()), + ), + } + } +} + +impl<const T: u8> ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> + for DummyConnector<T> +{ + //TODO: implement sessions flow +} + +impl<const T: u8> ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> + for DummyConnector<T> +{ +} + +impl<const T: u8> ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> + for DummyConnector<T> +{ + fn build_request( + &self, + _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + Err( + ConnectorError::NotImplemented("Setup Mandate flow for DummyConnector".to_string()) + .into(), + ) + } +} + +impl<const T: u8> ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> + for DummyConnector<T> +{ + fn get_headers( + &self, + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { + match req.payment_method { + PaymentMethod::Card + | PaymentMethod::Upi + | PaymentMethod::Wallet + | PaymentMethod::PayLater => Ok(format!("{}/payment", self.base_url(connectors))), + _ => Err(error_stack::report!(ConnectorError::NotSupported { + message: format!("The payment method {} is not supported", req.payment_method), + connector: Into::<transformers::DummyConnectors>::into(T).get_dummy_connector_id(), + })), + } + } + + fn get_request_body( + &self, + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let connector_req = transformers::DummyConnectorPaymentsRequest::<T>::try_from(req)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?) + .set_body(PaymentsAuthorizeType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsAuthorizeRouterData, ConnectorError> { + let response: transformers::PaymentsResponse = res + .response + .parse_struct("DummyConnector PaymentsResponse") + .change_context(ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl<const T: u8> ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> + for DummyConnector<T> +{ + fn get_headers( + &self, + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { + match req + .request + .connector_transaction_id + .get_connector_transaction_id() + { + Ok(transaction_id) => Ok(format!( + "{}/payments/{}", + self.base_url(connectors), + transaction_id + )), + Err(_) => Err(error_stack::report!( + ConnectorError::MissingConnectorTransactionID + )), + } + } + + fn build_request( + &self, + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Get) + .url(&PaymentsSyncType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(PaymentsSyncType::get_headers(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsSyncRouterData, ConnectorError> { + let response: transformers::PaymentsResponse = res + .response + .parse_struct("dummyconnector PaymentsSyncResponse") + .change_context(ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl<const T: u8> ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> + for DummyConnector<T> +{ + fn get_headers( + &self, + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &PaymentsCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { + Err(ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + _req: &PaymentsCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + Err(ConnectorError::NotImplemented("get_request_body method".to_string()).into()) + } + + fn build_request( + &self, + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsCaptureType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(PaymentsCaptureType::get_headers(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsCaptureRouterData, ConnectorError> { + let response: transformers::PaymentsResponse = res + .response + .parse_struct("transformers PaymentsCaptureResponse") + .change_context(ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl<const T: u8> ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> + for DummyConnector<T> +{ +} + +impl<const T: u8> ConnectorIntegration<Execute, RefundsData, RefundsResponseData> + for DummyConnector<T> +{ + fn get_headers( + &self, + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { + Ok(format!( + "{}/{}/refund", + self.base_url(connectors), + req.request.connector_transaction_id + )) + } + + fn get_request_body( + &self, + req: &RefundsRouterData<Execute>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let connector_req = transformers::DummyConnectorRefundRequest::try_from(req)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&RefundExecuteType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(RefundExecuteType::get_headers(self, req, connectors)?) + .set_body(RefundExecuteType::get_request_body(self, req, connectors)?) + .build(); + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &RefundsRouterData<Execute>, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<RefundsRouterData<Execute>, ConnectorError> { + let response: transformers::RefundResponse = res + .response + .parse_struct("transformers RefundResponse") + .change_context(ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl<const T: u8> ConnectorIntegration<RSync, RefundsData, RefundsResponseData> + for DummyConnector<T> +{ + fn get_headers( + &self, + req: &RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + req: &RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { + let refund_id = req.request.get_connector_refund_id()?; + Ok(format!( + "{}/refunds/{}", + self.base_url(connectors), + refund_id + )) + } + + fn build_request( + &self, + req: &RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Get) + .url(&RefundSyncType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(RefundSyncType::get_headers(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<RefundSyncRouterData, ConnectorError> { + let response: transformers::RefundResponse = res + .response + .parse_struct("transformers RefundSyncResponse") + .change_context(ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +#[async_trait::async_trait] +impl<const T: u8> IncomingWebhook for DummyConnector<T> { + fn get_webhook_object_reference_id( + &self, + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<ObjectReferenceId, ConnectorError> { + Err(report!(ConnectorError::WebhooksNotImplemented)) + } + + fn get_webhook_event_type( + &self, + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<IncomingWebhookEvent, ConnectorError> { + Ok(IncomingWebhookEvent::EventNotSupported) + } + + fn get_webhook_resource_object( + &self, + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> { + Err(report!(ConnectorError::WebhooksNotImplemented)) + } +} + +impl<const T: u8> ConnectorSpecifications for DummyConnector<T> {} diff --git a/crates/router/src/connector/dummyconnector/transformers.rs b/crates/hyperswitch_connectors/src/connectors/dummyconnector/transformers.rs similarity index 54% rename from crates/router/src/connector/dummyconnector/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/dummyconnector/transformers.rs index 392a2249d92..d0662e8612a 100644 --- a/crates/router/src/connector/dummyconnector/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/dummyconnector/transformers.rs @@ -1,14 +1,23 @@ -use common_utils::pii; -use diesel_models::enums::Currency; +use common_enums::{AttemptStatus, Currency, RefundStatus}; +use common_utils::{pii, request::Method}; +use hyperswitch_domain_models::{ + payment_method_data::{ + Card, PayLaterData, PaymentMethodData, UpiCollectData, UpiData, WalletData, + }, + router_data::{ConnectorAuthType, RouterData}, + router_flow_types::{Execute, RSync}, + router_request_types::ResponseId, + router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, + types::{PaymentsAuthorizeRouterData, RefundsRouterData}, +}; +use hyperswitch_interfaces::errors::ConnectorError; use masking::Secret; use serde::{Deserialize, Serialize}; use url::Url; use crate::{ - connector::utils::RouterData, - core::errors, - services, - types::{self, api, domain, storage::enums}, + types::{RefundsResponseRouterData, ResponseRouterData}, + utils::RouterData as _, }; #[derive(Debug, Serialize, strum::Display, Eq, PartialEq)] @@ -63,14 +72,14 @@ impl From<u8> for DummyConnectors { pub struct DummyConnectorPaymentsRequest<const T: u8> { amount: i64, currency: Currency, - payment_method_data: PaymentMethodData, + payment_method_data: DummyPaymentMethodData, return_url: Option<String>, connector: DummyConnectors, } #[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)] #[serde(rename_all = "lowercase")] -pub enum PaymentMethodData { +pub enum DummyPaymentMethodData { Card(DummyConnectorCard), Wallet(DummyConnectorWallet), PayLater(DummyConnectorPayLater), @@ -88,15 +97,13 @@ pub struct DummyConnectorUpiCollect { vpa_id: Secret<String, pii::UpiVpaMaskingStrategy>, } -impl TryFrom<domain::UpiCollectData> for DummyConnectorUpi { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(value: domain::UpiCollectData) -> Result<Self, Self::Error> { +impl TryFrom<UpiCollectData> for DummyConnectorUpi { + type Error = error_stack::Report<ConnectorError>; + fn try_from(value: UpiCollectData) -> Result<Self, Self::Error> { Ok(Self::UpiCollect(DummyConnectorUpiCollect { - vpa_id: value - .vpa_id - .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "vpa_id", - })?, + vpa_id: value.vpa_id.ok_or(ConnectorError::MissingRequiredField { + field_name: "vpa_id", + })?, })) } } @@ -110,10 +117,10 @@ pub struct DummyConnectorCard { cvc: Secret<String>, } -impl TryFrom<(domain::Card, Option<Secret<String>>)> for DummyConnectorCard { - type Error = error_stack::Report<errors::ConnectorError>; +impl TryFrom<(Card, Option<Secret<String>>)> for DummyConnectorCard { + type Error = error_stack::Report<ConnectorError>; fn try_from( - (value, card_holder_name): (domain::Card, Option<Secret<String>>), + (value, card_holder_name): (Card, Option<Secret<String>>), ) -> Result<Self, Self::Error> { Ok(Self { name: card_holder_name.unwrap_or(Secret::new("".to_string())), @@ -135,17 +142,17 @@ pub enum DummyConnectorWallet { AliPayHK, } -impl TryFrom<domain::WalletData> for DummyConnectorWallet { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(value: domain::WalletData) -> Result<Self, Self::Error> { +impl TryFrom<WalletData> for DummyConnectorWallet { + type Error = error_stack::Report<ConnectorError>; + fn try_from(value: WalletData) -> Result<Self, Self::Error> { match value { - domain::WalletData::GooglePayRedirect(_) => Ok(Self::GooglePay), - domain::WalletData::PaypalRedirect(_) => Ok(Self::Paypal), - domain::WalletData::WeChatPayRedirect(_) => Ok(Self::WeChatPay), - domain::WalletData::MbWayRedirect(_) => Ok(Self::MbWay), - domain::WalletData::AliPayRedirect(_) => Ok(Self::AliPay), - domain::WalletData::AliPayHkRedirect(_) => Ok(Self::AliPayHK), - _ => Err(errors::ConnectorError::NotImplemented("Dummy wallet".to_string()).into()), + WalletData::GooglePayRedirect(_) => Ok(Self::GooglePay), + WalletData::PaypalRedirect(_) => Ok(Self::Paypal), + WalletData::WeChatPayRedirect(_) => Ok(Self::WeChatPay), + WalletData::MbWayRedirect(_) => Ok(Self::MbWay), + WalletData::AliPayRedirect(_) => Ok(Self::AliPay), + WalletData::AliPayHkRedirect(_) => Ok(Self::AliPayHK), + _ => Err(ConnectorError::NotImplemented("Dummy wallet".to_string()).into()), } } } @@ -157,52 +164,45 @@ pub enum DummyConnectorPayLater { AfterPayClearPay, } -impl TryFrom<domain::payments::PayLaterData> for DummyConnectorPayLater { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(value: domain::payments::PayLaterData) -> Result<Self, Self::Error> { +impl TryFrom<PayLaterData> for DummyConnectorPayLater { + type Error = error_stack::Report<ConnectorError>; + fn try_from(value: PayLaterData) -> Result<Self, Self::Error> { match value { - domain::payments::PayLaterData::KlarnaRedirect { .. } => Ok(Self::Klarna), - domain::payments::PayLaterData::AffirmRedirect {} => Ok(Self::Affirm), - domain::payments::PayLaterData::AfterpayClearpayRedirect { .. } => { - Ok(Self::AfterPayClearPay) - } - _ => Err(errors::ConnectorError::NotImplemented("Dummy pay later".to_string()).into()), + PayLaterData::KlarnaRedirect { .. } => Ok(Self::Klarna), + PayLaterData::AffirmRedirect {} => Ok(Self::Affirm), + PayLaterData::AfterpayClearpayRedirect { .. } => Ok(Self::AfterPayClearPay), + _ => Err(ConnectorError::NotImplemented("Dummy pay later".to_string()).into()), } } } -impl<const T: u8> TryFrom<&types::PaymentsAuthorizeRouterData> - for DummyConnectorPaymentsRequest<T> -{ - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - let payment_method_data: Result<PaymentMethodData, Self::Error> = match item - .request - .payment_method_data - { - domain::PaymentMethodData::Card(ref req_card) => { - let card_holder_name = item.get_optional_billing_full_name(); - Ok(PaymentMethodData::Card(DummyConnectorCard::try_from(( - req_card.clone(), - card_holder_name, - ))?)) - } - domain::PaymentMethodData::Upi(ref req_upi_data) => match req_upi_data { - domain::UpiData::UpiCollect(data) => Ok(PaymentMethodData::Upi( - DummyConnectorUpi::try_from(data.clone())?, - )), - domain::UpiData::UpiIntent(_) => { - Err(errors::ConnectorError::NotImplemented("UPI Intent".to_string()).into()) +impl<const T: u8> TryFrom<&PaymentsAuthorizeRouterData> for DummyConnectorPaymentsRequest<T> { + type Error = error_stack::Report<ConnectorError>; + fn try_from(item: &PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { + let payment_method_data: Result<DummyPaymentMethodData, Self::Error> = + match item.request.payment_method_data { + PaymentMethodData::Card(ref req_card) => { + let card_holder_name = item.get_optional_billing_full_name(); + Ok(DummyPaymentMethodData::Card(DummyConnectorCard::try_from( + (req_card.clone(), card_holder_name), + )?)) } - }, - domain::PaymentMethodData::Wallet(ref wallet_data) => { - Ok(PaymentMethodData::Wallet(wallet_data.clone().try_into()?)) - } - domain::PaymentMethodData::PayLater(ref pay_later_data) => Ok( - PaymentMethodData::PayLater(pay_later_data.clone().try_into()?), - ), - _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), - }; + PaymentMethodData::Upi(ref req_upi_data) => match req_upi_data { + UpiData::UpiCollect(data) => Ok(DummyPaymentMethodData::Upi( + DummyConnectorUpi::try_from(data.clone())?, + )), + UpiData::UpiIntent(_) => { + Err(ConnectorError::NotImplemented("UPI Intent".to_string()).into()) + } + }, + PaymentMethodData::Wallet(ref wallet_data) => Ok(DummyPaymentMethodData::Wallet( + wallet_data.clone().try_into()?, + )), + PaymentMethodData::PayLater(ref pay_later_data) => Ok( + DummyPaymentMethodData::PayLater(pay_later_data.clone().try_into()?), + ), + _ => Err(ConnectorError::NotImplemented("Payment methods".to_string()).into()), + }; Ok(Self { amount: item.request.amount, currency: item.request.currency, @@ -218,14 +218,14 @@ pub struct DummyConnectorAuthType { pub(super) api_key: Secret<String>, } -impl TryFrom<&types::ConnectorAuthType> for DummyConnectorAuthType { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { +impl TryFrom<&ConnectorAuthType> for DummyConnectorAuthType { + type Error = error_stack::Report<ConnectorError>; + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { - types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self { + ConnectorAuthType::HeaderKey { api_key } => Ok(Self { api_key: api_key.to_owned(), }), - _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + _ => Err(ConnectorError::FailedToObtainAuthType.into()), } } } @@ -240,7 +240,7 @@ pub enum DummyConnectorPaymentStatus { Processing, } -impl From<DummyConnectorPaymentStatus> for enums::AttemptStatus { +impl From<DummyConnectorPaymentStatus> for AttemptStatus { fn from(item: DummyConnectorPaymentStatus) -> Self { match item { DummyConnectorPaymentStatus::Succeeded => Self::Charged, @@ -275,24 +275,22 @@ pub enum DummyConnectorUpiType { UpiCollect, } -impl<F, T> TryFrom<types::ResponseRouterData<F, PaymentsResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, PaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: types::ResponseRouterData<F, PaymentsResponse, T, types::PaymentsResponseData>, + item: ResponseRouterData<F, PaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let redirection_data = item .response .next_action .and_then(|redirection_data| redirection_data.get_url()) - .map(|redirection_url| { - services::RedirectForm::from((redirection_url, services::Method::Get)) - }); + .map(|redirection_url| RedirectForm::from((redirection_url, Method::Get))); Ok(Self { - status: enums::AttemptStatus::from(item.response.status), - response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + status: AttemptStatus::from(item.response.status), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.id), redirection_data: Box::new(redirection_data), mandate_reference: Box::new(None), connector_metadata: None, @@ -327,9 +325,9 @@ pub struct DummyConnectorRefundRequest { pub amount: i64, } -impl<F> TryFrom<&types::RefundsRouterData<F>> for DummyConnectorRefundRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { +impl<F> TryFrom<&RefundsRouterData<F>> for DummyConnectorRefundRequest { + type Error = error_stack::Report<ConnectorError>; + fn try_from(item: &RefundsRouterData<F>) -> Result<Self, Self::Error> { Ok(Self { amount: item.request.refund_amount, }) @@ -341,19 +339,19 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for DummyConnectorRefundRequest { #[allow(dead_code)] #[derive(Debug, Serialize, Default, Deserialize, Clone)] #[serde(rename_all = "lowercase")] -pub enum RefundStatus { +pub enum DummyRefundStatus { Succeeded, Failed, #[default] Processing, } -impl From<RefundStatus> for enums::RefundStatus { - fn from(item: RefundStatus) -> Self { +impl From<DummyRefundStatus> for RefundStatus { + fn from(item: DummyRefundStatus) -> Self { match item { - RefundStatus::Succeeded => Self::Success, - RefundStatus::Failed => Self::Failure, - RefundStatus::Processing => Self::Pending, + DummyRefundStatus::Succeeded => Self::Success, + DummyRefundStatus::Failed => Self::Failure, + DummyRefundStatus::Processing => Self::Pending, //TODO: Review mapping } } @@ -362,41 +360,37 @@ impl From<RefundStatus> for enums::RefundStatus { #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse { id: String, - status: RefundStatus, + status: DummyRefundStatus, currency: Currency, created: String, payment_amount: i64, refund_amount: i64, } -impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> - for types::RefundsRouterData<api::Execute> -{ - type Error = error_stack::Report<errors::ConnectorError>; +impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, + item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(types::RefundsResponseData { + response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), - refund_status: enums::RefundStatus::from(item.response.status), + refund_status: RefundStatus::from(item.response.status), }), ..item.data }) } } -impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> - for types::RefundsRouterData<api::RSync> -{ - type Error = error_stack::Report<errors::ConnectorError>; +impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: types::RefundsResponseRouterData<api::RSync, RefundResponse>, + item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(types::RefundsResponseData { + response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), - refund_status: enums::RefundStatus::from(item.response.status), + refund_status: RefundStatus::from(item.response.status), }), ..item.data }) diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 7c46a8ffc05..e78067e24e3 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -1,9 +1,29 @@ +#[cfg(feature = "dummy_connector")] +use common_enums::{CallConnectorAction, PaymentAction}; // impl api::PaymentIncrementalAuthorization for Helcim {} // impl api::ConnectorCustomer for Helcim {} // impl api::PaymentsPreProcessing for Helcim {} // impl api::PaymentReject for Helcim {} // impl api::PaymentApprove for Helcim {} use common_utils::errors::CustomResult; +#[cfg(all(feature = "v2", feature = "revenue_recovery"))] +use hyperswitch_domain_models::router_flow_types::{ + BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, RecoveryRecordBack, +}; +#[cfg(feature = "dummy_connector")] +use hyperswitch_domain_models::router_request_types::authentication::{ + ConnectorAuthenticationRequestData, ConnectorPostAuthenticationRequestData, PreAuthNRequestData, +}; +#[cfg(all(feature = "v2", feature = "revenue_recovery"))] +use hyperswitch_domain_models::router_request_types::revenue_recovery::{ + BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest, + RevenueRecoveryRecordBackRequest, +}; +#[cfg(all(feature = "v2", feature = "revenue_recovery"))] +use hyperswitch_domain_models::router_response_types::revenue_recovery::{ + BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse, + RevenueRecoveryRecordBackResponse, +}; #[cfg(feature = "frm")] use hyperswitch_domain_models::{ router_flow_types::fraud_check::{Checkout, Fulfillment, RecordReturn, Sale, Transaction}, @@ -22,12 +42,6 @@ use hyperswitch_domain_models::{ router_request_types::PayoutsData, router_response_types::PayoutsResponseData, }; -#[cfg(all(feature = "v2", feature = "revenue_recovery"))] -use hyperswitch_domain_models::{ - router_flow_types::revenue_recovery as recovery_router_flows, - router_request_types::revenue_recovery as recovery_request, - router_response_types::revenue_recovery as recovery_response, -}; use hyperswitch_domain_models::{ router_flow_types::{ authentication::{ @@ -79,6 +93,12 @@ use hyperswitch_interfaces::api::payouts::{ }; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] use hyperswitch_interfaces::api::revenue_recovery as recovery_traits; +#[cfg(all(feature = "v2", feature = "revenue_recovery"))] +use hyperswitch_interfaces::api::revenue_recovery::{ + BillingConnectorInvoiceSyncIntegration, BillingConnectorPaymentsSyncIntegration, +}; +#[cfg(feature = "dummy_connector")] +use hyperswitch_interfaces::api::ConnectorVerifyWebhookSource; use hyperswitch_interfaces::{ api::{ self, @@ -5144,9 +5164,9 @@ macro_rules! default_imp_for_billing_connector_payment_sync { $( impl recovery_traits::BillingConnectorPaymentsSyncIntegration for $path::$connector {} impl ConnectorIntegration< - recovery_router_flows::BillingConnectorPaymentsSync, - recovery_request::BillingConnectorPaymentsSyncRequest, - recovery_response::BillingConnectorPaymentsSyncResponse + BillingConnectorPaymentsSync, + BillingConnectorPaymentsSyncRequest, + BillingConnectorPaymentsSyncResponse > for $path::$connector {} )* @@ -5267,9 +5287,9 @@ macro_rules! default_imp_for_revenue_recovery_record_back { $( impl recovery_traits::RevenueRecoveryRecordBack for $path::$connector {} impl ConnectorIntegration< - recovery_router_flows::RecoveryRecordBack, - recovery_request::RevenueRecoveryRecordBackRequest, - recovery_response::RevenueRecoveryRecordBackResponse + RecoveryRecordBack, + RevenueRecoveryRecordBackRequest, + RevenueRecoveryRecordBackResponse > for $path::$connector {} )* @@ -5389,9 +5409,9 @@ macro_rules! default_imp_for_billing_connector_invoice_sync { $( impl recovery_traits::BillingConnectorInvoiceSyncIntegration for $path::$connector {} impl ConnectorIntegration< - recovery_router_flows::BillingConnectorInvoiceSync, - recovery_request::BillingConnectorInvoiceSyncRequest, - recovery_response::BillingConnectorInvoiceSyncResponse + BillingConnectorInvoiceSync, + BillingConnectorInvoiceSyncRequest, + BillingConnectorInvoiceSyncResponse > for $path::$connector {} )* @@ -6108,3 +6128,506 @@ default_imp_for_external_vault_create!( connectors::Zen, connectors::Zsl ); + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> PaymentsCompleteAuthorize for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData> + for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ConnectorVerifyWebhookSource for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + ConnectorIntegration< + VerifyWebhookSource, + VerifyWebhookSourceRequestData, + VerifyWebhookSourceResponseData, + > for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ConnectorCustomer for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData> + for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ConnectorRedirectResponse for connectors::DummyConnector<T> { + fn get_flow_type( + &self, + _query_params: &str, + _json_payload: Option<serde_json::Value>, + _action: PaymentAction, + ) -> CustomResult<CallConnectorAction, ConnectorError> { + Ok(CallConnectorAction::Trigger) + } +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ConnectorTransactionId for connectors::DummyConnector<T> {} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> Dispute for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> AcceptDispute for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ConnectorIntegration<Accept, AcceptDisputeRequestData, AcceptDisputeResponse> + for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> FileUpload for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> UploadFile for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ConnectorIntegration<Upload, UploadFileRequestData, UploadFileResponse> + for connectors::DummyConnector<T> +{ +} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> RetrieveFile for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ConnectorIntegration<Retrieve, RetrieveFileRequestData, RetrieveFileResponse> + for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> SubmitEvidence for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ConnectorIntegration<Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse> + for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> DefendDispute for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ConnectorIntegration<Defend, DefendDisputeRequestData, DefendDisputeResponse> + for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> PaymentsPreProcessing for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData> + for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> PaymentsPostProcessing for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + ConnectorIntegration<PostProcessing, PaymentsPostProcessingData, PaymentsResponseData> + for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> api::Payouts for connectors::DummyConnector<T> {} + +#[cfg(feature = "payouts")] +#[cfg(feature = "dummy_connector")] +impl<const T: u8> PayoutCreate for connectors::DummyConnector<T> {} +#[cfg(feature = "payouts")] +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ConnectorIntegration<PoCreate, PayoutsData, PayoutsResponseData> + for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "payouts")] +#[cfg(feature = "dummy_connector")] +impl<const T: u8> PayoutSync for connectors::DummyConnector<T> {} +#[cfg(feature = "payouts")] +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ConnectorIntegration<PoSync, PayoutsData, PayoutsResponseData> + for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "payouts")] +#[cfg(feature = "dummy_connector")] +impl<const T: u8> PayoutEligibility for connectors::DummyConnector<T> {} +#[cfg(feature = "payouts")] +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ConnectorIntegration<PoEligibility, PayoutsData, PayoutsResponseData> + for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "payouts")] +#[cfg(feature = "dummy_connector")] +impl<const T: u8> PayoutFulfill for connectors::DummyConnector<T> {} +#[cfg(feature = "payouts")] +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> + for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "payouts")] +#[cfg(feature = "dummy_connector")] +impl<const T: u8> PayoutCancel for connectors::DummyConnector<T> {} +#[cfg(feature = "payouts")] +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ConnectorIntegration<PoCancel, PayoutsData, PayoutsResponseData> + for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "payouts")] +#[cfg(feature = "dummy_connector")] +impl<const T: u8> PayoutQuote for connectors::DummyConnector<T> {} +#[cfg(feature = "payouts")] +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ConnectorIntegration<PoQuote, PayoutsData, PayoutsResponseData> + for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "payouts")] +#[cfg(feature = "dummy_connector")] +impl<const T: u8> PayoutRecipient for connectors::DummyConnector<T> {} +#[cfg(feature = "payouts")] +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ConnectorIntegration<PoRecipient, PayoutsData, PayoutsResponseData> + for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "payouts")] +#[cfg(feature = "dummy_connector")] +impl<const T: u8> PayoutRecipientAccount for connectors::DummyConnector<T> {} +#[cfg(feature = "payouts")] +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ConnectorIntegration<PoRecipientAccount, PayoutsData, PayoutsResponseData> + for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> PaymentApprove for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ConnectorIntegration<Approve, PaymentsApproveData, PaymentsResponseData> + for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> PaymentReject for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ConnectorIntegration<Reject, PaymentsRejectData, PaymentsResponseData> + for connectors::DummyConnector<T> +{ +} +#[cfg(all(feature = "frm", feature = "dummy_connector"))] +impl<const T: u8> FraudCheck for connectors::DummyConnector<T> {} + +#[cfg(all(feature = "frm", feature = "dummy_connector"))] +impl<const T: u8> FraudCheckSale for connectors::DummyConnector<T> {} +#[cfg(all(feature = "frm", feature = "dummy_connector"))] +impl<const T: u8> ConnectorIntegration<Sale, FraudCheckSaleData, FraudCheckResponseData> + for connectors::DummyConnector<T> +{ +} + +#[cfg(all(feature = "frm", feature = "dummy_connector"))] +impl<const T: u8> FraudCheckCheckout for connectors::DummyConnector<T> {} +#[cfg(all(feature = "frm", feature = "dummy_connector"))] +impl<const T: u8> ConnectorIntegration<Checkout, FraudCheckCheckoutData, FraudCheckResponseData> + for connectors::DummyConnector<T> +{ +} + +#[cfg(all(feature = "frm", feature = "dummy_connector"))] +impl<const T: u8> FraudCheckTransaction for connectors::DummyConnector<T> {} +#[cfg(all(feature = "frm", feature = "dummy_connector"))] +impl<const T: u8> + ConnectorIntegration<Transaction, FraudCheckTransactionData, FraudCheckResponseData> + for connectors::DummyConnector<T> +{ +} + +#[cfg(all(feature = "frm", feature = "dummy_connector"))] +impl<const T: u8> FraudCheckFulfillment for connectors::DummyConnector<T> {} +#[cfg(all(feature = "frm", feature = "dummy_connector"))] +impl<const T: u8> + ConnectorIntegration<Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData> + for connectors::DummyConnector<T> +{ +} + +#[cfg(all(feature = "frm", feature = "dummy_connector"))] +impl<const T: u8> FraudCheckRecordReturn for connectors::DummyConnector<T> {} +#[cfg(all(feature = "frm", feature = "dummy_connector"))] +impl<const T: u8> + ConnectorIntegration<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData> + for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> PaymentIncrementalAuthorization for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + ConnectorIntegration< + IncrementalAuthorization, + PaymentsIncrementalAuthorizationData, + PaymentsResponseData, + > for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ConnectorMandateRevoke for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData> + for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ExternalAuthentication for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ConnectorPreAuthentication for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ConnectorPreAuthenticationVersionCall for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ConnectorAuthentication for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ConnectorPostAuthentication for connectors::DummyConnector<T> {} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + ConnectorIntegration< + Authentication, + ConnectorAuthenticationRequestData, + AuthenticationResponseData, + > for connectors::DummyConnector<T> +{ +} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + ConnectorIntegration<PreAuthentication, PreAuthNRequestData, AuthenticationResponseData> + for connectors::DummyConnector<T> +{ +} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + ConnectorIntegration< + PreAuthenticationVersionCall, + PreAuthNRequestData, + AuthenticationResponseData, + > for connectors::DummyConnector<T> +{ +} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + ConnectorIntegration< + PostAuthentication, + ConnectorPostAuthenticationRequestData, + AuthenticationResponseData, + > for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> PaymentAuthorizeSessionToken for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + ConnectorIntegration<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData> + for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> TaxCalculation for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + ConnectorIntegration<CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData> + for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> PaymentSessionUpdate for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + ConnectorIntegration<SdkSessionUpdate, SdkPaymentsSessionUpdateData, PaymentsResponseData> + for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> PaymentPostSessionTokens for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + ConnectorIntegration<PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData> + for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> PaymentsCreateOrder for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ConnectorIntegration<CreateOrder, CreateOrderRequestData, PaymentsResponseData> + for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> PaymentUpdateMetadata for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + ConnectorIntegration<UpdateMetadata, PaymentsUpdateMetadataData, PaymentsResponseData> + for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> UasPreAuthentication for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> UnifiedAuthenticationService for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + ConnectorIntegration< + PreAuthenticate, + UasPreAuthenticationRequestData, + UasAuthenticationResponseData, + > for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> UasPostAuthentication for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + ConnectorIntegration< + PostAuthenticate, + UasPostAuthenticationRequestData, + UasAuthenticationResponseData, + > for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> UasAuthenticationConfirmation for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + ConnectorIntegration< + AuthenticationConfirmation, + UasConfirmationRequestData, + UasAuthenticationResponseData, + > for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> UasAuthentication for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + ConnectorIntegration<Authenticate, UasAuthenticationRequestData, UasAuthenticationResponseData> + for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> RevenueRecovery for connectors::DummyConnector<T> {} + +#[cfg(all(feature = "v2", feature = "revenue_recovery"))] +#[cfg(feature = "dummy_connector")] +impl<const T: u8> api::revenue_recovery::BillingConnectorPaymentsSyncIntegration + for connectors::DummyConnector<T> +{ +} +#[cfg(all(feature = "v2", feature = "revenue_recovery"))] +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + ConnectorIntegration< + BillingConnectorPaymentsSync, + BillingConnectorPaymentsSyncRequest, + BillingConnectorPaymentsSyncResponse, + > for connectors::DummyConnector<T> +{ +} + +#[cfg(all(feature = "v2", feature = "revenue_recovery"))] +#[cfg(feature = "dummy_connector")] +impl<const T: u8> api::revenue_recovery::RevenueRecoveryRecordBack + for connectors::DummyConnector<T> +{ +} +#[cfg(all(feature = "v2", feature = "revenue_recovery"))] +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + ConnectorIntegration< + RecoveryRecordBack, + RevenueRecoveryRecordBackRequest, + RevenueRecoveryRecordBackResponse, + > for connectors::DummyConnector<T> +{ +} + +#[cfg(all(feature = "v2", feature = "revenue_recovery"))] +#[cfg(feature = "dummy_connector")] +impl<const T: u8> BillingConnectorInvoiceSyncIntegration for connectors::DummyConnector<T> {} +#[cfg(all(feature = "v2", feature = "revenue_recovery"))] +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + ConnectorIntegration< + BillingConnectorInvoiceSync, + BillingConnectorInvoiceSyncRequest, + BillingConnectorInvoiceSyncResponse, + > for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ExternalVault for connectors::DummyConnector<T> {} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ExternalVaultInsert for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ConnectorIntegration<ExternalVaultInsertFlow, VaultRequestData, VaultResponseData> + for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ExternalVaultRetrieve for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + ConnectorIntegration<ExternalVaultRetrieveFlow, VaultRequestData, VaultResponseData> + for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ExternalVaultDelete for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ConnectorIntegration<ExternalVaultDeleteFlow, VaultRequestData, VaultResponseData> + for connectors::DummyConnector<T> +{ +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ExternalVaultCreate for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ConnectorIntegration<ExternalVaultCreateFlow, VaultRequestData, VaultResponseData> + for connectors::DummyConnector<T> +{ +} diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 82ea4945942..e0ae9fe8782 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -26,7 +26,7 @@ oltp = ["storage_impl/oltp"] kv_store = ["scheduler/kv_store"] accounts_cache = [] vergen = ["router_env/vergen"] -dummy_connector = ["api_models/dummy_connector", "euclid/dummy_connector", "hyperswitch_interfaces/dummy_connector", "kgraph_utils/dummy_connector", "payment_methods/dummy_connector", "hyperswitch_domain_models/dummy_connector"] +dummy_connector = ["api_models/dummy_connector", "euclid/dummy_connector", "hyperswitch_interfaces/dummy_connector", "kgraph_utils/dummy_connector", "payment_methods/dummy_connector", "hyperswitch_domain_models/dummy_connector","hyperswitch_connectors/dummy_connector"] external_access_dc = ["dummy_connector"] detailed_errors = ["api_models/detailed_errors", "error-stack/serde"] payouts = ["api_models/payouts", "common_enums/payouts", "hyperswitch_connectors/payouts", "hyperswitch_domain_models/payouts", "storage_impl/payouts", "payment_methods/payouts"] diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index a5af15325fc..4a6ae9b6680 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -1,7 +1,7 @@ -#[cfg(feature = "dummy_connector")] -pub mod dummyconnector; pub mod utils; +#[cfg(feature = "dummy_connector")] +pub use hyperswitch_connectors::connectors::DummyConnector; pub use hyperswitch_connectors::connectors::{ aci, aci::Aci, adyen, adyen::Adyen, adyenplatform, adyenplatform::Adyenplatform, airwallex, airwallex::Airwallex, amazonpay, amazonpay::Amazonpay, archipel, archipel::Archipel, @@ -41,6 +41,3 @@ pub use hyperswitch_connectors::connectors::{ worldpayvantiv::Worldpayvantiv, worldpayxml, worldpayxml::Worldpayxml, xendit, xendit::Xendit, zen, zen::Zen, zsl, zsl::Zsl, }; - -#[cfg(feature = "dummy_connector")] -pub use self::dummyconnector::DummyConnector; diff --git a/crates/router/src/connector/dummyconnector.rs b/crates/router/src/connector/dummyconnector.rs deleted file mode 100644 index ea63a27102c..00000000000 --- a/crates/router/src/connector/dummyconnector.rs +++ /dev/null @@ -1,630 +0,0 @@ -pub mod transformers; - -use std::fmt::Debug; - -use common_utils::{consts as common_consts, request::RequestContent}; -use diesel_models::enums; -use error_stack::{report, ResultExt}; - -use super::utils::RefundsRequestData; -use crate::{ - configs::settings, - connector::utils as connector_utils, - core::errors::{self, CustomResult}, - events::connector_api_logs::ConnectorEvent, - headers, - services::{ - self, - request::{self, Mask}, - ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, - }, - types::{ - self, - api::{self, ConnectorCommon, ConnectorCommonExt}, - ErrorResponse, Response, - }, - utils::BytesExt, -}; - -#[derive(Debug, Clone)] -pub struct DummyConnector<const T: u8>; - -impl<const T: u8> api::Payment for DummyConnector<T> {} -impl<const T: u8> api::PaymentSession for DummyConnector<T> {} -impl<const T: u8> api::ConnectorAccessToken for DummyConnector<T> {} -impl<const T: u8> api::MandateSetup for DummyConnector<T> {} -impl<const T: u8> api::PaymentAuthorize for DummyConnector<T> {} -impl<const T: u8> api::PaymentSync for DummyConnector<T> {} -impl<const T: u8> api::PaymentCapture for DummyConnector<T> {} -impl<const T: u8> api::PaymentVoid for DummyConnector<T> {} -impl<const T: u8> api::Refund for DummyConnector<T> {} -impl<const T: u8> api::RefundExecute for DummyConnector<T> {} -impl<const T: u8> api::RefundSync for DummyConnector<T> {} -impl<const T: u8> api::PaymentToken for DummyConnector<T> {} - -impl<const T: u8> - ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for DummyConnector<T> -{ - // Not Implemented (R) -} - -impl<const T: u8, Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> - for DummyConnector<T> -where - Self: ConnectorIntegration<Flow, Request, Response>, -{ - fn build_headers( - &self, - req: &types::RouterData<Flow, Request, Response>, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - let mut header = vec![ - ( - headers::CONTENT_TYPE.to_string(), - types::PaymentsAuthorizeType::get_content_type(self) - .to_string() - .into(), - ), - ( - common_consts::TENANT_HEADER.to_string(), - req.tenant_id.get_string_repr().to_string().into(), - ), - ]; - let mut api_key = self.get_auth_header(&req.connector_auth_type)?; - header.append(&mut api_key); - Ok(header) - } -} - -impl<const T: u8> ConnectorCommon for DummyConnector<T> { - fn id(&self) -> &'static str { - Into::<transformers::DummyConnectors>::into(T).get_dummy_connector_id() - } - - fn common_get_content_type(&self) -> &'static str { - "application/json" - } - - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { - connectors.dummyconnector.base_url.as_ref() - } - - fn get_auth_header( - &self, - auth_type: &types::ConnectorAuthType, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - let auth = transformers::DummyConnectorAuthType::try_from(auth_type) - .change_context(errors::ConnectorError::FailedToObtainAuthType)?; - Ok(vec![( - headers::AUTHORIZATION.to_string(), - auth.api_key.into_masked(), - )]) - } - - fn build_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - let response: transformers::DummyConnectorErrorResponse = res - .response - .parse_struct("DummyConnectorErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - - event_builder.map(|i| i.set_error_response_body(&response)); - router_env::logger::info!(connector_response=?response); - - Ok(ErrorResponse { - status_code: res.status_code, - code: response.error.code, - message: response.error.message, - reason: response.error.reason, - attempt_status: None, - connector_transaction_id: None, - network_advice_code: None, - network_decline_code: None, - network_error_message: None, - }) - } -} - -impl<const T: u8> ConnectorValidation for DummyConnector<T> { - fn validate_connector_against_payment_request( - &self, - capture_method: Option<enums::CaptureMethod>, - _payment_method: enums::PaymentMethod, - _pmt: Option<enums::PaymentMethodType>, - ) -> CustomResult<(), errors::ConnectorError> { - let capture_method = capture_method.unwrap_or_default(); - match capture_method { - enums::CaptureMethod::Automatic - | enums::CaptureMethod::Manual - | enums::CaptureMethod::SequentialAutomatic => Ok(()), - enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( - connector_utils::construct_not_supported_error_report(capture_method, self.id()), - ), - } - } -} - -impl<const T: u8> - ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> - for DummyConnector<T> -{ - //TODO: implement sessions flow -} - -impl<const T: u8> - ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> - for DummyConnector<T> -{ -} - -impl<const T: u8> - ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for DummyConnector<T> -{ - fn build_request( - &self, - _req: &types::RouterData< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - >, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented( - "Setup Mandate flow for DummyConnector".to_string(), - ) - .into()) - } -} - -impl<const T: u8> - ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> - for DummyConnector<T> -{ - fn get_headers( - &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, connectors) - } - - fn get_content_type(&self) -> &'static str { - self.common_get_content_type() - } - - fn get_url( - &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - match req.payment_method { - enums::PaymentMethod::Card - | enums::PaymentMethod::Upi - | enums::PaymentMethod::Wallet - | enums::PaymentMethod::PayLater => { - Ok(format!("{}/payment", self.base_url(connectors))) - } - _ => Err(error_stack::report!(errors::ConnectorError::NotSupported { - message: format!("The payment method {} is not supported", req.payment_method), - connector: Into::<transformers::DummyConnectors>::into(T).get_dummy_connector_id(), - })), - } - } - - fn get_request_body( - &self, - req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = transformers::DummyConnectorPaymentsRequest::<T>::try_from(req)?; - Ok(RequestContent::Json(Box::new(connector_req))) - } - - fn build_request( - &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsAuthorizeType::get_url( - self, req, connectors, - )?) - .attach_default_headers() - .headers(types::PaymentsAuthorizeType::get_headers( - self, req, connectors, - )?) - .set_body(types::PaymentsAuthorizeType::get_request_body( - self, req, connectors, - )?) - .build(), - )) - } - - fn handle_response( - &self, - data: &types::PaymentsAuthorizeRouterData, - event_builder: Option<&mut ConnectorEvent>, - res: Response, - ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { - let response: transformers::PaymentsResponse = res - .response - .parse_struct("DummyConnector PaymentsResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - .change_context(errors::ConnectorError::ResponseHandlingFailed) - } - - fn get_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res, event_builder) - } -} - -impl<const T: u8> - ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for DummyConnector<T> -{ - fn get_headers( - &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, connectors) - } - - fn get_content_type(&self) -> &'static str { - self.common_get_content_type() - } - - fn get_url( - &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - match req - .request - .connector_transaction_id - .get_connector_transaction_id() - { - Ok(transaction_id) => Ok(format!( - "{}/payments/{}", - self.base_url(connectors), - transaction_id - )), - Err(_) => Err(error_stack::report!( - errors::ConnectorError::MissingConnectorTransactionID - )), - } - } - - fn build_request( - &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Get) - .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) - .attach_default_headers() - .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) - .build(), - )) - } - - fn handle_response( - &self, - data: &types::PaymentsSyncRouterData, - event_builder: Option<&mut ConnectorEvent>, - res: Response, - ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { - let response: transformers::PaymentsResponse = res - .response - .parse_struct("dummyconnector PaymentsSyncResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - .change_context(errors::ConnectorError::ResponseHandlingFailed) - } - - fn get_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res, event_builder) - } -} - -impl<const T: u8> - ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> - for DummyConnector<T> -{ - fn get_headers( - &self, - req: &types::PaymentsCaptureRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, connectors) - } - - fn get_content_type(&self) -> &'static str { - self.common_get_content_type() - } - - fn get_url( - &self, - _req: &types::PaymentsCaptureRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) - } - - fn get_request_body( - &self, - _req: &types::PaymentsCaptureRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) - } - - fn build_request( - &self, - req: &types::PaymentsCaptureRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) - .attach_default_headers() - .headers(types::PaymentsCaptureType::get_headers( - self, req, connectors, - )?) - .build(), - )) - } - - fn handle_response( - &self, - data: &types::PaymentsCaptureRouterData, - event_builder: Option<&mut ConnectorEvent>, - res: Response, - ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { - let response: transformers::PaymentsResponse = res - .response - .parse_struct("transformers PaymentsCaptureResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - .change_context(errors::ConnectorError::ResponseHandlingFailed) - } - - fn get_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res, event_builder) - } -} - -impl<const T: u8> - ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> - for DummyConnector<T> -{ -} - -impl<const T: u8> ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> - for DummyConnector<T> -{ - fn get_headers( - &self, - req: &types::RefundsRouterData<api::Execute>, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, connectors) - } - - fn get_content_type(&self) -> &'static str { - self.common_get_content_type() - } - - fn get_url( - &self, - req: &types::RefundsRouterData<api::Execute>, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!( - "{}/{}/refund", - self.base_url(connectors), - req.request.connector_transaction_id - )) - } - - fn get_request_body( - &self, - req: &types::RefundsRouterData<api::Execute>, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = transformers::DummyConnectorRefundRequest::try_from(req)?; - Ok(RequestContent::Json(Box::new(connector_req))) - } - - fn build_request( - &self, - req: &types::RefundsRouterData<api::Execute>, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::RefundExecuteType::get_url(self, req, connectors)?) - .attach_default_headers() - .headers(types::RefundExecuteType::get_headers( - self, req, connectors, - )?) - .set_body(types::RefundExecuteType::get_request_body( - self, req, connectors, - )?) - .build(); - Ok(Some(request)) - } - - fn handle_response( - &self, - data: &types::RefundsRouterData<api::Execute>, - event_builder: Option<&mut ConnectorEvent>, - res: Response, - ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { - let response: transformers::RefundResponse = res - .response - .parse_struct("transformers RefundResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - .change_context(errors::ConnectorError::ResponseHandlingFailed) - } - - fn get_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res, event_builder) - } -} - -impl<const T: u8> ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> - for DummyConnector<T> -{ - fn get_headers( - &self, - req: &types::RefundSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, connectors) - } - - fn get_content_type(&self) -> &'static str { - self.common_get_content_type() - } - - fn get_url( - &self, - req: &types::RefundSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - let refund_id = req.request.get_connector_refund_id()?; - Ok(format!( - "{}/refunds/{}", - self.base_url(connectors), - refund_id - )) - } - - fn build_request( - &self, - req: &types::RefundSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Get) - .url(&types::RefundSyncType::get_url(self, req, connectors)?) - .attach_default_headers() - .headers(types::RefundSyncType::get_headers(self, req, connectors)?) - .build(), - )) - } - - fn handle_response( - &self, - data: &types::RefundSyncRouterData, - event_builder: Option<&mut ConnectorEvent>, - res: Response, - ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { - let response: transformers::RefundResponse = res - .response - .parse_struct("transformers RefundSyncResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - .change_context(errors::ConnectorError::ResponseHandlingFailed) - } - - fn get_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res, event_builder) - } -} - -#[async_trait::async_trait] -impl<const T: u8> api::IncomingWebhook for DummyConnector<T> { - fn get_webhook_object_reference_id( - &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) - } - - fn get_webhook_event_type( - &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { - Ok(api::IncomingWebhookEvent::EventNotSupported) - } - - fn get_webhook_resource_object( - &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) - } -} - -impl<const T: u8> ConnectorSpecifications for DummyConnector<T> {} diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 2a7026dd265..c518c42ad1c 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -1959,17 +1959,6 @@ where json.parse_value(std::any::type_name::<T>()).switch() } -pub fn construct_not_supported_error_report( - capture_method: enums::CaptureMethod, - connector_name: &'static str, -) -> error_stack::Report<errors::ConnectorError> { - errors::ConnectorError::NotSupported { - message: capture_method.to_string(), - connector: connector_name, - } - .into() -} - impl ForeignTryFrom<String> for UsStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index be009c127df..ae4da756d7f 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1383,7 +1383,7 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> { | api_enums::Connector::DummyConnector5 | api_enums::Connector::DummyConnector6 | api_enums::Connector::DummyConnector7 => { - dummyconnector::transformers::DummyConnectorAuthType::try_from(self.auth_type)?; + hyperswitch_connectors::connectors::dummyconnector::transformers::DummyConnectorAuthType::try_from(self.auth_type)?; Ok(()) } api_enums::Connector::Aci => { diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 212aab98261..fa951af010d 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -17,34 +17,13 @@ use async_trait::async_trait; use hyperswitch_domain_models::router_flow_types::{ BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, RecoveryRecordBack, }; -#[cfg(feature = "dummy_connector")] -use hyperswitch_domain_models::router_flow_types::{ - ExternalVaultCreateFlow, ExternalVaultDeleteFlow, ExternalVaultInsertFlow, - ExternalVaultRetrieveFlow, -}; use hyperswitch_domain_models::{ - mandates::CustomerAcceptance, - router_flow_types::{ - Authenticate, AuthenticationConfirmation, PostAuthenticate, PreAuthenticate, - }, - router_request_types::PaymentsCaptureData, -}; -#[cfg(feature = "dummy_connector")] -use hyperswitch_interfaces::api::vault::{ - ExternalVault, ExternalVaultCreate, ExternalVaultDelete, ExternalVaultInsert, - ExternalVaultRetrieve, -}; -use hyperswitch_interfaces::api::{ - payouts::Payouts, UasAuthentication, UasAuthenticationConfirmation, UasPostAuthentication, - UasPreAuthentication, UnifiedAuthenticationService, + mandates::CustomerAcceptance, router_request_types::PaymentsCaptureData, }; -#[cfg(feature = "frm")] -use crate::types::fraud_check as frm_types; use crate::{ - connector, core::{ - errors::{ApiErrorResponse, ConnectorError, CustomResult, RouterResult}, + errors::{ApiErrorResponse, RouterResult}, payments::{self, helpers}, }, logger, @@ -215,522 +194,6 @@ pub trait Feature<F, T> { } } -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::PaymentsCompleteAuthorize for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - api::CompleteAuthorize, - types::CompleteAuthorizeData, - types::PaymentsResponseData, - > for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::ConnectorVerifyWebhookSource for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - api::VerifyWebhookSource, - types::VerifyWebhookSourceRequestData, - types::VerifyWebhookSourceResponseData, - > for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::ConnectorCustomer for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - api::CreateConnectorCustomer, - types::ConnectorCustomerData, - types::PaymentsResponseData, - > for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> services::ConnectorRedirectResponse for connector::DummyConnector<T> { - fn get_flow_type( - &self, - _query_params: &str, - _json_payload: Option<serde_json::Value>, - _action: services::PaymentAction, - ) -> CustomResult<payments::CallConnectorAction, ConnectorError> { - Ok(payments::CallConnectorAction::Trigger) - } -} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::ConnectorTransactionId for connector::DummyConnector<T> {} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::Dispute for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::AcceptDispute for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - api::Accept, - types::AcceptDisputeRequestData, - types::AcceptDisputeResponse, - > for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::FileUpload for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::UploadFile for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - api::Upload, - types::UploadFileRequestData, - types::UploadFileResponse, - > for connector::DummyConnector<T> -{ -} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::RetrieveFile for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - api::Retrieve, - types::RetrieveFileRequestData, - types::RetrieveFileResponse, - > for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::SubmitEvidence for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - api::Evidence, - types::SubmitEvidenceRequestData, - types::SubmitEvidenceResponse, - > for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::DefendDispute for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - api::Defend, - types::DefendDisputeRequestData, - types::DefendDisputeResponse, - > for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::PaymentsPreProcessing for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - api::PreProcessing, - types::PaymentsPreProcessingData, - types::PaymentsResponseData, - > for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::PaymentsPostProcessing for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - api::PostProcessing, - types::PaymentsPostProcessingData, - types::PaymentsResponseData, - > for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> Payouts for connector::DummyConnector<T> {} - -#[cfg(feature = "payouts")] -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::PayoutCreate for connector::DummyConnector<T> {} -#[cfg(feature = "payouts")] -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::PayoutsResponseData> - for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "payouts")] -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::PayoutSync for connector::DummyConnector<T> {} -#[cfg(feature = "payouts")] -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration<api::PoSync, types::PayoutsData, types::PayoutsResponseData> - for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "payouts")] -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::PayoutEligibility for connector::DummyConnector<T> {} -#[cfg(feature = "payouts")] -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - api::PoEligibility, - types::PayoutsData, - types::PayoutsResponseData, - > for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "payouts")] -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::PayoutFulfill for connector::DummyConnector<T> {} -#[cfg(feature = "payouts")] -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResponseData> - for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "payouts")] -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::PayoutCancel for connector::DummyConnector<T> {} -#[cfg(feature = "payouts")] -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::PayoutsResponseData> - for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "payouts")] -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::PayoutQuote for connector::DummyConnector<T> {} -#[cfg(feature = "payouts")] -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration<api::PoQuote, types::PayoutsData, types::PayoutsResponseData> - for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "payouts")] -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::PayoutRecipient for connector::DummyConnector<T> {} -#[cfg(feature = "payouts")] -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration<api::PoRecipient, types::PayoutsData, types::PayoutsResponseData> - for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "payouts")] -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::PayoutRecipientAccount for connector::DummyConnector<T> {} -#[cfg(feature = "payouts")] -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - api::PoRecipientAccount, - types::PayoutsData, - types::PayoutsResponseData, - > for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::PaymentApprove for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - api::Approve, - types::PaymentsApproveData, - types::PaymentsResponseData, - > for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::PaymentReject for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - api::Reject, - types::PaymentsRejectData, - types::PaymentsResponseData, - > for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::FraudCheck for connector::DummyConnector<T> {} - -#[cfg(all(feature = "frm", feature = "dummy_connector"))] -impl<const T: u8> api::FraudCheckSale for connector::DummyConnector<T> {} -#[cfg(all(feature = "frm", feature = "dummy_connector"))] -impl<const T: u8> - services::ConnectorIntegration< - api::Sale, - frm_types::FraudCheckSaleData, - frm_types::FraudCheckResponseData, - > for connector::DummyConnector<T> -{ -} - -#[cfg(all(feature = "frm", feature = "dummy_connector"))] -impl<const T: u8> api::FraudCheckCheckout for connector::DummyConnector<T> {} -#[cfg(all(feature = "frm", feature = "dummy_connector"))] -impl<const T: u8> - services::ConnectorIntegration< - api::Checkout, - frm_types::FraudCheckCheckoutData, - frm_types::FraudCheckResponseData, - > for connector::DummyConnector<T> -{ -} - -#[cfg(all(feature = "frm", feature = "dummy_connector"))] -impl<const T: u8> api::FraudCheckTransaction for connector::DummyConnector<T> {} -#[cfg(all(feature = "frm", feature = "dummy_connector"))] -impl<const T: u8> - services::ConnectorIntegration< - api::Transaction, - frm_types::FraudCheckTransactionData, - frm_types::FraudCheckResponseData, - > for connector::DummyConnector<T> -{ -} - -#[cfg(all(feature = "frm", feature = "dummy_connector"))] -impl<const T: u8> api::FraudCheckFulfillment for connector::DummyConnector<T> {} -#[cfg(all(feature = "frm", feature = "dummy_connector"))] -impl<const T: u8> - services::ConnectorIntegration< - api::Fulfillment, - frm_types::FraudCheckFulfillmentData, - frm_types::FraudCheckResponseData, - > for connector::DummyConnector<T> -{ -} - -#[cfg(all(feature = "frm", feature = "dummy_connector"))] -impl<const T: u8> api::FraudCheckRecordReturn for connector::DummyConnector<T> {} -#[cfg(all(feature = "frm", feature = "dummy_connector"))] -impl<const T: u8> - services::ConnectorIntegration< - api::RecordReturn, - frm_types::FraudCheckRecordReturnData, - frm_types::FraudCheckResponseData, - > for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::PaymentIncrementalAuthorization for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - api::IncrementalAuthorization, - types::PaymentsIncrementalAuthorizationData, - types::PaymentsResponseData, - > for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::ConnectorMandateRevoke for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - api::MandateRevoke, - types::MandateRevokeRequestData, - types::MandateRevokeResponseData, - > for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::ExternalAuthentication for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::ConnectorPreAuthentication for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::ConnectorPreAuthenticationVersionCall for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::ConnectorAuthentication for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::ConnectorPostAuthentication for connector::DummyConnector<T> {} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - api::Authentication, - types::authentication::ConnectorAuthenticationRequestData, - types::authentication::AuthenticationResponseData, - > for connector::DummyConnector<T> -{ -} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - api::PreAuthentication, - types::authentication::PreAuthNRequestData, - types::authentication::AuthenticationResponseData, - > for connector::DummyConnector<T> -{ -} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - api::PreAuthenticationVersionCall, - types::authentication::PreAuthNRequestData, - types::authentication::AuthenticationResponseData, - > for connector::DummyConnector<T> -{ -} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - api::PostAuthentication, - types::authentication::ConnectorPostAuthenticationRequestData, - types::authentication::AuthenticationResponseData, - > for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::PaymentAuthorizeSessionToken for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - api::AuthorizeSessionToken, - types::AuthorizeSessionTokenData, - types::PaymentsResponseData, - > for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::TaxCalculation for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - api::CalculateTax, - types::PaymentsTaxCalculationData, - types::TaxCalculationResponseData, - > for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::PaymentSessionUpdate for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - api::SdkSessionUpdate, - types::SdkPaymentsSessionUpdateData, - types::PaymentsResponseData, - > for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::PaymentPostSessionTokens for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - api::PostSessionTokens, - types::PaymentsPostSessionTokensData, - types::PaymentsResponseData, - > for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::PaymentsCreateOrder for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - api::CreateOrder, - types::CreateOrderRequestData, - types::PaymentsResponseData, - > for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::PaymentUpdateMetadata for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - api::UpdateMetadata, - types::PaymentsUpdateMetadataData, - types::PaymentsResponseData, - > for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> UasPreAuthentication for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> UnifiedAuthenticationService for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - PreAuthenticate, - types::UasPreAuthenticationRequestData, - types::UasAuthenticationResponseData, - > for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> UasPostAuthentication for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - PostAuthenticate, - types::UasPostAuthenticationRequestData, - types::UasAuthenticationResponseData, - > for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> UasAuthenticationConfirmation for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - AuthenticationConfirmation, - types::UasConfirmationRequestData, - types::UasAuthenticationResponseData, - > for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> UasAuthentication for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - Authenticate, - types::UasAuthenticationRequestData, - types::UasAuthenticationResponseData, - > for connector::DummyConnector<T> -{ -} - /// Determines whether a capture API call should be made for a payment attempt /// This function evaluates whether an authorized payment should proceed with a capture API call /// based on various payment parameters. It's primarily used in two-step (auth + capture) payment flows for CaptureMethod SequentialAutomatic @@ -841,99 +304,3 @@ fn handle_post_capture_response( } } } - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::RevenueRecovery for connector::DummyConnector<T> {} - -#[cfg(all(feature = "v2", feature = "revenue_recovery"))] -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::BillingConnectorPaymentsSyncIntegration for connector::DummyConnector<T> {} -#[cfg(all(feature = "v2", feature = "revenue_recovery"))] -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - BillingConnectorPaymentsSync, - types::BillingConnectorPaymentsSyncRequest, - types::BillingConnectorPaymentsSyncResponse, - > for connector::DummyConnector<T> -{ -} - -#[cfg(all(feature = "v2", feature = "revenue_recovery"))] -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::RevenueRecoveryRecordBack for connector::DummyConnector<T> {} -#[cfg(all(feature = "v2", feature = "revenue_recovery"))] -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - RecoveryRecordBack, - types::RevenueRecoveryRecordBackRequest, - types::RevenueRecoveryRecordBackResponse, - > for connector::DummyConnector<T> -{ -} - -#[cfg(all(feature = "v2", feature = "revenue_recovery"))] -#[cfg(feature = "dummy_connector")] -impl<const T: u8> api::BillingConnectorInvoiceSyncIntegration for connector::DummyConnector<T> {} -#[cfg(all(feature = "v2", feature = "revenue_recovery"))] -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - BillingConnectorInvoiceSync, - types::BillingConnectorInvoiceSyncRequest, - types::BillingConnectorInvoiceSyncResponse, - > for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> ExternalVault for connector::DummyConnector<T> {} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> ExternalVaultInsert for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - ExternalVaultInsertFlow, - types::VaultRequestData, - types::VaultResponseData, - > for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> ExternalVaultRetrieve for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - ExternalVaultRetrieveFlow, - types::VaultRequestData, - types::VaultResponseData, - > for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> ExternalVaultDelete for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - ExternalVaultDeleteFlow, - types::VaultRequestData, - types::VaultResponseData, - > for connector::DummyConnector<T> -{ -} - -#[cfg(feature = "dummy_connector")] -impl<const T: u8> ExternalVaultCreate for connector::DummyConnector<T> {} -#[cfg(feature = "dummy_connector")] -impl<const T: u8> - services::ConnectorIntegration< - ExternalVaultCreateFlow, - types::VaultRequestData, - types::VaultResponseData, - > for connector::DummyConnector<T> -{ -}
2025-06-18T05:28:36Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Movement of dummy connector form `router` crate to `hyperswitch_connectors` crate ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/8371 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Only dummy connector moved to crate hyoerswitch_connectors hence no testing required. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
7b2919b46fda92aad14980280bc46c2c23d81086
7b2919b46fda92aad14980280bc46c2c23d81086
juspay/hyperswitch
juspay__hyperswitch-8374
Bug: chore: resolve warnings in v2 Resolve warnings in v2 across all crates except router crate.
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 50ae919d4f8..f12e6d5bd4a 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -17,13 +17,12 @@ use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use super::payments::AddressDetails; -#[cfg(feature = "v1")] -use crate::routing; use crate::{ consts::{MAX_ORDER_FULFILLMENT_EXPIRY, MIN_ORDER_FULFILLMENT_EXPIRY}, enums as api_enums, payment_methods, - profile_acquirer::ProfileAcquirerResponse, }; +#[cfg(feature = "v1")] +use crate::{profile_acquirer::ProfileAcquirerResponse, routing}; #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] pub struct MerchantAccountListRequest { diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs index 54fb4fb470f..d6ade7e339d 100644 --- a/crates/api_models/src/refunds.rs +++ b/crates/api_models/src/refunds.rs @@ -7,10 +7,9 @@ use time::PrimitiveDateTime; use utoipa::ToSchema; use super::payments::AmountFilter; -use crate::{ - admin::{self, MerchantConnectorInfo}, - enums, -}; +#[cfg(feature = "v1")] +use crate::admin; +use crate::{admin::MerchantConnectorInfo, enums}; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] diff --git a/crates/api_models/src/tokenization.rs b/crates/api_models/src/tokenization.rs index 5ee044ec1fb..131b0804fd6 100644 --- a/crates/api_models/src/tokenization.rs +++ b/crates/api_models/src/tokenization.rs @@ -1,6 +1,5 @@ use common_enums; use common_utils::id_type::{GlobalCustomerId, GlobalTokenId}; -use masking::Secret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::{schema, ToSchema}; diff --git a/crates/common_utils/src/id_type/global_id/token.rs b/crates/common_utils/src/id_type/global_id/token.rs index 929c03f0959..2ea927d675f 100644 --- a/crates/common_utils/src/id_type/global_id/token.rs +++ b/crates/common_utils/src/id_type/global_id/token.rs @@ -1,7 +1,3 @@ -use error_stack::ResultExt; - -use crate::{errors, generate_id_with_default_len, generate_time_ordered_id_without_prefix, types}; - crate::global_id_type!( GlobalTokenId, "A global id that can be used to identify a token. diff --git a/crates/common_utils/src/tokenization.rs b/crates/common_utils/src/tokenization.rs index aa0f3dda8c1..8d19d68668a 100644 --- a/crates/common_utils/src/tokenization.rs +++ b/crates/common_utils/src/tokenization.rs @@ -3,12 +3,7 @@ //! This module provides types and functions for handling tokenized payment data, //! including response structures and token generation utilities. -use common_enums::ApiVersion; -use diesel; -use serde::{Deserialize, Serialize}; -use time::PrimitiveDateTime; - -use crate::{consts::TOKEN_LENGTH, id_type::GlobalTokenId}; +use crate::consts::TOKEN_LENGTH; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] /// Generates a new token string diff --git a/crates/diesel_models/src/query/tokenization.rs b/crates/diesel_models/src/query/tokenization.rs index 0d818eb6636..8f20b903d7d 100644 --- a/crates/diesel_models/src/query/tokenization.rs +++ b/crates/diesel_models/src/query/tokenization.rs @@ -1,24 +1,5 @@ #[cfg(feature = "v2")] -use common_enums; -#[cfg(feature = "v2")] -use common_utils::{ - id_type::{GlobalTokenId, MerchantId}, - tokenization as tokenization_utils, -}; -#[cfg(feature = "v2")] -use diesel::{ - associations::HasTable, - deserialize::FromSqlRow, - expression::AsExpression, - pg::Pg, - serialize::{Output, ToSql}, - sql_types::{Jsonb, Text}, - AsChangeset, Identifiable, Insertable, Queryable, Selectable, -}; -#[cfg(feature = "v2")] -use serde::{Deserialize, Serialize}; -#[cfg(feature = "v2")] -use time::PrimitiveDateTime; +use diesel::associations::HasTable; #[cfg(feature = "v2")] use crate::{ diff --git a/crates/diesel_models/src/tokenization.rs b/crates/diesel_models/src/tokenization.rs index 50a97e62c90..e7ab2a4b136 100644 --- a/crates/diesel_models/src/tokenization.rs +++ b/crates/diesel_models/src/tokenization.rs @@ -1,27 +1,12 @@ #[cfg(feature = "v2")] use common_enums; #[cfg(feature = "v2")] -use common_utils::{ - id_type::{GlobalTokenId, MerchantId}, - tokenization as tokenization_utils, -}; -#[cfg(feature = "v2")] -use diesel::{ - associations::HasTable, - deserialize::FromSqlRow, - expression::AsExpression, - pg::Pg, - serialize::{Output, ToSql}, - sql_types::{Jsonb, Text}, - AsChangeset, Identifiable, Insertable, Queryable, Selectable, -}; -#[cfg(feature = "v2")] -use serde::{Deserialize, Serialize}; +use diesel::{AsChangeset, Identifiable, Insertable, Queryable}; #[cfg(feature = "v2")] use time::PrimitiveDateTime; #[cfg(feature = "v2")] -use crate::{query::generics, schema_v2::tokenization, PgPooledConn, StorageResult}; +use crate::schema_v2::tokenization; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] #[derive(Clone, Debug, Identifiable, Insertable, Queryable)] diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee.rs b/crates/hyperswitch_connectors/src/connectors/chargebee.rs index c0e73d43a19..4dcda9ad5d8 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee.rs @@ -1,8 +1,6 @@ pub mod transformers; use base64::Engine; -#[cfg(all(feature = "revenue_recovery", feature = "v2"))] -use common_utils::types::{StringMinorUnit, StringMinorUnitForConnector}; use common_utils::{ consts::BASE64_ENGINE, errors::CustomResult, @@ -10,7 +8,9 @@ use common_utils::{ request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, }; -use error_stack::{report, ResultExt}; +#[cfg(feature = "v1")] +use error_stack::report; +use error_stack::ResultExt; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] use hyperswitch_domain_models::{ revenue_recovery, router_flow_types::revenue_recovery::RecoveryRecordBack, @@ -47,8 +47,6 @@ use hyperswitch_interfaces::{ types::{self, Response}, webhooks, }; -#[cfg(all(feature = "revenue_recovery", feature = "v2"))] -use masking::ExposeInterface; use masking::{Mask, PeekInterface, Secret}; use transformers as chargebee; diff --git a/crates/hyperswitch_connectors/src/connectors/razorpay.rs b/crates/hyperswitch_connectors/src/connectors/razorpay.rs index 56080d73fb6..39b83c73e43 100644 --- a/crates/hyperswitch_connectors/src/connectors/razorpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/razorpay.rs @@ -835,8 +835,8 @@ impl ConnectorSpecifications for Razorpay { #[cfg(feature = "v2")] fn generate_connector_request_reference_id( &self, - payment_intent: &hyperswitch_domain_models::payments::PaymentIntent, - payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, + _payment_intent: &hyperswitch_domain_models::payments::PaymentIntent, + _payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, ) -> String { // The length of receipt for Razorpay order request should not exceed 40 characters. uuid::Uuid::now_v7().to_string() diff --git a/crates/hyperswitch_connectors/src/connectors/recurly.rs b/crates/hyperswitch_connectors/src/connectors/recurly.rs index bb7ea02a931..2a19a34e2b0 100644 --- a/crates/hyperswitch_connectors/src/connectors/recurly.rs +++ b/crates/hyperswitch_connectors/src/connectors/recurly.rs @@ -2,17 +2,11 @@ pub mod transformers; use base64::Engine; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] -use common_utils::request::{Method, Request, RequestBuilder, RequestContent}; +use common_utils::request::{Method, Request, RequestBuilder}; use common_utils::{consts, errors::CustomResult, ext_traits::BytesExt}; -use error_stack::{report, ResultExt}; -#[cfg(all(feature = "v2", feature = "revenue_recovery"))] -use hyperswitch_domain_models::{ - revenue_recovery, router_data_v2::flow_common_types as recovery_flow_common_types, - router_flow_types::revenue_recovery as recovery_router_flows, - router_request_types::revenue_recovery as recovery_request_types, - router_response_types::revenue_recovery as recovery_response_types, - types as recovery_router_data_types, -}; +#[cfg(feature = "v1")] +use error_stack::report; +use error_stack::ResultExt; use hyperswitch_domain_models::{ router_data::{ConnectorAuthType, ErrorResponse}, router_data_v2::UasFlowData, @@ -25,6 +19,14 @@ use hyperswitch_domain_models::{ }, }; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] +use hyperswitch_domain_models::{ + router_data_v2::flow_common_types as recovery_flow_common_types, + router_flow_types::revenue_recovery as recovery_router_flows, + router_request_types::revenue_recovery as recovery_request_types, + router_response_types::revenue_recovery as recovery_response_types, + types as recovery_router_data_types, +}; +#[cfg(all(feature = "v2", feature = "revenue_recovery"))] use hyperswitch_interfaces::types; use hyperswitch_interfaces::{ api::{self, ConnectorCommon, ConnectorSpecifications, ConnectorValidation}, @@ -43,7 +45,6 @@ use crate::{connectors::recurly::transformers::RecurlyWebhookBody, constants::he use crate::{ connectors::recurly::transformers::{RecurlyRecordStatus, RecurlyRecoveryDetailsData}, types::ResponseRouterDataV2, - utils, }; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] const STATUS_SUCCESSFUL_ENDPOINT: &str = "mark_successful"; diff --git a/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs b/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs index 9ffd900dc45..d7f71635cc8 100644 --- a/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs @@ -26,9 +26,7 @@ use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] -use crate::utils; -#[cfg(all(feature = "v2", feature = "revenue_recovery"))] -use crate::{types::ResponseRouterDataV2, utils::PaymentsAuthorizeRequestData}; +use crate::{types::ResponseRouterDataV2, utils}; pub struct RecurlyRouterData<T> { pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. diff --git a/crates/hyperswitch_connectors/src/connectors/stripebilling.rs b/crates/hyperswitch_connectors/src/connectors/stripebilling.rs index 39a8e5a0dae..a15ce5f1561 100644 --- a/crates/hyperswitch_connectors/src/connectors/stripebilling.rs +++ b/crates/hyperswitch_connectors/src/connectors/stripebilling.rs @@ -47,8 +47,6 @@ use hyperswitch_interfaces::{ types::{self, Response}, webhooks, }; -#[cfg(all(feature = "v2", feature = "revenue_recovery"))] -use masking::ExposeInterface; use masking::{Mask, PeekInterface}; use stripebilling::auth_headers; use transformers as stripebilling; diff --git a/crates/hyperswitch_connectors/src/types.rs b/crates/hyperswitch_connectors/src/types.rs index 0160457d2f8..6136d281ae4 100644 --- a/crates/hyperswitch_connectors/src/types.rs +++ b/crates/hyperswitch_connectors/src/types.rs @@ -100,6 +100,7 @@ pub(crate) type FrmCheckoutRouterData = pub(crate) struct ResponseRouterDataV2<Flow, R, ResourceCommonData, Request, Response> { pub response: R, pub data: RouterDataV2<Flow, ResourceCommonData, Request, Response>, + #[allow(dead_code)] // Used for metadata passing but this is not read pub http_code: u16, } diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs index 93ed2af4945..af51eae8bf3 100644 --- a/crates/hyperswitch_domain_models/src/business_profile.rs +++ b/crates/hyperswitch_domain_models/src/business_profile.rs @@ -1361,7 +1361,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { merchant_business_country, revenue_recovery_retry_algorithm_type: None, revenue_recovery_retry_algorithm_data: None, - is_iframe_redirection_enabled: None, + is_iframe_redirection_enabled, is_external_vault_enabled, external_vault_connector_details, merchant_category_code, diff --git a/crates/hyperswitch_domain_models/src/customer.rs b/crates/hyperswitch_domain_models/src/customer.rs index 6b364ce5807..fce8a2c31ff 100644 --- a/crates/hyperswitch_domain_models/src/customer.rs +++ b/crates/hyperswitch_domain_models/src/customer.rs @@ -629,7 +629,6 @@ where state: &KeyManagerState, id: &id_type::GlobalCustomerId, customer: Customer, - merchant_id: &id_type::MerchantId, customer_update: CustomerUpdate, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, @@ -640,7 +639,6 @@ where &self, state: &KeyManagerState, id: &id_type::GlobalCustomerId, - merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Customer, Self::Error>; diff --git a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs index 5c465937988..dcf5695135d 100644 --- a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs +++ b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs @@ -1,8 +1,6 @@ #[cfg(feature = "v2")] use std::collections::HashMap; -#[cfg(feature = "v2")] -use common_utils::transformers::ForeignTryFrom; use common_utils::{ crypto::Encryptable, date_time, @@ -26,7 +24,7 @@ use serde_json::Value; use super::behaviour; #[cfg(feature = "v2")] -use crate::errors::{self, api_error_response}; +use crate::errors::api_error_response; use crate::{ mandates::CommonMandateReference, router_data, diff --git a/crates/hyperswitch_domain_models/src/network_tokenization.rs b/crates/hyperswitch_domain_models/src/network_tokenization.rs index 06773caa683..df567124932 100644 --- a/crates/hyperswitch_domain_models/src/network_tokenization.rs +++ b/crates/hyperswitch_domain_models/src/network_tokenization.rs @@ -1,7 +1,7 @@ #[cfg(feature = "v1")] use cards::CardNumber; #[cfg(feature = "v2")] -use cards::{CardNumber, NetworkToken}; +use cards::NetworkToken; #[cfg(feature = "v1")] pub type NetworkTokenNumber = CardNumber; diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rs index f73621b49a5..0f6d4d6f924 100644 --- a/crates/hyperswitch_domain_models/src/payment_methods.rs +++ b/crates/hyperswitch_domain_models/src/payment_methods.rs @@ -2,10 +2,11 @@ use api_models::payment_methods::PaymentMethodsData; // specific imports because of using the macro use common_enums::enums::MerchantStorageScheme; +#[cfg(feature = "v1")] +use common_utils::crypto::OptionalEncryptableValue; #[cfg(feature = "v2")] use common_utils::{crypto::Encryptable, encryption::Encryption, types::keymanager::ToEncryptable}; use common_utils::{ - crypto::OptionalEncryptableValue, errors::{CustomResult, ParsingError, ValidationError}, id_type, pii, type_name, types::keymanager, @@ -24,12 +25,14 @@ use serde_json::Value; use time::PrimitiveDateTime; #[cfg(feature = "v2")] -use crate::{address::Address, type_encryption::OptionalEncryptableJsonType}; +use crate::address::Address; +#[cfg(feature = "v1")] +use crate::{mandates, type_encryption::AsyncLift}; use crate::{ - mandates::{self, CommonMandateReference}, + mandates::CommonMandateReference, merchant_key_store::MerchantKeyStore, payment_method_data as domain_payment_method_data, - type_encryption::{crypto_operation, AsyncLift, CryptoOperation}, + type_encryption::{crypto_operation, CryptoOperation}, }; #[cfg(feature = "v2")] @@ -477,7 +480,6 @@ impl super::behaviour::Conversion for PaymentMethod { Self: Sized, { use common_utils::ext_traits::ValueExt; - use masking::ExposeInterface; async { let decrypted_data = crypto_operation( diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index eb5c0a467c5..004098c8a1f 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -3,11 +3,10 @@ use std::marker::PhantomData; #[cfg(feature = "v2")] use api_models::payments::{MerchantConnectorDetails, SessionToken, VaultSessionDetails}; +#[cfg(feature = "v1")] use common_types::primitive_wrappers::{ AlwaysRequestExtendedAuthorization, RequestExtendedAuthorizationBool, }; -#[cfg(feature = "v2")] -use common_utils::ext_traits::OptionExt; use common_utils::{ self, crypto::Encryptable, @@ -21,8 +20,6 @@ use diesel_models::payment_intent::TaxDetails; #[cfg(feature = "v2")] use error_stack::ResultExt; use masking::Secret; -#[cfg(feature = "v2")] -use payment_intent::PaymentIntentUpdate; use router_derive::ToEncryption; use rustc_hash::FxHashMap; use serde_json::Value; @@ -33,18 +30,15 @@ pub mod payment_intent; use common_enums as storage_enums; #[cfg(feature = "v2")] -use diesel_models::{ - ephemeral_key, - types::{FeatureMetadata, OrderDetailsWithAmount}, -}; +use diesel_models::types::{FeatureMetadata, OrderDetailsWithAmount}; use self::payment_attempt::PaymentAttempt; #[cfg(feature = "v2")] use crate::{ - address::Address, business_profile, customer, errors, merchant_account, - merchant_connector_account, merchant_connector_account::MerchantConnectorAccountTypeDetails, - merchant_context, payment_address, payment_method_data, payment_methods, revenue_recovery, - routing, ApiModelToDieselModelConvertor, + address::Address, business_profile, customer, errors, merchant_connector_account, + merchant_connector_account::MerchantConnectorAccountTypeDetails, merchant_context, + payment_address, payment_method_data, payment_methods, revenue_recovery, routing, + ApiModelToDieselModelConvertor, }; #[cfg(feature = "v1")] use crate::{payment_method_data, RemoteStorageObject}; diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index 56e0942431c..3341ba0ee42 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -1,6 +1,7 @@ #[cfg(all(feature = "v1", feature = "olap"))] use api_models::enums::Connector; use common_enums as storage_enums; +#[cfg(feature = "v1")] use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool, }; @@ -20,10 +21,12 @@ use common_utils::{ ConnectorTransactionId, ConnectorTransactionIdTrait, CreatedBy, MinorUnit, }, }; +#[cfg(feature = "v1")] use diesel_models::{ - ConnectorMandateReferenceId, PaymentAttempt as DieselPaymentAttempt, - PaymentAttemptNew as DieselPaymentAttemptNew, - PaymentAttemptUpdate as DieselPaymentAttemptUpdate, + ConnectorMandateReferenceId, PaymentAttemptUpdate as DieselPaymentAttemptUpdate, +}; +use diesel_models::{ + PaymentAttempt as DieselPaymentAttempt, PaymentAttemptNew as DieselPaymentAttemptNew, }; #[cfg(feature = "v2")] use diesel_models::{ @@ -36,7 +39,9 @@ use masking::PeekInterface; use masking::Secret; #[cfg(feature = "v2")] use rustc_hash::FxHashMap; -use serde::{Deserialize, Serialize}; +#[cfg(feature = "v1")] +use serde::Deserialize; +use serde::Serialize; #[cfg(feature = "v2")] use serde_json::Value; use time::PrimitiveDateTime; @@ -51,10 +56,11 @@ use crate::{ router_response_types, type_encryption::{crypto_operation, CryptoOperation}, }; +use crate::{behaviour, errors, ForeignIDRef}; +#[cfg(feature = "v1")] use crate::{ - behaviour, errors, mandates::{MandateDataType, MandateDetails}, - router_request_types, ForeignIDRef, + router_request_types, }; #[async_trait::async_trait] @@ -2410,7 +2416,7 @@ impl behaviour::Conversion for PaymentAttempt { connector_metadata, payment_experience, payment_method_data, - routing_result, + routing_result: _, preprocessing_step_id, multiple_capture_count, connector_response_reference_id, @@ -2430,8 +2436,8 @@ impl behaviour::Conversion for PaymentAttempt { payment_method_type, connector_payment_id, payment_method_subtype, - authentication_applied, - external_reference_id, + authentication_applied: _, + external_reference_id: _, id, payment_method_id, payment_method_billing_address, diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index 572c7d08442..67a6ef6a795 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -1,11 +1,11 @@ -#[cfg(feature = "v2")] -use common_enums::RequestIncrementalAuthorization; +#[cfg(feature = "v1")] +use common_utils::consts::PAYMENTS_LIST_MAX_LIMIT_V2; #[cfg(feature = "v2")] use common_utils::errors::ParsingError; #[cfg(feature = "v2")] use common_utils::ext_traits::{Encode, ValueExt}; use common_utils::{ - consts::{PAYMENTS_LIST_MAX_LIMIT_V1, PAYMENTS_LIST_MAX_LIMIT_V2}, + consts::PAYMENTS_LIST_MAX_LIMIT_V1, crypto::Encryptable, encryption::Encryption, errors::{CustomResult, ValidationError}, @@ -17,8 +17,6 @@ use common_utils::{ CreatedBy, MinorUnit, }, }; -#[cfg(feature = "v2")] -use diesel_models::PaymentLinkConfigRequestForPayments; use diesel_models::{ PaymentIntent as DieselPaymentIntent, PaymentIntentNew as DieselPaymentIntentNew, }; @@ -37,13 +35,12 @@ use crate::address::Address; #[cfg(feature = "v2")] use crate::routing; use crate::{ - behaviour, errors, + behaviour, merchant_key_store::MerchantKeyStore, type_encryption::{crypto_operation, CryptoOperation}, - RemoteStorageObject, }; -#[cfg(feature = "v2")] -use crate::{FeatureMetadata, OrderDetailsWithAmount}; +#[cfg(feature = "v1")] +use crate::{errors, RemoteStorageObject}; #[async_trait::async_trait] pub trait PaymentIntentInterface { @@ -721,7 +718,7 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternal updated_by, force_3ds_challenge, - is_iframe_redirection_enabled: None, + is_iframe_redirection_enabled, }) } PaymentIntentUpdate::RecordUpdate { diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs index 2f2ed98f1a2..360359036fa 100644 --- a/crates/hyperswitch_domain_models/src/router_data.rs +++ b/crates/hyperswitch_domain_models/src/router_data.rs @@ -505,7 +505,6 @@ impl storage_scheme: common_enums::MerchantStorageScheme, ) -> PaymentIntentUpdate { let amount_captured = self.get_captured_amount(payment_data); - let status = payment_data.payment_attempt.status.is_terminal_status(); let updated_feature_metadata = payment_data .payment_intent @@ -567,12 +566,8 @@ impl router_response_types::PaymentsResponseData::TransactionResponse { resource_id, redirection_data, - mandate_reference, connector_metadata, - network_txn_id, - connector_response_reference_id, - incremental_authorization_allowed, - charges, + .. } => { let attempt_status = self.get_attempt_status_for_db_update(payment_data); @@ -642,7 +637,7 @@ impl message, reason, status_code: _, - attempt_status, + attempt_status: _, connector_transaction_id, network_decline_code, network_advice_code, @@ -801,16 +796,7 @@ impl match self.response { Ok(ref response_router_data) => match response_router_data { - router_response_types::PaymentsResponseData::TransactionResponse { - resource_id, - redirection_data, - mandate_reference, - connector_metadata, - network_txn_id, - connector_response_reference_id, - incremental_authorization_allowed, - charges, - } => { + router_response_types::PaymentsResponseData::TransactionResponse { .. } => { let attempt_status = self.status; PaymentAttemptUpdate::CaptureUpdate { @@ -1035,16 +1021,7 @@ impl match self.response { Ok(ref response_router_data) => match response_router_data { - router_response_types::PaymentsResponseData::TransactionResponse { - resource_id, - redirection_data, - mandate_reference, - connector_metadata, - network_txn_id, - connector_response_reference_id, - incremental_authorization_allowed, - charges, - } => { + router_response_types::PaymentsResponseData::TransactionResponse { .. } => { let attempt_status = self.get_attempt_status_for_db_update(payment_data); PaymentAttemptUpdate::SyncUpdate { @@ -1092,7 +1069,7 @@ impl message, reason, status_code: _, - attempt_status, + attempt_status: _, connector_transaction_id, network_advice_code, network_decline_code, @@ -1275,12 +1252,8 @@ impl router_response_types::PaymentsResponseData::TransactionResponse { resource_id, redirection_data, - mandate_reference, connector_metadata, - network_txn_id, - connector_response_reference_id, - incremental_authorization_allowed, - charges, + .. } => { let attempt_status = self.get_attempt_status_for_db_update(payment_data); diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index 8dfda368367..06932fb1265 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -662,7 +662,7 @@ impl )> for SurchargeDetails { fn from( - (request_surcharge_details, payment_attempt): ( + (_request_surcharge_details, _payment_attempt): ( &RequestSurchargeDetails, &payments::payment_attempt::PaymentAttempt, ), diff --git a/crates/hyperswitch_domain_models/src/tokenization.rs b/crates/hyperswitch_domain_models/src/tokenization.rs index 4bbdaa2fb41..918e647b6c2 100644 --- a/crates/hyperswitch_domain_models/src/tokenization.rs +++ b/crates/hyperswitch_domain_models/src/tokenization.rs @@ -2,16 +2,12 @@ use common_enums; use common_utils::{ self, errors::{CustomResult, ValidationError}, - id_type, pii, - types::{keymanager, MinorUnit}, + types::keymanager, }; -use diesel_models::tokenization; -use masking::{ExposeInterface, Secret}; +use masking::Secret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; -use crate::{merchant_key_store::MerchantKeyStore, types}; - #[cfg(all(feature = "v2", feature = "tokenization_v2"))] #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Tokenization { diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs index 2a2b2e5ae75..bd610feb430 100644 --- a/crates/kgraph_utils/src/mca.rs +++ b/crates/kgraph_utils/src/mca.rs @@ -1,9 +1,9 @@ +#[cfg(feature = "v1")] use std::str::FromStr; -use api_models::{ - admin as admin_api, enums as api_enums, payment_methods::RequestPaymentMethodTypes, - refunds::MinorUnit, -}; +#[cfg(feature = "v1")] +use api_models::payment_methods::RequestPaymentMethodTypes; +use api_models::{admin as admin_api, enums as api_enums, refunds::MinorUnit}; use euclid::{ dirval, frontend::{ast, dir}, diff --git a/crates/payment_methods/src/configs/payment_connector_required_fields.rs b/crates/payment_methods/src/configs/payment_connector_required_fields.rs index 8b2829a6f7a..4788c638c87 100644 --- a/crates/payment_methods/src/configs/payment_connector_required_fields.rs +++ b/crates/payment_methods/src/configs/payment_connector_required_fields.rs @@ -6,10 +6,11 @@ use api_models::{ }; use crate::configs::settings::{ - ConnectorFields, Mandates, PaymentMethodType, RequiredFieldFinal, RequiredFields, - SupportedConnectorsForMandate, SupportedPaymentMethodTypesForMandate, - SupportedPaymentMethodsForMandate, ZeroMandates, + ConnectorFields, Mandates, RequiredFieldFinal, SupportedConnectorsForMandate, + SupportedPaymentMethodTypesForMandate, SupportedPaymentMethodsForMandate, ZeroMandates, }; +#[cfg(feature = "v1")] +use crate::configs::settings::{PaymentMethodType, RequiredFields}; impl Default for ZeroMandates { fn default() -> Self { @@ -125,6 +126,7 @@ impl Default for Mandates { } #[derive(Clone, serde::Serialize)] +#[cfg_attr(feature = "v2", allow(dead_code))] // multiple variants are never constructed for v2 enum RequiredField { CardNumber, CardExpMonth, @@ -859,6 +861,7 @@ impl RequiredField { } // Define helper functions for common field groups +#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2 fn card_basic() -> Vec<RequiredField> { vec![ RequiredField::CardNumber, @@ -868,6 +871,7 @@ fn card_basic() -> Vec<RequiredField> { ] } +#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2 fn full_name() -> Vec<RequiredField> { vec![ RequiredField::BillingUserFirstName, @@ -875,6 +879,7 @@ fn full_name() -> Vec<RequiredField> { ] } +#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2 fn billing_name() -> Vec<RequiredField> { vec![ RequiredField::BillingFirstName("billing_first_name", FieldType::UserBillingName), @@ -882,18 +887,22 @@ fn billing_name() -> Vec<RequiredField> { ] } +#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2 fn email() -> Vec<RequiredField> { [RequiredField::Email].to_vec() } +#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2 fn billing_email() -> Vec<RequiredField> { [RequiredField::BillingEmail].to_vec() } +#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2 fn card_with_name() -> Vec<RequiredField> { [card_basic(), full_name()].concat() } +#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2 fn billing_email_name() -> Vec<RequiredField> { vec![ RequiredField::BillingEmail, @@ -902,6 +911,7 @@ fn billing_email_name() -> Vec<RequiredField> { ] } +#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2 fn billing_email_name_phone() -> Vec<RequiredField> { vec![ RequiredField::BillingUserFirstName, @@ -912,6 +922,7 @@ fn billing_email_name_phone() -> Vec<RequiredField> { ] } +#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2 fn billing_address() -> Vec<RequiredField> { vec![ RequiredField::BillingAddressCity, @@ -940,6 +951,7 @@ fn fields( } } +#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2 fn connectors(connectors: Vec<(Connector, RequiredFieldFinal)>) -> ConnectorFields { ConnectorFields { fields: connectors.into_iter().collect(), diff --git a/crates/payment_methods/src/controller.rs b/crates/payment_methods/src/controller.rs index f93d5569324..bd5a9f316ef 100644 --- a/crates/payment_methods/src/controller.rs +++ b/crates/payment_methods/src/controller.rs @@ -3,6 +3,7 @@ use std::fmt::Debug; #[cfg(feature = "payouts")] use api_models::payouts; use api_models::{enums as api_enums, payment_methods as api}; +#[cfg(feature = "v1")] use common_enums::enums as common_enums; #[cfg(feature = "v2")] use common_utils::encryption; @@ -10,6 +11,7 @@ use common_utils::{crypto, ext_traits, id_type, type_name, types::keymanager}; use error_stack::ResultExt; use hyperswitch_domain_models::{merchant_key_store, payment_methods, type_encryption}; use masking::{PeekInterface, Secret}; +#[cfg(feature = "v1")] use scheduler::errors as sch_errors; use serde::{Deserialize, Serialize}; use storage_impl::{errors as storage_errors, payment_method}; @@ -148,10 +150,10 @@ pub trait PaymentMethodsController { #[cfg(feature = "v2")] async fn get_or_insert_payment_method( &self, - req: api::PaymentMethodCreate, - resp: &mut api::PaymentMethodResponse, - customer_id: &id_type::CustomerId, - key_store: &merchant_key_store::MerchantKeyStore, + _req: api::PaymentMethodCreate, + _resp: &mut api::PaymentMethodResponse, + _customer_id: &id_type::CustomerId, + _key_store: &merchant_key_store::MerchantKeyStore, ) -> errors::PmResult<payment_methods::PaymentMethod> { todo!() } diff --git a/crates/payment_methods/src/core/migration.rs b/crates/payment_methods/src/core/migration.rs index 069a2c460c0..8b2694cf6fe 100644 --- a/crates/payment_methods/src/core/migration.rs +++ b/crates/payment_methods/src/core/migration.rs @@ -2,15 +2,19 @@ use actix_multipart::form::{self, bytes, text}; use api_models::payment_methods as pm_api; use csv::Reader; use error_stack::ResultExt; +#[cfg(feature = "v1")] use hyperswitch_domain_models::{api, merchant_context}; use masking::PeekInterface; use rdkafka::message::ToBytes; use router_env::{instrument, tracing}; -use crate::{controller as pm, core::errors, state}; +use crate::core::errors; +#[cfg(feature = "v1")] +use crate::{controller as pm, state}; pub mod payment_methods; pub use payment_methods::migrate_payment_method; +#[cfg(feature = "v1")] type PmMigrationResult<T> = errors::CustomResult<api::ApplicationResponse<T>, errors::ApiErrorResponse>; diff --git a/crates/payment_methods/src/core/migration/payment_methods.rs b/crates/payment_methods/src/core/migration/payment_methods.rs index d8dc1abdd09..10808f08a25 100644 --- a/crates/payment_methods/src/core/migration/payment_methods.rs +++ b/crates/payment_methods/src/core/migration/payment_methods.rs @@ -2,30 +2,39 @@ use std::str::FromStr; #[cfg(feature = "v2")] use api_models::enums as api_enums; -use api_models::{enums, payment_methods as pm_api}; +#[cfg(feature = "v1")] +use api_models::enums; +use api_models::payment_methods as pm_api; +#[cfg(feature = "v1")] use common_utils::{ consts, crypto::Encryptable, - errors::CustomResult, ext_traits::{AsyncExt, ConfigExt}, - generate_id, id_type, + generate_id, }; +use common_utils::{errors::CustomResult, id_type}; use error_stack::ResultExt; use hyperswitch_domain_models::{ - api::ApplicationResponse, errors::api_error_response as errors, ext_traits::OptionExt, - merchant_context, payment_methods as domain_pm, + api::ApplicationResponse, errors::api_error_response as errors, merchant_context, }; -use masking::{PeekInterface, Secret}; +#[cfg(feature = "v1")] +use hyperswitch_domain_models::{ext_traits::OptionExt, payment_methods as domain_pm}; +use masking::PeekInterface; +#[cfg(feature = "v1")] +use masking::Secret; +#[cfg(feature = "v1")] use router_env::{instrument, logger, tracing}; +#[cfg(feature = "v1")] use serde_json::json; use storage_impl::cards_info; +#[cfg(feature = "v1")] use crate::{ - controller::{create_encrypted_data, PaymentMethodsController}, + controller::create_encrypted_data, core::migration, - helpers::{ForeignFrom, ForeignTryFrom, StorageErrorExt}, - state, + helpers::{ForeignFrom, StorageErrorExt}, }; +use crate::{controller::PaymentMethodsController, helpers::ForeignTryFrom, state}; #[cfg(feature = "v1")] pub async fn migrate_payment_method( @@ -156,8 +165,8 @@ pub async fn migrate_payment_method( _state: &state::PaymentMethodsState, _req: pm_api::PaymentMethodMigrate, _merchant_id: &id_type::MerchantId, - merchant_context: &merchant_context::MerchantContext, - controller: &dyn PaymentMethodsController, + _merchant_context: &merchant_context::MerchantContext, + _controller: &dyn PaymentMethodsController, ) -> CustomResult<ApplicationResponse<pm_api::PaymentMethodMigrateResponse>, errors::ApiErrorResponse> { todo!() diff --git a/crates/payment_methods/src/helpers.rs b/crates/payment_methods/src/helpers.rs index 9dd93aa3c91..0ed24883e7e 100644 --- a/crates/payment_methods/src/helpers.rs +++ b/crates/payment_methods/src/helpers.rs @@ -1,6 +1,8 @@ use api_models::{enums as api_enums, payment_methods as api}; +#[cfg(feature = "v1")] use common_utils::ext_traits::AsyncExt; pub use hyperswitch_domain_models::{errors::api_error_response, payment_methods as domain}; +#[cfg(feature = "v1")] use router_env::logger; use crate::state; @@ -277,7 +279,7 @@ impl ForeignFrom<(Option<api::CardDetailFromLocker>, domain::PaymentMethod)> for api::PaymentMethodResponse { fn foreign_from( - (card_details, item): (Option<api::CardDetailFromLocker>, domain::PaymentMethod), + (_card_details, _item): (Option<api::CardDetailFromLocker>, domain::PaymentMethod), ) -> Self { todo!() } diff --git a/crates/payment_methods/src/state.rs b/crates/payment_methods/src/state.rs index 9782a328180..225b04a09ad 100644 --- a/crates/payment_methods/src/state.rs +++ b/crates/payment_methods/src/state.rs @@ -1,8 +1,10 @@ #[cfg(feature = "v1")] use common_utils::errors::CustomResult; use common_utils::types::keymanager; +#[cfg(feature = "v1")] +use hyperswitch_domain_models::merchant_account; use hyperswitch_domain_models::{ - cards_info, customer, merchant_account, merchant_key_store, payment_methods as pm_domain, + cards_info, customer, merchant_key_store, payment_methods as pm_domain, }; use storage_impl::{errors, kv_router_store::KVRouterStore, DatabaseStore, MockDb, RouterStore}; diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index 4b4c35dac2a..2cad1d91eb8 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -547,7 +547,6 @@ pub async fn retrieve_customer( .find_customer_by_global_id( key_manager_state, &id, - merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) @@ -633,7 +632,6 @@ impl CustomerDeleteBridge for id_type::GlobalCustomerId { .find_customer_by_global_id( key_manager_state, self, - merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) @@ -745,7 +743,6 @@ impl CustomerDeleteBridge for id_type::GlobalCustomerId { key_manager_state, self, customer_orig, - merchant_context.get_merchant_account().get_id(), updated_customer, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, @@ -1220,7 +1217,6 @@ impl VerifyIdForUpdateCustomer<'_> { .find_customer_by_global_id( self.key_manager_state, self.id, - self.merchant_account.get_id(), self.key_store, self.merchant_account.storage_scheme, ) @@ -1418,7 +1414,6 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest { key_manager_state, &domain_customer.id, domain_customer.to_owned(), - merchant_context.get_merchant_account().get_id(), storage::CustomerUpdate::Update(Box::new(storage::CustomerGeneralUpdate { name: encryptable_customer.name, email: Box::new(encryptable_customer.email.map(|email| { diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index c851b4842e5..59be79c66f6 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -913,7 +913,6 @@ pub async fn create_payment_method_core( db.find_customer_by_global_id( key_manager_state, &customer_id, - merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) @@ -1257,7 +1256,6 @@ pub async fn payment_method_intent_create( db.find_customer_by_global_id( key_manager_state, &customer_id, - merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) @@ -2473,7 +2471,6 @@ pub async fn delete_payment_method_core( .find_customer_by_global_id( key_manager_state, &payment_method.customer_id, - merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) @@ -2630,7 +2627,6 @@ pub async fn payment_methods_session_create( db.find_customer_by_global_id( key_manager_state, &request.customer_id, - merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 9f6e317531a..5b7c8041ce4 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -3170,7 +3170,6 @@ pub async fn make_client_secret( db.find_customer_by_global_id( key_manager_state, global_customer_id, - merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) diff --git a/crates/router/src/core/payments/operations/payment_capture_v2.rs b/crates/router/src/core/payments/operations/payment_capture_v2.rs index d644ea52357..1b46cb85d4a 100644 --- a/crates/router/src/core/payments/operations/payment_capture_v2.rs +++ b/crates/router/src/core/payments/operations/payment_capture_v2.rs @@ -226,7 +226,6 @@ impl<F: Clone + Send> Domain<F, PaymentsCaptureRequest, PaymentCaptureData<F>> f .find_customer_by_global_id( &state.into(), &id, - &payment_data.payment_intent.merchant_id, merchant_key_store, storage_scheme, ) diff --git a/crates/router/src/core/payments/operations/payment_confirm_intent.rs b/crates/router/src/core/payments/operations/payment_confirm_intent.rs index 4f58107fa9c..dce33895fde 100644 --- a/crates/router/src/core/payments/operations/payment_confirm_intent.rs +++ b/crates/router/src/core/payments/operations/payment_confirm_intent.rs @@ -299,7 +299,6 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsConfirmIntentRequest, PaymentConf .find_customer_by_global_id( &state.into(), &id, - &payment_data.payment_intent.merchant_id, merchant_key_store, storage_scheme, ) @@ -653,7 +652,6 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentConfirmData<F>, PaymentsConfirmInt key_manager_state, &customer_id, customer, - &customer_merchant_id, updated_customer, key_store, storage_scheme, diff --git a/crates/router/src/core/payments/operations/payment_create_intent.rs b/crates/router/src/core/payments/operations/payment_create_intent.rs index 10076585a98..0f1704938c4 100644 --- a/crates/router/src/core/payments/operations/payment_create_intent.rs +++ b/crates/router/src/core/payments/operations/payment_create_intent.rs @@ -253,13 +253,7 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsCreateIntentRequest, payments::Pa if let Some(id) = payment_data.payment_intent.customer_id.clone() { state .store - .find_customer_by_global_id( - &state.into(), - &id, - &payment_data.payment_intent.merchant_id, - merchant_key_store, - storage_scheme, - ) + .find_customer_by_global_id(&state.into(), &id, merchant_key_store, storage_scheme) .await?; } Ok((Box::new(self), None)) diff --git a/crates/router/src/core/payments/operations/payment_get.rs b/crates/router/src/core/payments/operations/payment_get.rs index 63f64fb233a..402c11e2f86 100644 --- a/crates/router/src/core/payments/operations/payment_get.rs +++ b/crates/router/src/core/payments/operations/payment_get.rs @@ -271,7 +271,6 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsRetrieveRequest, PaymentStatusDat .find_customer_by_global_id( &state.into(), &id, - &payment_data.payment_intent.merchant_id, merchant_key_store, storage_scheme, ) diff --git a/crates/router/src/core/payments/operations/payment_session_intent.rs b/crates/router/src/core/payments/operations/payment_session_intent.rs index 8f167a43112..8ae5d2cd19d 100644 --- a/crates/router/src/core/payments/operations/payment_session_intent.rs +++ b/crates/router/src/core/payments/operations/payment_session_intent.rs @@ -244,7 +244,6 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsSessionRequest, payments::Payment .find_customer_by_global_id( &state.into(), &id, - &payment_data.payment_intent.merchant_id, merchant_key_store, storage_scheme, ) diff --git a/crates/router/src/core/payments/vault_session.rs b/crates/router/src/core/payments/vault_session.rs index 51a2badfe2a..db77d6a9997 100644 --- a/crates/router/src/core/payments/vault_session.rs +++ b/crates/router/src/core/payments/vault_session.rs @@ -105,7 +105,6 @@ where &state.into(), &customer_id, customer, - &customer_merchant_id, updated_customer, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index 64c5ced78bc..cbb9957115b 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -1245,7 +1245,6 @@ pub async fn create_recipient( &state.into(), &customer_id, customer, - merchant_account.get_id(), updated_customer, key_store, merchant_account.storage_scheme, diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 1d20c7b27c1..7eef89c34e6 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -474,7 +474,6 @@ impl CustomerInterface for KafkaStore { state: &KeyManagerState, id: &id_type::GlobalCustomerId, customer: domain::Customer, - merchant_id: &id_type::MerchantId, customer_update: storage::CustomerUpdate, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, @@ -484,7 +483,6 @@ impl CustomerInterface for KafkaStore { state, id, customer, - merchant_id, customer_update, key_store, storage_scheme, @@ -549,12 +547,11 @@ impl CustomerInterface for KafkaStore { &self, state: &KeyManagerState, id: &id_type::GlobalCustomerId, - merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, errors::StorageError> { self.diesel_store - .find_customer_by_global_id(state, id, merchant_id, key_store, storage_scheme) + .find_customer_by_global_id(state, id, key_store, storage_scheme) .await } diff --git a/crates/storage_impl/src/customers.rs b/crates/storage_impl/src/customers.rs index 8df20a298e2..bedbcadd6a8 100644 --- a/crates/storage_impl/src/customers.rs +++ b/crates/storage_impl/src/customers.rs @@ -10,8 +10,9 @@ use hyperswitch_domain_models::{ use masking::PeekInterface; use router_env::{instrument, tracing}; +#[cfg(feature = "v1")] +use crate::diesel_error_to_data_error; use crate::{ - diesel_error_to_data_error, errors::StorageError, kv_router_store, redis::kv_store::{decide_storage_scheme, KvStorePartition, Op, PartitionKey}, @@ -368,7 +369,6 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterSt &self, state: &KeyManagerState, id: &id_type::GlobalCustomerId, - _merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { @@ -402,7 +402,6 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterSt state: &KeyManagerState, id: &id_type::GlobalCustomerId, customer: domain::Customer, - _merchant_id: &id_type::MerchantId, customer_update: domain::CustomerUpdate, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, @@ -670,11 +669,10 @@ impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> { &self, state: &KeyManagerState, id: &id_type::GlobalCustomerId, - customer: domain::Customer, - merchant_id: &id_type::MerchantId, + _customer: domain::Customer, customer_update: domain::CustomerUpdate, key_store: &MerchantKeyStore, - storage_scheme: MerchantStorageScheme, + _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { let conn = pg_connection_write(self).await?; self.call_database( @@ -691,7 +689,6 @@ impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> { &self, state: &KeyManagerState, id: &id_type::GlobalCustomerId, - merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { @@ -748,10 +745,10 @@ impl domain::CustomerInterface for MockDb { #[cfg(feature = "v2")] async fn find_optional_by_merchant_id_merchant_reference_id( &self, - state: &KeyManagerState, - customer_id: &id_type::CustomerId, - merchant_id: &id_type::MerchantId, - key_store: &MerchantKeyStore, + _state: &KeyManagerState, + _customer_id: &id_type::CustomerId, + _merchant_id: &id_type::MerchantId, + _key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<domain::Customer>, StorageError> { todo!() @@ -874,7 +871,6 @@ impl domain::CustomerInterface for MockDb { _state: &KeyManagerState, _id: &id_type::GlobalCustomerId, _customer: domain::Customer, - _merchant_id: &id_type::MerchantId, _customer_update: domain::CustomerUpdate, _key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, @@ -888,7 +884,6 @@ impl domain::CustomerInterface for MockDb { &self, _state: &KeyManagerState, _id: &id_type::GlobalCustomerId, - _merchant_id: &id_type::MerchantId, _key_store: &MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, StorageError> { diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs index 27b59052051..56df356547e 100644 --- a/crates/storage_impl/src/lib.rs +++ b/crates/storage_impl/src/lib.rs @@ -32,8 +32,6 @@ pub mod utils; use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState}; use database::store::PgPool; -#[cfg(all(feature = "v2", feature = "tokenization_v2"))] -use diesel_models::tokenization::Tokenization; pub mod tokenization; #[cfg(not(feature = "payouts"))] use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface}; diff --git a/crates/storage_impl/src/mock_db/payment_intent.rs b/crates/storage_impl/src/mock_db/payment_intent.rs index cbdf2b3b0c6..427f69d8958 100644 --- a/crates/storage_impl/src/mock_db/payment_intent.rs +++ b/crates/storage_impl/src/mock_db/payment_intent.rs @@ -1,8 +1,10 @@ use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState}; use diesel_models::enums as storage_enums; +#[cfg(feature = "v1")] use error_stack::ResultExt; +#[cfg(feature = "v1")] +use hyperswitch_domain_models::behaviour::Conversion; use hyperswitch_domain_models::{ - behaviour::Conversion, merchant_key_store::MerchantKeyStore, payments::{ payment_intent::{PaymentIntentInterface, PaymentIntentUpdate}, @@ -32,11 +34,11 @@ impl PaymentIntentInterface for MockDb { #[cfg(all(feature = "v2", feature = "olap"))] async fn get_filtered_payment_intents_attempt( &self, - state: &KeyManagerState, - merchant_id: &common_utils::id_type::MerchantId, - constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, - merchant_key_store: &MerchantKeyStore, - storage_scheme: storage_enums::MerchantStorageScheme, + _state: &KeyManagerState, + _merchant_id: &common_utils::id_type::MerchantId, + _constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, + _merchant_key_store: &MerchantKeyStore, + _storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result< Vec<( PaymentIntent, @@ -166,10 +168,10 @@ impl PaymentIntentInterface for MockDb { #[allow(clippy::unwrap_used)] async fn update_payment_intent( &self, - state: &KeyManagerState, - this: PaymentIntent, - update: PaymentIntentUpdate, - key_store: &MerchantKeyStore, + _state: &KeyManagerState, + _this: PaymentIntent, + _update: PaymentIntentUpdate, + _key_store: &MerchantKeyStore, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<PaymentIntent, StorageError> { todo!() diff --git a/crates/storage_impl/src/payment_method.rs b/crates/storage_impl/src/payment_method.rs index 020adf6a279..74be922c7f5 100644 --- a/crates/storage_impl/src/payment_method.rs +++ b/crates/storage_impl/src/payment_method.rs @@ -6,13 +6,14 @@ impl KvStorePartition for PaymentMethod {} use common_enums::enums::MerchantStorageScheme; use common_utils::{errors::CustomResult, id_type, types::keymanager::KeyManagerState}; -use diesel_models::{ - kv, - payment_method::{PaymentMethodUpdate, PaymentMethodUpdateInternal}, -}; +#[cfg(feature = "v1")] +use diesel_models::kv; +use diesel_models::payment_method::{PaymentMethodUpdate, PaymentMethodUpdateInternal}; use error_stack::ResultExt; +#[cfg(feature = "v1")] +use hyperswitch_domain_models::behaviour::ReverseConversion; use hyperswitch_domain_models::{ - behaviour::{Conversion, ReverseConversion}, + behaviour::Conversion, merchant_key_store::MerchantKeyStore, payment_methods::{PaymentMethod as DomainPaymentMethod, PaymentMethodInterface}, }; @@ -21,14 +22,15 @@ use router_env::{instrument, tracing}; use super::MockDb; use crate::{ diesel_error_to_data_error, errors, - kv_router_store::{ - FilterResourceParams, FindResourceBy, InsertResourceParams, KVRouterStore, - UpdateResourceParams, - }, - redis::kv_store::{Op, PartitionKey}, + kv_router_store::{FindResourceBy, KVRouterStore}, utils::{pg_connection_read, pg_connection_write}, DatabaseStore, RouterStore, }; +#[cfg(feature = "v1")] +use crate::{ + kv_router_store::{FilterResourceParams, InsertResourceParams, UpdateResourceParams}, + redis::kv_store::{Op, PartitionKey}, +}; #[async_trait::async_trait] impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> { @@ -389,7 +391,6 @@ impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> { key_store: &MerchantKeyStore, fingerprint_id: &str, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { - let conn = pg_connection_read(self).await?; self.router_store .find_payment_method_by_fingerprint_id(state, key_store, fingerprint_id) .await @@ -538,7 +539,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> { key_store: &MerchantKeyStore, payment_method: DomainPaymentMethod, payment_method_update: PaymentMethodUpdate, - storage_scheme: MerchantStorageScheme, + _storage_scheme: MerchantStorageScheme, ) -> CustomResult<DomainPaymentMethod, errors::StorageError> { let payment_method = Conversion::convert(payment_method) .await @@ -837,8 +838,8 @@ impl PaymentMethodInterface for MockDb { #[cfg(feature = "v2")] async fn find_payment_method_list_by_global_customer_id( &self, - state: &KeyManagerState, - key_store: &MerchantKeyStore, + _state: &KeyManagerState, + _key_store: &MerchantKeyStore, _id: &id_type::GlobalCustomerId, _limit: Option<i64>, ) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> { diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index db3400c5fa4..69de633aee0 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -1,7 +1,8 @@ +use common_utils::errors::CustomResult; #[cfg(feature = "v2")] use common_utils::types::keymanager::KeyManagerState; +#[cfg(feature = "v1")] use common_utils::{ - errors::CustomResult, fallback_reverse_lookup_not_found, types::{ConnectorTransactionId, ConnectorTransactionIdTrait, CreatedBy}, }; @@ -10,12 +11,11 @@ use diesel_models::{ MandateAmountData as DieselMandateAmountData, MandateDataType as DieselMandateType, MandateDetails as DieselMandateDetails, MerchantStorageScheme, }, - kv, - payment_attempt::{ - PaymentAttempt as DieselPaymentAttempt, PaymentAttemptNew as DieselPaymentAttemptNew, - }, + payment_attempt::PaymentAttempt as DieselPaymentAttempt, reverse_lookup::{ReverseLookup, ReverseLookupNew}, }; +#[cfg(feature = "v1")] +use diesel_models::{kv, payment_attempt::PaymentAttemptNew as DieselPaymentAttemptNew}; use error_stack::ResultExt; #[cfg(feature = "v1")] use hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptNew; @@ -28,22 +28,27 @@ use hyperswitch_domain_models::{ mandates::{MandateAmountData, MandateDataType, MandateDetails}, payments::payment_attempt::{PaymentAttempt, PaymentAttemptInterface, PaymentAttemptUpdate}, }; -#[cfg(feature = "olap")] +#[cfg(all(feature = "v1", feature = "olap"))] use hyperswitch_domain_models::{ payments::payment_attempt::PaymentListFilters, payments::PaymentIntent, }; +#[cfg(feature = "v1")] use redis_interface::HsetnxReply; use router_env::{instrument, tracing}; use crate::{ - diesel_error_to_data_error, - errors::{self, RedisErrorExt}, + diesel_error_to_data_error, errors, kv_router_store::KVRouterStore, lookup::ReverseLookupInterface, - redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey}, - utils::{pg_connection_read, pg_connection_write, try_redis_get_else_try_database_get}, + utils::{pg_connection_read, pg_connection_write}, DataModelExt, DatabaseStore, RouterStore, }; +#[cfg(feature = "v1")] +use crate::{ + errors::RedisErrorExt, + redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey}, + utils::try_redis_get_else_try_database_get, +}; #[async_trait::async_trait] impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs index e78d6244d50..17156855e13 100644 --- a/crates/storage_impl/src/payments/payment_intent.rs +++ b/crates/storage_impl/src/payments/payment_intent.rs @@ -2,14 +2,11 @@ use api_models::payments::{AmountFilter, Order, SortBy, SortOn}; #[cfg(feature = "olap")] use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl}; -use common_utils::{ - ext_traits::{AsyncExt, Encode}, - types::keymanager::KeyManagerState, -}; +#[cfg(feature = "v1")] +use common_utils::ext_traits::Encode; +use common_utils::{ext_traits::AsyncExt, types::keymanager::KeyManagerState}; #[cfg(feature = "olap")] use diesel::{associations::HasTable, ExpressionMethods, JoinOnDsl, QueryDsl}; -#[cfg(feature = "v1")] -use diesel_models::payment_intent::PaymentIntentUpdate as DieselPaymentIntentUpdate; #[cfg(feature = "olap")] use diesel_models::query::generics::db_metrics; #[cfg(all(feature = "v1", feature = "olap"))] @@ -23,8 +20,10 @@ use diesel_models::schema_v2::{ payment_intent::dsl as pi_dsl, }; use diesel_models::{ - enums::MerchantStorageScheme, kv, payment_intent::PaymentIntent as DieselPaymentIntent, + enums::MerchantStorageScheme, payment_intent::PaymentIntent as DieselPaymentIntent, }; +#[cfg(feature = "v1")] +use diesel_models::{kv, payment_intent::PaymentIntentUpdate as DieselPaymentIntentUpdate}; use error_stack::ResultExt; #[cfg(feature = "olap")] use hyperswitch_domain_models::payments::{ @@ -38,6 +37,7 @@ use hyperswitch_domain_models::{ PaymentIntent, }, }; +#[cfg(feature = "v1")] use redis_interface::HsetnxReply; #[cfg(feature = "olap")] use router_env::logger; @@ -47,12 +47,17 @@ use router_env::{instrument, tracing}; use crate::connection; use crate::{ diesel_error_to_data_error, - errors::{RedisErrorExt, StorageError}, + errors::StorageError, kv_router_store::KVRouterStore, - redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey}, - utils::{self, pg_connection_read, pg_connection_write}, + utils::{pg_connection_read, pg_connection_write}, DatabaseStore, }; +#[cfg(feature = "v1")] +use crate::{ + errors::RedisErrorExt, + redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey}, + utils, +}; #[async_trait::async_trait] impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { @@ -1136,8 +1141,6 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { use diesel::NullableExpressionMethods as _; use futures::{future::try_join_all, FutureExt}; - use crate::DataModelExt; - let conn = connection::pg_connection_read(self).await?; let conn = async_bb8_diesel::Connection::as_async_conn(&conn); let mut query = DieselPaymentIntent::table() diff --git a/crates/storage_impl/src/payouts/payouts.rs b/crates/storage_impl/src/payouts/payouts.rs index 482b77e300a..484328aabab 100644 --- a/crates/storage_impl/src/payouts/payouts.rs +++ b/crates/storage_impl/src/payouts/payouts.rs @@ -4,18 +4,13 @@ use api_models::enums::PayoutConnectors; use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl}; use common_utils::ext_traits::Encode; #[cfg(feature = "olap")] -use diesel::{ - associations::HasTable, ExpressionMethods, JoinOnDsl, NullableExpressionMethods, QueryDsl, -}; -#[cfg(all(feature = "olap", feature = "v1"))] -use diesel_models::schema::{ - address::dsl as add_dsl, customers::dsl as cust_dsl, payout_attempt::dsl as poa_dsl, -}; +use diesel::{associations::HasTable, ExpressionMethods, QueryDsl}; +#[cfg(all(feature = "v1", feature = "olap"))] +use diesel::{JoinOnDsl, NullableExpressionMethods}; #[cfg(feature = "olap")] use diesel_models::{ address::Address as DieselAddress, customers::Customer as DieselCustomer, - enums as storage_enums, payout_attempt::PayoutAttempt as DieselPayoutAttempt, - query::generics::db_metrics, schema::payouts::dsl as po_dsl, + enums as storage_enums, query::generics::db_metrics, schema::payouts::dsl as po_dsl, }; use diesel_models::{ enums::MerchantStorageScheme, @@ -25,6 +20,11 @@ use diesel_models::{ PayoutsUpdate as DieselPayoutsUpdate, }, }; +#[cfg(all(feature = "olap", feature = "v1"))] +use diesel_models::{ + payout_attempt::PayoutAttempt as DieselPayoutAttempt, + schema::{address::dsl as add_dsl, customers::dsl as cust_dsl, payout_attempt::dsl as poa_dsl}, +}; use error_stack::ResultExt; #[cfg(feature = "olap")] use hyperswitch_domain_models::payouts::PayoutFetchConstraints; @@ -876,8 +876,8 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> { #[instrument(skip_all)] async fn filter_active_payout_ids_by_constraints( &self, - merchant_id: &common_utils::id_type::MerchantId, - constraints: &PayoutFetchConstraints, + _merchant_id: &common_utils::id_type::MerchantId, + _constraints: &PayoutFetchConstraints, ) -> error_stack::Result<Vec<String>, StorageError> { todo!() } diff --git a/crates/storage_impl/src/tokenization.rs b/crates/storage_impl/src/tokenization.rs index 5ecb6b0a813..9a824e9126c 100644 --- a/crates/storage_impl/src/tokenization.rs +++ b/crates/storage_impl/src/tokenization.rs @@ -1,41 +1,16 @@ #[cfg(all(feature = "v2", feature = "tokenization_v2"))] -use async_bb8_diesel::AsyncRunQueryDsl; +use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState}; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] -use common_utils::{ - errors::CustomResult, - ext_traits::OptionExt, - id_type::{CellId, GlobalTokenId, MerchantId}, - types::keymanager::KeyManagerState, -}; -#[cfg(all(feature = "v2", feature = "tokenization_v2"))] -use diesel::{ExpressionMethods, Insertable, RunQueryDsl}; -#[cfg(all(feature = "v2", feature = "tokenization_v2"))] -use diesel_models::{ - enums::TokenizationFlag as DbTokenizationFlag, - schema_v2::tokenization::dsl as tokenization_dsl, tokenization, PgPooledConn, -}; -#[cfg(all(feature = "v2", feature = "tokenization_v2"))] -use error_stack::{report, Report, ResultExt}; -#[cfg(all(feature = "v2", feature = "tokenization_v2"))] -use hyperswitch_domain_models::tokenization::Tokenization; +use error_stack::{report, ResultExt}; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] use hyperswitch_domain_models::{ behaviour::{Conversion, ReverseConversion}, merchant_key_store::MerchantKeyStore, }; -#[cfg(all(feature = "v2", feature = "tokenization_v2"))] -use tokio::time; use super::MockDb; #[cfg(all(feature = "v2", feature = "tokenization_v2"))] -use crate::{ - connection, diesel_error_to_data_error, errors, - kv_router_store::{ - FilterResourceParams, FindResourceBy, InsertResourceParams, UpdateResourceParams, - }, - redis::kv_store::{Op, PartitionKey}, - utils::{pg_connection_read, pg_connection_write}, -}; +use crate::{connection, errors}; use crate::{kv_router_store::KVRouterStore, DatabaseStore, RouterStore}; #[cfg(not(all(feature = "v2", feature = "tokenization_v2")))] @@ -146,18 +121,18 @@ impl<T: DatabaseStore> TokenizationInterface for KVRouterStore<T> { impl TokenizationInterface for MockDb { async fn insert_tokenization( &self, - tokenization: hyperswitch_domain_models::tokenization::Tokenization, - merchant_key_store: &MerchantKeyStore, - key_manager_state: &KeyManagerState, + _tokenization: hyperswitch_domain_models::tokenization::Tokenization, + _merchant_key_store: &MerchantKeyStore, + _key_manager_state: &KeyManagerState, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn get_entity_id_vault_id_by_token_id( &self, - token: &common_utils::id_type::GlobalTokenId, - merchant_key_store: &MerchantKeyStore, - key_manager_state: &KeyManagerState, + _token: &common_utils::id_type::GlobalTokenId, + _merchant_key_store: &MerchantKeyStore, + _key_manager_state: &KeyManagerState, ) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError> { Err(errors::StorageError::MockDbError)?
2025-06-18T07:04:20Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR resolves the v2 warnings generated in crates common_utils, api_models, hyperswitch_domain_models, diesel_models, kgraph_utils, storage_impl, hyperswitch_connectors, payment_methods. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Testing not required. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
305ca9bda9d3c5bf3cc97458b7ed07b79e894154
305ca9bda9d3c5bf3cc97458b7ed07b79e894154
juspay/hyperswitch
juspay__hyperswitch-8341
Bug: chore(ci): `adyen` and `stripe` postman tests are failing Multiple Test Cases have been failing on Postman, - Adyen: <span style="color:red">88 Failures</span> - Stripe: <span style="color:red">3 Failures</span> <img width="500" alt="Image" src="https://github.com/user-attachments/assets/522a3f3b-ef4d-450d-b584-8233d9008389" />
diff --git a/postman/collection-dir/stripe/PaymentConnectors/.meta.json b/postman/collection-dir/stripe/PaymentConnectors/.meta.json index 6d68eeab4ab..c32be7223a6 100644 --- a/postman/collection-dir/stripe/PaymentConnectors/.meta.json +++ b/postman/collection-dir/stripe/PaymentConnectors/.meta.json @@ -5,7 +5,7 @@ "Payment Connector - Update", "List Connectors by MID", "Payment Connector - Delete", - "Merchant Account - Delete", - "Delete API Key" + "Delete API Key", + "Merchant Account - Delete" ] }
2025-06-13T04:05:49Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [x] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> Deleting API Key needs Merchant ID. So, deleting it after deleting the merchant itself yields a error message in the response which goes like `"API key not provided or invalid API key used"`, but, its solely because the Merchant ID used is not authenticated because the Merchant ID is already deleted. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> The respective test case was failing in the Automated Tests Run. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> <img width="864" alt="image" src="https://github.com/user-attachments/assets/86d7ab3a-46b4-4476-804f-b200b3d67a05" /> The Remaining failures are because of outdated certificates and their keys. Once we update that it will be like the following <img width="493" alt="image" src="https://github.com/user-attachments/assets/e45efb84-44d8-4f32-8d65-5ed7c1567a79" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
953bace38c1509c95fc8c1e2426fda72c65e3bf8
953bace38c1509c95fc8c1e2426fda72c65e3bf8
juspay/hyperswitch
juspay__hyperswitch-8338
Bug: fix(analytics): refactor auth analytics to support profile,org and merchant level auth ### Feature Description Exposed the auth analytics under profile, merchant and org levels ### Possible Implementation Expose different endpoints for auth analytics sankey ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/analytics/src/auth_events/core.rs b/crates/analytics/src/auth_events/core.rs index 41b7b724954..011633dce3d 100644 --- a/crates/analytics/src/auth_events/core.rs +++ b/crates/analytics/src/auth_events/core.rs @@ -27,7 +27,7 @@ use crate::{ #[instrument(skip_all)] pub async fn get_metrics( pool: &AnalyticsProvider, - merchant_id: &common_utils::id_type::MerchantId, + auth: &AuthInfo, req: GetAuthEventMetricRequest, ) -> AnalyticsResult<AuthEventMetricsResponse<MetricsBucketResponse>> { let mut metrics_accumulator: HashMap< @@ -38,14 +38,14 @@ pub async fn get_metrics( let mut set = tokio::task::JoinSet::new(); for metric_type in req.metrics.iter().cloned() { let req = req.clone(); - let merchant_id_scoped = merchant_id.to_owned(); + let auth_scoped = auth.to_owned(); let pool = pool.clone(); set.spawn(async move { let data = pool .get_auth_event_metrics( &metric_type, &req.group_by_names.clone(), - &merchant_id_scoped, + &auth_scoped, &req.filters, req.time_series.map(|t| t.granularity), &req.time_range, @@ -130,7 +130,7 @@ pub async fn get_metrics( pub async fn get_filters( pool: &AnalyticsProvider, req: GetAuthEventFilterRequest, - merchant_id: &common_utils::id_type::MerchantId, + auth: &AuthInfo, ) -> AnalyticsResult<AuthEventFiltersResponse> { let mut res = AuthEventFiltersResponse::default(); for dim in req.group_by_names { @@ -139,14 +139,14 @@ pub async fn get_filters( Err(report!(AnalyticsError::UnknownError)) } AnalyticsProvider::Clickhouse(pool) => { - get_auth_events_filter_for_dimension(dim, merchant_id, &req.time_range, pool) + get_auth_events_filter_for_dimension(dim, auth, &req.time_range, pool) .await .map_err(|e| e.change_context(AnalyticsError::UnknownError)) } AnalyticsProvider::CombinedCkh(sqlx_pool, ckh_pool) | AnalyticsProvider::CombinedSqlx(sqlx_pool, ckh_pool) => { let ckh_result = get_auth_events_filter_for_dimension( dim, - merchant_id, + auth, &req.time_range, ckh_pool, ) @@ -154,7 +154,7 @@ pub async fn get_filters( .map_err(|e| e.change_context(AnalyticsError::UnknownError)); let sqlx_result = get_auth_events_filter_for_dimension( dim, - merchant_id, + auth, &req.time_range, sqlx_pool, ) diff --git a/crates/analytics/src/auth_events/filters.rs b/crates/analytics/src/auth_events/filters.rs index 92496131727..7ecf2426dfa 100644 --- a/crates/analytics/src/auth_events/filters.rs +++ b/crates/analytics/src/auth_events/filters.rs @@ -6,6 +6,7 @@ use error_stack::ResultExt; use time::PrimitiveDateTime; use crate::{ + enums::AuthInfo, query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, types::{ AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, FiltersError, FiltersResult, @@ -17,7 +18,7 @@ pub trait AuthEventFilterAnalytics: LoadRow<AuthEventFilterRow> {} pub async fn get_auth_events_filter_for_dimension<T>( dimension: AuthEventDimensions, - merchant_id: &common_utils::id_type::MerchantId, + auth: &AuthInfo, time_range: &TimeRange, pool: &T, ) -> FiltersResult<Vec<AuthEventFilterRow>> @@ -38,12 +39,10 @@ where .attach_printable("Error filtering time range") .switch()?; - query_builder - .add_filter_clause("merchant_id", merchant_id) - .switch()?; - query_builder.set_distinct(); + auth.set_filter_clause(&mut query_builder).switch()?; + query_builder .execute_query::<AuthEventFilterRow, _>(pool) .await diff --git a/crates/analytics/src/auth_events/metrics.rs b/crates/analytics/src/auth_events/metrics.rs index 46c3805662a..ebb1d5d1f00 100644 --- a/crates/analytics/src/auth_events/metrics.rs +++ b/crates/analytics/src/auth_events/metrics.rs @@ -12,6 +12,7 @@ use time::PrimitiveDateTime; use crate::{ query::{Aggregate, GroupByClause, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, LoadRow, MetricsResult}, + AuthInfo, }; mod authentication_attempt_count; @@ -86,7 +87,7 @@ where { async fn load_metrics( &self, - merchant_id: &common_utils::id_type::MerchantId, + auth: &AuthInfo, dimensions: &[AuthEventDimensions], filters: &AuthEventFilters, granularity: Option<Granularity>, @@ -107,7 +108,7 @@ where { async fn load_metrics( &self, - merchant_id: &common_utils::id_type::MerchantId, + auth: &AuthInfo, dimensions: &[AuthEventDimensions], filters: &AuthEventFilters, granularity: Option<Granularity>, @@ -117,146 +118,62 @@ where match self { Self::AuthenticationCount => { AuthenticationCount - .load_metrics( - merchant_id, - dimensions, - filters, - granularity, - time_range, - pool, - ) + .load_metrics(auth, dimensions, filters, granularity, time_range, pool) .await } Self::AuthenticationAttemptCount => { AuthenticationAttemptCount - .load_metrics( - merchant_id, - dimensions, - filters, - granularity, - time_range, - pool, - ) + .load_metrics(auth, dimensions, filters, granularity, time_range, pool) .await } Self::AuthenticationSuccessCount => { AuthenticationSuccessCount - .load_metrics( - merchant_id, - dimensions, - filters, - granularity, - time_range, - pool, - ) + .load_metrics(auth, dimensions, filters, granularity, time_range, pool) .await } Self::ChallengeFlowCount => { ChallengeFlowCount - .load_metrics( - merchant_id, - dimensions, - filters, - granularity, - time_range, - pool, - ) + .load_metrics(auth, dimensions, filters, granularity, time_range, pool) .await } Self::ChallengeAttemptCount => { ChallengeAttemptCount - .load_metrics( - merchant_id, - dimensions, - filters, - granularity, - time_range, - pool, - ) + .load_metrics(auth, dimensions, filters, granularity, time_range, pool) .await } Self::ChallengeSuccessCount => { ChallengeSuccessCount - .load_metrics( - merchant_id, - dimensions, - filters, - granularity, - time_range, - pool, - ) + .load_metrics(auth, dimensions, filters, granularity, time_range, pool) .await } Self::FrictionlessFlowCount => { FrictionlessFlowCount - .load_metrics( - merchant_id, - dimensions, - filters, - granularity, - time_range, - pool, - ) + .load_metrics(auth, dimensions, filters, granularity, time_range, pool) .await } Self::FrictionlessSuccessCount => { FrictionlessSuccessCount - .load_metrics( - merchant_id, - dimensions, - filters, - granularity, - time_range, - pool, - ) + .load_metrics(auth, dimensions, filters, granularity, time_range, pool) .await } Self::AuthenticationErrorMessage => { AuthenticationErrorMessage - .load_metrics( - merchant_id, - dimensions, - filters, - granularity, - time_range, - pool, - ) + .load_metrics(auth, dimensions, filters, granularity, time_range, pool) .await } Self::AuthenticationFunnel => { AuthenticationFunnel - .load_metrics( - merchant_id, - dimensions, - filters, - granularity, - time_range, - pool, - ) + .load_metrics(auth, dimensions, filters, granularity, time_range, pool) .await } Self::AuthenticationExemptionApprovedCount => { AuthenticationExemptionApprovedCount - .load_metrics( - merchant_id, - dimensions, - filters, - granularity, - time_range, - pool, - ) + .load_metrics(auth, dimensions, filters, granularity, time_range, pool) .await } Self::AuthenticationExemptionRequestedCount => { AuthenticationExemptionRequestedCount - .load_metrics( - merchant_id, - dimensions, - filters, - granularity, - time_range, - pool, - ) + .load_metrics(auth, dimensions, filters, granularity, time_range, pool) .await } } diff --git a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs index 967513af32c..ce7d11e22a3 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs @@ -13,6 +13,7 @@ use super::AuthEventMetricRow; use crate::{ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, + AuthInfo, }; #[derive(Default)] @@ -30,7 +31,7 @@ where { async fn load_metrics( &self, - merchant_id: &common_utils::id_type::MerchantId, + auth: &AuthInfo, dimensions: &[AuthEventDimensions], filters: &AuthEventFilters, granularity: Option<Granularity>, @@ -65,10 +66,6 @@ where }) .switch()?; - query_builder - .add_filter_clause("merchant_id", merchant_id) - .switch()?; - query_builder .add_filter_in_range_clause( "authentication_status", @@ -80,6 +77,7 @@ where .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; + auth.set_filter_clause(&mut query_builder).switch()?; for dim in dimensions.iter() { query_builder diff --git a/crates/analytics/src/auth_events/metrics/authentication_count.rs b/crates/analytics/src/auth_events/metrics/authentication_count.rs index 0334f732f23..8ee5026d28e 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_count.rs @@ -12,6 +12,7 @@ use super::AuthEventMetricRow; use crate::{ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, + AuthInfo, }; #[derive(Default)] @@ -29,7 +30,7 @@ where { async fn load_metrics( &self, - merchant_id: &common_utils::id_type::MerchantId, + auth: &AuthInfo, dimensions: &[AuthEventDimensions], filters: &AuthEventFilters, granularity: Option<Granularity>, @@ -62,14 +63,12 @@ where }) .switch()?; - query_builder - .add_filter_clause("merchant_id", merchant_id) - .switch()?; filters.set_filter_clause(&mut query_builder).switch()?; time_range .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; + auth.set_filter_clause(&mut query_builder).switch()?; for dim in dimensions.iter() { query_builder diff --git a/crates/analytics/src/auth_events/metrics/authentication_error_message.rs b/crates/analytics/src/auth_events/metrics/authentication_error_message.rs index ac0adc7bbff..180306d9efa 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_error_message.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_error_message.rs @@ -16,6 +16,7 @@ use crate::{ ToSql, Window, }, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, + AuthInfo, }; #[derive(Default)] @@ -33,7 +34,7 @@ where { async fn load_metrics( &self, - merchant_id: &common_utils::id_type::MerchantId, + auth: &AuthInfo, dimensions: &[AuthEventDimensions], filters: &AuthEventFilters, granularity: Option<Granularity>, @@ -64,10 +65,6 @@ where }) .switch()?; - query_builder - .add_filter_clause("merchant_id", merchant_id) - .switch()?; - query_builder .add_filter_clause("authentication_status", AuthenticationStatus::Failed) .switch()?; @@ -84,6 +81,7 @@ where .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; + auth.set_filter_clause(&mut query_builder).switch()?; for dim in dimensions.iter() { query_builder diff --git a/crates/analytics/src/auth_events/metrics/authentication_exemption_approved_count.rs b/crates/analytics/src/auth_events/metrics/authentication_exemption_approved_count.rs index 89ec3affe6b..994f66f5f51 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_exemption_approved_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_exemption_approved_count.rs @@ -12,6 +12,7 @@ use super::AuthEventMetricRow; use crate::{ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, + AuthInfo, }; #[derive(Default)] @@ -29,7 +30,7 @@ where { async fn load_metrics( &self, - merchant_id: &common_utils::id_type::MerchantId, + auth: &AuthInfo, dimensions: &[AuthEventDimensions], filters: &AuthEventFilters, granularity: Option<Granularity>, @@ -62,10 +63,6 @@ where }) .switch()?; - query_builder - .add_filter_clause("merchant_id", merchant_id) - .switch()?; - query_builder .add_filter_clause(AuthEventDimensions::ExemptionAccepted, true) .switch()?; @@ -74,6 +71,7 @@ where .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; + auth.set_filter_clause(&mut query_builder).switch()?; for dim in dimensions.iter() { query_builder diff --git a/crates/analytics/src/auth_events/metrics/authentication_exemption_requested_count.rs b/crates/analytics/src/auth_events/metrics/authentication_exemption_requested_count.rs index aa4af1a47ff..f763533082b 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_exemption_requested_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_exemption_requested_count.rs @@ -12,6 +12,7 @@ use super::AuthEventMetricRow; use crate::{ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, + AuthInfo, }; #[derive(Default)] @@ -29,7 +30,7 @@ where { async fn load_metrics( &self, - merchant_id: &common_utils::id_type::MerchantId, + auth: &AuthInfo, dimensions: &[AuthEventDimensions], filters: &AuthEventFilters, granularity: Option<Granularity>, @@ -62,10 +63,6 @@ where }) .switch()?; - query_builder - .add_filter_clause("merchant_id", merchant_id) - .switch()?; - query_builder .add_filter_clause(AuthEventDimensions::ExemptionRequested, true) .switch()?; @@ -75,6 +72,7 @@ where .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; + auth.set_filter_clause(&mut query_builder).switch()?; for dim in dimensions.iter() { query_builder diff --git a/crates/analytics/src/auth_events/metrics/authentication_funnel.rs b/crates/analytics/src/auth_events/metrics/authentication_funnel.rs index 145a70a542a..e2eb4ce83b8 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_funnel.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_funnel.rs @@ -15,6 +15,7 @@ use crate::{ Window, }, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, + AuthInfo, }; #[derive(Default)] @@ -32,7 +33,7 @@ where { async fn load_metrics( &self, - merchant_id: &common_utils::id_type::MerchantId, + auth: &AuthInfo, dimensions: &[AuthEventDimensions], filters: &AuthEventFilters, granularity: Option<Granularity>, @@ -65,10 +66,6 @@ where }) .switch()?; - query_builder - .add_filter_clause("merchant_id", merchant_id) - .switch()?; - query_builder .add_custom_filter_clause( AuthEventDimensions::TransactionStatus, @@ -81,6 +78,7 @@ where .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; + auth.set_filter_clause(&mut query_builder).switch()?; for dim in dimensions.iter() { query_builder diff --git a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs index 9788b6477c1..fbbcdb32086 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs @@ -13,6 +13,7 @@ use super::AuthEventMetricRow; use crate::{ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, + AuthInfo, }; #[derive(Default)] @@ -30,7 +31,7 @@ where { async fn load_metrics( &self, - merchant_id: &common_utils::id_type::MerchantId, + auth: &AuthInfo, dimensions: &[AuthEventDimensions], filters: &AuthEventFilters, granularity: Option<Granularity>, @@ -63,10 +64,6 @@ where }) .switch()?; - query_builder - .add_filter_clause("merchant_id", merchant_id) - .switch()?; - query_builder .add_filter_clause("authentication_status", AuthenticationStatus::Success) .switch()?; @@ -75,6 +72,7 @@ where .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; + auth.set_filter_clause(&mut query_builder).switch()?; for dim in dimensions.iter() { query_builder diff --git a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs index d3d7dcc7471..29d1bb2230b 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs @@ -13,6 +13,7 @@ use super::AuthEventMetricRow; use crate::{ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, + AuthInfo, }; #[derive(Default)] @@ -30,7 +31,7 @@ where { async fn load_metrics( &self, - merchant_id: &common_utils::id_type::MerchantId, + auth: &AuthInfo, dimensions: &[AuthEventDimensions], filters: &AuthEventFilters, granularity: Option<Granularity>, @@ -63,10 +64,6 @@ where }) .switch()?; - query_builder - .add_filter_clause("merchant_id", merchant_id) - .switch()?; - query_builder .add_filter_clause( "authentication_type", @@ -85,6 +82,7 @@ where .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; + auth.set_filter_clause(&mut query_builder).switch()?; for dim in dimensions.iter() { query_builder diff --git a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs index 5b951e1fa85..55a9041ac62 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs @@ -13,6 +13,7 @@ use super::AuthEventMetricRow; use crate::{ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, + AuthInfo, }; #[derive(Default)] @@ -30,7 +31,7 @@ where { async fn load_metrics( &self, - merchant_id: &common_utils::id_type::MerchantId, + auth: &AuthInfo, dimensions: &[AuthEventDimensions], filters: &AuthEventFilters, granularity: Option<Granularity>, @@ -63,10 +64,6 @@ where }) .switch()?; - query_builder - .add_filter_clause("merchant_id", merchant_id) - .switch()?; - query_builder .add_filter_clause( "authentication_type", @@ -78,6 +75,7 @@ where .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; + auth.set_filter_clause(&mut query_builder).switch()?; for dim in dimensions.iter() { query_builder diff --git a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs index 2bbd4d81982..307b9ada16c 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs @@ -13,6 +13,7 @@ use super::AuthEventMetricRow; use crate::{ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, + AuthInfo, }; #[derive(Default)] @@ -30,7 +31,7 @@ where { async fn load_metrics( &self, - merchant_id: &common_utils::id_type::MerchantId, + auth: &AuthInfo, dimensions: &[AuthEventDimensions], filters: &AuthEventFilters, granularity: Option<Granularity>, @@ -63,10 +64,6 @@ where }) .switch()?; - query_builder - .add_filter_clause("merchant_id", merchant_id) - .switch()?; - query_builder .add_filter_clause("authentication_status", AuthenticationStatus::Success) .switch()?; @@ -82,6 +79,7 @@ where .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; + auth.set_filter_clause(&mut query_builder).switch()?; for dim in dimensions.iter() { query_builder diff --git a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs index da8a119d226..fb9ecfa8ef0 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs @@ -13,6 +13,7 @@ use super::AuthEventMetricRow; use crate::{ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, + AuthInfo, }; #[derive(Default)] @@ -30,7 +31,7 @@ where { async fn load_metrics( &self, - merchant_id: &common_utils::id_type::MerchantId, + auth: &AuthInfo, dimensions: &[AuthEventDimensions], filters: &AuthEventFilters, granularity: Option<Granularity>, @@ -63,10 +64,6 @@ where }) .switch()?; - query_builder - .add_filter_clause("merchant_id", merchant_id) - .switch()?; - query_builder .add_filter_clause( "authentication_type", @@ -78,6 +75,7 @@ where .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; + auth.set_filter_clause(&mut query_builder).switch()?; for dim in dimensions.iter() { query_builder diff --git a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs index b4fb18e48f6..a134b9b0e36 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs @@ -13,6 +13,7 @@ use super::AuthEventMetricRow; use crate::{ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, + AuthInfo, }; #[derive(Default)] @@ -30,7 +31,7 @@ where { async fn load_metrics( &self, - merchant_id: &common_utils::id_type::MerchantId, + auth: &AuthInfo, dimensions: &[AuthEventDimensions], filters: &AuthEventFilters, granularity: Option<Granularity>, @@ -63,10 +64,6 @@ where }) .switch()?; - query_builder - .add_filter_clause("merchant_id", merchant_id) - .switch()?; - query_builder .add_filter_clause( "authentication_type", @@ -82,6 +79,7 @@ where .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; + auth.set_filter_clause(&mut query_builder).switch()?; for dim in dimensions.iter() { query_builder diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index 1718c5044ae..e8a01c27caf 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -912,7 +912,7 @@ impl AnalyticsProvider { &self, metric: &AuthEventMetrics, dimensions: &[AuthEventDimensions], - merchant_id: &common_utils::id_type::MerchantId, + auth: &AuthInfo, filters: &AuthEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, @@ -921,20 +921,13 @@ impl AnalyticsProvider { Self::Sqlx(_pool) => Err(report!(MetricsError::NotImplemented)), Self::Clickhouse(pool) => { metric - .load_metrics( - merchant_id, - dimensions, - filters, - granularity, - time_range, - pool, - ) + .load_metrics(auth, dimensions, filters, granularity, time_range, pool) .await } Self::CombinedCkh(_sqlx_pool, ckh_pool) | Self::CombinedSqlx(_sqlx_pool, ckh_pool) => { metric .load_metrics( - merchant_id, + auth, dimensions, filters, granularity, diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index e40bce12339..e41b7e59531 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -116,11 +116,7 @@ pub mod routes { ) .service( web::resource("metrics/auth_events") - .route(web::post().to(get_auth_event_metrics)), - ) - .service( - web::resource("metrics/auth_events/sankey") - .route(web::post().to(get_auth_event_sankey)), + .route(web::post().to(get_merchant_auth_event_metrics)), ) .service( web::resource("filters/auth_events") @@ -177,6 +173,10 @@ pub mod routes { web::resource("metrics/sankey") .route(web::post().to(get_merchant_sankey)), ) + .service( + web::resource("metrics/auth_events/sankey") + .route(web::post().to(get_merchant_auth_event_sankey)), + ) .service( web::scope("/merchant") .service( @@ -191,6 +191,10 @@ pub mod routes { web::resource("metrics/refunds") .route(web::post().to(get_merchant_refund_metrics)), ) + .service( + web::resource("metrics/auth_events") + .route(web::post().to(get_merchant_auth_event_metrics)), + ) .service( web::resource("filters/payments") .route(web::post().to(get_merchant_payment_filters)), @@ -203,6 +207,10 @@ pub mod routes { web::resource("filters/refunds") .route(web::post().to(get_merchant_refund_filters)), ) + .service( + web::resource("filters/auth_events") + .route(web::post().to(get_merchant_auth_events_filters)), + ) .service( web::resource("{domain}/info").route(web::get().to(get_info)), ) @@ -242,6 +250,10 @@ pub mod routes { .service( web::resource("metrics/sankey") .route(web::post().to(get_merchant_sankey)), + ) + .service( + web::resource("metrics/auth_events/sankey") + .route(web::post().to(get_merchant_auth_event_sankey)), ), ) .service( @@ -277,10 +289,18 @@ pub mod routes { web::resource("metrics/disputes") .route(web::post().to(get_org_dispute_metrics)), ) + .service( + web::resource("metrics/auth_events") + .route(web::post().to(get_org_auth_event_metrics)), + ) .service( web::resource("filters/disputes") .route(web::post().to(get_org_dispute_filters)), ) + .service( + web::resource("filters/auth_events") + .route(web::post().to(get_org_auth_events_filters)), + ) .service( web::resource("report/dispute") .route(web::post().to(generate_org_dispute_report)), @@ -300,6 +320,10 @@ pub mod routes { .service( web::resource("metrics/sankey") .route(web::post().to(get_org_sankey)), + ) + .service( + web::resource("metrics/auth_events/sankey") + .route(web::post().to(get_org_auth_event_sankey)), ), ) .service( @@ -335,10 +359,18 @@ pub mod routes { web::resource("metrics/disputes") .route(web::post().to(get_profile_dispute_metrics)), ) + .service( + web::resource("metrics/auth_events") + .route(web::post().to(get_profile_auth_event_metrics)), + ) .service( web::resource("filters/disputes") .route(web::post().to(get_profile_dispute_filters)), ) + .service( + web::resource("filters/auth_events") + .route(web::post().to(get_profile_auth_events_filters)), + ) .service( web::resource("connector_event_logs") .route(web::get().to(get_profile_connector_events)), @@ -379,6 +411,10 @@ pub mod routes { .service( web::resource("metrics/sankey") .route(web::post().to(get_profile_sankey)), + ) + .service( + web::resource("metrics/auth_events/sankey") + .route(web::post().to(get_profile_auth_event_sankey)), ), ), ) @@ -1043,7 +1079,7 @@ pub mod routes { /// # Panics /// /// Panics if `json_payload` array does not contain one `GetAuthEventMetricRequest` element. - pub async fn get_auth_event_metrics( + pub async fn get_merchant_auth_event_metrics( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<[GetAuthEventMetricRequest; 1]>, @@ -1062,13 +1098,16 @@ pub mod routes { &req, payload, |state, auth: AuthenticationData, req, _| async move { - analytics::auth_events::get_metrics( - &state.pool, - auth.merchant_account.get_id(), - req, - ) - .await - .map(ApplicationResponse::Json) + let org_id = auth.merchant_account.get_org_id(); + let merchant_id = auth.merchant_account.get_id(); + let auth: AuthInfo = AuthInfo::MerchantLevel { + org_id: org_id.clone(), + merchant_ids: vec![merchant_id.clone()], + }; + + analytics::auth_events::get_metrics(&state.pool, &auth, req) + .await + .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::MerchantAnalyticsRead, @@ -1078,6 +1117,98 @@ pub mod routes { .await } + #[cfg(feature = "v1")] + /// # Panics + /// + /// Panics if `json_payload` array does not contain one `GetAuthEventMetricRequest` element. + pub async fn get_profile_auth_event_metrics( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<[GetAuthEventMetricRequest; 1]>, + ) -> impl Responder { + // safety: This shouldn't panic owing to the data type + #[allow(clippy::expect_used)] + let payload = json_payload + .into_inner() + .to_vec() + .pop() + .expect("Couldn't get GetAuthEventMetricRequest"); + let flow = AnalyticsFlow::GetAuthMetrics; + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, auth: AuthenticationData, req, _| async move { + let org_id = auth.merchant_account.get_org_id(); + let merchant_id = auth.merchant_account.get_id(); + let profile_id = auth + .profile_id + .ok_or(report!(UserErrors::JwtProfileIdMissing)) + .change_context(AnalyticsError::AccessForbiddenError)?; + let auth: AuthInfo = AuthInfo::ProfileLevel { + org_id: org_id.clone(), + merchant_id: merchant_id.clone(), + profile_ids: vec![profile_id.clone()], + }; + analytics::auth_events::get_metrics(&state.pool, &auth, req) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth { + permission: Permission::ProfileAnalyticsRead, + }, + api_locking::LockAction::NotApplicable, + )) + .await + } + + #[cfg(feature = "v1")] + /// # Panics + /// + /// Panics if `json_payload` array does not contain one `GetAuthEventMetricRequest` element. + pub async fn get_org_auth_event_metrics( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<[GetAuthEventMetricRequest; 1]>, + ) -> impl Responder { + // safety: This shouldn't panic owing to the data type + #[allow(clippy::expect_used)] + let payload = json_payload + .into_inner() + .to_vec() + .pop() + .expect("Couldn't get GetAuthEventMetricRequest"); + let flow = AnalyticsFlow::GetAuthMetrics; + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, auth: AuthenticationData, req, _| async move { + let org_id = auth.merchant_account.get_org_id(); + let auth: AuthInfo = AuthInfo::OrgLevel { + org_id: org_id.clone(), + }; + analytics::auth_events::get_metrics(&state.pool, &auth, req) + .await + .map(ApplicationResponse::Json) + }, + auth::auth_type( + &auth::PlatformOrgAdminAuth { + is_admin_auth_allowed: false, + organization_id: None, + }, + &auth::JWTAuth { + permission: Permission::OrganizationAnalyticsRead, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await + } + pub async fn get_merchant_payment_filters( state: web::Data<AppState>, req: actix_web::HttpRequest, @@ -1120,13 +1251,16 @@ pub mod routes { &req, json_payload.into_inner(), |state, auth: AuthenticationData, req, _| async move { - analytics::auth_events::get_filters( - &state.pool, - req, - auth.merchant_account.get_id(), - ) - .await - .map(ApplicationResponse::Json) + let org_id = auth.merchant_account.get_org_id(); + let merchant_id = auth.merchant_account.get_id(); + + let auth: AuthInfo = AuthInfo::MerchantLevel { + org_id: org_id.clone(), + merchant_ids: vec![merchant_id.clone()], + }; + analytics::auth_events::get_filters(&state.pool, req, &auth) + .await + .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::MerchantAnalyticsRead, @@ -1136,6 +1270,80 @@ pub mod routes { .await } + #[cfg(feature = "v1")] + pub async fn get_org_auth_events_filters( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<GetAuthEventFilterRequest>, + ) -> impl Responder { + let flow = AnalyticsFlow::GetAuthEventFilters; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, auth: AuthenticationData, req, _| async move { + let org_id = auth.merchant_account.get_org_id(); + let auth: AuthInfo = AuthInfo::OrgLevel { + org_id: org_id.clone(), + }; + + analytics::auth_events::get_filters(&state.pool, req, &auth) + .await + .map(ApplicationResponse::Json) + }, + auth::auth_type( + &auth::PlatformOrgAdminAuth { + is_admin_auth_allowed: false, + organization_id: None, + }, + &auth::JWTAuth { + permission: Permission::OrganizationAnalyticsRead, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await + } + + #[cfg(feature = "v1")] + pub async fn get_profile_auth_events_filters( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<GetAuthEventFilterRequest>, + ) -> impl Responder { + let flow = AnalyticsFlow::GetAuthEventFilters; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, auth: AuthenticationData, req, _| async move { + let org_id = auth.merchant_account.get_org_id(); + let merchant_id = auth.merchant_account.get_id(); + let profile_id = auth + .profile_id + .ok_or(report!(UserErrors::JwtProfileIdMissing)) + .change_context(AnalyticsError::AccessForbiddenError)?; + + let auth: AuthInfo = AuthInfo::ProfileLevel { + org_id: org_id.clone(), + merchant_id: merchant_id.clone(), + profile_ids: vec![profile_id.clone()], + }; + analytics::auth_events::get_filters(&state.pool, req, &auth) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth { + permission: Permission::ProfileAnalyticsRead, + }, + api_locking::LockAction::NotApplicable, + )) + .await + } + #[cfg(feature = "v1")] pub async fn get_org_payment_filters( state: web::Data<AppState>, @@ -2809,7 +3017,7 @@ pub mod routes { .await } - pub async fn get_auth_event_sankey( + pub async fn get_merchant_auth_event_sankey( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<TimeRange>, @@ -2840,6 +3048,80 @@ pub mod routes { .await } + #[cfg(feature = "v1")] + pub async fn get_org_auth_event_sankey( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<TimeRange>, + ) -> impl Responder { + let flow = AnalyticsFlow::GetSankey; + let payload = json_payload.into_inner(); + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, auth: AuthenticationData, req, _| async move { + let org_id = auth.merchant_account.get_org_id(); + let auth: AuthInfo = AuthInfo::OrgLevel { + org_id: org_id.clone(), + }; + analytics::auth_events::get_sankey(&state.pool, &auth, req) + .await + .map(ApplicationResponse::Json) + }, + auth::auth_type( + &auth::PlatformOrgAdminAuth { + is_admin_auth_allowed: false, + organization_id: None, + }, + &auth::JWTAuth { + permission: Permission::OrganizationAnalyticsRead, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await + } + + #[cfg(feature = "v1")] + pub async fn get_profile_auth_event_sankey( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<TimeRange>, + ) -> impl Responder { + let flow = AnalyticsFlow::GetSankey; + let payload = json_payload.into_inner(); + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, auth: AuthenticationData, req, _| async move { + let org_id = auth.merchant_account.get_org_id(); + let merchant_id = auth.merchant_account.get_id(); + let profile_id = auth + .profile_id + .ok_or(report!(UserErrors::JwtProfileIdMissing)) + .change_context(AnalyticsError::AccessForbiddenError)?; + let auth: AuthInfo = AuthInfo::ProfileLevel { + org_id: org_id.clone(), + merchant_id: merchant_id.clone(), + profile_ids: vec![profile_id.clone()], + }; + analytics::auth_events::get_sankey(&state.pool, &auth, req) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth { + permission: Permission::ProfileAnalyticsRead, + }, + api_locking::LockAction::NotApplicable, + )) + .await + } + #[cfg(feature = "v1")] pub async fn get_org_sankey( state: web::Data<AppState>,
2025-06-12T13:12:53Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Exposed endpoints for auth analytics under profile, merchant and org access levels. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables Here are the cURLs for the endpoint modified ``` curl 'http://localhost:8080/analytics/v1/merchant/metrics/auth_events' \ -H 'Accept: */*' \ -H 'Accept-Language: en-US,en;q=0.5' \ -H 'Cache-Control: no-cache' \ -H 'Connection: keep-alive' \ -H 'Content-Type: application/json' \ -b 'login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiY2IzYjdjNGQtYjQ0Mi00ZDk0LWJkMjQtNjk5NjI4ZjQ1MzBkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ4Mjg1ODc1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc1MDQxODczNiwib3JnX2lkIjoib3JnX1VBQnlpWmZ4TW44dFpuSnZUemlvIiwicHJvZmlsZV9pZCI6InByb19Pcjh5cmlGYzBPY1pJZHFBOVFVVyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.ihLlIahjaxw1Tq8OYv0601E93UpT8TKgYoskRK6Os0M' \ -H 'Origin: http://localhost:9000' \ -H 'Pragma: no-cache' \ -H 'Referer: http://localhost:9000/dashboard/analytics-authentication' \ -H 'Sec-Fetch-Dest: empty' \ -H 'Sec-Fetch-Mode: cors' \ -H 'Sec-Fetch-Site: same-origin' \ -H 'Sec-GPC: 1' \ -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36' \ -H 'X-Merchant-Id: merchant_1748285875' \ -H 'X-Profile-Id: pro_Or8yriFc0OcZIdqA9QUW' \ -H 'api-key: hyperswitch' \ -H 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiY2IzYjdjNGQtYjQ0Mi00ZDk0LWJkMjQtNjk5NjI4ZjQ1MzBkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ4Mjg1ODc1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc1MDQxODczNiwib3JnX2lkIjoib3JnX1VBQnlpWmZ4TW44dFpuSnZUemlvIiwicHJvZmlsZV9pZCI6InByb19Pcjh5cmlGYzBPY1pJZHFBOVFVVyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.ihLlIahjaxw1Tq8OYv0601E93UpT8TKgYoskRK6Os0M' \ -H 'sec-ch-ua: "Brave";v="137", "Chromium";v="137", "Not/A)Brand";v="24"' \ -H 'sec-ch-ua-mobile: ?0' \ -H 'sec-ch-ua-platform: "macOS"' \ --data-raw '[{"timeRange":{"startTime":"2025-01-10T18:30:00Z","endTime":"2025-06-18T11:25:39Z"},"mode":"ORDER","source":"BATCH","metrics":["authentication_count","authentication_attempt_count","authentication_success_count","challenge_flow_count","frictionless_flow_count","frictionless_success_count","challenge_attempt_count","challenge_success_count"],"delta":true}]' ``` ``` curl 'http://localhost:8080/analytics/v1/org/metrics/auth_events' \ -H 'Accept: */*' \ -H 'Accept-Language: en-US,en;q=0.5' \ -H 'Cache-Control: no-cache' \ -H 'Connection: keep-alive' \ -H 'Content-Type: application/json' \ -b 'login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiY2IzYjdjNGQtYjQ0Mi00ZDk0LWJkMjQtNjk5NjI4ZjQ1MzBkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ4Mjg1ODc1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc1MDQxODczNiwib3JnX2lkIjoib3JnX1VBQnlpWmZ4TW44dFpuSnZUemlvIiwicHJvZmlsZV9pZCI6InByb19Pcjh5cmlGYzBPY1pJZHFBOVFVVyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.ihLlIahjaxw1Tq8OYv0601E93UpT8TKgYoskRK6Os0M' \ -H 'Origin: http://localhost:9000' \ -H 'Pragma: no-cache' \ -H 'Referer: http://localhost:9000/dashboard/analytics-authentication' \ -H 'Sec-Fetch-Dest: empty' \ -H 'Sec-Fetch-Mode: cors' \ -H 'Sec-Fetch-Site: same-origin' \ -H 'Sec-GPC: 1' \ -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36' \ -H 'X-Merchant-Id: merchant_1748285875' \ -H 'X-Profile-Id: pro_Or8yriFc0OcZIdqA9QUW' \ -H 'api-key: hyperswitch' \ -H 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiY2IzYjdjNGQtYjQ0Mi00ZDk0LWJkMjQtNjk5NjI4ZjQ1MzBkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ4Mjg1ODc1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc1MDQxODczNiwib3JnX2lkIjoib3JnX1VBQnlpWmZ4TW44dFpuSnZUemlvIiwicHJvZmlsZV9pZCI6InByb19Pcjh5cmlGYzBPY1pJZHFBOVFVVyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.ihLlIahjaxw1Tq8OYv0601E93UpT8TKgYoskRK6Os0M' \ -H 'sec-ch-ua: "Brave";v="137", "Chromium";v="137", "Not/A)Brand";v="24"' \ -H 'sec-ch-ua-mobile: ?0' \ -H 'sec-ch-ua-platform: "macOS"' \ --data-raw '[{"timeRange":{"startTime":"2025-01-10T18:30:00Z","endTime":"2025-06-18T11:25:39Z"},"mode":"ORDER","source":"BATCH","metrics":["authentication_count","authentication_attempt_count","authentication_success_count","challenge_flow_count","frictionless_flow_count","frictionless_success_count","challenge_attempt_count","challenge_success_count"],"delta":true}]' ``` ``` curl 'http://localhost:8080/analytics/v1/profile/metrics/auth_events' \ -H 'Accept: */*' \ -H 'Accept-Language: en-US,en;q=0.5' \ -H 'Cache-Control: no-cache' \ -H 'Connection: keep-alive' \ -H 'Content-Type: application/json' \ -b 'login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiY2IzYjdjNGQtYjQ0Mi00ZDk0LWJkMjQtNjk5NjI4ZjQ1MzBkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ4Mjg1ODc1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc1MDQxODczNiwib3JnX2lkIjoib3JnX1VBQnlpWmZ4TW44dFpuSnZUemlvIiwicHJvZmlsZV9pZCI6InByb19Pcjh5cmlGYzBPY1pJZHFBOVFVVyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.ihLlIahjaxw1Tq8OYv0601E93UpT8TKgYoskRK6Os0M' \ -H 'Origin: http://localhost:9000' \ -H 'Pragma: no-cache' \ -H 'Referer: http://localhost:9000/dashboard/analytics-authentication' \ -H 'Sec-Fetch-Dest: empty' \ -H 'Sec-Fetch-Mode: cors' \ -H 'Sec-Fetch-Site: same-origin' \ -H 'Sec-GPC: 1' \ -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36' \ -H 'X-Merchant-Id: merchant_1748285875' \ -H 'X-Profile-Id: pro_Or8yriFc0OcZIdqA9QUW' \ -H 'api-key: hyperswitch' \ -H 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiY2IzYjdjNGQtYjQ0Mi00ZDk0LWJkMjQtNjk5NjI4ZjQ1MzBkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ4Mjg1ODc1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc1MDQxODczNiwib3JnX2lkIjoib3JnX1VBQnlpWmZ4TW44dFpuSnZUemlvIiwicHJvZmlsZV9pZCI6InByb19Pcjh5cmlGYzBPY1pJZHFBOVFVVyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.ihLlIahjaxw1Tq8OYv0601E93UpT8TKgYoskRK6Os0M' \ -H 'sec-ch-ua: "Brave";v="137", "Chromium";v="137", "Not/A)Brand";v="24"' \ -H 'sec-ch-ua-mobile: ?0' \ -H 'sec-ch-ua-platform: "macOS"' \ --data-raw '[{"timeRange":{"startTime":"2025-01-10T18:30:00Z","endTime":"2025-06-18T11:25:39Z"},"mode":"ORDER","source":"BATCH","metrics":["authentication_count","authentication_attempt_count","authentication_success_count","challenge_flow_count","frictionless_flow_count","frictionless_success_count","challenge_attempt_count","challenge_success_count"],"delta":true}]' ``` ``` curl 'http://localhost:8080/analytics/v1/org/metrics/auth_events/sankey' \ -H 'Accept: */*' \ -H 'Accept-Language: en-US,en;q=0.6' \ -H 'Cache-Control: no-cache' \ -H 'Connection: keep-alive' \ -H 'Content-Type: application/json' \ -b 'login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiY2IzYjdjNGQtYjQ0Mi00ZDk0LWJkMjQtNjk5NjI4ZjQ1MzBkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ4Mjg1ODc1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0OTg5OTA3MCwib3JnX2lkIjoib3JnX1VBQnlpWmZ4TW44dFpuSnZUemlvIiwicHJvZmlsZV9pZCI6InByb19Pcjh5cmlGYzBPY1pJZHFBOVFVVyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.mSG74WirYlo_Bogh2P8mN-EujL3nw9xlRGlOZ5t7Aiw' \ -H 'Origin: http://localhost:9000' \ -H 'Pragma: no-cache' \ -H 'Referer: http://localhost:9000/dashboard/analytics-authentication' \ -H 'Sec-Fetch-Dest: empty' \ -H 'Sec-Fetch-Mode: cors' \ -H 'Sec-Fetch-Site: same-origin' \ -H 'Sec-GPC: 1' \ -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36' \ -H 'X-Merchant-Id: merchant_1748285875' \ -H 'X-Profile-Id: pro_Or8yriFc0OcZIdqA9QUW' \ -H 'api-key: hyperswitch' \ -H 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiY2IzYjdjNGQtYjQ0Mi00ZDk0LWJkMjQtNjk5NjI4ZjQ1MzBkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ4Mjg1ODc1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0OTg5OTA3MCwib3JnX2lkIjoib3JnX1VBQnlpWmZ4TW44dFpuSnZUemlvIiwicHJvZmlsZV9pZCI6InByb19Pcjh5cmlGYzBPY1pJZHFBOVFVVyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.mSG74WirYlo_Bogh2P8mN-EujL3nw9xlRGlOZ5t7Aiw' \ -H 'sec-ch-ua: "Brave";v="137", "Chromium";v="137", "Not/A)Brand";v="24"' \ -H 'sec-ch-ua-mobile: ?0' \ -H 'sec-ch-ua-platform: "macOS"' \ --data-raw '{"startTime": "2025-01-22T18:30:00Z","endTime": "2025-05-29T12:59:33Z"}' ``` ``` curl 'http://localhost:8080/analytics/v1/merchant/metrics/auth_events/sankey' \ -H 'Accept: */*' \ -H 'Accept-Language: en-US,en;q=0.6' \ -H 'Cache-Control: no-cache' \ -H 'Connection: keep-alive' \ -H 'Content-Type: application/json' \ -b 'login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiY2IzYjdjNGQtYjQ0Mi00ZDk0LWJkMjQtNjk5NjI4ZjQ1MzBkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ4Mjg1ODc1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0OTg5OTA3MCwib3JnX2lkIjoib3JnX1VBQnlpWmZ4TW44dFpuSnZUemlvIiwicHJvZmlsZV9pZCI6InByb19Pcjh5cmlGYzBPY1pJZHFBOVFVVyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.mSG74WirYlo_Bogh2P8mN-EujL3nw9xlRGlOZ5t7Aiw' \ -H 'Origin: http://localhost:9000' \ -H 'Pragma: no-cache' \ -H 'Referer: http://localhost:9000/dashboard/analytics-authentication' \ -H 'Sec-Fetch-Dest: empty' \ -H 'Sec-Fetch-Mode: cors' \ -H 'Sec-Fetch-Site: same-origin' \ -H 'Sec-GPC: 1' \ -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36' \ -H 'X-Merchant-Id: merchant_1748285875' \ -H 'X-Profile-Id: pro_Or8yriFc0OcZIdqA9QUW' \ -H 'api-key: hyperswitch' \ -H 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiY2IzYjdjNGQtYjQ0Mi00ZDk0LWJkMjQtNjk5NjI4ZjQ1MzBkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ4Mjg1ODc1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0OTg5OTA3MCwib3JnX2lkIjoib3JnX1VBQnlpWmZ4TW44dFpuSnZUemlvIiwicHJvZmlsZV9pZCI6InByb19Pcjh5cmlGYzBPY1pJZHFBOVFVVyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.mSG74WirYlo_Bogh2P8mN-EujL3nw9xlRGlOZ5t7Aiw' \ -H 'sec-ch-ua: "Brave";v="137", "Chromium";v="137", "Not/A)Brand";v="24"' \ -H 'sec-ch-ua-mobile: ?0' \ -H 'sec-ch-ua-platform: "macOS"' \ --data-raw '{"startTime": "2025-01-22T18:30:00Z","endTime": "2025-05-29T12:59:33Z"}' ``` ``` curl 'http://localhost:8080/analytics/v1/profile/metrics/auth_events/sankey' \ -H 'Accept: */*' \ -H 'Accept-Language: en-US,en;q=0.6' \ -H 'Cache-Control: no-cache' \ -H 'Connection: keep-alive' \ -H 'Content-Type: application/json' \ -b 'login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiY2IzYjdjNGQtYjQ0Mi00ZDk0LWJkMjQtNjk5NjI4ZjQ1MzBkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ4Mjg1ODc1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0OTg5OTA3MCwib3JnX2lkIjoib3JnX1VBQnlpWmZ4TW44dFpuSnZUemlvIiwicHJvZmlsZV9pZCI6InByb19Pcjh5cmlGYzBPY1pJZHFBOVFVVyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.mSG74WirYlo_Bogh2P8mN-EujL3nw9xlRGlOZ5t7Aiw' \ -H 'Origin: http://localhost:9000' \ -H 'Pragma: no-cache' \ -H 'Referer: http://localhost:9000/dashboard/analytics-authentication' \ -H 'Sec-Fetch-Dest: empty' \ -H 'Sec-Fetch-Mode: cors' \ -H 'Sec-Fetch-Site: same-origin' \ -H 'Sec-GPC: 1' \ -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36' \ -H 'X-Merchant-Id: merchant_1748285875' \ -H 'X-Profile-Id: pro_Or8yriFc0OcZIdqA9QUW' \ -H 'api-key: hyperswitch' \ -H 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiY2IzYjdjNGQtYjQ0Mi00ZDk0LWJkMjQtNjk5NjI4ZjQ1MzBkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ4Mjg1ODc1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0OTg5OTA3MCwib3JnX2lkIjoib3JnX1VBQnlpWmZ4TW44dFpuSnZUemlvIiwicHJvZmlsZV9pZCI6InByb19Pcjh5cmlGYzBPY1pJZHFBOVFVVyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.mSG74WirYlo_Bogh2P8mN-EujL3nw9xlRGlOZ5t7Aiw' \ -H 'sec-ch-ua: "Brave";v="137", "Chromium";v="137", "Not/A)Brand";v="24"' \ -H 'sec-ch-ua-mobile: ?0' \ -H 'sec-ch-ua-platform: "macOS"' \ --data-raw '{"startTime": "2025-01-22T18:30:00Z","endTime": "2025-05-29T12:59:33Z"}' ``` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
d305fad2e6c403fde11b9eea785fddefbf3477df
d305fad2e6c403fde11b9eea785fddefbf3477df
juspay/hyperswitch
juspay__hyperswitch-8348
Bug: [FEAT] implement capture and webhooks flow in ACI implement capture and webhooks flow in ACI
diff --git a/config/deployments/production.toml b/config/deployments/production.toml index f9b884489ba..e044183a416 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -23,7 +23,7 @@ payout_connector_list = "nomupay,stripe,wise" # base urls based on your need. # Note: These are not optional attributes. hyperswitch request can fail due to invalid/empty values. [connectors] -aci.base_url = "https://eu-test.oppwa.com/" +aci.base_url = "https://eu-prod.oppwa.com/" adyen.base_url = "https://{{merchant_endpoint_prefix}}-checkout-live.adyenpayments.com/checkout/" adyen.payout_base_url = "https://{{merchant_endpoint_prefix}}-pal-live.adyenpayments.com/" adyen.dispute_base_url = "https://{{merchant_endpoint_prefix}}-ca-live.adyen.com/" diff --git a/config/development.toml b/config/development.toml index c5e56a1b3a3..0f7ea051adf 100644 --- a/config/development.toml +++ b/config/development.toml @@ -685,8 +685,8 @@ red_pagos = { country = "UY", currency = "UYU" } local_bank_transfer = { country = "CN", currency = "CNY" } [pm_filters.aci] -credit = { not_available_flows = { capture_method = "manual" }, country = "AD,AE,AT,BE,BG,CH,CN,CO,CR,CY,CZ,DE,DK,DO,EE,EG,ES,ET,FI,FR,GB,GH,GI,GR,GT,HN,HK,HR,HU,ID,IE,IS,IT,JP,KH,LA,LI,LT,LU,LY,MK,MM,MX,MY,MZ,NG,NZ,OM,PA,PE,PK,PL,PT,QA,RO,SA,SN,SE,SI,SK,SV,TH,UA,US,UY,VN,ZM", currency = "AED,ALL,ARS,BGN,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,EGP,EUR,GBP,GHS,HKD,HNL,HRK,HUF,IDR,ILS,ISK,JPY,KHR,KPW,LAK,LKR,MAD,MKD,MMK,MXN,MYR,MZN,NGN,NOK,NZD,OMR,PAB,PEN,PHP,PKR,PLN,QAR,RON,RSD,SAR,SEK,SGD,THB,TRY,TWD,UAH,USD,UYU,VND,ZAR,ZMW" } -debit = { not_available_flows = { capture_method = "manual" }, country = "AD,AE,AT,BE,BG,CH,CN,CO,CR,CY,CZ,DE,DK,DO,EE,EG,ES,ET,FI,FR,GB,GH,GI,GR,GT,HN,HK,HR,HU,ID,IE,IS,IT,JP,KH,LA,LI,LT,LU,LY,MK,MM,MX,MY,MZ,NG,NZ,OM,PA,PE,PK,PL,PT,QA,RO,SA,SN,SE,SI,SK,SV,TH,UA,US,UY,VN,ZM", currency = "AED,ALL,ARS,BGN,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,EGP,EUR,GBP,GHS,HKD,HNL,HRK,HUF,IDR,ILS,ISK,JPY,KHR,KPW,LAK,LKR,MAD,MKD,MMK,MXN,MYR,MZN,NGN,NOK,NZD,OMR,PAB,PEN,PHP,PKR,PLN,QAR,RON,RSD,SAR,SEK,SGD,THB,TRY,TWD,UAH,USD,UYU,VND,ZAR,ZMW" } +credit = { country = "AD,AE,AT,BE,BG,CH,CN,CO,CR,CY,CZ,DE,DK,DO,EE,EG,ES,ET,FI,FR,GB,GH,GI,GR,GT,HN,HK,HR,HU,ID,IE,IS,IT,JP,KH,LA,LI,LT,LU,LY,MK,MM,MX,MY,MZ,NG,NZ,OM,PA,PE,PK,PL,PT,QA,RO,SA,SN,SE,SI,SK,SV,TH,UA,US,UY,VN,ZM", currency = "AED,ALL,ARS,BGN,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,EGP,EUR,GBP,GHS,HKD,HNL,HRK,HUF,IDR,ILS,ISK,JPY,KHR,KPW,LAK,LKR,MAD,MKD,MMK,MXN,MYR,MZN,NGN,NOK,NZD,OMR,PAB,PEN,PHP,PKR,PLN,QAR,RON,RSD,SAR,SEK,SGD,THB,TRY,TWD,UAH,USD,UYU,VND,ZAR,ZMW" } +debit = { country = "AD,AE,AT,BE,BG,CH,CN,CO,CR,CY,CZ,DE,DK,DO,EE,EG,ES,ET,FI,FR,GB,GH,GI,GR,GT,HN,HK,HR,HU,ID,IE,IS,IT,JP,KH,LA,LI,LT,LU,LY,MK,MM,MX,MY,MZ,NG,NZ,OM,PA,PE,PK,PL,PT,QA,RO,SA,SN,SE,SI,SK,SV,TH,UA,US,UY,VN,ZM", currency = "AED,ALL,ARS,BGN,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,EGP,EUR,GBP,GHS,HKD,HNL,HRK,HUF,IDR,ILS,ISK,JPY,KHR,KPW,LAK,LKR,MAD,MKD,MMK,MXN,MYR,MZN,NGN,NOK,NZD,OMR,PAB,PEN,PHP,PKR,PLN,QAR,RON,RSD,SAR,SEK,SGD,THB,TRY,TWD,UAH,USD,UYU,VND,ZAR,ZMW" } mb_way = { country = "EE,ES,PT", currency = "EUR" } ali_pay = { country = "CN", currency = "CNY" } eps = { country = "AT", currency = "EUR" } diff --git a/crates/common_utils/src/errors.rs b/crates/common_utils/src/errors.rs index a731a5f4630..c2cddf41bce 100644 --- a/crates/common_utils/src/errors.rs +++ b/crates/common_utils/src/errors.rs @@ -101,6 +101,9 @@ pub enum CryptoError { /// The provided IV length is invalid for the cryptographic algorithm #[error("Invalid IV length")] InvalidIvLength, + /// The provided authentication tag length is invalid for the cryptographic algorithm + #[error("Invalid authentication tag length")] + InvalidTagLength, } /// Errors for Qr code handling diff --git a/crates/hyperswitch_connectors/src/connectors/aci.rs b/crates/hyperswitch_connectors/src/connectors/aci.rs index 9218ef3e9fb..16a85965e79 100644 --- a/crates/hyperswitch_connectors/src/connectors/aci.rs +++ b/crates/hyperswitch_connectors/src/connectors/aci.rs @@ -6,7 +6,8 @@ use std::sync::LazyLock; use api_models::webhooks::IncomingWebhookEvent; use common_enums::enums; use common_utils::{ - errors::CustomResult, + crypto, + errors::{CryptoError, CustomResult}, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector}, @@ -30,8 +31,8 @@ use hyperswitch_domain_models::{ SupportedPaymentMethods, SupportedPaymentMethodsExt, }, types::{ - PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsSyncRouterData, - RefundsRouterData, + PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, + PaymentsSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ @@ -42,11 +43,13 @@ use hyperswitch_interfaces::{ errors, events::connector_api_logs::ConnectorEvent, types::{ - PaymentsAuthorizeType, PaymentsSyncType, PaymentsVoidType, RefundExecuteType, Response, + PaymentsAuthorizeType, PaymentsCaptureType, PaymentsSyncType, PaymentsVoidType, + RefundExecuteType, Response, }, webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, }; use masking::{Mask, PeekInterface}; +use ring::aead::{self, UnboundKey}; use transformers as aci; use crate::{ @@ -181,8 +184,101 @@ impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsRespons } } +// TODO: Investigate unexplained error in capture flow from connector. impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Aci { - // Not Implemented (R) + fn get_headers( + &self, + req: &PaymentsCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let mut header = vec![( + headers::CONTENT_TYPE.to_string(), + PaymentsCaptureType::get_content_type(self) + .to_string() + .into(), + )]; + let mut api_key = self.get_auth_header(&req.connector_auth_type)?; + header.append(&mut api_key); + Ok(header) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}{}{}", + self.base_url(connectors), + "v1/payments/", + req.request.connector_transaction_id, + )) + } + + fn get_request_body( + &self, + req: &PaymentsCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let amount = convert_amount( + self.amount_converter, + req.request.minor_amount_to_capture, + req.request.currency, + )?; + let connector_router_data = aci::AciRouterData::from((amount, req)); + let connector_req = aci::AciCaptureRequest::try_from(&connector_router_data)?; + Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsCaptureType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(PaymentsCaptureType::get_headers(self, req, connectors)?) + .set_body(PaymentsCaptureType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { + let response: aci::AciCaptureResponse = res + .response + .parse_struct("AciCaptureResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } } impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Aci { @@ -555,32 +651,252 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Aci { impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Aci {} +/// Decrypts an AES-256-GCM encrypted payload where the IV, auth tag, and ciphertext +/// are provided separately as hex strings. This is specifically tailored for ACI webhooks. +/// +/// # Arguments +/// * `hex_key`: The encryption key as a hex string (must decode to 32 bytes). +/// * `hex_iv`: The initialization vector (nonce) as a hex string (must decode to 12 bytes). +/// * `hex_auth_tag`: The authentication tag as a hex string (must decode to 16 bytes). +/// * `hex_encrypted_body`: The encrypted payload as a hex string. +fn decrypt_aci_webhook_payload( + hex_key: &str, + hex_iv: &str, + hex_auth_tag: &str, + hex_encrypted_body: &str, +) -> CustomResult<Vec<u8>, CryptoError> { + let key_bytes = hex::decode(hex_key) + .change_context(CryptoError::DecodingFailed) + .attach_printable("Failed to decode hex key")?; + let iv_bytes = hex::decode(hex_iv) + .change_context(CryptoError::DecodingFailed) + .attach_printable("Failed to decode hex IV")?; + let auth_tag_bytes = hex::decode(hex_auth_tag) + .change_context(CryptoError::DecodingFailed) + .attach_printable("Failed to decode hex auth tag")?; + let encrypted_body_bytes = hex::decode(hex_encrypted_body) + .change_context(CryptoError::DecodingFailed) + .attach_printable("Failed to decode hex encrypted body")?; + if key_bytes.len() != 32 { + return Err(CryptoError::InvalidKeyLength) + .attach_printable("Key must be 32 bytes for AES-256-GCM"); + } + if iv_bytes.len() != aead::NONCE_LEN { + return Err(CryptoError::InvalidIvLength) + .attach_printable(format!("IV must be {} bytes for AES-GCM", aead::NONCE_LEN)); + } + if auth_tag_bytes.len() != 16 { + return Err(CryptoError::InvalidTagLength) + .attach_printable("Auth tag must be 16 bytes for AES-256-GCM"); + } + + let unbound_key = UnboundKey::new(&aead::AES_256_GCM, &key_bytes) + .change_context(CryptoError::DecodingFailed) + .attach_printable("Failed to create unbound key")?; + + let less_safe_key = aead::LessSafeKey::new(unbound_key); + + let nonce_arr: [u8; aead::NONCE_LEN] = iv_bytes + .as_slice() + .try_into() + .map_err(|_| CryptoError::InvalidIvLength) + .attach_printable_lazy(|| { + format!( + "IV length is {} but expected {}", + iv_bytes.len(), + aead::NONCE_LEN + ) + })?; + let nonce = aead::Nonce::assume_unique_for_key(nonce_arr); + + let mut ciphertext_and_tag = encrypted_body_bytes; + ciphertext_and_tag.extend_from_slice(&auth_tag_bytes); + + less_safe_key + .open_in_place(nonce, aead::Aad::empty(), &mut ciphertext_and_tag) + .change_context(CryptoError::DecodingFailed) + .attach_printable("Failed to decrypt payload using LessSafeKey")?; + + let original_ciphertext_len = ciphertext_and_tag.len() - auth_tag_bytes.len(); + ciphertext_and_tag.truncate(original_ciphertext_len); + + Ok(ciphertext_and_tag) +} + +// TODO: Test this webhook flow once dashboard access is available. #[async_trait::async_trait] impl IncomingWebhook for Aci { - fn get_webhook_object_reference_id( + fn get_webhook_source_verification_algorithm( &self, _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { + Ok(Box::new(crypto::NoAlgorithm)) + } + + fn get_webhook_source_verification_signature( + &self, + request: &IncomingWebhookRequestDetails<'_>, + _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, + ) -> CustomResult<Vec<u8>, errors::ConnectorError> { + let header_value_str = request + .headers + .get("X-Authentication-Tag") + .ok_or(errors::ConnectorError::WebhookSignatureNotFound) + .attach_printable("Missing X-Authentication-Tag header")? + .to_str() + .map_err(|_| errors::ConnectorError::WebhookSignatureNotFound) + .attach_printable("Invalid X-Authentication-Tag header value (not UTF-8)")?; + Ok(header_value_str.as_bytes().to_vec()) + } + + fn get_webhook_source_verification_message( + &self, + request: &IncomingWebhookRequestDetails<'_>, + _merchant_id: &common_utils::id_type::MerchantId, + connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, + ) -> CustomResult<Vec<u8>, errors::ConnectorError> { + let webhook_secret_str = String::from_utf8(connector_webhook_secrets.secret.to_vec()) + .map_err(|_| errors::ConnectorError::WebhookVerificationSecretInvalid) + .attach_printable("ACI webhook secret is not a valid UTF-8 string")?; + + let iv_hex_str = request + .headers + .get("X-Initialization-Vector") + .ok_or(errors::ConnectorError::WebhookSourceVerificationFailed) + .attach_printable("Missing X-Initialization-Vector header")? + .to_str() + .map_err(|_| errors::ConnectorError::WebhookSourceVerificationFailed) + .attach_printable("Invalid X-Initialization-Vector header value (not UTF-8)")?; + + let auth_tag_hex_str = request + .headers + .get("X-Authentication-Tag") + .ok_or(errors::ConnectorError::WebhookSourceVerificationFailed) + .attach_printable("Missing X-Authentication-Tag header")? + .to_str() + .map_err(|_| errors::ConnectorError::WebhookSourceVerificationFailed) + .attach_printable("Invalid X-Authentication-Tag header value (not UTF-8)")?; + + let encrypted_body_hex = String::from_utf8(request.body.to_vec()) + .map_err(|_| errors::ConnectorError::WebhookBodyDecodingFailed) + .attach_printable( + "Failed to read encrypted body as UTF-8 string for verification message", + )?; + + decrypt_aci_webhook_payload( + &webhook_secret_str, + iv_hex_str, + auth_tag_hex_str, + &encrypted_body_hex, + ) + .change_context(errors::ConnectorError::WebhookSourceVerificationFailed) + .attach_printable("Failed to decrypt ACI webhook payload for verification") + } + + fn get_webhook_object_reference_id( + &self, + request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + let aci_notification: aci::AciWebhookNotification = + serde_json::from_slice(request.body) + .change_context(errors::ConnectorError::WebhookResourceObjectNotFound) + .attach_printable("Failed to deserialize ACI webhook notification for ID extraction (expected decrypted payload)")?; + + let id_value_str = aci_notification + .payload + .get("id") + .and_then(|id| id.as_str()) + .ok_or_else(|| { + report!(errors::ConnectorError::WebhookResourceObjectNotFound) + .attach_printable("Missing 'id' in webhook payload for ID extraction") + })?; + + let payment_type_str = aci_notification + .payload + .get("paymentType") + .and_then(|pt| pt.as_str()); + + if payment_type_str.is_some_and(|pt| pt.to_uppercase() == "RF") { + Ok(api_models::webhooks::ObjectReferenceId::RefundId( + api_models::webhooks::RefundIdType::ConnectorRefundId(id_value_str.to_string()), + )) + } else { + Ok(api_models::webhooks::ObjectReferenceId::PaymentId( + api_models::payments::PaymentIdType::ConnectorTransactionId( + id_value_str.to_string(), + ), + )) + } } fn get_webhook_event_type( &self, - _request: &IncomingWebhookRequestDetails<'_>, + request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> { - Ok(IncomingWebhookEvent::EventNotSupported) + let aci_notification: aci::AciWebhookNotification = + serde_json::from_slice(request.body) + .change_context(errors::ConnectorError::WebhookEventTypeNotFound) + .attach_printable("Failed to deserialize ACI webhook notification for event type (expected decrypted payload)")?; + + match aci_notification.event_type { + aci::AciWebhookEventType::Payment => { + let payment_payload: aci::AciPaymentWebhookPayload = + serde_json::from_value(aci_notification.payload) + .change_context(errors::ConnectorError::WebhookEventTypeNotFound) + .attach_printable("Could not deserialize ACI payment webhook payload for event type determination")?; + + let code = &payment_payload.result.code; + if aci_result_codes::SUCCESSFUL_CODES.contains(&code.as_str()) { + if payment_payload.payment_type.to_uppercase() == "RF" { + Ok(IncomingWebhookEvent::RefundSuccess) + } else { + Ok(IncomingWebhookEvent::PaymentIntentSuccess) + } + } else if aci_result_codes::PENDING_CODES.contains(&code.as_str()) { + if payment_payload.payment_type.to_uppercase() == "RF" { + Ok(IncomingWebhookEvent::EventNotSupported) + } else { + Ok(IncomingWebhookEvent::PaymentIntentProcessing) + } + } else if aci_result_codes::FAILURE_CODES.contains(&code.as_str()) { + if payment_payload.payment_type.to_uppercase() == "RF" { + Ok(IncomingWebhookEvent::RefundFailure) + } else { + Ok(IncomingWebhookEvent::PaymentIntentFailure) + } + } else { + Ok(IncomingWebhookEvent::EventNotSupported) + } + } + } } fn get_webhook_resource_object( &self, - _request: &IncomingWebhookRequestDetails<'_>, + request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + let aci_notification: aci::AciWebhookNotification = + serde_json::from_slice(request.body) + .change_context(errors::ConnectorError::WebhookResourceObjectNotFound) + .attach_printable("Failed to deserialize ACI webhook notification for resource object (expected decrypted payload)")?; + + match aci_notification.event_type { + aci::AciWebhookEventType::Payment => { + let payment_payload: aci::AciPaymentWebhookPayload = + serde_json::from_value(aci_notification.payload) + .change_context(errors::ConnectorError::WebhookResourceObjectNotFound) + .attach_printable("Failed to deserialize ACI payment webhook payload")?; + Ok(Box::new(payment_payload)) + } + } } } static ACI_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { - let supported_capture_methods = vec![enums::CaptureMethod::Automatic]; + let supported_capture_methods = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::Manual, + ]; let supported_card_network = vec![ common_enums::CardNetwork::AmericanExpress, @@ -600,7 +916,7 @@ static ACI_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLo enums::PaymentMethodType::MbWay, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, - refunds: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, @@ -611,7 +927,7 @@ static ACI_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLo enums::PaymentMethodType::AliPay, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, - refunds: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, @@ -659,7 +975,7 @@ static ACI_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLo enums::PaymentMethodType::Eps, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, - refunds: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, @@ -669,7 +985,7 @@ static ACI_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLo enums::PaymentMethodType::Eft, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, - refunds: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, @@ -679,7 +995,7 @@ static ACI_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLo enums::PaymentMethodType::Ideal, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, - refunds: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, @@ -689,7 +1005,7 @@ static ACI_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLo enums::PaymentMethodType::Giropay, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, - refunds: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, @@ -699,7 +1015,7 @@ static ACI_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLo enums::PaymentMethodType::Sofort, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, - refunds: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, @@ -709,7 +1025,7 @@ static ACI_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLo enums::PaymentMethodType::Interac, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, - refunds: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, @@ -719,7 +1035,7 @@ static ACI_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLo enums::PaymentMethodType::Przelewy24, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, - refunds: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, @@ -729,7 +1045,7 @@ static ACI_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLo enums::PaymentMethodType::Trustly, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, - refunds: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, @@ -739,7 +1055,7 @@ static ACI_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLo enums::PaymentMethodType::Klarna, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, - refunds: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, diff --git a/crates/hyperswitch_connectors/src/connectors/aci/transformers.rs b/crates/hyperswitch_connectors/src/connectors/aci/transformers.rs index e5f7ec19b50..b2074cb8dc4 100644 --- a/crates/hyperswitch_connectors/src/connectors/aci/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/aci/transformers.rs @@ -6,11 +6,16 @@ use error_stack::report; use hyperswitch_domain_models::{ payment_method_data::{BankRedirectData, Card, PayLaterData, PaymentMethodData, WalletData}, router_data::{ConnectorAuthType, RouterData}, - router_request_types::ResponseId, + router_request_types::{ + PaymentsAuthorizeData, PaymentsCancelData, PaymentsSyncData, ResponseId, + }, router_response_types::{ MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData, }, - types::{PaymentsAuthorizeRouterData, PaymentsCancelRouterData, RefundsRouterData}, + types::{ + PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, + RefundsRouterData, + }, }; use hyperswitch_interfaces::errors; use masking::{ExposeInterface, Secret}; @@ -25,6 +30,28 @@ use crate::{ type Error = error_stack::Report<errors::ConnectorError>; +trait GetCaptureMethod { + fn get_capture_method(&self) -> Option<enums::CaptureMethod>; +} + +impl GetCaptureMethod for PaymentsAuthorizeData { + fn get_capture_method(&self) -> Option<enums::CaptureMethod> { + self.capture_method + } +} + +impl GetCaptureMethod for PaymentsSyncData { + fn get_capture_method(&self) -> Option<enums::CaptureMethod> { + self.capture_method + } +} + +impl GetCaptureMethod for PaymentsCancelData { + fn get_capture_method(&self) -> Option<enums::CaptureMethod> { + None + } +} + #[derive(Debug, Serialize)] pub struct AciRouterData<T> { amount: StringMajorUnit, @@ -629,14 +656,18 @@ pub enum AciPaymentStatus { RedirectShopper, } -impl From<AciPaymentStatus> for enums::AttemptStatus { - fn from(item: AciPaymentStatus) -> Self { - match item { - AciPaymentStatus::Succeeded => Self::Charged, - AciPaymentStatus::Failed => Self::Failure, - AciPaymentStatus::Pending => Self::Authorizing, - AciPaymentStatus::RedirectShopper => Self::AuthenticationPending, +fn map_aci_attempt_status(item: AciPaymentStatus, auto_capture: bool) -> enums::AttemptStatus { + match item { + AciPaymentStatus::Succeeded => { + if auto_capture { + enums::AttemptStatus::Charged + } else { + enums::AttemptStatus::Authorized + } } + AciPaymentStatus::Failed => enums::AttemptStatus::Failure, + AciPaymentStatus::Pending => enums::AttemptStatus::Authorizing, + AciPaymentStatus::RedirectShopper => enums::AttemptStatus::AuthenticationPending, } } impl FromStr for AciPaymentStatus { @@ -708,12 +739,14 @@ pub struct ErrorParameters { pub(super) message: String, } -impl<F, T> TryFrom<ResponseRouterData<F, AciPaymentsResponse, T, PaymentsResponseData>> - for RouterData<F, T, PaymentsResponseData> +impl<F, Req> TryFrom<ResponseRouterData<F, AciPaymentsResponse, Req, PaymentsResponseData>> + for RouterData<F, Req, PaymentsResponseData> +where + Req: GetCaptureMethod, { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: ResponseRouterData<F, AciPaymentsResponse, T, PaymentsResponseData>, + item: ResponseRouterData<F, AciPaymentsResponse, Req, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let redirection_data = item.response.redirect.map(|data| { let form_fields = std::collections::HashMap::<_, _>::from_iter( @@ -740,16 +773,22 @@ impl<F, T> TryFrom<ResponseRouterData<F, AciPaymentsResponse, T, PaymentsRespons connector_mandate_request_reference_id: None, }); + let auto_capture = matches!( + item.data.request.get_capture_method(), + Some(enums::CaptureMethod::Automatic) | None + ); + + let status = if redirection_data.is_some() { + map_aci_attempt_status(AciPaymentStatus::RedirectShopper, auto_capture) + } else { + map_aci_attempt_status( + AciPaymentStatus::from_str(&item.response.result.code)?, + auto_capture, + ) + }; + Ok(Self { - status: { - if redirection_data.is_some() { - enums::AttemptStatus::from(AciPaymentStatus::RedirectShopper) - } else { - enums::AttemptStatus::from(AciPaymentStatus::from_str( - &item.response.result.code, - )?) - } - }, + status, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(redirection_data), @@ -765,6 +804,95 @@ impl<F, T> TryFrom<ResponseRouterData<F, AciPaymentsResponse, T, PaymentsRespons } } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AciCaptureRequest { + #[serde(flatten)] + pub txn_details: TransactionDetails, +} + +impl TryFrom<&AciRouterData<&PaymentsCaptureRouterData>> for AciCaptureRequest { + type Error = error_stack::Report<errors::ConnectorError>; + + fn try_from(item: &AciRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> { + let auth = AciAuthType::try_from(&item.router_data.connector_auth_type)?; + Ok(Self { + txn_details: TransactionDetails { + entity_id: auth.entity_id, + amount: item.amount.to_owned(), + currency: item.router_data.request.currency.to_string(), + payment_type: AciPaymentType::Capture, + }, + }) + } +} + +#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AciCaptureResponse { + id: String, + referenced_id: String, + payment_type: AciPaymentType, + amount: StringMajorUnit, + currency: String, + descriptor: String, + result: AciCaptureResult, + result_details: AciCaptureResultDetails, + build_number: String, + timestamp: String, + ndc: Secret<String>, + source: Secret<String>, + payment_method: String, + short_id: String, +} + +#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AciCaptureResult { + code: String, + description: String, +} + +#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq, Serialize)] +#[serde(rename_all = "PascalCase")] +pub struct AciCaptureResultDetails { + extended_description: String, + #[serde(rename = "clearingInstituteName")] + clearing_institute_name: String, + connector_tx_id1: String, + connector_tx_id3: String, + connector_tx_id2: String, + acquirer_response: String, +} + +impl<F, T> TryFrom<ResponseRouterData<F, AciCaptureResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData<F, AciCaptureResponse, T, PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: map_aci_attempt_status( + AciPaymentStatus::from_str(&item.response.result.code)?, + false, + ), + reference_id: Some(item.response.referenced_id.clone()), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), + redirection_data: Box::new(None), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: Some(item.response.referenced_id), + incremental_authorization_allowed: None, + charges: None, + }), + ..item.data + }) + } +} + #[derive(Default, Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct AciRefundRequest { @@ -854,3 +982,89 @@ impl<F> TryFrom<RefundsResponseRouterData<F, AciRefundResponse>> for RefundsRout }) } } + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] +pub enum AciWebhookEventType { + Payment, +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] +pub enum AciWebhookAction { + Created, + Updated, + Deleted, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AciWebhookCardDetails { + pub bin: Option<String>, + #[serde(rename = "last4Digits")] + pub last4_digits: Option<String>, + pub holder: Option<String>, + pub expiry_month: Option<Secret<String>>, + pub expiry_year: Option<Secret<String>>, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AciWebhookCustomerDetails { + #[serde(rename = "givenName")] + pub given_name: Option<Secret<String>>, + pub surname: Option<Secret<String>>, + #[serde(rename = "merchantCustomerId")] + pub merchant_customer_id: Option<Secret<String>>, + pub sex: Option<Secret<String>>, + pub email: Option<Email>, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AciWebhookAuthenticationDetails { + #[serde(rename = "entityId")] + pub entity_id: Secret<String>, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AciWebhookRiskDetails { + pub score: Option<String>, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AciPaymentWebhookPayload { + pub id: String, + pub payment_type: String, + pub payment_brand: String, + pub amount: StringMajorUnit, + pub currency: String, + pub presentation_amount: Option<StringMajorUnit>, + pub presentation_currency: Option<String>, + pub descriptor: Option<String>, + pub result: ResultCode, + pub authentication: Option<AciWebhookAuthenticationDetails>, + pub card: Option<AciWebhookCardDetails>, + pub customer: Option<AciWebhookCustomerDetails>, + #[serde(rename = "customParameters")] + pub custom_parameters: Option<serde_json::Value>, + pub risk: Option<AciWebhookRiskDetails>, + pub build_number: Option<String>, + pub timestamp: String, + pub ndc: String, + #[serde(rename = "channelName")] + pub channel_name: Option<String>, + pub source: Option<String>, + pub payment_method: Option<String>, + #[serde(rename = "shortId")] + pub short_id: Option<String>, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AciWebhookNotification { + #[serde(rename = "type")] + pub event_type: AciWebhookEventType, + pub action: Option<AciWebhookAction>, + pub payload: serde_json::Value, +} diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 160e6490efc..bda3eed02aa 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -500,8 +500,8 @@ credit = { country = "AD,AT,AU,BE,BG,CA,CH,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GG,GI,GR,H debit = { country = "AD,AT,AU,BE,BG,CA,CH,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GG,GI,GR,HK,HR,HU,IE,IM,IT,JE,LI,LT,LU,LV,MT,MC,MY,NL,NO,NZ,PL,PT,RO,SE,SG,SI,SK,SM,US", currency = "AED,AMD,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BIF,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CHF,CLP,CNY,COP,CRC,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,ISK,JMD,JPY,KES,KGS,KHR,KMF,KRW,KYD,KZT,LAK,LBP,LKR,LRD,LSL,MAD,MDL,MKD,MNT,MOP,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLL,SOS,SRD,STD,SVC,SYP,SZL,THB,TJS,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL"} [pm_filters.aci] -credit = { not_available_flows = { capture_method = "manual" }, country = "AD,AE,AT,BE,BG,CH,CN,CO,CR,CY,CZ,DE,DK,DO,EE,EG,ES,ET,FI,FR,GB,GH,GI,GR,GT,HN,HK,HR,HU,ID,IE,IS,IT,JP,KH,LA,LI,LT,LU,LY,MK,MM,MX,MY,MZ,NG,NZ,OM,PA,PE,PK,PL,PT,QA,RO,SA,SN,SE,SI,SK,SV,TH,UA,US,UY,VN,ZM", currency = "AED,ALL,ARS,BGN,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,EGP,EUR,GBP,GHS,HKD,HNL,HRK,HUF,IDR,ILS,ISK,JPY,KHR,KPW,LAK,LKR,MAD,MKD,MMK,MXN,MYR,MZN,NGN,NOK,NZD,OMR,PAB,PEN,PHP,PKR,PLN,QAR,RON,RSD,SAR,SEK,SGD,THB,TRY,TWD,UAH,USD,UYU,VND,ZAR,ZMW" } -debit = { not_available_flows = { capture_method = "manual" }, country = "AD,AE,AT,BE,BG,CH,CN,CO,CR,CY,CZ,DE,DK,DO,EE,EG,ES,ET,FI,FR,GB,GH,GI,GR,GT,HN,HK,HR,HU,ID,IE,IS,IT,JP,KH,LA,LI,LT,LU,LY,MK,MM,MX,MY,MZ,NG,NZ,OM,PA,PE,PK,PL,PT,QA,RO,SA,SN,SE,SI,SK,SV,TH,UA,US,UY,VN,ZM", currency = "AED,ALL,ARS,BGN,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,EGP,EUR,GBP,GHS,HKD,HNL,HRK,HUF,IDR,ILS,ISK,JPY,KHR,KPW,LAK,LKR,MAD,MKD,MMK,MXN,MYR,MZN,NGN,NOK,NZD,OMR,PAB,PEN,PHP,PKR,PLN,QAR,RON,RSD,SAR,SEK,SGD,THB,TRY,TWD,UAH,USD,UYU,VND,ZAR,ZMW" } +credit = { country = "AD,AE,AT,BE,BG,CH,CN,CO,CR,CY,CZ,DE,DK,DO,EE,EG,ES,ET,FI,FR,GB,GH,GI,GR,GT,HN,HK,HR,HU,ID,IE,IS,IT,JP,KH,LA,LI,LT,LU,LY,MK,MM,MX,MY,MZ,NG,NZ,OM,PA,PE,PK,PL,PT,QA,RO,SA,SN,SE,SI,SK,SV,TH,UA,US,UY,VN,ZM", currency = "AED,ALL,ARS,BGN,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,EGP,EUR,GBP,GHS,HKD,HNL,HRK,HUF,IDR,ILS,ISK,JPY,KHR,KPW,LAK,LKR,MAD,MKD,MMK,MXN,MYR,MZN,NGN,NOK,NZD,OMR,PAB,PEN,PHP,PKR,PLN,QAR,RON,RSD,SAR,SEK,SGD,THB,TRY,TWD,UAH,USD,UYU,VND,ZAR,ZMW" } +debit = { country = "AD,AE,AT,BE,BG,CH,CN,CO,CR,CY,CZ,DE,DK,DO,EE,EG,ES,ET,FI,FR,GB,GH,GI,GR,GT,HN,HK,HR,HU,ID,IE,IS,IT,JP,KH,LA,LI,LT,LU,LY,MK,MM,MX,MY,MZ,NG,NZ,OM,PA,PE,PK,PL,PT,QA,RO,SA,SN,SE,SI,SK,SV,TH,UA,US,UY,VN,ZM", currency = "AED,ALL,ARS,BGN,CHF,CLP,CNY,COP,CRC,CZK,DKK,DOP,EGP,EUR,GBP,GHS,HKD,HNL,HRK,HUF,IDR,ILS,ISK,JPY,KHR,KPW,LAK,LKR,MAD,MKD,MMK,MXN,MYR,MZN,NGN,NOK,NZD,OMR,PAB,PEN,PHP,PKR,PLN,QAR,RON,RSD,SAR,SEK,SGD,THB,TRY,TWD,UAH,USD,UYU,VND,ZAR,ZMW" } mb_way = { country = "EE,ES,PT", currency = "EUR" } ali_pay = { country = "CN", currency = "CNY" } eps = { country = "AT", currency = "EUR" }
2025-06-16T03:44:04Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD closes this [issue](https://github.com/juspay/hyperswitch/issues/8348) ## Description <!-- Describe your changes in detail --> Implemented capture and webhook flow, fix some issues in ACI ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> **NOTE**: This PR adds test cases for the ACI capture flow. Currently, the capture-related tests are failing with the error: `Cannot capture (PA value exceeded, PA reverted or invalid workflow?)` I've already raised this issue with the ACI team and am awaiting their response. Once resolved, we can revalidate the flow accordingly. We will follow up with validation once ACI provides the necessary support and access. Additionally, we do not have dashboard access for ACI to test webhook functionality end-to-end. Postman Test (For capture flow): Payments - Create (Confirm: true): Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_Zc8oIJUK0i4PD7sOckK3GefgrZrPYR7B0yHsazdUVemSff6GLX4O6rhOEDMtcrUI' \ --data-raw ' { "amount": 1000, "currency": "USD", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 1000, "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "billing": { "address": { "first_name": "John", "last_name": "Doe", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "AT" } }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "11", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "276" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Response: ``` { "payment_id": "pay_IiHYDvxclZJ4UZEr9irY", "merchant_id": "merchant_1751352542", "status": "requires_capture", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 1000, "amount_received": null, "connector": "aci", "client_secret": "pay_IiHYDvxclZJ4UZEr9irY_secret_kvCV7sR0WZkxpOAFHOgt", "created": "2025-07-01T06:51:50.527Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "11", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "AT", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1751352710, "expires": 1751356310, "secret": "epk_27f6d5062c894d2eada4b67c4eae1abc" }, "manual_retry_allowed": false, "connector_transaction_id": "8ac7a4a297c2d96a0197c4c19aca4810", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "8ac7a4a297c2d96a0197c4c19aca4810", "payment_link": null, "profile_id": "pro_sPevIjlEfalGATQpyx0N", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_cBSc84vPxAVKJqfS3Db3", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-07-01T07:06:50.527Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "127.0.0.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-07-01T06:51:52.447Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` Payments - Capture: Request: ``` curl --location 'http://localhost:8080/payments/pay_IiHYDvxclZJ4UZEr9irY/capture' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_Zc8oIJUK0i4PD7sOckK3GefgrZrPYR7B0yHsazdUVemSff6GLX4O6rhOEDMtcrUI' \ --data '{ "amount_to_capture": 1000, "statement_descriptor_name": "Joseph", "statement_descriptor_prefix" :"joseph", "statement_descriptor_suffix": "JS" }' ``` Response: ``` { "payment_id": "pay_IiHYDvxclZJ4UZEr9irY", "merchant_id": "merchant_1751352542", "status": "failed", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 1000, "amount_received": null, "connector": "aci", "client_secret": "pay_IiHYDvxclZJ4UZEr9irY_secret_kvCV7sR0WZkxpOAFHOgt", "created": "2025-07-01T06:51:50.527Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "11", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "AT", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": "700.400.100", "error_message": "cannot capture (PA value exceeded, PA reverted or invalid workflow?)", "unified_code": "UE_9000", "unified_message": "Something went wrong", "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": true, "connector_transaction_id": "8ac7a4a297c2d96a0197c4c19aca4810", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "8ac7a4a297c2d96a0197c4c19aca4810", "payment_link": null, "profile_id": "pro_sPevIjlEfalGATQpyx0N", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_cBSc84vPxAVKJqfS3Db3", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-07-01T07:06:50.527Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "127.0.0.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-07-01T06:53:15.846Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
4003c176f6dc1abd25b3b27182aedfea5c514e62
4003c176f6dc1abd25b3b27182aedfea5c514e62
juspay/hyperswitch
juspay__hyperswitch-8332
Bug: docs(openapi): Show API version selection dropdown in API Reference Add a version selection dropdown in API reference to allow exploring v2 APIs
diff --git a/api-reference-v2/README.md b/api-reference-v2/README.md deleted file mode 100644 index 61bc1f08938..00000000000 --- a/api-reference-v2/README.md +++ /dev/null @@ -1,45 +0,0 @@ -# Api Reference - -We use the [openapi specification](https://swagger.io/specification) for the api reference. The openapi file is generated from the code base [openapi_spec.json](openapi_spec.json). - -## How to generate the file - -This file is automatically generated from our CI pipeline when the PR is raised. However if you want to generate it manually, the following command can be used - -```bash -cargo r -p openapi --features v2 -``` - -## Render the generated openapi spec file - -In order to render the openapi spec file, we use a tool called [mintlify](https://mintlify.com/). Local setup instructions can be found [here](https://mintlify.com/docs/development#development). Once the cli is installed, Run the following command to render the openapi spec - -- Navigate to the directory where `mint.json` exists - -```bash -cd api-reference-v2 -``` - -- Run the cli - -```bash -mintlify dev -``` - -## Add new routes to openapi - -If you have added new routes to the openapi. Then in order for them to be displayed on the mintlify, run the following commands - -- Switch to the directory where api reference ( mint.json ) exists - -```bash -cd api-reference-v2 -``` - -- Run the following command to generate the route files - -```bash -npx @mintlify/scraping@latest openapi-file openapi_spec.json -o api-reference -``` - -This will generate files in [api-reference](api-reference) folder. These routes should be added to the [mint.json](mint.json) file under navigation, under respective group. diff --git a/api-reference-v2/assets/images/image.png b/api-reference-v2/assets/images/image.png deleted file mode 100644 index d13e2459328..00000000000 Binary files a/api-reference-v2/assets/images/image.png and /dev/null differ diff --git a/api-reference-v2/essentials/error_codes.mdx b/api-reference-v2/essentials/error_codes.mdx deleted file mode 100644 index 2f633e9cffe..00000000000 --- a/api-reference-v2/essentials/error_codes.mdx +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: Error Codes ---- - -Hyperswitch uses Error codes, types, and messages to communicate errors during API calls. There are three types of error codes: - -| Error Code | Type | Description | -| ---------- | --------------------- | ------------------------------------------------------------ | -| IR | Invalid Request Error | Error caused due to invalid fields and values in API request | -| CE | Connector Error | Errors originating from connector’s end | -| HE | Hyperswitch Error | Errors originating from Hyperswitch’s end | -| WE | Webhook Error | Errors related to Webhooks | - -| Error Codes | HTTP Status codes | Error Type | Error message | Error Handling | -| ----------- | ------------------------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| IR_00 | 501 | server_not_available | This API is under development and will be made available soon | No action required. If you require this feature, please reach out to Hyperswitch support | -| IR_01 | 401 | invalid_request_error | API key not provided or invalid API key used. Provide the API key in the Authorization header using api-key (e.g api-key: API_KEY) or create a new API key from the dashboard | Provide the API key in the Authorization header using api-key (e.g api-key: API_KEY) or create a new API key from the dashboard | -| IR_02 | 404 | invalid_request_error | Unrecognized request URL | Please recheck and enter the correct request URL. Refer to our API documentation | -| IR_03 | 405 | invalid_request_error | The HTTP method is not applicable for this API | Please recheck the HTTP method used in the request. Refer to our API documentation | -| IR_04 | 400 | invalid_request_error | Missing required param: “field_name” | Please pass the missing required parameter. Refer to our API documentation | -| IR_05 | 422 | invalid_request_error | “field_name” contains invalid data. Expected format is “expected_format” | Please pass the data in the expected format. Refer to our API documentation | -| IR_06 | 400 | invalid_request_error | “message” | Refer to our API documentation for required fields and format | -| IR_07 | 400 | invalid_request_error | Invalid value provided: “field_name” | Provide a valid value for the required fields in the expected format. Refer to our API documentation | -| IR_08 | 400 | invalid_request_error | Client secret was not provided | Provide the client secret received in payments/create API response | -| IR_09 | 400 | invalid_request_error | The client_secret provided does not match the client_secret associated with the Payment | Provide the same client secret received in payments/create API response for the corresponding payment | -| IR_10 | 400 | invalid_request_error | Customer has an existing mandate/subscription | Cancel the active mandates/subscriptions for the customer before proceeding to delete the customer data | -| IR_11 | 400 | invalid_request_error | Customer has already been redacted | Customer has already been redacted. No action required | -| IR_12 | 400 | invalid_request_error | Reached the maximum refund attempts | Maximum refund attempts reached for this payment. Please contact Hyperswitch support for attempting more refunds for the same payment | -| IR_13 | 400 | invalid_request_error | Refund amount exceeds the payment amount | Please verify and pass a refund amount equal to or less than the payment amount | -| IR_14 | 400 | invalid_request_error | This Payment could not be “current_flow” because it has a “field_name” of “current_value”. The expected state is “states” | Please verify the status of the payment and make sure that you are performing an action that is allowed for the current status of the payment | -| IR_15 | 400 | invalid_request_error | Invalid Ephemeral Key for the customer | Please pass the right Ephemeral key for the customer | -| IR_16 | 400 | invalid_request_error | “message” | Typically used when information involving multiple fields or previously provided information doesn’t satisfy a condition. Refer to our API documentation for required fields and format | -| IR_17 | 401 | invalid_request_error | Access forbidden, an invalid JWT token was used | Provide a valid JWT token to access the APIs | -| IR_18 | 401 | invalid_request_error | "message" | The user is not authorised to update the customer, Contact Org. Admin for the appropriate access. | -| IR_19 | 400 | invalid_request_error | "message" | Please check and retry with correct details. Refer to our API documentation | -| IR_20 | 400 | invalid_request_error | "flow" not supported by the "connector" | Requested flow is not supported for this Connector. | -| IR_21 | 400 | invalid_request_error | Missing required params | Please add the required params in the request. Refer to our API documentation | -| IR_22 | 403 | invalid_request_error | Access forbidden. Not authorized to access this "resource" | Contact Org. Admin for the appropriate access. | -| IR_23 | 400 | invalid_request_error | "message" | Use a supported file provider. Refer to our API documentation | -| IR_24 | 422 | processing_error | Invalid "wallet_name" wallet token | Share the correct wallet token. | -| IR_25 | 400 | invalid_request_error | Cannot delete the default payment method | Check if the Payment method is activated. Refer to Control centre to check this. | -| IR_26 | 400 | invalid_request_error | Invalid Cookie | Recheck the site setting for the cookies. | -| IR_27 | 404 | invalid_request_error | Extended card info does not exist | Recheck the card info shared in the request. | -| IR_28 | 400 | invalid_request_error | "message" | Use a valid currency. Refer to our API documentation | -| IR_29 | 422 | invalid_request_error | "message" | The data format is invalid for this request. Refer to our API documentation | -| IR_30 | 400 | invalid_request_error | Merchant connector account is configured with invalid config | Correct the config for merchant connector account | -| IR_31 | 400 | invalid_request_error | Card with the provided iin does not exist | Check the IIN (Issuer Identification Number) and ensure it is correct. | -| IR_32 | 400 | invalid_request_error | The provided card IIN length is invalid, please provide an iin with 6 or 8 digits | Provide a valid IIN with either 6 or 8 digits. | -| IR_33 | 400 | invalid_request_error | File not found / valid in the request | Ensure the required file is included in the request and is valid. Refer to our API documentation | -| IR_34 | 400 | invalid_request_error | Dispute id not found in the request | Ensure that a valid dispute ID is included in the request. | -| IR_35 | 400 | invalid_request_error | File purpose not found in the request or is invalid | Specify a valid file purpose in the request. | -| IR_36 | 400 | invalid_request_error | File content type not found / valid | Ensure the file content type is specified and is valid. | -| IR_37 | 404 | invalid_request_error | "message" | Check the request for the resource being accessed and ensure it exists. | -| IR_38 | 400 | invalid_request_error | "message" | Check for any duplicate entries in the request and correct them. | -| IR_39 | 400 | invalid_request_error | required payment method is not configured or configured incorrectly for all configured connectors | Verify that the required payment method is correctly configured for all connectors in use. | -| CE_00 | Status codes shared by the connectors | connector_error | “message” | The error code and message passed from the connectors. Refer to the respective connector’s documentation for more information on the error | -| CE_01 | 400 | processing_error | Payment failed during authorization with the connector. Retry payment | Retry the payment again as payment failed at the connector during authorization | -| CE_02 | 400 | processing_error | Payment failed during authentication with the connector. Retry payment | Retry the payment again as payment failed at the connector during authentication | -| CE_03 | 400 | processing_error | Capture attempt failed while processing with the connector | Capture failed for the payment at the connector. Please retry the payment | -| CE_04 | 400 | processing_error | The card data is invalid | Invalid card data passed. Please pass valid card data | -| CE_05 | 400 | processing_error | The card has expired | Card expired. Please pass valid card data | -| CE_06 | 400 | processing_error | Refund failed while processing with the connector. Retry refund | Refund failed to process at the connector. Please retry refund | -| CE_07 | 400 | processing_error | Verification failed while processing with the connector. Retry operation | Retry the operation again as verification failed at the connector | -| CE_08 | 400 | processing_error | Dispute operation failed while processing with connector. Retry operation | Retry the operation again as dispute failed at the connector | -| CE_09 | 400 | invalid_request_error | Payout validation failed | Retry the operation again with correct Payout details. | -| HE_00 | 422,500 | server_not_available | Resource not available right now, Please try again later. | Please Wait for a few moments and try again. If the error still persists, please reach out to Hyperswitch support | -| HE_01 | 400,422 | duplicate_request | Requested operation(Customer, Payments, Merchants, Refunds etc.) for these identifier already exists. | Please verify the Details(Customer, Payments, Merchants, Refunds, as applicable on the basis of request) and enter valid details. | -| HE_02 | 404 | object_not_found | Requested object(Customer, Payments, Merchants, Refunds etc.) does not exist in our records | Please verify the Details(Customer, Payments, Merchants, Refunds, as applicable on the basis of request) and enter valid details. | -| HE_03 | 500 | validation_error | Validation Failed for the requested operation with the given details. | Please verify the details again and enter valid details | -| HE_04 | 404 | object_not_found | Requested object(Customer, Payments, Merchants, Refunds etc.) does not exist in our records | Please verify the Details(Customer, Payments, Merchants, Refunds, as applicable on the basis of request) and enter valid details. | -| HE_05 | 500 | processing_error | Missing or invalid tenant details. | Please verify the tenant Details and try again. | -| WE_01 | 400 | invalid_request_error | Failed to authenticate the webhook | Please verify the authentication credentials and try again. | -| WE_02 | 400 | invalid_request_error | Bad request received in webhook | Check the request parameters and format, then try again. | -| WE_03 | 500 | router_error | There was some issue processing the webhook | Please try again later. If the issue persists, contact Hyperswitch support. | -| WE_04 | 404 | object_not_found | Webhook resource not found | Ensure the webhook URL is correct and the resource exists. | -| WE_05 | 400 | invalid_request_error | Unable to process the webhook body | Ensure the webhook body is correctly formatted and try again. | -| WE_06 | 400 | invalid_request_error | Merchant Secret set by merchant for webhook source verification is invalid | Verify the Merchant Secret, then try again. | \ No newline at end of file diff --git a/api-reference-v2/essentials/go-live.mdx b/api-reference-v2/essentials/go-live.mdx deleted file mode 100644 index 80d030e4c5e..00000000000 --- a/api-reference-v2/essentials/go-live.mdx +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: Go-live Checklist ---- - -Refer to this checklist for a seamless transition as you prepare to go live with your integration. - -<Warning> -The connector configurations set up in the sandbox need to be replicated on the Hyperswitch production account. -</Warning> - -### Signing of Hyperswitch services agreement - -- [ ] Ensure that the Hyperswitch services agreement is signed and shared with the Hyperswitch team. In case you need any help, please drop an email to [email protected]. - -<Warning> -The Hyperswitch team will share your production Hyperswitch credentials once the above process is completed. -</Warning> - -### Connector Configurations - -- [ ] Configure all the required connectors using production credentials on the Hyperswitch production dashboard and enable the required payment methods. -- [ ] Ensure that the payment methods are enabled on the connector (payment processor) dashboard. -- [ ] Enable raw card processing for each connector. Some connectors offer this as a dashboard toggle feature. Some processors might need you to share a PCI Attestation of Compliance over email to enable this. Drop an email to [email protected] if you need any support with PCI AOC. - -### Secure your api-keys - -- [ ] Make sure your secret key (api-key) is not exposed on the front-end (website/mobile app). -- [ ] Ensure that your workflow avoids the duplication or storage of your API keys in multiple locations. - -### Set up Webhooks - -- [ ] [Configure your webhook endpoint](https://juspay-78.mintlify.app/essentials/webhooks#configuring-webhooks) on our dashboard to receive notifications for different events. -- [ ] Update Hyperswitch's webhook endpoints on your connector's Dashboard. [Refer here](https://juspay-78.mintlify.app/essentials/webhooks#configuring-webhooks) for detailed instructions. -- [ ] Update the connector secret key in our dashboard for us to authenticate webhooks sent by your connector. - -### Secure your Payments - -- [ ] Make sure you decrypt and verify the signed payload sent along with the payment status in your return URL. -- [ ] Always verify the payment amount and payment status before fulfilling your customer's shopping cart/service request. - -### Error Handling - -- [ ] Make sure your API integration is set up to handle all the possible error scenarios (refer this [link](https://juspay-78.mintlify.app/essentials/error_codes)). -- [ ] Ensure your Unified Checkout (SDK) integration is set up to handle all the possible error scenarios (refer this [link](https://hyperswitch.io/docs/sdkIntegrations/unifiedCheckoutWeb/errorCodes)). -- [ ] Ensure that your integration can handle the entire payments lifecycle and test various scenarios using actual payment details. - -### Customize and sanity check the payment experience - -- [ ] Ensure the pay button is properly highlighted to the customer. -- [ ] Ensure a blended look and feel of the payment experience using the [styling APIs](https://hyperswitch.io/docs/sdkIntegrations/unifiedCheckoutWeb/customization) of Unified Checkout. diff --git a/api-reference-v2/essentials/rate_limit.mdx b/api-reference-v2/essentials/rate_limit.mdx deleted file mode 100644 index 2857271f96c..00000000000 --- a/api-reference-v2/essentials/rate_limit.mdx +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: Rate Limits ---- - -The Hyperswitch API has multiple checks in place to enhance its stability when faced with sudden surges of incoming traffic. Merchants who send numerous requests in rapid succession could encounter error responses indicated by the status code 429. - -<Warning> - The default rate limit for all Hyperswitch APIs is **80 requests per second**. - Reach out to [email protected] if you have a requirement for higher limits. -</Warning> - -## How to handle rate limits - -Effectively handling rate limit 429 errors is crucial for maintaining a seamless user experience. - -- Implement retry mechanisms with progressively increasing intervals to avoid overwhelming the system with repeated requests. -- To proactively manage these errors, monitoring tools can help track usage patterns and provide insights for adjusting rate limits as necessary. -- Ultimately, a well-orchestrated strategy for managing 429 errors not only prevents disruption but also fosters positive user engagement by transparently addressing limitations and promoting responsible API usage. - -## Understanding API locking - -If you see a 429 error with the following error message, it is due to API locking and not due to rate limiting: - -```text -At this moment, access to this object is restricted due to ongoing utilization by another API request or an ongoing Hyperswitch process. Retry after some time if this error persists. -``` - -API locking is a robust feature that empowers us to proactively secure and optimize access to our APIs. Our API locks objects on some operations to prevent the disruption caused by concurrent workloads that could potentially lead to inconsistent outcomes. - -This proactive measure not only ensures the continued integrity and performance of our APIs but also guarantees a high standard of security for our users. Once triggered, the API lock initiates a controlled pause in access, preventing any potential threats from compromising the system. diff --git a/api-reference-v2/favicon.png b/api-reference-v2/favicon.png deleted file mode 100644 index c9a0fc50f7a..00000000000 Binary files a/api-reference-v2/favicon.png and /dev/null differ diff --git a/api-reference-v2/introduction.mdx b/api-reference-v2/introduction.mdx deleted file mode 100644 index 5c59dbc11eb..00000000000 --- a/api-reference-v2/introduction.mdx +++ /dev/null @@ -1,51 +0,0 @@ ---- -tags: [Getting Started] -stoplight-id: 3lmsk7ocvq21v ---- - -# 👋 Welcome to Hyperswitch API Reference - -Hyperswitch provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body and return standard HTTP response codes. You can consume the APIs directly using your favorite HTTP/REST library. - -## Environment - -We have a testing environment referred to "sandbox," which you can set up to test API calls without affecting production data. You can sign up on our Dashboard to get API keys to access Hyperswitch API. - -Use the following base URLs when making requests to the APIs: - -| Environment | Base URL | -| ----------- | ------------------------------ | -| Sandbox | https://sandbox.hyperswitch.io | -| Production | https://api.hyperswitch.io | - -<Note> If you **do not hold a PCI certification** to collect and store card data on your servers, we recommend using [**Unified Checkout**](https://hyperswitch.io/docs/sdkIntegrations/unifiedCheckoutWeb/#unified-checkout) to accept card information from users. </Note> - -## Authentication and API keys - -Hyperswitch authenticates your API requests using your account’s API keys. Each account has two API keys for authentication: - -| Key | Example | When to Use | -| -------------------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | -| Secret key (API-key) | `snd_c69***` | Used to authenticate API requests from your merchant server. **Don’t expose this key** on a website or embed it in a mobile application. | -| Publishable key | `pk_snd_3b3***` | Used to authenticate API requests from your app’s client. Can be publicly-accessible in your web or mobile app’s client-side code. | - -<Check> -Get your [API key](https://app.hyperswitch.io/developers?tabIndex=1) and [Publishable Key](https://app.hyperswitch.io/home) -</Check> -<Check> -[Postman Collection](https://www.postman.com/hyperswitch/workspace/hyperswitch-development/collection/25176162-630b5353-7002-44d1-8ba1-ead6c230f2e3) -</Check> - -## Payment Status Lifecycle -Hyperswitch handles the complex functionality of a comprehensive payments flow through the Payments object that transitions through multiple states during its payments lifecycle. Given below are the various statuses a payment can have: -| Payment Status | Description | -| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| requires_payment_method | Once you create a payment through payments/create endpoint with no payment method attached to it, the payments object transitions to ‘requires_payment_method’. | -| requires_confirmation | After attaching a payment method through payments/update endpoint, the payments object requires you to confirm the payment. | -| requires_customer_action | Once the payment is confirmed through payments/confirm endpoint, if additional authentication is required, the payments object transitions to this state. | -| requires_capture | If you want to do separate authorize and capture, setting capture field to ‘manual’ during payments/create or confirm call will transition the payment object to this state after customer action succeeds. | -| processing | In case of automatic capture, the payments object transitions to processing state post confirm call and subsequent customer authentication if available. | -| succeeded | The payments object reaches success state post confirmation of successful processing from the payment processor. | -| failed | The payments object transitions to a failed state when the payment processor confirms the processing failure. | -| expired | You can expire the payments object while it is in any state except when it is under ‘processing’ or ‘succeeded’ state. | - <img src="assets/images/image.png" /> diff --git a/api-reference-v2/logo/dark.svg b/api-reference-v2/logo/dark.svg deleted file mode 100644 index f07be0cea14..00000000000 --- a/api-reference-v2/logo/dark.svg +++ /dev/null @@ -1,21 +0,0 @@ -<svg width="545" height="58" viewBox="0 0 545 58" fill="none" xmlns="http://www.w3.org/2000/svg"> -<path fill-rule="evenodd" clip-rule="evenodd" d="M27.2375 54.3079C25.9366 54.3441 24.6718 54.2355 23.3708 54.0545C19.8655 53.5477 16.577 52.4255 13.5414 50.5792C6.81987 46.5246 2.51952 40.6238 0.748782 32.8766C0.35127 31.139 0.170583 29.3651 0.170583 27.5912C0.134446 20.4957 2.44724 14.2691 7.1451 8.98363C11.2286 4.42224 16.2879 1.63472 22.2505 0.476271C23.9129 0.150457 25.5752 -0.0305508 27.2375 0.0418522C27.2375 2.75697 27.2375 5.43588 27.2375 8.15099C27.1652 8.18719 27.093 8.2234 27.0207 8.2958C26.045 8.98363 25.0693 9.70766 24.1297 10.4679C21.9976 12.2056 19.9739 14.0518 18.2754 16.2601C15.9988 19.1925 14.481 22.4144 14.2642 26.2156C14.1558 28.0256 14.3726 29.7995 14.9508 31.501C16.3601 35.7366 20.7328 40.1169 26.8761 40.2255C27.2375 40.2255 27.3098 40.298 27.3098 40.6962C27.2736 42.5424 27.2736 46.235 27.2736 46.235C27.2736 46.235 27.2736 46.4522 27.2736 46.5608C27.2375 49.1311 27.2375 51.7014 27.2375 54.3079Z" fill="#0099FF"/> -<path fill-rule="evenodd" clip-rule="evenodd" d="M27.2368 8.11469C27.2368 8.11469 27.2368 2.72066 27.2368 0.00554404C28.7184 -0.0306575 30.1639 0.114149 31.6094 0.331358C34.3197 0.765776 36.9216 1.56221 39.379 2.82926C44.4743 5.47197 48.4856 9.23693 51.1959 14.3775C52.7498 17.3461 53.7617 20.4956 54.1592 23.7899C54.6289 27.6635 54.2676 31.5009 53.1112 35.2296C51.7741 39.4652 49.5336 43.194 46.3896 46.3435C42.5591 50.1447 38.0057 52.6064 32.7297 53.7286C30.9228 54.0906 29.0798 54.3078 27.2368 54.2716C27.2368 51.6651 27.2368 49.0948 27.2368 46.4883C27.2368 46.3797 27.2368 46.1987 27.2368 46.1987C27.2368 46.1987 27.3452 46.1263 27.3813 46.0901C30.2001 44.099 32.8742 41.9269 35.187 39.3204C36.7048 37.6189 38.0057 35.8088 38.9092 33.7092C40.174 30.7406 40.6799 27.6997 40.0294 24.4778C38.873 18.6131 33.6331 14.2327 27.5982 14.0879C27.2007 14.0879 27.2368 13.7621 27.2368 13.7621V8.11469Z" fill="#0561E2"/> -<path d="M89.2508 35.5966C89.2508 37.0921 89.0055 38.5164 88.55 39.9051C88.0944 41.2937 87.3586 42.5044 86.4475 43.5726C85.5013 44.6408 84.3449 45.4598 82.9432 46.1007C81.5415 46.7061 79.8945 47.0265 78.0723 47.0265C75.1288 47.0265 72.7109 46.3144 70.8536 44.9257C68.9614 43.537 67.7349 41.3293 67.1392 38.3027L73.3416 36.8072C73.5519 38.0535 74.0425 39.0505 74.8485 39.7982C75.6194 40.546 76.6006 40.9021 77.757 40.9021C79.6492 40.9021 80.9458 40.2611 81.6116 38.9437C82.2774 37.6618 82.6278 35.8458 82.6278 33.5669V8.25005H89.2508V35.5966Z" fill="white"/> -<path d="M125.764 32.1782C125.764 34.4571 125.378 36.5223 124.607 38.3383C123.836 40.1899 122.785 41.721 121.453 43.0029C120.122 44.2848 118.545 45.2818 116.723 45.9583C114.901 46.6705 112.903 46.9909 110.766 46.9909C108.628 46.9909 106.631 46.6349 104.843 45.9583C103.021 45.2818 101.444 44.2848 100.078 43.0029C98.711 41.721 97.6597 40.1543 96.9238 38.3383C96.1529 36.5223 95.8025 34.4571 95.8025 32.1782V8.25005H102.425V31.9646C102.425 32.8904 102.566 33.8518 102.846 34.8844C103.126 35.8814 103.582 36.8428 104.248 37.6974C104.878 38.552 105.754 39.2641 106.841 39.7982C107.892 40.3679 109.224 40.6172 110.801 40.6172C112.377 40.6172 113.709 40.3323 114.76 39.7982C115.812 39.2641 116.688 38.552 117.353 37.6974C117.984 36.8428 118.475 35.917 118.755 34.8844C119.036 33.8518 119.176 32.8904 119.176 31.9646V8.25005H125.799V32.1782H125.764Z" fill="white"/> -<path d="M150.854 16.3685C150.153 15.3358 149.207 14.5881 148.051 14.0896C146.859 13.5911 145.633 13.3774 144.336 13.3774C143.565 13.3774 142.83 13.4843 142.094 13.6623C141.358 13.8403 140.727 14.1252 140.166 14.5169C139.571 14.9086 139.115 15.4071 138.765 16.048C138.414 16.6889 138.239 17.4011 138.239 18.2557C138.239 19.5375 138.66 20.5345 139.571 21.1755C140.447 21.852 141.533 22.4573 142.83 22.9202C144.126 23.4187 145.528 23.9172 147.07 24.3801C148.612 24.843 150.013 25.484 151.345 26.3029C152.641 27.1219 153.728 28.2257 154.604 29.5432C155.48 30.8963 155.935 32.7123 155.935 34.9199C155.935 36.9496 155.585 38.7299 154.849 40.2254C154.113 41.7566 153.132 43.0028 151.871 43.9998C150.609 44.9968 149.172 45.7446 147.525 46.2431C145.878 46.7416 144.126 46.9908 142.339 46.9908C140.026 46.9908 137.784 46.5992 135.681 45.8158C133.543 45.0324 131.686 43.715 130.144 41.8634L135.155 36.9496C135.961 38.1958 137.013 39.1572 138.344 39.8694C139.676 40.5815 141.042 40.902 142.514 40.902C143.285 40.902 144.056 40.7952 144.827 40.5815C145.598 40.3679 146.299 40.0474 146.93 39.6201C147.56 39.1928 148.051 38.6587 148.436 37.9822C148.822 37.3412 149.032 36.5579 149.032 35.7033C149.032 34.3146 148.577 33.2464 147.7 32.4986C146.824 31.7509 145.738 31.1099 144.442 30.6114C143.145 30.1129 141.708 29.6144 140.166 29.1515C138.625 28.6886 137.188 28.0477 135.926 27.2643C134.63 26.481 133.543 25.4127 132.667 24.0597C131.791 22.7066 131.336 20.9262 131.336 18.6829C131.336 16.7245 131.721 15.051 132.527 13.6267C133.298 12.2024 134.349 11.0273 135.646 10.0659C136.907 9.14016 138.379 8.42801 140.026 7.96511C141.673 7.50222 143.355 7.28857 145.072 7.28857C147.035 7.28857 148.927 7.60904 150.784 8.17876C152.606 8.78408 154.288 9.78109 155.76 11.1698L150.854 16.3685Z" fill="white"/> -<path d="M173.983 8.25005C175.77 8.25005 177.487 8.42809 179.169 8.78416C180.816 9.14024 182.288 9.74556 183.549 10.5645C184.811 11.4191 185.827 12.5229 186.563 13.9116C187.299 15.3359 187.684 17.0807 187.684 19.1815C187.684 21.5672 187.264 23.49 186.458 24.9499C185.652 26.4098 184.566 27.5493 183.199 28.3326C181.832 29.116 180.255 29.6857 178.433 29.9706C176.611 30.2554 174.754 30.3979 172.791 30.3979H168.061V46.0651H161.438V8.25005H173.983ZM172.091 24.6651C173.037 24.6651 174.018 24.6295 175.034 24.5583C176.05 24.487 176.997 24.2734 177.838 23.9173C178.679 23.5612 179.379 23.0271 179.94 22.315C180.466 21.6028 180.746 20.6058 180.746 19.324C180.746 18.1489 180.501 17.2231 180.01 16.511C179.52 15.7988 178.889 15.2647 178.118 14.9086C177.347 14.517 176.471 14.3033 175.525 14.1965C174.579 14.0897 173.668 14.0185 172.791 14.0185H168.061V24.6651H172.091Z" fill="white"/> -<path d="M200.404 8.25005H206.116L222.166 46.0651H214.596L211.127 37.4125H195.008L191.644 46.0651H184.215L200.404 8.25005ZM208.814 31.6441L203.068 16.2617L197.251 31.6441H208.814Z" fill="white"/> -<path d="M230.225 29.8994L216.243 8.25005H224.548L233.694 23.312L242.945 8.25005H250.83L236.848 29.8994V46.1007H230.225V29.8994Z" fill="white"/> -<path d="M266.826 46.6572V8.06836H271.566V24.5336L270.7 24.0748C271.379 22.3417 272.467 20.9993 273.962 20.0477C275.492 19.0622 277.276 18.5694 279.315 18.5694C281.286 18.5694 283.036 19.0112 284.565 19.8948C286.129 20.7784 287.352 22.0018 288.236 23.5651C289.153 25.1283 289.612 26.8955 289.612 28.8666V46.6572H284.82V30.3959C284.82 28.8666 284.531 27.5752 283.954 26.5217C283.41 25.4682 282.645 24.6526 281.66 24.0748C280.674 23.4631 279.536 23.1573 278.244 23.1573C276.987 23.1573 275.848 23.4631 274.829 24.0748C273.809 24.6526 273.011 25.4852 272.433 26.5727C271.855 27.6262 271.566 28.9006 271.566 30.3959V46.6572H266.826Z" fill="#B1B0B6"/> -<path d="M295.847 57.872C295.235 57.872 294.624 57.821 294.012 57.719C293.4 57.6171 292.822 57.4472 292.279 57.2093V52.9783C292.652 53.0462 293.111 53.1142 293.655 53.1822C294.233 53.2841 294.793 53.3351 295.337 53.3351C296.934 53.3351 298.141 52.9783 298.956 52.2646C299.806 51.5849 300.605 50.3955 301.352 48.6963L303.086 44.5672L302.984 48.6963L291.259 19.1811H296.408L305.532 42.6301H304.003L313.077 19.1811H318.327L305.94 49.9197C305.362 51.381 304.615 52.7064 303.697 53.8958C302.814 55.1193 301.726 56.0878 300.435 56.8015C299.143 57.5151 297.614 57.872 295.847 57.872Z" fill="#B1B0B6"/> -<path d="M321.016 56.8525V19.1811H325.654V25.0944L325.043 23.9219C326.062 22.2907 327.456 20.9993 329.223 20.0477C330.99 19.0622 333.012 18.5694 335.289 18.5694C337.872 18.5694 340.183 19.1981 342.222 20.4555C344.295 21.713 345.926 23.4291 347.115 25.6041C348.305 27.7451 348.899 30.192 348.899 32.9447C348.899 35.6294 348.305 38.0593 347.115 40.2343C345.926 42.4092 344.295 44.1254 342.222 45.3828C340.183 46.6402 337.855 47.269 335.238 47.269C333.029 47.269 331.007 46.7762 329.172 45.7906C327.371 44.8051 325.977 43.4118 324.992 41.6106L325.756 40.795V56.8525H321.016ZM334.881 42.6811C336.614 42.6811 338.161 42.2563 339.52 41.4067C340.879 40.5571 341.933 39.4016 342.68 37.9403C343.462 36.445 343.853 34.7798 343.853 32.9447C343.853 31.0416 343.462 29.3764 342.68 27.949C341.933 26.4877 340.879 25.3323 339.52 24.4827C338.161 23.5991 336.614 23.1573 334.881 23.1573C333.148 23.1573 331.585 23.5821 330.191 24.4317C328.832 25.2813 327.744 26.4537 326.929 27.949C326.147 29.4103 325.756 31.0756 325.756 32.9447C325.756 34.7798 326.147 36.445 326.929 37.9403C327.744 39.4016 328.832 40.5571 330.191 41.4067C331.585 42.2563 333.148 42.6811 334.881 42.6811Z" fill="#B1B0B6"/> -<path d="M366.229 47.269C363.578 47.269 361.216 46.6402 359.143 45.3828C357.07 44.1254 355.439 42.4092 354.249 40.2343C353.06 38.0253 352.465 35.5614 352.465 32.8427C352.465 30.09 353.043 27.6432 354.198 25.5022C355.388 23.3612 356.985 21.679 358.99 20.4555C361.029 19.1981 363.306 18.5694 365.821 18.5694C367.86 18.5694 369.661 18.9433 371.224 19.6909C372.821 20.4046 374.164 21.3901 375.251 22.6475C376.373 23.8709 377.222 25.2813 377.8 26.8785C378.412 28.4418 378.718 30.073 378.718 31.7722C378.718 32.1461 378.684 32.5709 378.616 33.0466C378.582 33.4884 378.531 33.9132 378.463 34.321H355.931V30.2429H375.71L373.467 32.0781C373.773 30.3109 373.603 28.7307 372.957 27.3373C372.312 25.944 371.36 24.8395 370.103 24.0239C368.845 23.2082 367.418 22.8004 365.821 22.8004C364.223 22.8004 362.762 23.2082 361.437 24.0239C360.111 24.8395 359.075 26.0119 358.327 27.5412C357.614 29.0365 357.325 30.8207 357.461 32.8937C357.325 34.8988 357.631 36.6659 358.378 38.1952C359.16 39.6905 360.247 40.863 361.641 41.7126C363.068 42.5282 364.614 42.936 366.28 42.936C368.115 42.936 369.661 42.5112 370.918 41.6616C372.176 40.812 373.195 39.7245 373.977 38.3991L377.953 40.4382C377.409 41.6956 376.56 42.851 375.404 43.9045C374.283 44.924 372.94 45.7397 371.377 46.3514C369.848 46.9631 368.132 47.269 366.229 47.269Z" fill="#B1B0B6"/> -<path d="M383.37 46.6572V19.1811H388.008V24.2278L387.499 23.5141C388.144 21.9508 389.13 20.7954 390.455 20.0477C391.781 19.2661 393.395 18.8753 395.298 18.8753H396.98V23.3612H394.584C392.647 23.3612 391.084 23.9729 389.895 25.1963C388.705 26.3858 388.11 28.085 388.11 30.2939V46.6572H383.37Z" fill="#B1B0B6"/> -<path d="M409.5 47.269C406.748 47.269 404.352 46.5893 402.313 45.2299C400.274 43.8705 398.829 42.0354 397.98 39.7245L401.752 37.8894C402.534 39.5206 403.604 40.812 404.964 41.7635C406.323 42.7151 407.835 43.1909 409.5 43.1909C410.996 43.1909 412.236 42.834 413.222 42.1204C414.207 41.4067 414.7 40.4721 414.7 39.3167C414.7 38.5011 414.462 37.8554 413.986 37.3796C413.545 36.8698 413.001 36.479 412.355 36.2071C411.709 35.9013 411.115 35.6804 410.571 35.5445L406.442 34.372C403.961 33.6583 402.143 32.6388 400.987 31.3134C399.866 29.9881 399.305 28.4418 399.305 26.6746C399.305 25.0434 399.713 23.633 400.529 22.4436C401.378 21.2202 402.517 20.2686 403.944 19.5889C405.405 18.9093 407.037 18.5694 408.838 18.5694C411.251 18.5694 413.409 19.1811 415.312 20.4046C417.249 21.628 418.625 23.3442 419.441 25.5531L415.567 27.3373C414.955 25.91 414.037 24.7885 412.814 23.9729C411.59 23.1233 410.214 22.6985 408.685 22.6985C407.291 22.6985 406.187 23.0553 405.371 23.769C404.556 24.4487 404.148 25.3153 404.148 26.3688C404.148 27.1504 404.352 27.7961 404.76 28.3059C405.167 28.7816 405.66 29.1555 406.238 29.4273C406.816 29.6652 407.376 29.8691 407.92 30.039L412.406 31.3644C414.649 32.0101 416.382 33.0126 417.606 34.372C418.863 35.7314 419.492 37.3626 419.492 39.2657C419.492 40.795 419.067 42.1713 418.217 43.3948C417.368 44.6182 416.195 45.5697 414.7 46.2494C413.205 46.9291 411.472 47.269 409.5 47.269Z" fill="#B1B0B6"/> -<path d="M429.992 46.6572L420.561 19.1811H425.812L433.305 42.1713L431.47 42.1204L438.81 19.1811H443.296L450.637 42.1204L448.802 42.1713L456.346 19.1811H461.546L452.115 46.6572H447.578L440.34 23.718H441.767L434.528 46.6572H429.992Z" fill="#B1B0B6"/> -<path d="M464.256 46.6572V19.1811H468.997V46.6572H464.256ZM464.256 14.7972V8.68007H468.997V14.7972H464.256Z" fill="#B1B0B6"/> -<path d="M485.988 46.9631C483.303 46.9631 481.23 46.1985 479.769 44.6692C478.341 43.1399 477.628 40.9819 477.628 38.1952V23.718H472.632V19.1811H473.651C474.875 19.1811 475.843 18.8073 476.557 18.0597C477.271 17.312 477.628 16.3265 477.628 15.1031V12.8601H482.368V19.1811H488.536V23.718H482.368V38.0423C482.368 38.9599 482.504 39.7585 482.776 40.4382C483.082 41.1178 483.575 41.6616 484.254 42.0694C484.934 42.4432 485.835 42.6301 486.956 42.6301C487.194 42.6301 487.483 42.6131 487.823 42.5792C488.197 42.5452 488.536 42.5112 488.842 42.4772V46.6572C488.401 46.7592 487.908 46.8272 487.364 46.8611C486.82 46.9291 486.361 46.9631 485.988 46.9631Z" fill="#B1B0B6"/> -<path d="M505.503 47.269C502.818 47.269 500.422 46.6402 498.315 45.3828C496.242 44.1254 494.611 42.4092 493.422 40.2343C492.232 38.0593 491.638 35.6124 491.638 32.8937C491.638 30.141 492.232 27.6941 493.422 25.5531C494.611 23.4122 496.242 21.713 498.315 20.4555C500.422 19.1981 502.818 18.5694 505.503 18.5694C507.304 18.5694 508.986 18.8923 510.55 19.538C512.113 20.1837 513.489 21.0503 514.679 22.1378C515.868 23.2252 516.735 24.4996 517.279 25.961L513.048 28C512.402 26.5727 511.416 25.4172 510.091 24.5336C508.766 23.6161 507.236 23.1573 505.503 23.1573C503.838 23.1573 502.326 23.5821 500.966 24.4317C499.641 25.2813 498.587 26.4367 497.806 27.898C497.024 29.3594 496.633 31.0416 496.633 32.9447C496.633 34.7798 497.024 36.445 497.806 37.9403C498.587 39.4016 499.641 40.5571 500.966 41.4067C502.326 42.2563 503.838 42.6811 505.503 42.6811C507.236 42.6811 508.766 42.2393 510.091 41.3557C511.416 40.4382 512.402 39.2317 513.048 37.7364L517.279 39.8774C516.735 41.3048 515.868 42.5792 514.679 43.7006C513.489 44.7881 512.113 45.6547 510.55 46.3004C508.986 46.9461 507.304 47.269 505.503 47.269Z" fill="#B1B0B6"/> -<path d="M521.945 46.6572V8.06836H526.686V24.5336L525.819 24.0748C526.499 22.3417 527.586 20.9993 529.082 20.0477C530.611 19.0622 532.395 18.5694 534.434 18.5694C536.405 18.5694 538.155 19.0112 539.685 19.8948C541.248 20.7784 542.471 22.0018 543.355 23.5651C544.272 25.1283 544.731 26.8955 544.731 28.8666V46.6572H539.939V30.3959C539.939 28.8666 539.651 27.5752 539.073 26.5217C538.529 25.4682 537.764 24.6526 536.779 24.0748C535.793 23.4631 534.655 23.1573 533.363 23.1573C532.106 23.1573 530.968 23.4631 529.948 24.0748C528.929 24.6526 528.13 25.4852 527.552 26.5727C526.975 27.6262 526.686 28.9006 526.686 30.3959V46.6572H521.945Z" fill="#B1B0B6"/> -</svg> diff --git a/api-reference-v2/logo/light.svg b/api-reference-v2/logo/light.svg deleted file mode 100644 index 66b2c279d06..00000000000 --- a/api-reference-v2/logo/light.svg +++ /dev/null @@ -1,21 +0,0 @@ -<svg width="545" height="58" viewBox="0 0 545 58" fill="none" xmlns="http://www.w3.org/2000/svg"> -<path fill-rule="evenodd" clip-rule="evenodd" d="M27.0673 54.3079C25.7664 54.3441 24.5016 54.2355 23.2006 54.0545C19.6953 53.5477 16.4068 52.4255 13.3713 50.5792C6.6497 46.5246 2.34935 40.6238 0.578616 32.8766C0.181104 31.139 0.000416954 29.3651 0.000416954 27.5912C-0.0357205 20.4957 2.27707 14.2691 6.97494 8.98363C11.0585 4.42224 16.1177 1.63472 22.0804 0.476271C23.7427 0.150457 25.405 -0.0305508 27.0673 0.0418522C27.0673 2.75697 27.0673 5.43588 27.0673 8.15099C26.9951 8.18719 26.9228 8.2234 26.8505 8.2958C25.8748 8.98363 24.8991 9.70766 23.9595 10.4679C21.8274 12.2056 19.8037 14.0518 18.1053 16.2601C15.8286 19.1925 14.3108 22.4144 14.094 26.2156C13.9856 28.0256 14.2024 29.7995 14.7806 31.501C16.19 35.7366 20.5626 40.1169 26.706 40.2255C27.0673 40.2255 27.1396 40.298 27.1396 40.6962C27.1035 42.5424 27.1035 46.235 27.1035 46.235C27.1035 46.235 27.1035 46.4522 27.1035 46.5608C27.0673 49.1311 27.0673 51.7014 27.0673 54.3079Z" fill="#0099FF"/> -<path fill-rule="evenodd" clip-rule="evenodd" d="M27.0666 8.11469C27.0666 8.11469 27.0666 2.72066 27.0666 0.00554404C28.5483 -0.0306575 29.9938 0.114149 31.4393 0.331358C34.1496 0.765776 36.7515 1.56221 39.2088 2.82926C44.3042 5.47197 48.3154 9.23693 51.0257 14.3775C52.5796 17.3461 53.5915 20.4956 53.989 23.7899C54.4588 27.6635 54.0974 31.5009 52.941 35.2296C51.6039 39.4652 49.3634 43.194 46.2195 46.3435C42.3889 50.1447 37.8356 52.6064 32.5595 53.7286C30.7526 54.0906 28.9096 54.3078 27.0666 54.2716C27.0666 51.6651 27.0666 49.0948 27.0666 46.4883C27.0666 46.3797 27.0666 46.1987 27.0666 46.1987C27.0666 46.1987 27.175 46.1263 27.2112 46.0901C30.0299 44.099 32.7041 41.9269 35.0169 39.3204C36.5346 37.6189 37.8356 35.8088 38.739 33.7092C40.0038 30.7406 40.5097 27.6997 39.8593 24.4778C38.7029 18.6131 33.463 14.2327 27.428 14.0879C27.0305 14.0879 27.0666 13.7621 27.0666 13.7621V8.11469Z" fill="#0561E2"/> -<path d="M89.0807 35.5966C89.0807 37.0921 88.8354 38.5164 88.3798 39.9051C87.9243 41.2937 87.1884 42.5044 86.2773 43.5726C85.3311 44.6408 84.1748 45.4598 82.7731 46.1007C81.3714 46.7061 79.7244 47.0265 77.9022 47.0265C74.9586 47.0265 72.5407 46.3144 70.6835 44.9257C68.7912 43.537 67.5647 41.3293 66.969 38.3027L73.1715 36.8072C73.3817 38.0535 73.8723 39.0505 74.6783 39.7982C75.4492 40.546 76.4304 40.9021 77.5868 40.9021C79.4791 40.9021 80.7757 40.2611 81.4415 38.9437C82.1073 37.6618 82.4577 35.8458 82.4577 33.5669V8.25005H89.0807V35.5966Z" fill="#1C1C1C"/> -<path d="M125.593 32.1782C125.593 34.4571 125.208 36.5223 124.437 38.3383C123.666 40.1899 122.615 41.721 121.283 43.0029C119.952 44.2848 118.375 45.2818 116.553 45.9583C114.73 46.6705 112.733 46.9909 110.595 46.9909C108.458 46.9909 106.46 46.6349 104.673 45.9583C102.851 45.2818 101.274 44.2848 99.9075 43.0029C98.5408 41.721 97.4895 40.1543 96.7536 38.3383C95.9827 36.5223 95.6323 34.4571 95.6323 32.1782V8.25005H102.255V31.9646C102.255 32.8904 102.395 33.8518 102.676 34.8844C102.956 35.8814 103.412 36.8428 104.077 37.6974C104.708 38.552 105.584 39.2641 106.671 39.7982C107.722 40.3679 109.053 40.6172 110.63 40.6172C112.207 40.6172 113.539 40.3323 114.59 39.7982C115.641 39.2641 116.518 38.552 117.183 37.6974C117.814 36.8428 118.305 35.917 118.585 34.8844C118.865 33.8518 119.006 32.8904 119.006 31.9646V8.25005H125.629V32.1782H125.593Z" fill="#1C1C1C"/> -<path d="M150.684 16.3685C149.983 15.3358 149.037 14.5881 147.881 14.0896C146.689 13.5911 145.463 13.3774 144.166 13.3774C143.395 13.3774 142.659 13.4843 141.924 13.6623C141.188 13.8403 140.557 14.1252 139.996 14.5169C139.4 14.9086 138.945 15.4071 138.595 16.048C138.244 16.6889 138.069 17.4011 138.069 18.2557C138.069 19.5375 138.489 20.5345 139.4 21.1755C140.277 21.852 141.363 22.4573 142.659 22.9202C143.956 23.4187 145.358 23.9172 146.9 24.3801C148.441 24.843 149.843 25.484 151.175 26.3029C152.471 27.1219 153.558 28.2257 154.434 29.5432C155.31 30.8963 155.765 32.7123 155.765 34.9199C155.765 36.9496 155.415 38.7299 154.679 40.2254C153.943 41.7566 152.962 43.0028 151.7 43.9998C150.439 44.9968 149.002 45.7446 147.355 46.2431C145.708 46.7416 143.956 46.9908 142.169 46.9908C139.856 46.9908 137.613 46.5992 135.511 45.8158C133.373 45.0324 131.516 43.715 129.974 41.8634L134.985 36.9496C135.791 38.1958 136.842 39.1572 138.174 39.8694C139.506 40.5815 140.872 40.902 142.344 40.902C143.115 40.902 143.886 40.7952 144.657 40.5815C145.428 40.3679 146.129 40.0474 146.759 39.6201C147.39 39.1928 147.881 38.6587 148.266 37.9822C148.652 37.3412 148.862 36.5579 148.862 35.7033C148.862 34.3146 148.406 33.2464 147.53 32.4986C146.654 31.7509 145.568 31.1099 144.271 30.6114C142.975 30.1129 141.538 29.6144 139.996 29.1515C138.454 28.6886 137.018 28.0477 135.756 27.2643C134.46 26.481 133.373 25.4127 132.497 24.0597C131.621 22.7066 131.166 20.9262 131.166 18.6829C131.166 16.7245 131.551 15.051 132.357 13.6267C133.128 12.2024 134.179 11.0273 135.476 10.0659C136.737 9.14016 138.209 8.42801 139.856 7.96511C141.503 7.50222 143.185 7.28857 144.902 7.28857C146.865 7.28857 148.757 7.60904 150.614 8.17876C152.436 8.78408 154.118 9.78109 155.59 11.1698L150.684 16.3685Z" fill="#1C1C1C"/> -<path d="M173.813 8.25005C175.6 8.25005 177.317 8.42809 178.999 8.78416C180.646 9.14024 182.118 9.74556 183.379 10.5645C184.641 11.4191 185.657 12.5229 186.393 13.9116C187.129 15.3359 187.514 17.0807 187.514 19.1815C187.514 21.5672 187.094 23.49 186.288 24.9499C185.482 26.4098 184.396 27.5493 183.029 28.3326C181.662 29.116 180.085 29.6857 178.263 29.9706C176.441 30.2554 174.584 30.3979 172.621 30.3979H167.891V46.0651H161.268V8.25005H173.813ZM171.92 24.6651C172.867 24.6651 173.848 24.6295 174.864 24.5583C175.88 24.487 176.826 24.2734 177.667 23.9173C178.508 23.5612 179.209 23.0271 179.77 22.315C180.296 21.6028 180.576 20.6058 180.576 19.324C180.576 18.1489 180.331 17.2231 179.84 16.511C179.349 15.7988 178.719 15.2647 177.948 14.9086C177.177 14.517 176.301 14.3033 175.355 14.1965C174.408 14.0897 173.497 14.0185 172.621 14.0185H167.891V24.6651H171.92Z" fill="#1C1C1C"/> -<path d="M200.234 8.25005H205.946L221.995 46.0651H214.426L210.957 37.4125H194.838L191.474 46.0651H184.045L200.234 8.25005ZM208.644 31.6441L202.897 16.2617L197.08 31.6441H208.644Z" fill="#1C1C1C"/> -<path d="M230.055 29.8994L216.073 8.25005H224.378L233.524 23.312L242.775 8.25005H250.66L236.678 29.8994V46.1007H230.055V29.8994Z" fill="#1C1C1C"/> -<path d="M266.655 46.6572V8.06836H271.396V24.5336L270.53 24.0748C271.209 22.3417 272.297 20.9993 273.792 20.0477C275.321 19.0622 277.106 18.5694 279.145 18.5694C281.116 18.5694 282.866 19.0112 284.395 19.8948C285.958 20.7784 287.182 22.0018 288.065 23.5651C288.983 25.1283 289.442 26.8955 289.442 28.8666V46.6572H284.65V30.3959C284.65 28.8666 284.361 27.5752 283.783 26.5217C283.24 25.4682 282.475 24.6526 281.489 24.0748C280.504 23.4631 279.365 23.1573 278.074 23.1573C276.817 23.1573 275.678 23.4631 274.659 24.0748C273.639 24.6526 272.841 25.4852 272.263 26.5727C271.685 27.6262 271.396 28.9006 271.396 30.3959V46.6572H266.655Z" fill="#7D7B86"/> -<path d="M295.677 57.872C295.065 57.872 294.453 57.821 293.842 57.719C293.23 57.6171 292.652 57.4472 292.108 57.2093V52.9783C292.482 53.0462 292.941 53.1142 293.485 53.1822C294.063 53.2841 294.623 53.3351 295.167 53.3351C296.764 53.3351 297.971 52.9783 298.786 52.2646C299.636 51.5849 300.435 50.3955 301.182 48.6963L302.915 44.5672L302.813 48.6963L291.089 19.1811H296.237L305.362 42.6301H303.833L312.907 19.1811H318.157L305.77 49.9197C305.192 51.381 304.445 52.7064 303.527 53.8958C302.643 55.1193 301.556 56.0878 300.265 56.8015C298.973 57.5151 297.444 57.872 295.677 57.872Z" fill="#7D7B86"/> -<path d="M320.845 56.8525V19.1811H325.484V25.0944L324.873 23.9219C325.892 22.2907 327.285 20.9993 329.053 20.0477C330.82 19.0622 332.842 18.5694 335.119 18.5694C337.701 18.5694 340.012 19.1981 342.051 20.4555C344.124 21.713 345.756 23.4291 346.945 25.6041C348.135 27.7451 348.729 30.192 348.729 32.9447C348.729 35.6294 348.135 38.0593 346.945 40.2343C345.756 42.4092 344.124 44.1254 342.051 45.3828C340.012 46.6402 337.684 47.269 335.068 47.269C332.859 47.269 330.837 46.7762 329.002 45.7906C327.2 44.8051 325.807 43.4118 324.822 41.6106L325.586 40.795V56.8525H320.845ZM334.711 42.6811C336.444 42.6811 337.99 42.2563 339.35 41.4067C340.709 40.5571 341.763 39.4016 342.51 37.9403C343.292 36.445 343.683 34.7798 343.683 32.9447C343.683 31.0416 343.292 29.3764 342.51 27.949C341.763 26.4877 340.709 25.3323 339.35 24.4827C337.99 23.5991 336.444 23.1573 334.711 23.1573C332.978 23.1573 331.414 23.5821 330.021 24.4317C328.662 25.2813 327.574 26.4537 326.759 27.949C325.977 29.4103 325.586 31.0756 325.586 32.9447C325.586 34.7798 325.977 36.445 326.759 37.9403C327.574 39.4016 328.662 40.5571 330.021 41.4067C331.414 42.2563 332.978 42.6811 334.711 42.6811Z" fill="#7D7B86"/> -<path d="M366.058 47.269C363.408 47.269 361.046 46.6402 358.973 45.3828C356.9 44.1254 355.268 42.4092 354.079 40.2343C352.89 38.0253 352.295 35.5614 352.295 32.8427C352.295 30.09 352.873 27.6432 354.028 25.5022C355.217 23.3612 356.815 21.679 358.82 20.4555C360.859 19.1981 363.136 18.5694 365.651 18.5694C367.69 18.5694 369.491 18.9433 371.054 19.6909C372.651 20.4046 373.994 21.3901 375.081 22.6475C376.203 23.8709 377.052 25.2813 377.63 26.8785C378.242 28.4418 378.548 30.073 378.548 31.7722C378.548 32.1461 378.514 32.5709 378.446 33.0466C378.412 33.4884 378.361 33.9132 378.293 34.321H355.761V30.2429H375.54L373.297 32.0781C373.603 30.3109 373.433 28.7307 372.787 27.3373C372.142 25.944 371.19 24.8395 369.933 24.0239C368.675 23.2082 367.248 22.8004 365.651 22.8004C364.053 22.8004 362.592 23.2082 361.267 24.0239C359.941 24.8395 358.905 26.0119 358.157 27.5412C357.443 29.0365 357.155 30.8207 357.29 32.8937C357.155 34.8988 357.46 36.6659 358.208 38.1952C358.99 39.6905 360.077 40.863 361.471 41.7126C362.898 42.5282 364.444 42.936 366.109 42.936C367.944 42.936 369.491 42.5112 370.748 41.6616C372.006 40.812 373.025 39.7245 373.807 38.3991L377.783 40.4382C377.239 41.6956 376.39 42.851 375.234 43.9045C374.113 44.924 372.77 45.7397 371.207 46.3514C369.678 46.9631 367.961 47.269 366.058 47.269Z" fill="#7D7B86"/> -<path d="M383.199 46.6572V19.1811H387.838V24.2278L387.329 23.5141C387.974 21.9508 388.96 20.7954 390.285 20.0477C391.611 19.2661 393.225 18.8753 395.128 18.8753H396.81V23.3612H394.414C392.477 23.3612 390.914 23.9729 389.724 25.1963C388.535 26.3858 387.94 28.085 387.94 30.2939V46.6572H383.199Z" fill="#7D7B86"/> -<path d="M409.33 47.269C406.578 47.269 404.182 46.5893 402.143 45.2299C400.104 43.8705 398.659 42.0354 397.81 39.7245L401.582 37.8894C402.364 39.5206 403.434 40.812 404.793 41.7635C406.153 42.7151 407.665 43.1909 409.33 43.1909C410.826 43.1909 412.066 42.834 413.052 42.1204C414.037 41.4067 414.53 40.4721 414.53 39.3167C414.53 38.5011 414.292 37.8554 413.816 37.3796C413.374 36.8698 412.831 36.479 412.185 36.2071C411.539 35.9013 410.945 35.6804 410.401 35.5445L406.272 34.372C403.791 33.6583 401.973 32.6388 400.817 31.3134C399.696 29.9881 399.135 28.4418 399.135 26.6746C399.135 25.0434 399.543 23.633 400.358 22.4436C401.208 21.2202 402.347 20.2686 403.774 19.5889C405.235 18.9093 406.866 18.5694 408.668 18.5694C411.08 18.5694 413.238 19.1811 415.142 20.4046C417.079 21.628 418.455 23.3442 419.271 25.5531L415.396 27.3373C414.785 25.91 413.867 24.7885 412.644 23.9729C411.42 23.1233 410.044 22.6985 408.515 22.6985C407.121 22.6985 406.017 23.0553 405.201 23.769C404.386 24.4487 403.978 25.3153 403.978 26.3688C403.978 27.1504 404.182 27.7961 404.59 28.3059C404.997 28.7816 405.49 29.1555 406.068 29.4273C406.646 29.6652 407.206 29.8691 407.75 30.039L412.236 31.3644C414.479 32.0101 416.212 33.0126 417.435 34.372C418.693 35.7314 419.322 37.3626 419.322 39.2657C419.322 40.795 418.897 42.1713 418.047 43.3948C417.198 44.6182 416.025 45.5697 414.53 46.2494C413.035 46.9291 411.301 47.269 409.33 47.269Z" fill="#7D7B86"/> -<path d="M429.821 46.6572L420.391 19.1811H425.641L433.135 42.1713L431.3 42.1204L438.64 19.1811H443.126L450.467 42.1204L448.632 42.1713L456.176 19.1811H461.376L451.945 46.6572H447.408L440.17 23.718H441.597L434.358 46.6572H429.821Z" fill="#7D7B86"/> -<path d="M464.086 46.6572V19.1811H468.827V46.6572H464.086ZM464.086 14.7972V8.68007H468.827V14.7972H464.086Z" fill="#7D7B86"/> -<path d="M485.817 46.9631C483.133 46.9631 481.06 46.1985 479.598 44.6692C478.171 43.1399 477.457 40.9819 477.457 38.1952V23.718H472.462V19.1811H473.481C474.705 19.1811 475.673 18.8073 476.387 18.0597C477.101 17.312 477.457 16.3265 477.457 15.1031V12.8601H482.198V19.1811H488.366V23.718H482.198V38.0423C482.198 38.9599 482.334 39.7585 482.606 40.4382C482.912 41.1178 483.405 41.6616 484.084 42.0694C484.764 42.4432 485.665 42.6301 486.786 42.6301C487.024 42.6301 487.313 42.6131 487.653 42.5792C488.026 42.5452 488.366 42.5112 488.672 42.4772V46.6572C488.23 46.7592 487.738 46.8272 487.194 46.8611C486.65 46.9291 486.191 46.9631 485.817 46.9631Z" fill="#7D7B86"/> -<path d="M505.333 47.269C502.648 47.269 500.252 46.6402 498.145 45.3828C496.072 44.1254 494.441 42.4092 493.252 40.2343C492.062 38.0593 491.467 35.6124 491.467 32.8937C491.467 30.141 492.062 27.6941 493.252 25.5531C494.441 23.4122 496.072 21.713 498.145 20.4555C500.252 19.1981 502.648 18.5694 505.333 18.5694C507.134 18.5694 508.816 18.8923 510.38 19.538C511.943 20.1837 513.319 21.0503 514.509 22.1378C515.698 23.2252 516.565 24.4996 517.108 25.961L512.877 28C512.232 26.5727 511.246 25.4172 509.921 24.5336C508.595 23.6161 507.066 23.1573 505.333 23.1573C503.668 23.1573 502.155 23.5821 500.796 24.4317C499.471 25.2813 498.417 26.4367 497.636 27.898C496.854 29.3594 496.463 31.0416 496.463 32.9447C496.463 34.7798 496.854 36.445 497.636 37.9403C498.417 39.4016 499.471 40.5571 500.796 41.4067C502.155 42.2563 503.668 42.6811 505.333 42.6811C507.066 42.6811 508.595 42.2393 509.921 41.3557C511.246 40.4382 512.232 39.2317 512.877 37.7364L517.108 39.8774C516.565 41.3048 515.698 42.5792 514.509 43.7006C513.319 44.7881 511.943 45.6547 510.38 46.3004C508.816 46.9461 507.134 47.269 505.333 47.269Z" fill="#7D7B86"/> -<path d="M521.775 46.6572V8.06836H526.515V24.5336L525.649 24.0748C526.329 22.3417 527.416 20.9993 528.911 20.0477C530.441 19.0622 532.225 18.5694 534.264 18.5694C536.235 18.5694 537.985 19.0112 539.514 19.8948C541.078 20.7784 542.301 22.0018 543.185 23.5651C544.102 25.1283 544.561 26.8955 544.561 28.8666V46.6572H539.769V30.3959C539.769 28.8666 539.48 27.5752 538.903 26.5217C538.359 25.4682 537.594 24.6526 536.609 24.0748C535.623 23.4631 534.485 23.1573 533.193 23.1573C531.936 23.1573 530.797 23.4631 529.778 24.0748C528.758 24.6526 527.96 25.4852 527.382 26.5727C526.804 27.6262 526.515 28.9006 526.515 30.3959V46.6572H521.775Z" fill="#7D7B86"/> -</svg> diff --git a/api-reference-v2/mint.json b/api-reference-v2/mint.json deleted file mode 100644 index 8c49d3dd708..00000000000 --- a/api-reference-v2/mint.json +++ /dev/null @@ -1,163 +0,0 @@ -{ - "$schema": "https://mintlify.com/schema.json", - "name": "Hyperswitch", - "logo": { - "dark": "/logo/dark.svg", - "light": "/logo/light.svg" - }, - "favicon": "/favicon.png", - "colors": { - "primary": "#006DF9", - "light": "#006DF9", - "dark": "#006DF9", - "background": { - "dark": "#242F48" - } - }, - "tabs": [ - { - "name": "API Reference", - "url": "api-reference" - } - ], - "navigation": [ - { - "group": "Get Started", - "pages": ["introduction"] - }, - { - "group": "Essentials", - "pages": [ - "essentials/error_codes", - "essentials/rate_limit", - "essentials/go-live" - ] - }, - { - "group": "Payments", - "pages": [ - "api-reference/payments/payments--create-intent", - "api-reference/payments/payments--get-intent", - "api-reference/payments/payments--update-intent", - "api-reference/payments/payments--session-token", - "api-reference/payments/payments--payment-methods-list", - "api-reference/payments/payments--confirm-intent", - "api-reference/payments/payments--get", - "api-reference/payments/payments--create-and-confirm-intent", - "api-reference/payments/payments--list" - ] - }, - { - "group": "Payment Methods", - "pages": [ - "api-reference/payment-methods/payment-method--create", - "api-reference/payment-methods/payment-method--create-intent", - "api-reference/payment-methods/payment-method--payment-methods-list", - "api-reference/payment-methods/payment-method--confirm-intent", - "api-reference/payment-methods/payment-method--update", - "api-reference/payment-methods/payment-method--retrieve", - "api-reference/payment-methods/payment-method--delete", - "api-reference/payment-methods/list-saved-payment-methods-for-a-customer" - ] - }, - { - "group": "Payment Method Session", - "pages": [ - "api-reference/payment-method-session/payment-method-session--create", - "api-reference/payment-method-session/payment-method-session--retrieve", - "api-reference/payment-method-session/payment-method-session--list-payment-methods", - "api-reference/payment-method-session/payment-method-session--update-a-saved-payment-method", - "api-reference/payment-method-session/payment-method-session--confirm-a-payment-method-session", - "api-reference/payment-method-session/payment-method-session--delete-a-saved-payment-method" - ] - }, - { - "group": "Organization", - "pages": [ - "api-reference/organization/organization--create", - "api-reference/organization/organization--retrieve", - "api-reference/organization/organization--update", - "api-reference/organization/organization--merchant-account--list" - ] - }, - { - "group": "Merchant Account", - "pages": [ - "api-reference/merchant-account/merchant-account--create", - "api-reference/merchant-account/merchant-account--retrieve", - "api-reference/merchant-account/merchant-account--update", - "api-reference/merchant-account/business-profile--list" - ] - }, - { - "group": "Profile", - "pages": [ - "api-reference/profile/profile--create", - "api-reference/profile/profile--update", - "api-reference/profile/profile--activate-routing-algorithm", - "api-reference/profile/profile--update-default-fallback-routing-algorithm", - "api-reference/profile/profile--deactivate-routing-algorithm", - "api-reference/profile/profile--retrieve", - "api-reference/profile/merchant-connector--list", - "api-reference/profile/profile--retrieve-active-routing-algorithm", - "api-reference/profile/profile--retrieve-default-fallback-routing-algorithm" - ] - }, - { - "group": "Connector Account", - "pages": [ - "api-reference/connector-account/connector-account--create", - "api-reference/connector-account/connector-account--retrieve", - "api-reference/connector-account/connector-account--update" - ] - }, - { - "group": "API Key", - "pages": [ - "api-reference/api-key/api-key--create", - "api-reference/api-key/api-key--retrieve", - "api-reference/api-key/api-key--update", - "api-reference/api-key/api-key--revoke", - "api-reference/api-key/api-key--list" - ] - }, - { - "group": "Routing", - "pages": [ - "api-reference/routing/routing--create", - "api-reference/routing/routing--retrieve" - ] - }, - { - "group": "Customers", - "pages": [ - "api-reference/customers/customers--create", - "api-reference/customers/customers--retrieve", - "api-reference/customers/customers--update", - "api-reference/customers/customers--delete", - "api-reference/customers/customers--list", - "api-reference/customers/customers--list-saved-payment-methods" - ] - }, - { - "group": "Refunds", - "pages": ["api-reference/refunds/refunds--create"] - }, - { - "group": "Proxy", - "pages": ["api-reference/proxy/proxy"] - }, - { - "group": "Tokenization", - "pages": ["api-reference/tokenization/tokenization--create"] - } - ], - "footerSocials": { - "github": "https://github.com/juspay/hyperswitch", - "linkedin": "https://www.linkedin.com/company/hyperswitch" - }, - "openapi": ["openapi_spec.json"], - "api": { - "maintainOrder": true - } -} diff --git a/api-reference-v2/rust_locker_open_api_spec.yml b/api-reference-v2/rust_locker_open_api_spec.yml deleted file mode 100644 index 17a19fec44d..00000000000 --- a/api-reference-v2/rust_locker_open_api_spec.yml +++ /dev/null @@ -1,372 +0,0 @@ -openapi: "3.0.2" -info: - title: Tartarus - OpenAPI 3.0 - description: |- - This is the OpenAPI 3.0 specification for the card locker. - This is used by the [hyperswitch](https://github.com/juspay/hyperswitch) for storing card information securely. - version: "1.0" -tags: - - name: Key Custodian - description: API used to initialize the locker after deployment. - - name: Data - description: CRUD APIs for working with data to be stored in the locker - - name: Cards - description: CRUD APIs for working with cards data to be stored in the locker (deprecated) -paths: - /custodian/key1: - post: - tags: - - Key Custodian - summary: Provide Key 1 - description: Provide the first key to unlock the locker - operationId: setKey1 - requestBody: - description: Provide key 1 to unlock the locker - content: - application/json: - schema: - $ref: "#/components/schemas/Key" - required: true - responses: - "200": - description: Key 1 provided - content: - text/plain: - schema: - $ref: "#/components/schemas/Key1Set" - /custodian/key2: - post: - tags: - - Key Custodian - summary: Provide Key 2 - description: Provide the second key to unlock the locker - operationId: setKey2 - requestBody: - description: Provide key 2 to unlock the locker - content: - application/json: - schema: - $ref: "#/components/schemas/Key" - required: true - responses: - "200": - description: Key 2 provided - content: - text/plain: - schema: - $ref: "#/components/schemas/Key2Set" - /custodian/decrypt: - post: - tags: - - Key Custodian - summary: Unlock the locker - description: Unlock the locker with the key1 and key2 provided - responses: - "200": - description: Successfully Unlocked - content: - text/plain: - schema: - $ref: "#/components/schemas/Decrypt200" - /health: - get: - summary: Get Health - description: To check whether the application is up - responses: - "200": - description: Health is good - content: - text/plain: - schema: - $ref: "#/components/schemas/Health" - /data/add: - post: - tags: - - Cards - - Data - summary: Add Data in Locker - description: Add sensitive data in the locker - requestBody: - description: The request body might be JWE + JWS encrypted when using middleware - content: - application/json: - schema: - oneOf: - - $ref: "#/components/schemas/StoreDataReq" - - $ref: "#/components/schemas/JWEReq" - required: true - responses: - "200": - description: Store Data Response - content: - application/json: - schema: - oneOf: - - $ref: "#/components/schemas/StoreDataRes" - - $ref: "#/components/schemas/JWERes" - /data/delete: - post: - tags: - - Cards - - Data - summary: Delete Data from Locker - description: Delete sensitive data from the locker - requestBody: - description: The request body might be JWE + JWS encrypted when using middleware - content: - application/json: - schema: - oneOf: - - $ref: "#/components/schemas/DeleteDataReq" - - $ref: "#/components/schemas/JWEReq" - required: true - responses: - "200": - description: Delete Data Response - content: - application/json: - schema: - oneOf: - - $ref: "#/components/schemas/DeleteDataRes" - - $ref: "#/components/schemas/JWERes" - /data/retrieve: - post: - tags: - - Cards - - Data - summary: Retrieve Data from Locker - description: Retrieve sensitive data from the locker - requestBody: - description: The request body might be JWE + JWS encrypted when using middleware - content: - application/json: - schema: - oneOf: - - $ref: "#/components/schemas/RetrieveDataReq" - - $ref: "#/components/schemas/JWEReq" - required: true - responses: - "200": - description: Retrieve Data Response - content: - application/json: - schema: - oneOf: - - $ref: "#/components/schemas/RetrieveDataRes" - - $ref: "#/components/schemas/JWERes" - /data/fingerprint: - post: - tags: - - Cards - - Data - summary: Get or insert the card fingerprint - description: Get or insert the card fingerprint - requestBody: - description: Provide card number and hash key - content: - application/json: - schema: - $ref: "#/components/schemas/FingerprintReq" - required: true - responses: - "200": - description: Fingerprint Response - content: - application/json: - schema: - $ref: "#/components/schemas/FingerprintRes" -components: - schemas: - Key: - type: object - properties: - key: - type: string - example: 801bb63c1bd51820acbc8ac20c674675 - required: - - key - StoreDataReq: - title: StoreDataReq - type: object - properties: - merchant_id: - type: string - example: m0100 - merchant_customer_id: - type: string - example: HsCustomer1 - requester_card_reference: - type: string - example: 3ffdf1e5-7f38-4f26-936f-c66a6f4296fa - card: - $ref: "#/components/schemas/Card" - enc_card_data: - type: string - example: "qwe4tyusdfg" - RetrieveDataReq: - title: RetrieveDataReq - type: object - properties: - merchant_id: - type: string - example: m0100 - merchant_customer_id: - type: string - example: HsCustomer1 - card_reference: - type: string - example: 3ffdf1e5-7f38-4f26-936f-c66a6f4296fa - DeleteDataReq: - title: DeleteDataReq - type: object - properties: - merchant_id: - type: string - example: m0100 - merchant_customer_id: - type: string - example: HsCustomer1 - card_reference: - type: string - example: 3ffdf1e5-7f38-4f26-936f-c66a6f4296fa - FingerprintReq: - type: object - properties: - card: - $ref: "#/components/schemas/FingerprintCardData" - hash_key: - type: string - example: Hash1 - JWEReq: - title: JWEReq - type: object - properties: - header: - type: string - iv: - type: string - encrypted_payload: - type: string - tag: - type: string - encrypted_key: - type: string - RetrieveRes: - title: RetrieveRes - oneOf: - - type: object - properties: - card: - $ref: "#/components/schemas/Card" - - type: object - properties: - enc_card_data: - type: string - Card: - title: Card - type: object - required: - - card_number - properties: - card_number: - type: string - name_on_card: - type: string - card_exp_month: - type: string - card_exp_year: - type: string - card_brand: - type: string - card_isin: - type: string - nick_name: - type: string - FingerprintCardData: - type: object - properties: - card_number: - type: string - example: 4242424242424242 - Key1Set: - title: Key1Set - type: string - # summary: Response after setting key1 - description: Received Key1 - example: Received Key1 - Key2Set: - title: Key2Set - type: string - # description: Response after setting key2 - description: Received Key2 - example: Received Key2 - Decrypt200: - title: Decrypt200 - type: string - # description: Response if the locker key custodian decryption was successful - description: Decryption successful - example: Decryption successful - Health: - title: Health - type: string - # description: Response when the health is good - description: health is good - example: health is good - StoreDataRes: - title: StoreDataRes - type: object - description: Response received if the data was stored successfully - properties: - status: - type: string - enum: [Ok] - payload: - type: object - properties: - card_reference: - type: string - RetrieveDataRes: - title: RetrieveDataRes - type: object - description: Response received with the sensitive data, associated to the card reference - properties: - status: - type: string - enum: [Ok] - payload: - $ref: "#/components/schemas/RetrieveRes" - DeleteDataRes: - title: DeleteDataRes - type: object - description: Response received if the data deletion was successful - properties: - status: - type: string - enum: [Ok] - FingerprintRes: - type: object - description: Response received if the fingerprint insertion or retrieval was successful - properties: - status: - type: string - enum: [Ok] - payload: - type: object - properties: - fingerprint: - type: string - JWERes: - title: JWERes - type: object - description: JWE encrypted response equivalent - properties: - header: - type: string - iv: - type: string - encrypted_payload: - type: string - tag: - type: string - encrypted_key: - type: string \ No newline at end of file diff --git a/api-reference/README.md b/api-reference/README.md index a883fc663db..b0343f44e62 100644 --- a/api-reference/README.md +++ b/api-reference/README.md @@ -1,6 +1,6 @@ # Api Reference -We use the [openapi specification](https://swagger.io/specification) for the api reference. The openapi file is generated from the code base [openapi_spec.json](openapi_spec.json). +We use the [openapi specification](https://swagger.io/specification) for the api reference. The openapi file is generated from the code base [openapi_spec_v1.json](v1/openapi_spec_v1.json). ## How to generate the file @@ -14,7 +14,7 @@ cargo r -p openapi --features v1 In order to render the openapi spec file, we use a tool called [mintlify](https://mintlify.com/). Local setup instructions can be found [here](https://mintlify.com/docs/development#development). Once the cli is installed, Run the following command to render the openapi spec -- Navigate to the directory where `mint.json` exists +- Navigate to the directory where `docs.json` exists ```bash cd api-reference @@ -23,14 +23,14 @@ cd api-reference - Run the cli ```bash -mintlify dev +mint dev ``` ## Add new routes to openapi If you have added new routes to the openapi. Then in order for them to be displayed on the mintlify, run the following commands -- Switch to the directory where api reference ( mint.json ) exists +- Switch to the directory where api reference ( docs.json ) exists ```bash cd api-reference @@ -39,7 +39,10 @@ cd api-reference - Run the following command to generate the route files ```bash -npx @mintlify/scraping@latest openapi-file openapi_spec.json -o api-reference +npx @mintlify/scraping@latest openapi-file v1/openapi_spec_v1.json -o v1 ``` This will generate files in [api-reference](api-reference) folder. These routes should be added to the [mint.json](mint.json) file under navigation, under respective group. + + +NOTE: For working with V2 API reference, replace every occurence of `v1` with `v2` in above commands \ No newline at end of file diff --git a/api-reference/api-reference/customers/customers--create.mdx b/api-reference/api-reference/customers/customers--create.mdx deleted file mode 100644 index 2482c4b75c5..00000000000 --- a/api-reference/api-reference/customers/customers--create.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec post /customers ---- \ No newline at end of file diff --git a/api-reference/api-reference/customers/customers--delete.mdx b/api-reference/api-reference/customers/customers--delete.mdx deleted file mode 100644 index 3e226a29199..00000000000 --- a/api-reference/api-reference/customers/customers--delete.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec delete /customers/{customer_id} ---- \ No newline at end of file diff --git a/api-reference/api-reference/customers/customers--list.mdx b/api-reference/api-reference/customers/customers--list.mdx deleted file mode 100644 index 6fb6b632862..00000000000 --- a/api-reference/api-reference/customers/customers--list.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec get /customers/list ---- \ No newline at end of file diff --git a/api-reference/api-reference/customers/customers--retrieve.mdx b/api-reference/api-reference/customers/customers--retrieve.mdx deleted file mode 100644 index 341216a1e84..00000000000 --- a/api-reference/api-reference/customers/customers--retrieve.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec get /customers/{customer_id} ---- \ No newline at end of file diff --git a/api-reference/api-reference/customers/customers--update.mdx b/api-reference/api-reference/customers/customers--update.mdx deleted file mode 100644 index ec11ed710de..00000000000 --- a/api-reference/api-reference/customers/customers--update.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec post /customers/{customer_id} ---- \ No newline at end of file diff --git a/api-reference/api-reference/disputes/disputes--list.mdx b/api-reference/api-reference/disputes/disputes--list.mdx deleted file mode 100644 index 254366f0733..00000000000 --- a/api-reference/api-reference/disputes/disputes--list.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec get /disputes/list ---- \ No newline at end of file diff --git a/api-reference/api-reference/disputes/disputes--retrieve.mdx b/api-reference/api-reference/disputes/disputes--retrieve.mdx deleted file mode 100644 index abdbabc5644..00000000000 --- a/api-reference/api-reference/disputes/disputes--retrieve.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec get /disputes/{dispute_id} ---- \ No newline at end of file diff --git a/api-reference/api-reference/gsm/gsm--create.mdx b/api-reference/api-reference/gsm/gsm--create.mdx deleted file mode 100644 index 1c610fe39dc..00000000000 --- a/api-reference/api-reference/gsm/gsm--create.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec post /gsm ---- \ No newline at end of file diff --git a/api-reference/api-reference/gsm/gsm--delete.mdx b/api-reference/api-reference/gsm/gsm--delete.mdx deleted file mode 100644 index caf315c6d59..00000000000 --- a/api-reference/api-reference/gsm/gsm--delete.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec post /gsm/delete ---- \ No newline at end of file diff --git a/api-reference/api-reference/gsm/gsm--get.mdx b/api-reference/api-reference/gsm/gsm--get.mdx deleted file mode 100644 index 8c793283439..00000000000 --- a/api-reference/api-reference/gsm/gsm--get.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec post /gsm/get ---- \ No newline at end of file diff --git a/api-reference/api-reference/gsm/gsm--update.mdx b/api-reference/api-reference/gsm/gsm--update.mdx deleted file mode 100644 index 59dc8a77f60..00000000000 --- a/api-reference/api-reference/gsm/gsm--update.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec post /gsm/update ---- \ No newline at end of file diff --git a/api-reference/api-reference/mandates/mandates--retrieve-mandate.mdx b/api-reference/api-reference/mandates/mandates--retrieve-mandate.mdx deleted file mode 100644 index d9eca03f923..00000000000 --- a/api-reference/api-reference/mandates/mandates--retrieve-mandate.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec get /mandates/{mandate_id} ---- \ No newline at end of file diff --git a/api-reference/api-reference/mandates/mandates--revoke-mandate.mdx b/api-reference/api-reference/mandates/mandates--revoke-mandate.mdx deleted file mode 100644 index daa307ecda5..00000000000 --- a/api-reference/api-reference/mandates/mandates--revoke-mandate.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec post /mandates/revoke/{mandate_id} ---- \ No newline at end of file diff --git a/api-reference/api-reference/payment-methods/list-payment-methods-for-a-customer.mdx b/api-reference/api-reference/payment-methods/list-payment-methods-for-a-customer.mdx deleted file mode 100644 index f51fcd1a640..00000000000 --- a/api-reference/api-reference/payment-methods/list-payment-methods-for-a-customer.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec get /customers/{customer_id}/payment_methods ---- \ No newline at end of file diff --git a/api-reference/api-reference/payment-methods/list-payment-methods-for-a-merchant.mdx b/api-reference/api-reference/payment-methods/list-payment-methods-for-a-merchant.mdx deleted file mode 100644 index 53f9be27d08..00000000000 --- a/api-reference/api-reference/payment-methods/list-payment-methods-for-a-merchant.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec get /account/payment_methods ---- \ No newline at end of file diff --git a/api-reference/api-reference/payment-methods/payment-method--delete.mdx b/api-reference/api-reference/payment-methods/payment-method--delete.mdx deleted file mode 100644 index c828a8b7a23..00000000000 --- a/api-reference/api-reference/payment-methods/payment-method--delete.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec delete /payment_methods/{method_id} ---- \ No newline at end of file diff --git a/api-reference/api-reference/payment-methods/payment-method--retrieve.mdx b/api-reference/api-reference/payment-methods/payment-method--retrieve.mdx deleted file mode 100644 index 9183ca34a97..00000000000 --- a/api-reference/api-reference/payment-methods/payment-method--retrieve.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec get /payment_methods/{method_id} ---- \ No newline at end of file diff --git a/api-reference/api-reference/payment-methods/payment-method--update.mdx b/api-reference/api-reference/payment-methods/payment-method--update.mdx deleted file mode 100644 index fe5db5f2b47..00000000000 --- a/api-reference/api-reference/payment-methods/payment-method--update.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec post /payment_methods/{method_id}/update ---- \ No newline at end of file diff --git a/api-reference/api-reference/payment-methods/paymentmethods--create.mdx b/api-reference/api-reference/payment-methods/paymentmethods--create.mdx deleted file mode 100644 index 34df9e3c17b..00000000000 --- a/api-reference/api-reference/payment-methods/paymentmethods--create.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec post /payment_methods ---- \ No newline at end of file diff --git a/api-reference/api-reference/payments/payments--cancel.mdx b/api-reference/api-reference/payments/payments--cancel.mdx deleted file mode 100644 index 54ce60ea3b3..00000000000 --- a/api-reference/api-reference/payments/payments--cancel.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec post /payments/{payment_id}/cancel ---- \ No newline at end of file diff --git a/api-reference/api-reference/payments/payments--capture.mdx b/api-reference/api-reference/payments/payments--capture.mdx deleted file mode 100644 index 1a00d84ec17..00000000000 --- a/api-reference/api-reference/payments/payments--capture.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec post /payments/{payment_id}/capture ---- \ No newline at end of file diff --git a/api-reference/api-reference/payments/payments--confirm.mdx b/api-reference/api-reference/payments/payments--confirm.mdx deleted file mode 100644 index 81e3e2134b9..00000000000 --- a/api-reference/api-reference/payments/payments--confirm.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec post /payments/{payment_id}/confirm ---- \ No newline at end of file diff --git a/api-reference/api-reference/payments/payments--list.mdx b/api-reference/api-reference/payments/payments--list.mdx deleted file mode 100644 index c16239788e7..00000000000 --- a/api-reference/api-reference/payments/payments--list.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec get /payments/list ---- \ No newline at end of file diff --git a/api-reference/api-reference/payments/payments--retrieve.mdx b/api-reference/api-reference/payments/payments--retrieve.mdx deleted file mode 100644 index f5de441830e..00000000000 --- a/api-reference/api-reference/payments/payments--retrieve.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec get /payments/{payment_id} ---- \ No newline at end of file diff --git a/api-reference/api-reference/payments/payments--session-token.mdx b/api-reference/api-reference/payments/payments--session-token.mdx deleted file mode 100644 index 33d736ab36b..00000000000 --- a/api-reference/api-reference/payments/payments--session-token.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec post /payments/session_tokens ---- \ No newline at end of file diff --git a/api-reference/api-reference/payments/payments--update.mdx b/api-reference/api-reference/payments/payments--update.mdx deleted file mode 100644 index f097578a6a5..00000000000 --- a/api-reference/api-reference/payments/payments--update.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec post /payments/{payment_id} ---- \ No newline at end of file diff --git a/api-reference/api-reference/payments/payments-link--retrieve.mdx b/api-reference/api-reference/payments/payments-link--retrieve.mdx deleted file mode 100644 index 92dca125ecb..00000000000 --- a/api-reference/api-reference/payments/payments-link--retrieve.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec get /payment_link/{payment_link_id} ---- \ No newline at end of file diff --git a/api-reference/api-reference/payouts/payouts--cancel.mdx b/api-reference/api-reference/payouts/payouts--cancel.mdx deleted file mode 100644 index 66bebcc6006..00000000000 --- a/api-reference/api-reference/payouts/payouts--cancel.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec post /payouts/{payout_id}/cancel ---- \ No newline at end of file diff --git a/api-reference/api-reference/payouts/payouts--confirm.mdx b/api-reference/api-reference/payouts/payouts--confirm.mdx deleted file mode 100644 index baa20bc4375..00000000000 --- a/api-reference/api-reference/payouts/payouts--confirm.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec post /payouts/{payout_id}/confirm ---- \ No newline at end of file diff --git a/api-reference/api-reference/payouts/payouts--create.mdx b/api-reference/api-reference/payouts/payouts--create.mdx deleted file mode 100644 index 2ceea05aad0..00000000000 --- a/api-reference/api-reference/payouts/payouts--create.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec post /payouts/create ---- \ No newline at end of file diff --git a/api-reference/api-reference/payouts/payouts--fulfill.mdx b/api-reference/api-reference/payouts/payouts--fulfill.mdx deleted file mode 100644 index bf41fcf29ed..00000000000 --- a/api-reference/api-reference/payouts/payouts--fulfill.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec post /payouts/{payout_id}/fulfill ---- \ No newline at end of file diff --git a/api-reference/api-reference/payouts/payouts--retrieve.mdx b/api-reference/api-reference/payouts/payouts--retrieve.mdx deleted file mode 100644 index 9e47516e915..00000000000 --- a/api-reference/api-reference/payouts/payouts--retrieve.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec get /payouts/{payout_id} ---- \ No newline at end of file diff --git a/api-reference/api-reference/payouts/payouts--update.mdx b/api-reference/api-reference/payouts/payouts--update.mdx deleted file mode 100644 index 953b8332c2f..00000000000 --- a/api-reference/api-reference/payouts/payouts--update.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec post /payouts/{payout_id} ---- \ No newline at end of file diff --git a/api-reference/api-reference/refunds/refunds--create.mdx b/api-reference/api-reference/refunds/refunds--create.mdx deleted file mode 100644 index 98f059244f4..00000000000 --- a/api-reference/api-reference/refunds/refunds--create.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec post /refunds ---- \ No newline at end of file diff --git a/api-reference/api-reference/refunds/refunds--list.mdx b/api-reference/api-reference/refunds/refunds--list.mdx deleted file mode 100644 index 5362713df96..00000000000 --- a/api-reference/api-reference/refunds/refunds--list.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec post /refunds/list ---- \ No newline at end of file diff --git a/api-reference/api-reference/refunds/refunds--retrieve.mdx b/api-reference/api-reference/refunds/refunds--retrieve.mdx deleted file mode 100644 index 1ca602bfa94..00000000000 --- a/api-reference/api-reference/refunds/refunds--retrieve.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec get /refunds/{refund_id} ---- \ No newline at end of file diff --git a/api-reference/api-reference/refunds/refunds--update.mdx b/api-reference/api-reference/refunds/refunds--update.mdx deleted file mode 100644 index 8ab210521b8..00000000000 --- a/api-reference/api-reference/refunds/refunds--update.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec post /refunds/{refund_id} ---- \ No newline at end of file diff --git a/api-reference/api-reference/relay/relay--retrieve.mdx b/api-reference/api-reference/relay/relay--retrieve.mdx deleted file mode 100644 index d65e62d31d7..00000000000 --- a/api-reference/api-reference/relay/relay--retrieve.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec get /relay/{relay_id} ---- \ No newline at end of file diff --git a/api-reference/api-reference/relay/relay.mdx b/api-reference/api-reference/relay/relay.mdx deleted file mode 100644 index a6b5962740a..00000000000 --- a/api-reference/api-reference/relay/relay.mdx +++ /dev/null @@ -1,3 +0,0 @@ ---- -openapi: openapi_spec post /relay ---- \ No newline at end of file diff --git a/api-reference/docs.json b/api-reference/docs.json index 4746d186836..ecdf944452c 100644 --- a/api-reference/docs.json +++ b/api-reference/docs.json @@ -12,222 +12,368 @@ "tabs": [ { "tab": "Documentation", - "groups": [ - { - "group": "Get Started", - "pages": [ - "introduction" - ] - }, - { - "group": "Essentials", - "pages": [ - "essentials/error_codes", - "essentials/rate_limit", - "essentials/go-live" - ] - }, + "versions": [ { - "group": "Payments Core APIs", - "pages": [ - "api-reference/payments/setup--instructions", - "api-reference/payments/payment--flows", - { - "group": "Payments", - "pages": [ - "api-reference/payments/payments--create", - "api-reference/payments/payments--update", - "api-reference/payments/payments--confirm", - "api-reference/payments/payments--retrieve", - "api-reference/payments/payments--cancel", - "api-reference/payments/payments--capture", - "api-reference/payments/payments--incremental-authorization", - "api-reference/payments/payments--session-token", - "api-reference/payments/payments-link--retrieve", - "api-reference/payments/payments--list", - "api-reference/payments/payments--external-3ds-authentication", - "api-reference/payments/payments--complete-authorize", - "api-reference/payments/payments--update-metadata" - ] - }, + "version": "1.0.0", + "groups": [ { - "group": "Payment Methods", - "pages": [ - "api-reference/payment-methods/paymentmethods--create", - "api-reference/payment-methods/payment-method--retrieve", - "api-reference/payment-methods/payment-method--update", - "api-reference/payment-methods/payment-method--delete", - "api-reference/payment-methods/payment-method--set-default-payment-method-for-customer", - "api-reference/payment-methods/list-payment-methods-for-a-merchant", - "api-reference/payment-methods/list-customer-saved-payment-methods-for-a-payment", - "api-reference/payment-methods/list-payment-methods-for-a-customer", - "api-reference/customer-set-default-payment-method/customers--set-default-payment-method" - ] + "group": "Get Started", + "pages": ["introduction"] }, { - "group": "Customers", + "group": "Essentials", "pages": [ - "api-reference/customers/customers--create", - "api-reference/customers/customers--retrieve", - "api-reference/customers/customers--update", - "api-reference/customers/customers--delete", - "api-reference/customers/customers--list" + "essentials/error_codes", + "essentials/rate_limit", + "essentials/go-live" ] }, { - "group": "Mandates", + "group": "Payments Core APIs", "pages": [ - "api-reference/mandates/mandates--revoke-mandate", - "api-reference/mandates/mandates--retrieve-mandate", - "api-reference/mandates/mandates--customer-mandates-list" + "v1/payments/setup--instructions", + "v1/payments/payment--flows", + { + "group": "Payments", + "pages": [ + "v1/payments/payments--create", + "v1/payments/payments--update", + "v1/payments/payments--confirm", + "v1/payments/payments--retrieve", + "v1/payments/payments--cancel", + "v1/payments/payments--capture", + "v1/payments/payments--incremental-authorization", + "v1/payments/payments--session-token", + "v1/payments/payments-link--retrieve", + "v1/payments/payments--list", + "v1/payments/payments--external-3ds-authentication", + "v1/payments/payments--complete-authorize", + "v1/payments/payments--update-metadata" + ] + }, + { + "group": "Payment Methods", + "pages": [ + "v1/payment-methods/paymentmethods--create", + "v1/payment-methods/payment-method--retrieve", + "v1/payment-methods/payment-method--update", + "v1/payment-methods/payment-method--delete", + "v1/payment-methods/payment-method--set-default-payment-method-for-customer", + "v1/payment-methods/list-payment-methods-for-a-merchant", + "v1/payment-methods/list-customer-saved-payment-methods-for-a-payment", + "v1/payment-methods/list-payment-methods-for-a-customer", + "v1/customer-set-default-payment-method/customers--set-default-payment-method" + ] + }, + { + "group": "Customers", + "pages": [ + "v1/customers/customers--create", + "v1/customers/customers--retrieve", + "v1/customers/customers--update", + "v1/customers/customers--delete", + "v1/customers/customers--list" + ] + }, + { + "group": "Mandates", + "pages": [ + "v1/mandates/mandates--revoke-mandate", + "v1/mandates/mandates--retrieve-mandate", + "v1/mandates/mandates--customer-mandates-list" + ] + }, + { + "group": "Refunds", + "pages": [ + "v1/refunds/refunds--create", + "v1/refunds/refunds--update", + "v1/refunds/refunds--retrieve", + "v1/refunds/refunds--list" + ] + }, + { + "group": "Disputes", + "pages": [ + "v1/disputes/disputes--retrieve", + "v1/disputes/disputes--list" + ] + }, + { + "group": "Payouts", + "pages": [ + "v1/payouts/payouts--create", + "v1/payouts/payouts--update", + "v1/payouts/payouts--cancel", + "v1/payouts/payouts--fulfill", + "v1/payouts/payouts--confirm", + "v1/payouts/payouts--retrieve", + "v1/payouts/payouts--list", + "v1/payouts/payouts--list-filters", + "v1/payouts/payouts--filter" + ] + } ] }, { - "group": "Refunds", + "group": "Account management APIs", "pages": [ - "api-reference/refunds/refunds--create", - "api-reference/refunds/refunds--update", - "api-reference/refunds/refunds--retrieve", - "api-reference/refunds/refunds--list" + { + "group": "Organization", + "pages": [ + "v1/organization/organization--create", + "v1/organization/organization--retrieve", + "v1/organization/organization--update" + ] + }, + { + "group": "Merchant Account", + "pages": [ + "v1/merchant-account/merchant-account--create", + "v1/merchant-account/merchant-account--retrieve", + "v1/merchant-account/merchant-account--update", + "v1/merchant-account/merchant-account--delete", + "v1/merchant-account/merchant-account--kv-status" + ] + }, + { + "group": "Business Profile", + "pages": [ + "v1/business-profile/business-profile--create", + "v1/business-profile/business-profile--update", + "v1/business-profile/business-profile--retrieve", + "v1/business-profile/business-profile--delete", + "v1/business-profile/business-profile--list" + ] + }, + { + "group": "API Key", + "pages": [ + "v1/api-key/api-key--create", + "v1/api-key/api-key--retrieve", + "v1/api-key/api-key--update", + "v1/api-key/api-key--revoke", + "v1/api-key/api-key--list" + ] + }, + { + "group": "Merchant Connector Account", + "pages": [ + "v1/merchant-connector-account/merchant-connector--create", + "v1/merchant-connector-account/merchant-connector--retrieve", + "v1/merchant-connector-account/merchant-connector--update", + "v1/merchant-connector-account/merchant-connector--delete", + "v1/merchant-connector-account/merchant-connector--list" + ] + }, + { + "group": "GSM (Global Status Mapping)", + "pages": [ + "v1/gsm/gsm--create", + "v1/gsm/gsm--get", + "v1/gsm/gsm--update", + "v1/gsm/gsm--delete" + ] + } ] }, { - "group": "Disputes", + "group": "Other APIs", "pages": [ - "api-reference/disputes/disputes--retrieve", - "api-reference/disputes/disputes--list" - ] - }, - { - "group": "Payouts", - "pages": [ - "api-reference/payouts/payouts--create", - "api-reference/payouts/payouts--update", - "api-reference/payouts/payouts--cancel", - "api-reference/payouts/payouts--fulfill", - "api-reference/payouts/payouts--confirm", - "api-reference/payouts/payouts--retrieve", - "api-reference/payouts/payouts--list", - "api-reference/payouts/payouts--list-filters", - "api-reference/payouts/payouts--filter" + { + "group": "Event", + "pages": [ + "v1/event/events--list", + "v1/event/events--delivery-attempt-list", + "v1/event/events--manual-retry" + ] + }, + { + "group": "Poll", + "pages": ["v1/poll/poll--retrieve-poll-status"] + }, + { + "group": "Blocklist", + "pages": [ + "v1/blocklist/get-blocklist", + "v1/blocklist/post-blocklist", + "v1/blocklist/delete-blocklist", + "v1/blocklist/post-blocklisttoggle" + ] + }, + { + "group": "Routing", + "pages": [ + "v1/routing/routing--list", + "v1/routing/routing--create", + "v1/routing/routing--retrieve-config", + "v1/routing/routing--deactivate", + "v1/routing/routing--retrieve-default-config", + "v1/routing/routing--update-default-config", + "v1/routing/routing--retrieve-default-for-profile", + "v1/routing/routing--update-default-for-profile", + "v1/routing/routing--retrieve", + "v1/routing/routing--activate-config" + ] + }, + { + "group": "Relay", + "pages": ["v1/relay/relay", "v1/relay/relay--retrieve"] + }, + { + "group": "Schemas", + "pages": ["v1/schemas/outgoing--webhook"] + } ] } ] }, { - "group": "Account management APIs", - "pages": [ + "version": "2.0.0 [BETA]", + "groups": [ { - "group": "Organization", - "pages": [ - "api-reference/organization/organization--create", - "api-reference/organization/organization--retrieve", - "api-reference/organization/organization--update" - ] + "group": "Get Started [BETA]", + "pages": ["introduction"] }, { - "group": "Merchant Account", + "group": "Essentials [BETA]", "pages": [ - "api-reference/merchant-account/merchant-account--create", - "api-reference/merchant-account/merchant-account--retrieve", - "api-reference/merchant-account/merchant-account--update", - "api-reference/merchant-account/merchant-account--delete", - "api-reference/merchant-account/merchant-account--kv-status" + "essentials/error_codes", + "essentials/rate_limit", + "essentials/go-live" ] }, { - "group": "Business Profile", + "group": "Payments Core APIs [BETA]", "pages": [ - "api-reference/business-profile/business-profile--create", - "api-reference/business-profile/business-profile--update", - "api-reference/business-profile/business-profile--retrieve", - "api-reference/business-profile/business-profile--delete", - "api-reference/business-profile/business-profile--list" + { + "group": "Payments", + "pages": [ + "v2/payments/payments--create-intent", + "v2/payments/payments--get-intent", + "v2/payments/payments--update-intent", + "v2/payments/payments--session-token", + "v2/payments/payments--payment-methods-list", + "v2/payments/payments--confirm-intent", + "v2/payments/payments--get", + "v2/payments/payments--create-and-confirm-intent", + "v2/payments/payments--list" + ] + }, + { + "group": "Payment Methods", + "pages": [ + "v2/payment-methods/payment-method--create", + "v2/payment-methods/payment-method--create-intent", + "v2/payment-methods/payment-method--payment-methods-list", + "v2/payment-methods/payment-method--confirm-intent", + "v2/payment-methods/payment-method--update", + "v2/payment-methods/payment-method--retrieve", + "v2/payment-methods/payment-method--delete", + "v2/payment-methods/list-saved-payment-methods-for-a-customer" + ] + }, + { + "group": "Payment Method Session", + "pages": [ + "v2/payment-method-session/payment-method-session--create", + "v2/payment-method-session/payment-method-session--retrieve", + "v2/payment-method-session/payment-method-session--list-payment-methods", + "v2/payment-method-session/payment-method-session--update-a-saved-payment-method", + "v2/payment-method-session/payment-method-session--confirm-a-payment-method-session", + "v2/payment-method-session/payment-method-session--delete-a-saved-payment-method" + ] + }, + { + "group": "Customers", + "pages": [ + "v2/customers/customers--create", + "v2/customers/customers--retrieve", + "v2/customers/customers--update", + "v2/customers/customers--delete", + "v2/customers/customers--list", + "v2/customers/customers--list-saved-payment-methods" + ] + }, + { + "group": "Refunds", + "pages": ["v2/refunds/refunds--create"] + } ] }, { - "group": "API Key", + "group": "Account management APIs [BETA]", "pages": [ - "api-reference/api-key/api-key--create", - "api-reference/api-key/api-key--retrieve", - "api-reference/api-key/api-key--update", - "api-reference/api-key/api-key--revoke", - "api-reference/api-key/api-key--list" + { + "group": "Organization", + "pages": [ + "v2/organization/organization--create", + "v2/organization/organization--retrieve", + "v2/organization/organization--update", + "v2/organization/organization--merchant-account--list" + ] + }, + { + "group": "Merchant Account", + "pages": [ + "v2/merchant-account/merchant-account--create", + "v2/merchant-account/merchant-account--retrieve", + "v2/merchant-account/merchant-account--update", + "v2/merchant-account/business-profile--list" + ] + }, + { + "group": "Profile", + "pages": [ + "v2/profile/profile--create", + "v2/profile/profile--update", + "v2/profile/profile--activate-routing-algorithm", + "v2/profile/profile--update-default-fallback-routing-algorithm", + "v2/profile/profile--deactivate-routing-algorithm", + "v2/profile/profile--retrieve", + "v2/profile/merchant-connector--list", + "v2/profile/profile--retrieve-active-routing-algorithm", + "v2/profile/profile--retrieve-default-fallback-routing-algorithm" + ] + }, + { + "group": "Connector Account", + "pages": [ + "v2/connector-account/connector-account--create", + "v2/connector-account/connector-account--retrieve", + "v2/connector-account/connector-account--update" + ] + }, + { + "group": "API Key", + "pages": [ + "v2/api-key/api-key--create", + "v2/api-key/api-key--retrieve", + "v2/api-key/api-key--update", + "v2/api-key/api-key--revoke", + "v2/api-key/api-key--list" + ] + }, + { + "group": "Routing", + "pages": [ + "v2/routing/routing--create", + "v2/routing/routing--retrieve" + ] + } ] }, { - "group": "Merchant Connector Account", + "group": "Other APIs [BETA]", "pages": [ - "api-reference/merchant-connector-account/merchant-connector--create", - "api-reference/merchant-connector-account/merchant-connector--retrieve", - "api-reference/merchant-connector-account/merchant-connector--update", - "api-reference/merchant-connector-account/merchant-connector--delete", - "api-reference/merchant-connector-account/merchant-connector--list" - ] - }, - { - "group": "GSM (Global Status Mapping)", - "pages": [ - "api-reference/gsm/gsm--create", - "api-reference/gsm/gsm--get", - "api-reference/gsm/gsm--update", - "api-reference/gsm/gsm--delete" - ] - } - ] - }, - { - "group": "Other APIs", - "pages": [ - { - "group": "Event", - "pages": [ - "api-reference/event/events--list", - "api-reference/event/events--delivery-attempt-list", - "api-reference/event/events--manual-retry" - ] - }, - { - "group": "Poll", - "pages": [ - "api-reference/poll/poll--retrieve-poll-status" - ] - }, - { - "group": "Blocklist", - "pages": [ - "api-reference/blocklist/get-blocklist", - "api-reference/blocklist/post-blocklist", - "api-reference/blocklist/delete-blocklist", - "api-reference/blocklist/post-blocklisttoggle" - ] - }, - { - "group": "Routing", - "pages": [ - "api-reference/routing/routing--list", - "api-reference/routing/routing--create", - "api-reference/routing/routing--retrieve-config", - "api-reference/routing/routing--deactivate", - "api-reference/routing/routing--retrieve-default-config", - "api-reference/routing/routing--update-default-config", - "api-reference/routing/routing--retrieve-default-for-profile", - "api-reference/routing/routing--update-default-for-profile", - "api-reference/routing/routing--retrieve", - "api-reference/routing/routing--activate-config" - ] - }, - { - "group": "Relay", - "pages": [ - "api-reference/relay/relay", - "api-reference/relay/relay--retrieve" - ] - }, - { - "group": "Schemas", - "pages": [ - "api-reference/schemas/outgoing--webhook" + { + "group": "Proxy", + "pages": ["v2/proxy/proxy"] + }, + { + "group": "Tokenization", + "pages": ["v2/tokenization/tokenization--create"] + } ] } ] @@ -239,18 +385,14 @@ "groups": [ { "group": "Hyperswitch Card Vault", - "pages": [ - "locker-api-reference/overview" - ] + "pages": ["locker-api-reference/overview"] }, { "group": "API Reference", "pages": [ { "group": "Locker - Health", - "pages": [ - "locker-api-reference/locker-health/get-health" - ] + "pages": ["locker-api-reference/locker-health/get-health"] }, { "group": "Locker - Key Custodian", @@ -278,9 +420,7 @@ "groups": [ { "group": "Hyperswitch Intelligent Router", - "pages": [ - "intelligent-router-api-reference/overview" - ] + "pages": ["intelligent-router-api-reference/overview"] }, { "group": "API Reference", @@ -329,7 +469,8 @@ }, "api": { "openapi": [ - "openapi_spec.json", + "v1/openapi_spec_v1.json", + "v2/openapi_spec_v2.json", "rust_locker_open_api_spec.yml" ] }, @@ -371,11 +512,6 @@ } }, "contextual": { - "options": [ - "copy", - "claude", - "chatgpt", - "view" - ] - } -} \ No newline at end of file + "options": ["copy", "claude", "chatgpt", "view"] + } +} diff --git a/api-reference/api-reference/3ds-decision-rule/execute-a-3ds-decision-rule-based-on-the-provided-input.mdx b/api-reference/v1/3ds-decision-rule/execute-a-3ds-decision-rule-based-on-the-provided-input.mdx similarity index 100% rename from api-reference/api-reference/3ds-decision-rule/execute-a-3ds-decision-rule-based-on-the-provided-input.mdx rename to api-reference/v1/3ds-decision-rule/execute-a-3ds-decision-rule-based-on-the-provided-input.mdx diff --git a/api-reference/api-reference/api-key/api-key--create.mdx b/api-reference/v1/api-key/api-key--create.mdx similarity index 100% rename from api-reference/api-reference/api-key/api-key--create.mdx rename to api-reference/v1/api-key/api-key--create.mdx diff --git a/api-reference/api-reference/api-key/api-key--list.mdx b/api-reference/v1/api-key/api-key--list.mdx similarity index 100% rename from api-reference/api-reference/api-key/api-key--list.mdx rename to api-reference/v1/api-key/api-key--list.mdx diff --git a/api-reference/api-reference/api-key/api-key--retrieve.mdx b/api-reference/v1/api-key/api-key--retrieve.mdx similarity index 100% rename from api-reference/api-reference/api-key/api-key--retrieve.mdx rename to api-reference/v1/api-key/api-key--retrieve.mdx diff --git a/api-reference/api-reference/api-key/api-key--revoke.mdx b/api-reference/v1/api-key/api-key--revoke.mdx similarity index 100% rename from api-reference/api-reference/api-key/api-key--revoke.mdx rename to api-reference/v1/api-key/api-key--revoke.mdx diff --git a/api-reference/api-reference/api-key/api-key--update.mdx b/api-reference/v1/api-key/api-key--update.mdx similarity index 100% rename from api-reference/api-reference/api-key/api-key--update.mdx rename to api-reference/v1/api-key/api-key--update.mdx diff --git a/api-reference/api-reference/blocklist/delete-blocklist.mdx b/api-reference/v1/blocklist/delete-blocklist.mdx similarity index 100% rename from api-reference/api-reference/blocklist/delete-blocklist.mdx rename to api-reference/v1/blocklist/delete-blocklist.mdx diff --git a/api-reference/api-reference/blocklist/get-blocklist.mdx b/api-reference/v1/blocklist/get-blocklist.mdx similarity index 100% rename from api-reference/api-reference/blocklist/get-blocklist.mdx rename to api-reference/v1/blocklist/get-blocklist.mdx diff --git a/api-reference/api-reference/blocklist/post-blocklist.mdx b/api-reference/v1/blocklist/post-blocklist.mdx similarity index 100% rename from api-reference/api-reference/blocklist/post-blocklist.mdx rename to api-reference/v1/blocklist/post-blocklist.mdx diff --git a/api-reference/api-reference/blocklist/post-blocklisttoggle.mdx b/api-reference/v1/blocklist/post-blocklisttoggle.mdx similarity index 100% rename from api-reference/api-reference/blocklist/post-blocklisttoggle.mdx rename to api-reference/v1/blocklist/post-blocklisttoggle.mdx diff --git a/api-reference/api-reference/business-profile/business-profile--create.mdx b/api-reference/v1/business-profile/business-profile--create.mdx similarity index 100% rename from api-reference/api-reference/business-profile/business-profile--create.mdx rename to api-reference/v1/business-profile/business-profile--create.mdx diff --git a/api-reference/api-reference/business-profile/business-profile--delete.mdx b/api-reference/v1/business-profile/business-profile--delete.mdx similarity index 100% rename from api-reference/api-reference/business-profile/business-profile--delete.mdx rename to api-reference/v1/business-profile/business-profile--delete.mdx diff --git a/api-reference/api-reference/business-profile/business-profile--list.mdx b/api-reference/v1/business-profile/business-profile--list.mdx similarity index 100% rename from api-reference/api-reference/business-profile/business-profile--list.mdx rename to api-reference/v1/business-profile/business-profile--list.mdx diff --git a/api-reference/api-reference/business-profile/business-profile--retrieve.mdx b/api-reference/v1/business-profile/business-profile--retrieve.mdx similarity index 100% rename from api-reference/api-reference/business-profile/business-profile--retrieve.mdx rename to api-reference/v1/business-profile/business-profile--retrieve.mdx diff --git a/api-reference/api-reference/business-profile/business-profile--update.mdx b/api-reference/v1/business-profile/business-profile--update.mdx similarity index 100% rename from api-reference/api-reference/business-profile/business-profile--update.mdx rename to api-reference/v1/business-profile/business-profile--update.mdx diff --git a/api-reference/api-reference/customer-set-default-payment-method/customers--set-default-payment-method.mdx b/api-reference/v1/customer-set-default-payment-method/customers--set-default-payment-method.mdx similarity index 100% rename from api-reference/api-reference/customer-set-default-payment-method/customers--set-default-payment-method.mdx rename to api-reference/v1/customer-set-default-payment-method/customers--set-default-payment-method.mdx diff --git a/api-reference/v1/customers/customers--create.mdx b/api-reference/v1/customers/customers--create.mdx new file mode 100644 index 00000000000..d679fa09b12 --- /dev/null +++ b/api-reference/v1/customers/customers--create.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /customers +--- \ No newline at end of file diff --git a/api-reference/v1/customers/customers--delete.mdx b/api-reference/v1/customers/customers--delete.mdx new file mode 100644 index 00000000000..536094bac3e --- /dev/null +++ b/api-reference/v1/customers/customers--delete.mdx @@ -0,0 +1,3 @@ +--- +openapi: delete /customers/{customer_id} +--- \ No newline at end of file diff --git a/api-reference/v1/customers/customers--list.mdx b/api-reference/v1/customers/customers--list.mdx new file mode 100644 index 00000000000..5dce4f2e7fd --- /dev/null +++ b/api-reference/v1/customers/customers--list.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /customers/list +--- \ No newline at end of file diff --git a/api-reference/v1/customers/customers--retrieve.mdx b/api-reference/v1/customers/customers--retrieve.mdx new file mode 100644 index 00000000000..0f4e1fa2917 --- /dev/null +++ b/api-reference/v1/customers/customers--retrieve.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /customers/{customer_id} +--- \ No newline at end of file diff --git a/api-reference/v1/customers/customers--update.mdx b/api-reference/v1/customers/customers--update.mdx new file mode 100644 index 00000000000..3f4c55d96e7 --- /dev/null +++ b/api-reference/v1/customers/customers--update.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /customers/{customer_id} +--- \ No newline at end of file diff --git a/api-reference/v1/disputes/disputes--list.mdx b/api-reference/v1/disputes/disputes--list.mdx new file mode 100644 index 00000000000..33850e5e419 --- /dev/null +++ b/api-reference/v1/disputes/disputes--list.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /disputes/list +--- \ No newline at end of file diff --git a/api-reference/v1/disputes/disputes--retrieve.mdx b/api-reference/v1/disputes/disputes--retrieve.mdx new file mode 100644 index 00000000000..e3e71f29fa4 --- /dev/null +++ b/api-reference/v1/disputes/disputes--retrieve.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /disputes/{dispute_id} +--- \ No newline at end of file diff --git a/api-reference/api-reference/event/events--delivery-attempt-list.mdx b/api-reference/v1/event/events--delivery-attempt-list.mdx similarity index 100% rename from api-reference/api-reference/event/events--delivery-attempt-list.mdx rename to api-reference/v1/event/events--delivery-attempt-list.mdx diff --git a/api-reference/api-reference/event/events--list.mdx b/api-reference/v1/event/events--list.mdx similarity index 100% rename from api-reference/api-reference/event/events--list.mdx rename to api-reference/v1/event/events--list.mdx diff --git a/api-reference/api-reference/event/events--manual-retry.mdx b/api-reference/v1/event/events--manual-retry.mdx similarity index 100% rename from api-reference/api-reference/event/events--manual-retry.mdx rename to api-reference/v1/event/events--manual-retry.mdx diff --git a/api-reference/v1/gsm/gsm--create.mdx b/api-reference/v1/gsm/gsm--create.mdx new file mode 100644 index 00000000000..7de9aad1b1b --- /dev/null +++ b/api-reference/v1/gsm/gsm--create.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /gsm +--- \ No newline at end of file diff --git a/api-reference/v1/gsm/gsm--delete.mdx b/api-reference/v1/gsm/gsm--delete.mdx new file mode 100644 index 00000000000..e8ebc8561d7 --- /dev/null +++ b/api-reference/v1/gsm/gsm--delete.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /gsm/delete +--- \ No newline at end of file diff --git a/api-reference/v1/gsm/gsm--get.mdx b/api-reference/v1/gsm/gsm--get.mdx new file mode 100644 index 00000000000..3a4b58590ee --- /dev/null +++ b/api-reference/v1/gsm/gsm--get.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /gsm/get +--- \ No newline at end of file diff --git a/api-reference/v1/gsm/gsm--update.mdx b/api-reference/v1/gsm/gsm--update.mdx new file mode 100644 index 00000000000..c50fbb75e90 --- /dev/null +++ b/api-reference/v1/gsm/gsm--update.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /gsm/update +--- \ No newline at end of file diff --git a/api-reference/api-reference/mandates/mandates--customer-mandates-list.mdx b/api-reference/v1/mandates/mandates--customer-mandates-list.mdx similarity index 100% rename from api-reference/api-reference/mandates/mandates--customer-mandates-list.mdx rename to api-reference/v1/mandates/mandates--customer-mandates-list.mdx diff --git a/api-reference/v1/mandates/mandates--retrieve-mandate.mdx b/api-reference/v1/mandates/mandates--retrieve-mandate.mdx new file mode 100644 index 00000000000..6211cd09b61 --- /dev/null +++ b/api-reference/v1/mandates/mandates--retrieve-mandate.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /mandates/{mandate_id} +--- \ No newline at end of file diff --git a/api-reference/v1/mandates/mandates--revoke-mandate.mdx b/api-reference/v1/mandates/mandates--revoke-mandate.mdx new file mode 100644 index 00000000000..590bde6ea9c --- /dev/null +++ b/api-reference/v1/mandates/mandates--revoke-mandate.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /mandates/revoke/{mandate_id} +--- \ No newline at end of file diff --git a/api-reference/api-reference/merchant-account/merchant-account--create.mdx b/api-reference/v1/merchant-account/merchant-account--create.mdx similarity index 100% rename from api-reference/api-reference/merchant-account/merchant-account--create.mdx rename to api-reference/v1/merchant-account/merchant-account--create.mdx diff --git a/api-reference/api-reference/merchant-account/merchant-account--delete.mdx b/api-reference/v1/merchant-account/merchant-account--delete.mdx similarity index 100% rename from api-reference/api-reference/merchant-account/merchant-account--delete.mdx rename to api-reference/v1/merchant-account/merchant-account--delete.mdx diff --git a/api-reference/api-reference/merchant-account/merchant-account--kv-status.mdx b/api-reference/v1/merchant-account/merchant-account--kv-status.mdx similarity index 100% rename from api-reference/api-reference/merchant-account/merchant-account--kv-status.mdx rename to api-reference/v1/merchant-account/merchant-account--kv-status.mdx diff --git a/api-reference/api-reference/merchant-account/merchant-account--retrieve.mdx b/api-reference/v1/merchant-account/merchant-account--retrieve.mdx similarity index 100% rename from api-reference/api-reference/merchant-account/merchant-account--retrieve.mdx rename to api-reference/v1/merchant-account/merchant-account--retrieve.mdx diff --git a/api-reference/api-reference/merchant-account/merchant-account--update.mdx b/api-reference/v1/merchant-account/merchant-account--update.mdx similarity index 100% rename from api-reference/api-reference/merchant-account/merchant-account--update.mdx rename to api-reference/v1/merchant-account/merchant-account--update.mdx diff --git a/api-reference/api-reference/merchant-connector-account/merchant-connector--create.mdx b/api-reference/v1/merchant-connector-account/merchant-connector--create.mdx similarity index 100% rename from api-reference/api-reference/merchant-connector-account/merchant-connector--create.mdx rename to api-reference/v1/merchant-connector-account/merchant-connector--create.mdx diff --git a/api-reference/api-reference/merchant-connector-account/merchant-connector--delete.mdx b/api-reference/v1/merchant-connector-account/merchant-connector--delete.mdx similarity index 100% rename from api-reference/api-reference/merchant-connector-account/merchant-connector--delete.mdx rename to api-reference/v1/merchant-connector-account/merchant-connector--delete.mdx diff --git a/api-reference/api-reference/merchant-connector-account/merchant-connector--list.mdx b/api-reference/v1/merchant-connector-account/merchant-connector--list.mdx similarity index 100% rename from api-reference/api-reference/merchant-connector-account/merchant-connector--list.mdx rename to api-reference/v1/merchant-connector-account/merchant-connector--list.mdx diff --git a/api-reference/api-reference/merchant-connector-account/merchant-connector--retrieve.mdx b/api-reference/v1/merchant-connector-account/merchant-connector--retrieve.mdx similarity index 100% rename from api-reference/api-reference/merchant-connector-account/merchant-connector--retrieve.mdx rename to api-reference/v1/merchant-connector-account/merchant-connector--retrieve.mdx diff --git a/api-reference/api-reference/merchant-connector-account/merchant-connector--update.mdx b/api-reference/v1/merchant-connector-account/merchant-connector--update.mdx similarity index 100% rename from api-reference/api-reference/merchant-connector-account/merchant-connector--update.mdx rename to api-reference/v1/merchant-connector-account/merchant-connector--update.mdx diff --git a/api-reference/openapi_spec.json b/api-reference/v1/openapi_spec_v1.json similarity index 100% rename from api-reference/openapi_spec.json rename to api-reference/v1/openapi_spec_v1.json diff --git a/api-reference/api-reference/organization/organization--create.mdx b/api-reference/v1/organization/organization--create.mdx similarity index 100% rename from api-reference/api-reference/organization/organization--create.mdx rename to api-reference/v1/organization/organization--create.mdx diff --git a/api-reference/api-reference/organization/organization--retrieve.mdx b/api-reference/v1/organization/organization--retrieve.mdx similarity index 100% rename from api-reference/api-reference/organization/organization--retrieve.mdx rename to api-reference/v1/organization/organization--retrieve.mdx diff --git a/api-reference/api-reference/organization/organization--update.mdx b/api-reference/v1/organization/organization--update.mdx similarity index 100% rename from api-reference/api-reference/organization/organization--update.mdx rename to api-reference/v1/organization/organization--update.mdx diff --git a/api-reference/api-reference/payment-methods/list-customer-saved-payment-methods-for-a-payment.mdx b/api-reference/v1/payment-methods/list-customer-saved-payment-methods-for-a-payment.mdx similarity index 100% rename from api-reference/api-reference/payment-methods/list-customer-saved-payment-methods-for-a-payment.mdx rename to api-reference/v1/payment-methods/list-customer-saved-payment-methods-for-a-payment.mdx diff --git a/api-reference/v1/payment-methods/list-payment-methods-for-a-customer.mdx b/api-reference/v1/payment-methods/list-payment-methods-for-a-customer.mdx new file mode 100644 index 00000000000..5b18efafe7e --- /dev/null +++ b/api-reference/v1/payment-methods/list-payment-methods-for-a-customer.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /customers/{customer_id}/payment_methods +--- \ No newline at end of file diff --git a/api-reference/v1/payment-methods/list-payment-methods-for-a-merchant.mdx b/api-reference/v1/payment-methods/list-payment-methods-for-a-merchant.mdx new file mode 100644 index 00000000000..6ef3be6e559 --- /dev/null +++ b/api-reference/v1/payment-methods/list-payment-methods-for-a-merchant.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /account/payment_methods +--- \ No newline at end of file diff --git a/api-reference/v1/payment-methods/payment-method--delete.mdx b/api-reference/v1/payment-methods/payment-method--delete.mdx new file mode 100644 index 00000000000..7b8758e68b3 --- /dev/null +++ b/api-reference/v1/payment-methods/payment-method--delete.mdx @@ -0,0 +1,3 @@ +--- +openapi: delete /payment_methods/{method_id} +--- \ No newline at end of file diff --git a/api-reference/v1/payment-methods/payment-method--retrieve.mdx b/api-reference/v1/payment-methods/payment-method--retrieve.mdx new file mode 100644 index 00000000000..504f4644c47 --- /dev/null +++ b/api-reference/v1/payment-methods/payment-method--retrieve.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /payment_methods/{method_id} +--- \ No newline at end of file diff --git a/api-reference/api-reference/payment-methods/payment-method--set-default-payment-method-for-customer.mdx b/api-reference/v1/payment-methods/payment-method--set-default-payment-method-for-customer.mdx similarity index 100% rename from api-reference/api-reference/payment-methods/payment-method--set-default-payment-method-for-customer.mdx rename to api-reference/v1/payment-methods/payment-method--set-default-payment-method-for-customer.mdx diff --git a/api-reference/v1/payment-methods/payment-method--update.mdx b/api-reference/v1/payment-methods/payment-method--update.mdx new file mode 100644 index 00000000000..c4ff42b87a7 --- /dev/null +++ b/api-reference/v1/payment-methods/payment-method--update.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /payment_methods/{method_id}/update +--- \ No newline at end of file diff --git a/api-reference/v1/payment-methods/paymentmethods--create.mdx b/api-reference/v1/payment-methods/paymentmethods--create.mdx new file mode 100644 index 00000000000..2675d224f0e --- /dev/null +++ b/api-reference/v1/payment-methods/paymentmethods--create.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /payment_methods +--- \ No newline at end of file diff --git a/api-reference/api-reference/payments/payment--flows.mdx b/api-reference/v1/payments/payment--flows.mdx similarity index 100% rename from api-reference/api-reference/payments/payment--flows.mdx rename to api-reference/v1/payments/payment--flows.mdx diff --git a/api-reference/v1/payments/payments--cancel.mdx b/api-reference/v1/payments/payments--cancel.mdx new file mode 100644 index 00000000000..5aed48140e2 --- /dev/null +++ b/api-reference/v1/payments/payments--cancel.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /payments/{payment_id}/cancel +--- \ No newline at end of file diff --git a/api-reference/v1/payments/payments--capture.mdx b/api-reference/v1/payments/payments--capture.mdx new file mode 100644 index 00000000000..3797a56952c --- /dev/null +++ b/api-reference/v1/payments/payments--capture.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /payments/{payment_id}/capture +--- \ No newline at end of file diff --git a/api-reference/api-reference/payments/payments--complete-authorize.mdx b/api-reference/v1/payments/payments--complete-authorize.mdx similarity index 100% rename from api-reference/api-reference/payments/payments--complete-authorize.mdx rename to api-reference/v1/payments/payments--complete-authorize.mdx diff --git a/api-reference/v1/payments/payments--confirm.mdx b/api-reference/v1/payments/payments--confirm.mdx new file mode 100644 index 00000000000..9779c7192b5 --- /dev/null +++ b/api-reference/v1/payments/payments--confirm.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /payments/{payment_id}/confirm +--- \ No newline at end of file diff --git a/api-reference/api-reference/payments/payments--create.mdx b/api-reference/v1/payments/payments--create.mdx similarity index 76% rename from api-reference/api-reference/payments/payments--create.mdx rename to api-reference/v1/payments/payments--create.mdx index af436038731..6ee948cb83b 100644 --- a/api-reference/api-reference/payments/payments--create.mdx +++ b/api-reference/v1/payments/payments--create.mdx @@ -1,4 +1,4 @@ --- -openapi: openapi_spec post /payments +openapi: post /payments --- <Tip> Use the dropdown on the top right corner of the code snippet to try out different payment scenarios. </Tip> \ No newline at end of file diff --git a/api-reference/api-reference/payments/payments--external-3ds-authentication.mdx b/api-reference/v1/payments/payments--external-3ds-authentication.mdx similarity index 100% rename from api-reference/api-reference/payments/payments--external-3ds-authentication.mdx rename to api-reference/v1/payments/payments--external-3ds-authentication.mdx diff --git a/api-reference/api-reference/payments/payments--incremental-authorization.mdx b/api-reference/v1/payments/payments--incremental-authorization.mdx similarity index 100% rename from api-reference/api-reference/payments/payments--incremental-authorization.mdx rename to api-reference/v1/payments/payments--incremental-authorization.mdx diff --git a/api-reference/v1/payments/payments--list.mdx b/api-reference/v1/payments/payments--list.mdx new file mode 100644 index 00000000000..13c3a03df40 --- /dev/null +++ b/api-reference/v1/payments/payments--list.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /payments/list +--- \ No newline at end of file diff --git a/api-reference/api-reference/payments/payments--post-session-tokens.mdx b/api-reference/v1/payments/payments--post-session-tokens.mdx similarity index 100% rename from api-reference/api-reference/payments/payments--post-session-tokens.mdx rename to api-reference/v1/payments/payments--post-session-tokens.mdx diff --git a/api-reference/v1/payments/payments--retrieve.mdx b/api-reference/v1/payments/payments--retrieve.mdx new file mode 100644 index 00000000000..269ab887a5b --- /dev/null +++ b/api-reference/v1/payments/payments--retrieve.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /payments/{payment_id} +--- \ No newline at end of file diff --git a/api-reference/v1/payments/payments--session-token.mdx b/api-reference/v1/payments/payments--session-token.mdx new file mode 100644 index 00000000000..7f060a06af5 --- /dev/null +++ b/api-reference/v1/payments/payments--session-token.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /payments/session_tokens +--- \ No newline at end of file diff --git a/api-reference/api-reference/payments/payments--update-metadata.mdx b/api-reference/v1/payments/payments--update-metadata.mdx similarity index 100% rename from api-reference/api-reference/payments/payments--update-metadata.mdx rename to api-reference/v1/payments/payments--update-metadata.mdx diff --git a/api-reference/v1/payments/payments--update.mdx b/api-reference/v1/payments/payments--update.mdx new file mode 100644 index 00000000000..9eb6f4bf89d --- /dev/null +++ b/api-reference/v1/payments/payments--update.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /payments/{payment_id} +--- \ No newline at end of file diff --git a/api-reference/v1/payments/payments-link--retrieve.mdx b/api-reference/v1/payments/payments-link--retrieve.mdx new file mode 100644 index 00000000000..d5ed6957f7c --- /dev/null +++ b/api-reference/v1/payments/payments-link--retrieve.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /payment_link/{payment_link_id} +--- \ No newline at end of file diff --git a/api-reference/api-reference/payments/setup--instructions.mdx b/api-reference/v1/payments/setup--instructions.mdx similarity index 100% rename from api-reference/api-reference/payments/setup--instructions.mdx rename to api-reference/v1/payments/setup--instructions.mdx diff --git a/api-reference/v1/payouts/payouts--cancel.mdx b/api-reference/v1/payouts/payouts--cancel.mdx new file mode 100644 index 00000000000..5bd8875e19e --- /dev/null +++ b/api-reference/v1/payouts/payouts--cancel.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /payouts/{payout_id}/cancel +--- \ No newline at end of file diff --git a/api-reference/v1/payouts/payouts--confirm.mdx b/api-reference/v1/payouts/payouts--confirm.mdx new file mode 100644 index 00000000000..14373744eb1 --- /dev/null +++ b/api-reference/v1/payouts/payouts--confirm.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /payouts/{payout_id}/confirm +--- \ No newline at end of file diff --git a/api-reference/v1/payouts/payouts--create.mdx b/api-reference/v1/payouts/payouts--create.mdx new file mode 100644 index 00000000000..923d4f0bc13 --- /dev/null +++ b/api-reference/v1/payouts/payouts--create.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /payouts/create +--- \ No newline at end of file diff --git a/api-reference/api-reference/payouts/payouts--filter.mdx b/api-reference/v1/payouts/payouts--filter.mdx similarity index 100% rename from api-reference/api-reference/payouts/payouts--filter.mdx rename to api-reference/v1/payouts/payouts--filter.mdx diff --git a/api-reference/v1/payouts/payouts--fulfill.mdx b/api-reference/v1/payouts/payouts--fulfill.mdx new file mode 100644 index 00000000000..5e11b3b11c5 --- /dev/null +++ b/api-reference/v1/payouts/payouts--fulfill.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /payouts/{payout_id}/fulfill +--- \ No newline at end of file diff --git a/api-reference/api-reference/payouts/payouts--list-filters.mdx b/api-reference/v1/payouts/payouts--list-filters.mdx similarity index 100% rename from api-reference/api-reference/payouts/payouts--list-filters.mdx rename to api-reference/v1/payouts/payouts--list-filters.mdx diff --git a/api-reference/api-reference/payouts/payouts--list.mdx b/api-reference/v1/payouts/payouts--list.mdx similarity index 100% rename from api-reference/api-reference/payouts/payouts--list.mdx rename to api-reference/v1/payouts/payouts--list.mdx diff --git a/api-reference/v1/payouts/payouts--retrieve.mdx b/api-reference/v1/payouts/payouts--retrieve.mdx new file mode 100644 index 00000000000..81b9c2b6a0a --- /dev/null +++ b/api-reference/v1/payouts/payouts--retrieve.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /payouts/{payout_id} +--- \ No newline at end of file diff --git a/api-reference/v1/payouts/payouts--update.mdx b/api-reference/v1/payouts/payouts--update.mdx new file mode 100644 index 00000000000..c6a61c7715a --- /dev/null +++ b/api-reference/v1/payouts/payouts--update.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /payouts/{payout_id} +--- \ No newline at end of file diff --git a/api-reference/api-reference/poll/poll--retrieve-poll-status.mdx b/api-reference/v1/poll/poll--retrieve-poll-status.mdx similarity index 100% rename from api-reference/api-reference/poll/poll--retrieve-poll-status.mdx rename to api-reference/v1/poll/poll--retrieve-poll-status.mdx diff --git a/api-reference/v1/refunds/refunds--create.mdx b/api-reference/v1/refunds/refunds--create.mdx new file mode 100644 index 00000000000..1c60568f2a7 --- /dev/null +++ b/api-reference/v1/refunds/refunds--create.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /refunds +--- \ No newline at end of file diff --git a/api-reference/v1/refunds/refunds--list.mdx b/api-reference/v1/refunds/refunds--list.mdx new file mode 100644 index 00000000000..a577ab28514 --- /dev/null +++ b/api-reference/v1/refunds/refunds--list.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /refunds/list +--- \ No newline at end of file diff --git a/api-reference/v1/refunds/refunds--retrieve.mdx b/api-reference/v1/refunds/refunds--retrieve.mdx new file mode 100644 index 00000000000..bbed228309c --- /dev/null +++ b/api-reference/v1/refunds/refunds--retrieve.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /refunds/{refund_id} +--- \ No newline at end of file diff --git a/api-reference/v1/refunds/refunds--update.mdx b/api-reference/v1/refunds/refunds--update.mdx new file mode 100644 index 00000000000..dc6c5d585c6 --- /dev/null +++ b/api-reference/v1/refunds/refunds--update.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /refunds/{refund_id} +--- \ No newline at end of file diff --git a/api-reference/v1/relay/relay--retrieve.mdx b/api-reference/v1/relay/relay--retrieve.mdx new file mode 100644 index 00000000000..de0f42bbe53 --- /dev/null +++ b/api-reference/v1/relay/relay--retrieve.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /relay/{relay_id} +--- \ No newline at end of file diff --git a/api-reference/v1/relay/relay.mdx b/api-reference/v1/relay/relay.mdx new file mode 100644 index 00000000000..393df84d0a5 --- /dev/null +++ b/api-reference/v1/relay/relay.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /relay +--- \ No newline at end of file diff --git a/api-reference/api-reference/routing/routing--activate-config.mdx b/api-reference/v1/routing/routing--activate-config.mdx similarity index 100% rename from api-reference/api-reference/routing/routing--activate-config.mdx rename to api-reference/v1/routing/routing--activate-config.mdx diff --git a/api-reference/api-reference/routing/routing--create.mdx b/api-reference/v1/routing/routing--create.mdx similarity index 100% rename from api-reference/api-reference/routing/routing--create.mdx rename to api-reference/v1/routing/routing--create.mdx diff --git a/api-reference/api-reference/routing/routing--deactivate.mdx b/api-reference/v1/routing/routing--deactivate.mdx similarity index 100% rename from api-reference/api-reference/routing/routing--deactivate.mdx rename to api-reference/v1/routing/routing--deactivate.mdx diff --git a/api-reference/api-reference/routing/routing--list.mdx b/api-reference/v1/routing/routing--list.mdx similarity index 100% rename from api-reference/api-reference/routing/routing--list.mdx rename to api-reference/v1/routing/routing--list.mdx diff --git a/api-reference/api-reference/routing/routing--retrieve-config.mdx b/api-reference/v1/routing/routing--retrieve-config.mdx similarity index 100% rename from api-reference/api-reference/routing/routing--retrieve-config.mdx rename to api-reference/v1/routing/routing--retrieve-config.mdx diff --git a/api-reference/api-reference/routing/routing--retrieve-default-config.mdx b/api-reference/v1/routing/routing--retrieve-default-config.mdx similarity index 100% rename from api-reference/api-reference/routing/routing--retrieve-default-config.mdx rename to api-reference/v1/routing/routing--retrieve-default-config.mdx diff --git a/api-reference/api-reference/routing/routing--retrieve-default-for-profile.mdx b/api-reference/v1/routing/routing--retrieve-default-for-profile.mdx similarity index 100% rename from api-reference/api-reference/routing/routing--retrieve-default-for-profile.mdx rename to api-reference/v1/routing/routing--retrieve-default-for-profile.mdx diff --git a/api-reference/api-reference/routing/routing--retrieve.mdx b/api-reference/v1/routing/routing--retrieve.mdx similarity index 100% rename from api-reference/api-reference/routing/routing--retrieve.mdx rename to api-reference/v1/routing/routing--retrieve.mdx diff --git a/api-reference/api-reference/routing/routing--update-default-config.mdx b/api-reference/v1/routing/routing--update-default-config.mdx similarity index 100% rename from api-reference/api-reference/routing/routing--update-default-config.mdx rename to api-reference/v1/routing/routing--update-default-config.mdx diff --git a/api-reference/api-reference/routing/routing--update-default-for-profile.mdx b/api-reference/v1/routing/routing--update-default-for-profile.mdx similarity index 100% rename from api-reference/api-reference/routing/routing--update-default-for-profile.mdx rename to api-reference/v1/routing/routing--update-default-for-profile.mdx diff --git a/api-reference/api-reference/schemas/outgoing--webhook.mdx b/api-reference/v1/schemas/outgoing--webhook.mdx similarity index 100% rename from api-reference/api-reference/schemas/outgoing--webhook.mdx rename to api-reference/v1/schemas/outgoing--webhook.mdx diff --git a/api-reference-v2/api-reference/api-key/api-key--create.mdx b/api-reference/v2/api-key/api-key--create.mdx similarity index 100% rename from api-reference-v2/api-reference/api-key/api-key--create.mdx rename to api-reference/v2/api-key/api-key--create.mdx diff --git a/api-reference-v2/api-reference/api-key/api-key--list.mdx b/api-reference/v2/api-key/api-key--list.mdx similarity index 100% rename from api-reference-v2/api-reference/api-key/api-key--list.mdx rename to api-reference/v2/api-key/api-key--list.mdx diff --git a/api-reference-v2/api-reference/api-key/api-key--retrieve.mdx b/api-reference/v2/api-key/api-key--retrieve.mdx similarity index 100% rename from api-reference-v2/api-reference/api-key/api-key--retrieve.mdx rename to api-reference/v2/api-key/api-key--retrieve.mdx diff --git a/api-reference-v2/api-reference/api-key/api-key--revoke.mdx b/api-reference/v2/api-key/api-key--revoke.mdx similarity index 100% rename from api-reference-v2/api-reference/api-key/api-key--revoke.mdx rename to api-reference/v2/api-key/api-key--revoke.mdx diff --git a/api-reference-v2/api-reference/api-key/api-key--update.mdx b/api-reference/v2/api-key/api-key--update.mdx similarity index 100% rename from api-reference-v2/api-reference/api-key/api-key--update.mdx rename to api-reference/v2/api-key/api-key--update.mdx diff --git a/api-reference-v2/api-reference/business-profile/merchant-connector--list.mdx b/api-reference/v2/business-profile/merchant-connector--list.mdx similarity index 100% rename from api-reference-v2/api-reference/business-profile/merchant-connector--list.mdx rename to api-reference/v2/business-profile/merchant-connector--list.mdx diff --git a/api-reference-v2/api-reference/business-profile/profile--connector-accounts-list.mdx b/api-reference/v2/business-profile/profile--connector-accounts-list.mdx similarity index 100% rename from api-reference-v2/api-reference/business-profile/profile--connector-accounts-list.mdx rename to api-reference/v2/business-profile/profile--connector-accounts-list.mdx diff --git a/api-reference-v2/api-reference/connector-account/connector-account--create.mdx b/api-reference/v2/connector-account/connector-account--create.mdx similarity index 100% rename from api-reference-v2/api-reference/connector-account/connector-account--create.mdx rename to api-reference/v2/connector-account/connector-account--create.mdx diff --git a/api-reference-v2/api-reference/connector-account/connector-account--delete.mdx b/api-reference/v2/connector-account/connector-account--delete.mdx similarity index 100% rename from api-reference-v2/api-reference/connector-account/connector-account--delete.mdx rename to api-reference/v2/connector-account/connector-account--delete.mdx diff --git a/api-reference-v2/api-reference/connector-account/connector-account--retrieve.mdx b/api-reference/v2/connector-account/connector-account--retrieve.mdx similarity index 100% rename from api-reference-v2/api-reference/connector-account/connector-account--retrieve.mdx rename to api-reference/v2/connector-account/connector-account--retrieve.mdx diff --git a/api-reference-v2/api-reference/connector-account/connector-account--update.mdx b/api-reference/v2/connector-account/connector-account--update.mdx similarity index 100% rename from api-reference-v2/api-reference/connector-account/connector-account--update.mdx rename to api-reference/v2/connector-account/connector-account--update.mdx diff --git a/api-reference-v2/api-reference/customers/customers--create.mdx b/api-reference/v2/customers/customers--create.mdx similarity index 100% rename from api-reference-v2/api-reference/customers/customers--create.mdx rename to api-reference/v2/customers/customers--create.mdx diff --git a/api-reference-v2/api-reference/customers/customers--delete.mdx b/api-reference/v2/customers/customers--delete.mdx similarity index 100% rename from api-reference-v2/api-reference/customers/customers--delete.mdx rename to api-reference/v2/customers/customers--delete.mdx diff --git a/api-reference-v2/api-reference/customers/customers--list-saved-payment-methods.mdx b/api-reference/v2/customers/customers--list-saved-payment-methods.mdx similarity index 100% rename from api-reference-v2/api-reference/customers/customers--list-saved-payment-methods.mdx rename to api-reference/v2/customers/customers--list-saved-payment-methods.mdx diff --git a/api-reference-v2/api-reference/customers/customers--list.mdx b/api-reference/v2/customers/customers--list.mdx similarity index 100% rename from api-reference-v2/api-reference/customers/customers--list.mdx rename to api-reference/v2/customers/customers--list.mdx diff --git a/api-reference-v2/api-reference/customers/customers--retrieve.mdx b/api-reference/v2/customers/customers--retrieve.mdx similarity index 100% rename from api-reference-v2/api-reference/customers/customers--retrieve.mdx rename to api-reference/v2/customers/customers--retrieve.mdx diff --git a/api-reference-v2/api-reference/customers/customers--update.mdx b/api-reference/v2/customers/customers--update.mdx similarity index 100% rename from api-reference-v2/api-reference/customers/customers--update.mdx rename to api-reference/v2/customers/customers--update.mdx diff --git a/api-reference-v2/api-reference/merchant-account/business-profile--list.mdx b/api-reference/v2/merchant-account/business-profile--list.mdx similarity index 100% rename from api-reference-v2/api-reference/merchant-account/business-profile--list.mdx rename to api-reference/v2/merchant-account/business-profile--list.mdx diff --git a/api-reference-v2/api-reference/merchant-account/merchant-account--create.mdx b/api-reference/v2/merchant-account/merchant-account--create.mdx similarity index 100% rename from api-reference-v2/api-reference/merchant-account/merchant-account--create.mdx rename to api-reference/v2/merchant-account/merchant-account--create.mdx diff --git a/api-reference-v2/api-reference/merchant-account/merchant-account--profile-list.mdx b/api-reference/v2/merchant-account/merchant-account--profile-list.mdx similarity index 100% rename from api-reference-v2/api-reference/merchant-account/merchant-account--profile-list.mdx rename to api-reference/v2/merchant-account/merchant-account--profile-list.mdx diff --git a/api-reference-v2/api-reference/merchant-account/merchant-account--retrieve.mdx b/api-reference/v2/merchant-account/merchant-account--retrieve.mdx similarity index 100% rename from api-reference-v2/api-reference/merchant-account/merchant-account--retrieve.mdx rename to api-reference/v2/merchant-account/merchant-account--retrieve.mdx diff --git a/api-reference-v2/api-reference/merchant-account/merchant-account--update.mdx b/api-reference/v2/merchant-account/merchant-account--update.mdx similarity index 100% rename from api-reference-v2/api-reference/merchant-account/merchant-account--update.mdx rename to api-reference/v2/merchant-account/merchant-account--update.mdx diff --git a/api-reference-v2/api-reference/merchant-connector-account/connector-account--create.mdx b/api-reference/v2/merchant-connector-account/connector-account--create.mdx similarity index 100% rename from api-reference-v2/api-reference/merchant-connector-account/connector-account--create.mdx rename to api-reference/v2/merchant-connector-account/connector-account--create.mdx diff --git a/api-reference-v2/api-reference/merchant-connector-account/connector-account--retrieve.mdx b/api-reference/v2/merchant-connector-account/connector-account--retrieve.mdx similarity index 100% rename from api-reference-v2/api-reference/merchant-connector-account/connector-account--retrieve.mdx rename to api-reference/v2/merchant-connector-account/connector-account--retrieve.mdx diff --git a/api-reference-v2/api-reference/merchant-connector-account/connector-account--update.mdx b/api-reference/v2/merchant-connector-account/connector-account--update.mdx similarity index 100% rename from api-reference-v2/api-reference/merchant-connector-account/connector-account--update.mdx rename to api-reference/v2/merchant-connector-account/connector-account--update.mdx diff --git a/api-reference-v2/api-reference/merchant-connector-account/merchant-connector--delete.mdx b/api-reference/v2/merchant-connector-account/merchant-connector--delete.mdx similarity index 100% rename from api-reference-v2/api-reference/merchant-connector-account/merchant-connector--delete.mdx rename to api-reference/v2/merchant-connector-account/merchant-connector--delete.mdx diff --git a/api-reference-v2/openapi_spec.json b/api-reference/v2/openapi_spec_v2.json similarity index 100% rename from api-reference-v2/openapi_spec.json rename to api-reference/v2/openapi_spec_v2.json diff --git a/api-reference-v2/api-reference/organization/organization--create.mdx b/api-reference/v2/organization/organization--create.mdx similarity index 100% rename from api-reference-v2/api-reference/organization/organization--create.mdx rename to api-reference/v2/organization/organization--create.mdx diff --git a/api-reference-v2/api-reference/organization/organization--merchant-account--list.mdx b/api-reference/v2/organization/organization--merchant-account--list.mdx similarity index 100% rename from api-reference-v2/api-reference/organization/organization--merchant-account--list.mdx rename to api-reference/v2/organization/organization--merchant-account--list.mdx diff --git a/api-reference-v2/api-reference/organization/organization--retrieve.mdx b/api-reference/v2/organization/organization--retrieve.mdx similarity index 100% rename from api-reference-v2/api-reference/organization/organization--retrieve.mdx rename to api-reference/v2/organization/organization--retrieve.mdx diff --git a/api-reference-v2/api-reference/organization/organization--update.mdx b/api-reference/v2/organization/organization--update.mdx similarity index 100% rename from api-reference-v2/api-reference/organization/organization--update.mdx rename to api-reference/v2/organization/organization--update.mdx diff --git a/api-reference-v2/api-reference/payment-method-session/payment-method-session--confirm-a-payment-method-session.mdx b/api-reference/v2/payment-method-session/payment-method-session--confirm-a-payment-method-session.mdx similarity index 100% rename from api-reference-v2/api-reference/payment-method-session/payment-method-session--confirm-a-payment-method-session.mdx rename to api-reference/v2/payment-method-session/payment-method-session--confirm-a-payment-method-session.mdx diff --git a/api-reference-v2/api-reference/payment-method-session/payment-method-session--create.mdx b/api-reference/v2/payment-method-session/payment-method-session--create.mdx similarity index 100% rename from api-reference-v2/api-reference/payment-method-session/payment-method-session--create.mdx rename to api-reference/v2/payment-method-session/payment-method-session--create.mdx diff --git a/api-reference-v2/api-reference/payment-method-session/payment-method-session--delete-a-saved-payment-method.mdx b/api-reference/v2/payment-method-session/payment-method-session--delete-a-saved-payment-method.mdx similarity index 100% rename from api-reference-v2/api-reference/payment-method-session/payment-method-session--delete-a-saved-payment-method.mdx rename to api-reference/v2/payment-method-session/payment-method-session--delete-a-saved-payment-method.mdx diff --git a/api-reference-v2/api-reference/payment-method-session/payment-method-session--list-payment-methods.mdx b/api-reference/v2/payment-method-session/payment-method-session--list-payment-methods.mdx similarity index 100% rename from api-reference-v2/api-reference/payment-method-session/payment-method-session--list-payment-methods.mdx rename to api-reference/v2/payment-method-session/payment-method-session--list-payment-methods.mdx diff --git a/api-reference-v2/api-reference/payment-method-session/payment-method-session--retrieve.mdx b/api-reference/v2/payment-method-session/payment-method-session--retrieve.mdx similarity index 100% rename from api-reference-v2/api-reference/payment-method-session/payment-method-session--retrieve.mdx rename to api-reference/v2/payment-method-session/payment-method-session--retrieve.mdx diff --git a/api-reference-v2/api-reference/payment-method-session/payment-method-session--update-a-saved-payment-method.mdx b/api-reference/v2/payment-method-session/payment-method-session--update-a-saved-payment-method.mdx similarity index 100% rename from api-reference-v2/api-reference/payment-method-session/payment-method-session--update-a-saved-payment-method.mdx rename to api-reference/v2/payment-method-session/payment-method-session--update-a-saved-payment-method.mdx diff --git a/api-reference-v2/api-reference/payment-methods/list-customer-saved-payment-methods-for-a-payment.mdx b/api-reference/v2/payment-methods/list-customer-saved-payment-methods-for-a-payment.mdx similarity index 100% rename from api-reference-v2/api-reference/payment-methods/list-customer-saved-payment-methods-for-a-payment.mdx rename to api-reference/v2/payment-methods/list-customer-saved-payment-methods-for-a-payment.mdx diff --git a/api-reference-v2/api-reference/payment-methods/list-payment-methods-for-a-customer.mdx b/api-reference/v2/payment-methods/list-payment-methods-for-a-customer.mdx similarity index 100% rename from api-reference-v2/api-reference/payment-methods/list-payment-methods-for-a-customer.mdx rename to api-reference/v2/payment-methods/list-payment-methods-for-a-customer.mdx diff --git a/api-reference-v2/api-reference/payment-methods/list-saved-payment-methods-for-a-customer.mdx b/api-reference/v2/payment-methods/list-saved-payment-methods-for-a-customer.mdx similarity index 100% rename from api-reference-v2/api-reference/payment-methods/list-saved-payment-methods-for-a-customer.mdx rename to api-reference/v2/payment-methods/list-saved-payment-methods-for-a-customer.mdx diff --git a/api-reference-v2/api-reference/payment-methods/payment-method--confirm-intent.mdx b/api-reference/v2/payment-methods/payment-method--confirm-intent.mdx similarity index 100% rename from api-reference-v2/api-reference/payment-methods/payment-method--confirm-intent.mdx rename to api-reference/v2/payment-methods/payment-method--confirm-intent.mdx diff --git a/api-reference-v2/api-reference/payment-methods/payment-method--create-intent.mdx b/api-reference/v2/payment-methods/payment-method--create-intent.mdx similarity index 100% rename from api-reference-v2/api-reference/payment-methods/payment-method--create-intent.mdx rename to api-reference/v2/payment-methods/payment-method--create-intent.mdx diff --git a/api-reference-v2/api-reference/payment-methods/payment-method--create.mdx b/api-reference/v2/payment-methods/payment-method--create.mdx similarity index 100% rename from api-reference-v2/api-reference/payment-methods/payment-method--create.mdx rename to api-reference/v2/payment-methods/payment-method--create.mdx diff --git a/api-reference-v2/api-reference/payment-methods/payment-method--delete.mdx b/api-reference/v2/payment-methods/payment-method--delete.mdx similarity index 100% rename from api-reference-v2/api-reference/payment-methods/payment-method--delete.mdx rename to api-reference/v2/payment-methods/payment-method--delete.mdx diff --git a/api-reference-v2/api-reference/payment-methods/payment-method--payment-methods-list.mdx b/api-reference/v2/payment-methods/payment-method--payment-methods-list.mdx similarity index 100% rename from api-reference-v2/api-reference/payment-methods/payment-method--payment-methods-list.mdx rename to api-reference/v2/payment-methods/payment-method--payment-methods-list.mdx diff --git a/api-reference-v2/api-reference/payment-methods/payment-method--retrieve.mdx b/api-reference/v2/payment-methods/payment-method--retrieve.mdx similarity index 100% rename from api-reference-v2/api-reference/payment-methods/payment-method--retrieve.mdx rename to api-reference/v2/payment-methods/payment-method--retrieve.mdx diff --git a/api-reference-v2/api-reference/payment-methods/payment-method--update.mdx b/api-reference/v2/payment-methods/payment-method--update.mdx similarity index 100% rename from api-reference-v2/api-reference/payment-methods/payment-method--update.mdx rename to api-reference/v2/payment-methods/payment-method--update.mdx diff --git a/api-reference-v2/api-reference/payment-methods/payment-methods--payment-methods-list.mdx b/api-reference/v2/payment-methods/payment-methods--payment-methods-list.mdx similarity index 100% rename from api-reference-v2/api-reference/payment-methods/payment-methods--payment-methods-list.mdx rename to api-reference/v2/payment-methods/payment-methods--payment-methods-list.mdx diff --git a/api-reference-v2/api-reference/payments/payments--confirm-intent.mdx b/api-reference/v2/payments/payments--confirm-intent.mdx similarity index 100% rename from api-reference-v2/api-reference/payments/payments--confirm-intent.mdx rename to api-reference/v2/payments/payments--confirm-intent.mdx diff --git a/api-reference-v2/api-reference/payments/payments--create-and-confirm-intent.mdx b/api-reference/v2/payments/payments--create-and-confirm-intent.mdx similarity index 100% rename from api-reference-v2/api-reference/payments/payments--create-and-confirm-intent.mdx rename to api-reference/v2/payments/payments--create-and-confirm-intent.mdx diff --git a/api-reference-v2/api-reference/payments/payments--create-intent.mdx b/api-reference/v2/payments/payments--create-intent.mdx similarity index 100% rename from api-reference-v2/api-reference/payments/payments--create-intent.mdx rename to api-reference/v2/payments/payments--create-intent.mdx diff --git a/api-reference-v2/api-reference/payments/payments--get-intent.mdx b/api-reference/v2/payments/payments--get-intent.mdx similarity index 100% rename from api-reference-v2/api-reference/payments/payments--get-intent.mdx rename to api-reference/v2/payments/payments--get-intent.mdx diff --git a/api-reference-v2/api-reference/payments/payments--get.mdx b/api-reference/v2/payments/payments--get.mdx similarity index 100% rename from api-reference-v2/api-reference/payments/payments--get.mdx rename to api-reference/v2/payments/payments--get.mdx diff --git a/api-reference-v2/api-reference/payments/payments--list.mdx b/api-reference/v2/payments/payments--list.mdx similarity index 100% rename from api-reference-v2/api-reference/payments/payments--list.mdx rename to api-reference/v2/payments/payments--list.mdx diff --git a/api-reference-v2/api-reference/payments/payments--payment-methods-list.mdx b/api-reference/v2/payments/payments--payment-methods-list.mdx similarity index 100% rename from api-reference-v2/api-reference/payments/payments--payment-methods-list.mdx rename to api-reference/v2/payments/payments--payment-methods-list.mdx diff --git a/api-reference-v2/api-reference/payments/payments--session-token.mdx b/api-reference/v2/payments/payments--session-token.mdx similarity index 100% rename from api-reference-v2/api-reference/payments/payments--session-token.mdx rename to api-reference/v2/payments/payments--session-token.mdx diff --git a/api-reference-v2/api-reference/payments/payments--update-intent.mdx b/api-reference/v2/payments/payments--update-intent.mdx similarity index 100% rename from api-reference-v2/api-reference/payments/payments--update-intent.mdx rename to api-reference/v2/payments/payments--update-intent.mdx diff --git a/api-reference-v2/api-reference/profile/merchant-connector--list.mdx b/api-reference/v2/profile/merchant-connector--list.mdx similarity index 100% rename from api-reference-v2/api-reference/profile/merchant-connector--list.mdx rename to api-reference/v2/profile/merchant-connector--list.mdx diff --git a/api-reference-v2/api-reference/profile/profile--activate-routing-algorithm.mdx b/api-reference/v2/profile/profile--activate-routing-algorithm.mdx similarity index 100% rename from api-reference-v2/api-reference/profile/profile--activate-routing-algorithm.mdx rename to api-reference/v2/profile/profile--activate-routing-algorithm.mdx diff --git a/api-reference-v2/api-reference/profile/profile--create.mdx b/api-reference/v2/profile/profile--create.mdx similarity index 100% rename from api-reference-v2/api-reference/profile/profile--create.mdx rename to api-reference/v2/profile/profile--create.mdx diff --git a/api-reference-v2/api-reference/profile/profile--deactivate-routing-algorithm.mdx b/api-reference/v2/profile/profile--deactivate-routing-algorithm.mdx similarity index 100% rename from api-reference-v2/api-reference/profile/profile--deactivate-routing-algorithm.mdx rename to api-reference/v2/profile/profile--deactivate-routing-algorithm.mdx diff --git a/api-reference-v2/api-reference/profile/profile--retrieve-active-routing-algorithm.mdx b/api-reference/v2/profile/profile--retrieve-active-routing-algorithm.mdx similarity index 100% rename from api-reference-v2/api-reference/profile/profile--retrieve-active-routing-algorithm.mdx rename to api-reference/v2/profile/profile--retrieve-active-routing-algorithm.mdx diff --git a/api-reference-v2/api-reference/profile/profile--retrieve-default-fallback-routing-algorithm.mdx b/api-reference/v2/profile/profile--retrieve-default-fallback-routing-algorithm.mdx similarity index 100% rename from api-reference-v2/api-reference/profile/profile--retrieve-default-fallback-routing-algorithm.mdx rename to api-reference/v2/profile/profile--retrieve-default-fallback-routing-algorithm.mdx diff --git a/api-reference-v2/api-reference/profile/profile--retrieve.mdx b/api-reference/v2/profile/profile--retrieve.mdx similarity index 100% rename from api-reference-v2/api-reference/profile/profile--retrieve.mdx rename to api-reference/v2/profile/profile--retrieve.mdx diff --git a/api-reference-v2/api-reference/profile/profile--update-default-fallback-routing-algorithm.mdx b/api-reference/v2/profile/profile--update-default-fallback-routing-algorithm.mdx similarity index 100% rename from api-reference-v2/api-reference/profile/profile--update-default-fallback-routing-algorithm.mdx rename to api-reference/v2/profile/profile--update-default-fallback-routing-algorithm.mdx diff --git a/api-reference-v2/api-reference/profile/profile--update.mdx b/api-reference/v2/profile/profile--update.mdx similarity index 100% rename from api-reference-v2/api-reference/profile/profile--update.mdx rename to api-reference/v2/profile/profile--update.mdx diff --git a/api-reference-v2/api-reference/proxy/proxy.mdx b/api-reference/v2/proxy/proxy.mdx similarity index 100% rename from api-reference-v2/api-reference/proxy/proxy.mdx rename to api-reference/v2/proxy/proxy.mdx diff --git a/api-reference-v2/api-reference/refunds/refunds--create.mdx b/api-reference/v2/refunds/refunds--create.mdx similarity index 100% rename from api-reference-v2/api-reference/refunds/refunds--create.mdx rename to api-reference/v2/refunds/refunds--create.mdx diff --git a/api-reference-v2/api-reference/routing/routing--create.mdx b/api-reference/v2/routing/routing--create.mdx similarity index 100% rename from api-reference-v2/api-reference/routing/routing--create.mdx rename to api-reference/v2/routing/routing--create.mdx diff --git a/api-reference-v2/api-reference/routing/routing--retrieve.mdx b/api-reference/v2/routing/routing--retrieve.mdx similarity index 100% rename from api-reference-v2/api-reference/routing/routing--retrieve.mdx rename to api-reference/v2/routing/routing--retrieve.mdx diff --git a/api-reference-v2/api-reference/tokenization/tokenization--create.mdx b/api-reference/v2/tokenization/tokenization--create.mdx similarity index 100% rename from api-reference-v2/api-reference/tokenization/tokenization--create.mdx rename to api-reference/v2/tokenization/tokenization--create.mdx diff --git a/crates/openapi/src/main.rs b/crates/openapi/src/main.rs index 975ff33107f..cf8158cfb02 100644 --- a/crates/openapi/src/main.rs +++ b/crates/openapi/src/main.rs @@ -10,10 +10,10 @@ fn main() { compile_error!("features v1 and v2 are mutually exclusive, please enable only one of them"); #[cfg(feature = "v1")] - let relative_file_path = "api-reference/openapi_spec.json"; + let relative_file_path = "api-reference/v1/openapi_spec_v1.json"; #[cfg(feature = "v2")] - let relative_file_path = "api-reference-v2/openapi_spec.json"; + let relative_file_path = "api-reference/v2/openapi_spec_v2.json"; #[cfg(any(feature = "v1", feature = "v2"))] let mut file_path = router_env::workspace_path();
2025-06-12T09:49:44Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [x] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - Moved both `v1` and `v2` API docs under `api-reference` directory - Renamed `openapi_spec.json` files for v1 and v2 - Updated OpenAPI spec file paths in `openapi` crate - Modified OpenAPI spec path in CI pipeline ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #8332 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Executed: ```bash cargo run -p openapi --features v1 ``` and verified `openapi_spec_v1.json` generated How the version dropdown looks like: <img width="599" alt="image" src="https://github.com/user-attachments/assets/41d0c676-9a80-4a7e-ac33-9f56d9f18703" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
61c2e2c75fabdb03c5599df97240a030cb7b5b6a
61c2e2c75fabdb03c5599df97240a030cb7b5b6a
juspay/hyperswitch
juspay__hyperswitch-8318
Bug: [FEATURE] include connector_customer creation during payment methods migration ### Feature Description `connector_customer` is a map of merchant_connector_id (key) and connector_customer_id (value) in `customers` table which stores the customer's ID created at connector's end. This is usually populated as a part of payments flow when customer creation is required at connector's end. The requirement here is to populate this during payment methods migration which also handles creation of customers. ### Possible Implementation 1. Read `connector_customer_id` in payment methods migrate API 2. Pass it down to `create_customer` which handles creation of new customers 3. In case customer already exists, do nothing 4. In case customer does not exist, `connector_customer` is populated with the merchant's connector ID and connector's customer ID. ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 6b0e9dcb38d..5ecd2f71ef7 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -16,12 +16,10 @@ use masking::PeekInterface; use serde::de; use utoipa::{schema, ToSchema}; -#[cfg(feature = "v1")] -use crate::customers; #[cfg(feature = "payouts")] use crate::payouts; use crate::{ - admin, enums as api_enums, + admin, customers, enums as api_enums, payments::{self, BankCodeResponse}, }; @@ -2485,6 +2483,7 @@ pub struct PaymentMethodRecord { pub payment_method_type: Option<api_enums::PaymentMethodType>, pub nick_name: masking::Secret<String>, pub payment_instrument_id: Option<masking::Secret<String>>, + pub connector_customer_id: Option<String>, pub card_number_masked: masking::Secret<String>, pub card_expiry_month: masking::Secret<String>, pub card_expiry_year: masking::Secret<String>, @@ -2510,6 +2509,18 @@ pub struct PaymentMethodRecord { pub network_token_requestor_ref_id: Option<String>, } +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] +pub struct ConnectorCustomerDetails { + pub connector_customer_id: String, + pub merchant_connector_id: id_type::MerchantConnectorAccountId, +} + +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] +pub struct PaymentMethodCustomerMigrate { + pub customer: customers::CustomerRequest, + pub connector_customer_details: Option<ConnectorCustomerDetails>, +} + #[derive(Debug, Default, serde::Serialize)] pub struct PaymentMethodMigrationResponse { pub line_number: Option<i64>, @@ -2678,29 +2689,40 @@ impl } #[cfg(feature = "v1")] -impl From<(PaymentMethodRecord, id_type::MerchantId)> for customers::CustomerRequest { +impl From<(PaymentMethodRecord, id_type::MerchantId)> for PaymentMethodCustomerMigrate { fn from(value: (PaymentMethodRecord, id_type::MerchantId)) -> Self { let (record, merchant_id) = value; Self { - customer_id: Some(record.customer_id), - merchant_id, - name: record.name, - email: record.email, - phone: record.phone, - description: None, - phone_country_code: record.phone_country_code, - address: Some(payments::AddressDetails { - city: Some(record.billing_address_city), - country: record.billing_address_country, - line1: Some(record.billing_address_line1), - line2: record.billing_address_line2, - state: Some(record.billing_address_state), - line3: record.billing_address_line3, - zip: Some(record.billing_address_zip), - first_name: Some(record.billing_address_first_name), - last_name: Some(record.billing_address_last_name), - }), - metadata: None, + customer: customers::CustomerRequest { + customer_id: Some(record.customer_id), + merchant_id, + name: record.name, + email: record.email, + phone: record.phone, + description: None, + phone_country_code: record.phone_country_code, + address: Some(payments::AddressDetails { + city: Some(record.billing_address_city), + country: record.billing_address_country, + line1: Some(record.billing_address_line1), + line2: record.billing_address_line2, + state: Some(record.billing_address_state), + line3: record.billing_address_line3, + zip: Some(record.billing_address_zip), + first_name: Some(record.billing_address_first_name), + last_name: Some(record.billing_address_last_name), + }), + metadata: None, + }, + connector_customer_details: record + .connector_customer_id + .zip(record.merchant_connector_id) + .map( + |(connector_customer_id, merchant_connector_id)| ConnectorCustomerDetails { + connector_customer_id, + merchant_connector_id, + }, + ), } } } diff --git a/crates/common_types/src/customers.rs b/crates/common_types/src/customers.rs index 1d53630cade..1610bef511d 100644 --- a/crates/common_types/src/customers.rs +++ b/crates/common_types/src/customers.rs @@ -9,6 +9,16 @@ pub struct ConnectorCustomerMap( std::collections::HashMap<common_utils::id_type::MerchantConnectorAccountId, String>, ); +#[cfg(feature = "v2")] +impl ConnectorCustomerMap { + /// Creates a new `ConnectorCustomerMap` from a HashMap + pub fn new( + map: std::collections::HashMap<common_utils::id_type::MerchantConnectorAccountId, String>, + ) -> Self { + Self(map) + } +} + #[cfg(feature = "v2")] common_utils::impl_to_sql_from_sql_json!(ConnectorCustomerMap); diff --git a/crates/router/src/compatibility/stripe/customers.rs b/crates/router/src/compatibility/stripe/customers.rs index 8acd4d10d43..9c5ebb22bc0 100644 --- a/crates/router/src/compatibility/stripe/customers.rs +++ b/crates/router/src/compatibility/stripe/customers.rs @@ -57,7 +57,7 @@ pub async fn customer_create( let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); - customers::create_customer(state, merchant_context, req) + customers::create_customer(state, merchant_context, req, None) }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index 5ad3d95405c..4b4c35dac2a 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -27,7 +27,7 @@ use crate::{ routes::{metrics, SessionState}, services, types::{ - api::customers, + api::{customers, payment_methods as payment_methods_api}, domain::{self, types}, storage::{self, enums}, transformers::ForeignFrom, @@ -41,6 +41,7 @@ pub async fn create_customer( state: SessionState, merchant_context: domain::MerchantContext, customer_data: customers::CustomerRequest, + connector_customer_details: Option<payment_methods_api::ConnectorCustomerDetails>, ) -> errors::CustomerResponse<customers::CustomerResponse> { let db: &dyn StorageInterface = state.store.as_ref(); let key_manager_state = &(&state).into(); @@ -69,6 +70,7 @@ pub async fn create_customer( let domain_customer = customer_data .create_domain_model_from_request( + &connector_customer_details, db, &merchant_reference_id, &merchant_context, @@ -94,6 +96,7 @@ pub async fn create_customer( trait CustomerCreateBridge { async fn create_domain_model_from_request<'a>( &'a self, + connector_customer_details: &'a Option<payment_methods_api::ConnectorCustomerDetails>, db: &'a dyn StorageInterface, merchant_reference_id: &'a Option<id_type::CustomerId>, merchant_context: &'a domain::MerchantContext, @@ -112,6 +115,7 @@ trait CustomerCreateBridge { impl CustomerCreateBridge for customers::CustomerRequest { async fn create_domain_model_from_request<'a>( &'a self, + connector_customer_details: &'a Option<payment_methods_api::ConnectorCustomerDetails>, db: &'a dyn StorageInterface, merchant_reference_id: &'a Option<id_type::CustomerId>, merchant_context: &'a domain::MerchantContext, @@ -171,6 +175,15 @@ impl CustomerCreateBridge for customers::CustomerRequest { domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data) .change_context(errors::CustomersErrorResponse::InternalServerError)?; + let connector_customer = connector_customer_details.as_ref().map(|details| { + let merchant_connector_id = details.merchant_connector_id.get_string_repr().to_string(); + let connector_customer_id = details.connector_customer_id.to_string(); + let object = serde_json::json!({ + merchant_connector_id: connector_customer_id + }); + pii::SecretSerdeValue::new(object) + }); + Ok(domain::Customer { customer_id: merchant_reference_id .to_owned() @@ -188,7 +201,7 @@ impl CustomerCreateBridge for customers::CustomerRequest { description: self.description.clone(), phone_country_code: self.phone_country_code.clone(), metadata: self.metadata.clone(), - connector_customer: None, + connector_customer, address_id: address_from_db.clone().map(|addr| addr.address_id), created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), @@ -214,6 +227,7 @@ impl CustomerCreateBridge for customers::CustomerRequest { impl CustomerCreateBridge for customers::CustomerRequest { async fn create_domain_model_from_request<'a>( &'a self, + connector_customer_details: &'a Option<payment_methods_api::ConnectorCustomerDetails>, _db: &'a dyn StorageInterface, merchant_reference_id: &'a Option<id_type::CustomerId>, merchant_context: &'a domain::MerchantContext, @@ -283,6 +297,15 @@ impl CustomerCreateBridge for customers::CustomerRequest { domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data) .change_context(errors::CustomersErrorResponse::InternalServerError)?; + let connector_customer = connector_customer_details.as_ref().map(|details| { + let mut map = std::collections::HashMap::new(); + map.insert( + details.merchant_connector_id.clone(), + details.connector_customer_id.to_string(), + ); + common_types::customers::ConnectorCustomerMap::new(map) + }); + Ok(domain::Customer { id: id_type::GlobalCustomerId::generate(&state.conf.cell_information.id), merchant_reference_id: merchant_reference_id.to_owned(), @@ -299,7 +322,7 @@ impl CustomerCreateBridge for customers::CustomerRequest { description: self.description.clone(), phone_country_code: self.phone_country_code.clone(), metadata: self.metadata.clone(), - connector_customer: None, + connector_customer, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), default_payment_method_id: None, @@ -1024,6 +1047,7 @@ pub async fn update_customer( let updated_customer = update_customer .request .create_domain_model_from_request( + &None, db, &merchant_context, key_manager_state, @@ -1039,6 +1063,7 @@ pub async fn update_customer( trait CustomerUpdateBridge { async fn create_domain_model_from_request<'a>( &'a self, + connector_customer_details: &'a Option<payment_methods_api::ConnectorCustomerDetails>, db: &'a dyn StorageInterface, merchant_context: &'a domain::MerchantContext, key_manager_state: &'a KeyManagerState, @@ -1211,6 +1236,7 @@ impl VerifyIdForUpdateCustomer<'_> { impl CustomerUpdateBridge for customers::CustomerUpdateRequest { async fn create_domain_model_from_request<'a>( &'a self, + _connector_customer_details: &'a Option<payment_methods_api::ConnectorCustomerDetails>, db: &'a dyn StorageInterface, merchant_context: &'a domain::MerchantContext, key_manager_state: &'a KeyManagerState, @@ -1315,6 +1341,7 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest { impl CustomerUpdateBridge for customers::CustomerUpdateRequest { async fn create_domain_model_from_request<'a>( &'a self, + connector_customer_details: &'a Option<payment_methods_api::ConnectorCustomerDetails>, db: &'a dyn StorageInterface, merchant_context: &'a domain::MerchantContext, key_manager_state: &'a KeyManagerState, @@ -1432,11 +1459,18 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest { pub async fn migrate_customers( state: SessionState, - customers: Vec<customers::CustomerRequest>, + customers_migration: Vec<payment_methods_api::PaymentMethodCustomerMigrate>, merchant_context: domain::MerchantContext, ) -> errors::CustomerResponse<()> { - for customer in customers { - match create_customer(state.clone(), merchant_context.clone(), customer).await { + for customer_migration in customers_migration { + match create_customer( + state.clone(), + merchant_context.clone(), + customer_migration.customer, + customer_migration.connector_customer_details, + ) + .await + { Ok(_) => (), Err(e) => match e.current_context() { errors::CustomersErrorResponse::CustomerAlreadyExists => (), diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs index ce5d007fcde..96733181600 100644 --- a/crates/router/src/routes/customers.rs +++ b/crates/router/src/routes/customers.rs @@ -25,7 +25,7 @@ pub async fn customers_create( let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); - create_customer(state, merchant_context, req) + create_customer(state, merchant_context, req, None) }, auth::auth_type( &auth::V2ApiKeyAuth { @@ -58,7 +58,7 @@ pub async fn customers_create( let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); - create_customer(state, merchant_context, req) + create_customer(state, merchant_context, req, None) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 3288a912ade..f094b89a16c 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -14,6 +14,8 @@ use hyperswitch_domain_models::{ 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::{ api_locking, @@ -27,11 +29,6 @@ use crate::{ storage::payment_method::PaymentTokenData, }, }; -#[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))] -use crate::{ - core::{customers, payment_methods::tokenize}, - types::api::customers::CustomerRequest, -}; #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsCreate))] @@ -360,7 +357,12 @@ pub async fn migrate_payment_methods( customers::migrate_customers( state.clone(), req.iter() - .map(|e| CustomerRequest::from((e.clone(), merchant_id.clone()))) + .map(|e| { + payment_methods::PaymentMethodCustomerMigrate::from(( + e.clone(), + merchant_id.clone(), + )) + }) .collect(), merchant_context.clone(), ) diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs index 4c094af5acc..0c29b58cbb6 100644 --- a/crates/router/src/types/api/payment_methods.rs +++ b/crates/router/src/types/api/payment_methods.rs @@ -1,30 +1,32 @@ #[cfg(feature = "v2")] pub use api_models::payment_methods::{ CardDetail, CardDetailFromLocker, CardDetailsPaymentMethod, CardNetworkTokenizeRequest, - CardNetworkTokenizeResponse, CardType, CustomerPaymentMethodResponseItem, - DeleteTokenizeByTokenRequest, GetTokenizePayloadRequest, GetTokenizePayloadResponse, - ListCountriesCurrenciesRequest, MigrateCardDetail, NetworkTokenDetailsPaymentMethod, - NetworkTokenDetailsResponse, NetworkTokenResponse, PaymentMethodCollectLinkRenderRequest, - PaymentMethodCollectLinkRequest, PaymentMethodCreate, PaymentMethodCreateData, - PaymentMethodDeleteResponse, PaymentMethodId, PaymentMethodIntentConfirm, - PaymentMethodIntentCreate, PaymentMethodListData, PaymentMethodListRequest, - PaymentMethodListResponseForSession, PaymentMethodMigrate, PaymentMethodMigrateResponse, - PaymentMethodResponse, PaymentMethodResponseData, PaymentMethodUpdate, PaymentMethodUpdateData, - PaymentMethodsData, TokenDataResponse, TokenDetailsResponse, TokenizePayloadEncrypted, - TokenizePayloadRequest, TokenizedCardValue1, TokenizedCardValue2, TokenizedWalletValue1, - TokenizedWalletValue2, TotalPaymentMethodCountResponse, + CardNetworkTokenizeResponse, CardType, ConnectorCustomerDetails, + CustomerPaymentMethodResponseItem, DeleteTokenizeByTokenRequest, GetTokenizePayloadRequest, + GetTokenizePayloadResponse, ListCountriesCurrenciesRequest, MigrateCardDetail, + NetworkTokenDetailsPaymentMethod, NetworkTokenDetailsResponse, NetworkTokenResponse, + PaymentMethodCollectLinkRenderRequest, PaymentMethodCollectLinkRequest, PaymentMethodCreate, + PaymentMethodCreateData, PaymentMethodCustomerMigrate, PaymentMethodDeleteResponse, + PaymentMethodId, PaymentMethodIntentConfirm, PaymentMethodIntentCreate, PaymentMethodListData, + PaymentMethodListRequest, PaymentMethodListResponseForSession, PaymentMethodMigrate, + PaymentMethodMigrateResponse, PaymentMethodResponse, PaymentMethodResponseData, + PaymentMethodUpdate, PaymentMethodUpdateData, PaymentMethodsData, TokenDataResponse, + TokenDetailsResponse, TokenizePayloadEncrypted, TokenizePayloadRequest, TokenizedCardValue1, + TokenizedCardValue2, TokenizedWalletValue1, TokenizedWalletValue2, + TotalPaymentMethodCountResponse, }; #[cfg(feature = "v1")] pub use api_models::payment_methods::{ CardDetail, CardDetailFromLocker, CardDetailsPaymentMethod, CardNetworkTokenizeRequest, - CardNetworkTokenizeResponse, CustomerPaymentMethod, CustomerPaymentMethodsListResponse, - DefaultPaymentMethod, DeleteTokenizeByTokenRequest, GetTokenizePayloadRequest, - GetTokenizePayloadResponse, ListCountriesCurrenciesRequest, MigrateCardDetail, - PaymentMethodCollectLinkRenderRequest, PaymentMethodCollectLinkRequest, PaymentMethodCreate, - PaymentMethodCreateData, PaymentMethodDeleteResponse, PaymentMethodId, - PaymentMethodListRequest, PaymentMethodListResponse, PaymentMethodMigrate, - PaymentMethodMigrateResponse, PaymentMethodResponse, PaymentMethodUpdate, PaymentMethodsData, - TokenizeCardRequest, TokenizeDataRequest, TokenizePayloadEncrypted, TokenizePayloadRequest, + CardNetworkTokenizeResponse, ConnectorCustomerDetails, CustomerPaymentMethod, + CustomerPaymentMethodsListResponse, DefaultPaymentMethod, DeleteTokenizeByTokenRequest, + GetTokenizePayloadRequest, GetTokenizePayloadResponse, ListCountriesCurrenciesRequest, + MigrateCardDetail, PaymentMethodCollectLinkRenderRequest, PaymentMethodCollectLinkRequest, + PaymentMethodCreate, PaymentMethodCreateData, PaymentMethodCustomerMigrate, + PaymentMethodDeleteResponse, PaymentMethodId, PaymentMethodListRequest, + PaymentMethodListResponse, PaymentMethodMigrate, PaymentMethodMigrateResponse, + PaymentMethodResponse, PaymentMethodUpdate, PaymentMethodsData, TokenizeCardRequest, + TokenizeDataRequest, TokenizePayloadEncrypted, TokenizePayloadRequest, TokenizePaymentMethodRequest, TokenizedCardValue1, TokenizedCardValue2, TokenizedWalletValue1, TokenizedWalletValue2, };
2025-06-11T12:24:41Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR introduces populating `connector_customer` field in `customers` table during payment method migration. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Allows merchants to populate `connector_customer` per `merchant_connector_id` based on `connector_customer_id` passed in the request. ## How did you test it? Steps for testing - 1. Create a merchant account 2. Create a merchant's connector account <details> <summary>3. Run /migrate-form API</summary> cURL curl --location --request POST 'http://localhost:8080/payment_methods/migrate-batch' \ --header 'api-key: test_admin' \ --form 'merchant_id="merchant_1749642145"' \ --form 'merchant_connector_id="mca_llNSJsE2tTVdpfrb6n3x"' \ --form 'file=@"/Users/test/Downloads/migrate_sample.csv"' Response [{"line_number":1,"customer_id":"customerReference-43","migration_status":"Failed","migration_error":"{\"error\":{\"type\":\"invalid_request_error\",\"code\":\"IR_16\",\"message\":\"Card Expired\"}}","card_number_masked":"420000XXXXXX0000","card_migrated":null,"network_token_migrated":null,"connector_mandate_details_migrated":null,"network_transaction_id_migrated":null},{"line_number":2,"customer_id":"customerReference-44","migration_status":"Failed","migration_error":"{\"error\":{\"type\":\"invalid_request_error\",\"code\":\"IR_16\",\"message\":\"Card Expired\"}}","card_number_masked":"420000XXXXXX0000","card_migrated":null,"network_token_migrated":null,"connector_mandate_details_migrated":null,"network_transaction_id_migrated":null},{"line_number":3,"customer_id":"customerReference-45","migration_status":"Failed","migration_error":"{\"error\":{\"type\":\"invalid_request_error\",\"code\":\"IR_16\",\"message\":\"Card Expired\"}}","card_number_masked":"420000XXXXXX0000","card_migrated":null,"network_token_migrated":null,"connector_mandate_details_migrated":null,"network_transaction_id_migrated":null},{"line_number":4,"customer_id":"customerReference-46","migration_status":"Failed","migration_error":"{\"error\":{\"type\":\"invalid_request_error\",\"code\":\"IR_16\",\"message\":\"Card Expired\"}}","card_number_masked":"420000XXXXXX0000","card_migrated":null,"network_token_migrated":null,"connector_mandate_details_migrated":null,"network_transaction_id_migrated":null},{"line_number":5,"customer_id":"customerReference-47","migration_status":"Failed","migration_error":"{\"error\":{\"type\":\"invalid_request_error\",\"code\":\"IR_16\",\"message\":\"Card Expired\"}}","card_number_masked":"420000XXXXXX0000","card_migrated":null,"network_token_migrated":null,"connector_mandate_details_migrated":null,"network_transaction_id_migrated":null},{"line_number":6,"payment_method_id":"pm_YQMH2vTIIhT0dDwIz2wu","payment_method":"card","payment_method_type":"credit","customer_id":"customerReference-48","migration_status":"Success","card_number_masked":"420000XXXXXX0000","card_migrated":null,"network_token_migrated":true,"connector_mandate_details_migrated":null,"network_transaction_id_migrated":true},{"line_number":7,"payment_method_id":"pm_6ir1orxpyF5wy4kkOYwh","payment_method":"card","payment_method_type":"credit","customer_id":"customerReference-49","migration_status":"Success","card_number_masked":"","card_migrated":null,"network_token_migrated":true,"connector_mandate_details_migrated":null,"network_transaction_id_migrated":true},{"line_number":8,"customer_id":"customerReference-50","migration_status":"Failed","migration_error":"{\"error\":{\"type\":\"invalid_request_error\",\"code\":\"IR_07\",\"message\":\"Invalid value provided: card_exp_month\"}}","card_number_masked":"","card_migrated":null,"network_token_migrated":null,"connector_mandate_details_migrated":null,"network_transaction_id_migrated":null},{"line_number":9,"payment_method_id":"pm_uMqDIb7yeJL6cKDXHOm0","payment_method":"card","payment_method_type":"credit","customer_id":"customerReference-51","migration_status":"Success","card_number_masked":"420000XXXXXX0000","card_migrated":null,"network_token_migrated":true,"connector_mandate_details_migrated":null,"network_transaction_id_migrated":null},{"line_number":10,"customer_id":"customerReference-69","migration_status":"Failed","migration_error":"{\"error\":{\"type\":\"invalid_request_error\",\"code\":\"IR_16\",\"message\":\"Card Expired\"}}","card_number_masked":"420000XXXXXX0000","card_migrated":null,"network_token_migrated":null,"connector_mandate_details_migrated":null,"network_transaction_id_migrated":null},{"line_number":11,"customer_id":"customerReference-89","migration_status":"Failed","migration_error":"{\"error\":{\"type\":\"invalid_request_error\",\"code\":\"IR_16\",\"message\":\"Invalid Expiry Year\"}}","card_number_masked":"420000XXXXXX0000","card_migrated":null,"network_token_migrated":null,"connector_mandate_details_migrated":null,"network_transaction_id_migrated":null},{"line_number":12,"customer_id":"customerReference-99","migration_status":"Failed","migration_error":"{\"error\":{\"type\":\"invalid_request_error\",\"code\":\"IR_16\",\"message\":\"Invalid Expiry Year\"}}","card_number_masked":"420000XXXXXX0000","card_migrated":null,"network_token_migrated":null,"connector_mandate_details_migrated":null,"network_transaction_id_migrated":null},{"line_number":13,"payment_method_id":"pm_CuESKjB4r0rosTccLRMV","payment_method":"card","payment_method_type":"credit","customer_id":"customerReference-52","migration_status":"Success","card_number_masked":"420000XXXXXX0000","card_migrated":null,"network_token_migrated":true,"connector_mandate_details_migrated":null,"network_transaction_id_migrated":null}] </details> <details> <summary>Look for connector_customer in customers table</summary> <img width="587" alt="Screenshot 2025-06-11 at 10 08 27 PM" src="https://github.com/user-attachments/assets/21247f0f-2998-4fd3-8ccb-a77a15a25f95" /> </details> <details> <summary>Find CSV data below</summary> name,email,phone,phone_country_code,customer_id,subscription_id,payment_method,payment_method_type,nick_name,payment_instrument_id,raw_card_number,card_number_masked,card_expiry_month,card_expiry_year,card_scheme,network_token_number,network_token_requestor_ref_id,network_token_expiry_month,network_token_expiry_year,original_transaction_id,billing_address_zip,billing_address_state,billing_address_first_name,billing_address_last_name,billing_address_city,billing_address_country,billing_address_line1,billing_address_line2,connector_customer_id,merchant_connector_id Max Mustermann,[email protected],,,customerReference-43,orderReference-20240930-220107,card,credit,real joe,instructionReference-20240930-220107-S,4200000000000000,420000XXXXXX0000,1,2025,,5595300359062662,RR16qBRBV-00a00a20uBPVV-18sNRV20uFBTTD22w18s12mRR18sZ00000334051,1,2025,60720116005060,530004,Oman,joey,joey,Oman,,st mark,oman,1,mca_llNSJsE2tTVdpfrb6n3x Max Mustermann,[email protected],,,customerReference-44,orderReference-20240930-220107,card,credit,real joe,instructionReference-20240930-220107-S,4200000000000000,420000XXXXXX0000,1,2025,,5595300359062662,RR16qBRBV-00a00a20uBPVV-18sNRV20uFBTTD22w18s12mRR18sZ00000334051,1,2025,60720116005060,530004,Oman,joey,joey,Oman,,st mark,oman,2,mca_llNSJsE2tTVdpfrb6n3x Max Mustermann,[email protected],,,customerReference-45,orderReference-20240930-220107,card,credit,real joe,,4200000000000000,420000XXXXXX0000,1,2025,,5595300359062662,RR16qBRBV-00a00a20uBPVV-18sNRV20uFBTTD22w18s12mRR18sZ00000334051,1,2025,60720116005060,530004,Oman,joey,joey,Oman,,st mark,oman,3,mca_llNSJsE2tTVdpfrb6n3x Max Mustermann,[email protected],,,customerReference-46,orderReference-20240930-220107,card,credit,real joe,,4200000000000000,420000XXXXXX0000,1,2025,,5595300359062662,RR16qBRBV-00a00a20uBPVV-18sNRV20uFBTTD22w18s12mRR18sZ00000334051,1,2025,60720116005060,530004,Oman,joey,joey,Oman,,st mark,oman,4,mca_llNSJsE2tTVdpfrb6n3x Max Mustermann,[email protected],,,customerReference-47,orderReference-20240930-220107,card,credit,real joe,,4200000000000000,420000XXXXXX0000,1,2025,,5595300359062662,RR16qBRBV-00a00a20uBPVV-18sNRV20uFBTTD22w18s12mRR18sZ00000334051,1,2025,60720116005060,530004,Oman,joey,joey,Oman,,st mark,oman,5,mca_llNSJsE2tTVdpfrb6n3x Max Mustermann,[email protected],,,customerReference-48,orderReference-20240930-220107,card,credit,real joe,,,420000XXXXXX0000,1,2025,,5595300359062662,RR16qBRBV-00a00a20uBPVV-18sNRV20uFBTTD22w18s12mRR18sZ00000334051,1,2025,60720116005060,530004,Oman,joey,joey,Oman,,st mark,oman,7,mca_llNSJsE2tTVdpfrb6n3x Max Mustermann,[email protected],,,customerReference-49,orderReference-20240930-220107,card,credit,real joe,,,,1,2025,,5595300359062662,RR16qBRBV-00a00a20uBPVV-18sNRV20uFBTTD22w18s12mRR18sZ00000334051,1,2025,60720116005060,530004,Oman,joey,joey,Oman,,st mark,oman,6,mca_llNSJsE2tTVdpfrb6n3x Max Mustermann,[email protected],,,customerReference-50,orderReference-20240930-220107,card,credit,real joe,,,,,,,5595300359062662,RR16qBRBV-00a00a20uBPVV-18sNRV20uFBTTD22w18s12mRR18sZ00000334051,1,2025,60720116005060,530004,Oman,joey,joey,Oman,,st mark,oman,8,mca_llNSJsE2tTVdpfrb6n3x Max Mustermann,[email protected],,,customerReference-51,orderReference-20240930-220107,card,credit,real joe,,,420000XXXXXX0000,1,25,,5595300359062662,RR16qBRBV-00a00a20uBPVV-18sNRV20uFBTTD22w18s12mRR18sZ00000334051,1,2025,,530004,Oman,joey,joey,Oman,,st mark,oman,9,mca_llNSJsE2tTVdpfrb6n3x Max Mustermann,[email protected],,,customerReference-69,orderReference-20240930-220107,card,credit,real joe,,4200000000000000,420000XXXXXX0000,1,25,,5595300359062662,RR16qBRBV-00a00a20uBPVV-18sNRV20uFBTTD22w18s12mRR18sZ00000334051,1,2022,,530004,Oman,joey,joey,Oman,,st mark,oman,10,mca_llNSJsE2tTVdpfrb6n3x Max Mustermann,[email protected],,,customerReference-89,orderReference-20240930-220107,card,credit,real joe,,4200000000000000,420000XXXXXX0000,1,22,,5595300359062662,RR16qBRBV-00a00a20uBPVV-18sNRV20uFBTTD22w18s12mRR18sZ00000334051,1,2022,,530004,Oman,joey,joey,Oman,,st mark,oman,11,mca_llNSJsE2tTVdpfrb6n3x Max Mustermann,[email protected],,,customerReference-99,orderReference-20240930-220107,card,credit,real joe,,4200000000000000,420000XXXXXX0000,1,2022,,5595300359062662,RR16qBRBV-00a00a20uBPVV-18sNRV20uFBTTD22w18s12mRR18sZ00000334051,1,2022,,530004,Oman,joey,joey,Oman,,st mark,oman,12,mca_llNSJsE2tTVdpfrb6n3x Max Mustermann,[email protected],,,customerReference-52,orderReference-20240930-220107,card,credit,real joe,,,420000XXXXXX0000,1,25,,,,,,,530004,Oman,joey,joey,Oman,,st mark,oman,13,mca_llNSJsE2tTVdpfrb6n3x </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Added support for associating connector-specific customer details with customers during creation and migration. - Enhanced customer migration to include connector customer information when available. - **Bug Fixes** - Updated customer creation and migration flows to handle new customer details without disrupting existing functionality. - **Chores** - Improved internal handling of customer data to support future extensibility with connector-specific fields. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
v1.114.0
0eab55d17aef3caa160878bc9b2be29deb37711d
0eab55d17aef3caa160878bc9b2be29deb37711d
juspay/hyperswitch
juspay__hyperswitch-8302
Bug: fix(router): Move Customer PML endpoint to OLAP (v2) [This PR](https://github.com/juspay/hyperswitch/pull/7241) added customer PML for v2, but the route was incorrectly added under OLTP instead of OLAP, need to fix
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index a22d71a5d66..a9cda83bd41 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1080,6 +1080,10 @@ impl Customers { web::resource("/total-payment-methods") .route(web::get().to(payment_methods::get_total_payment_method_count)), ) + .service( + web::resource("/{id}/saved-payment-methods") + .route(web::get().to(payment_methods::list_customer_payment_method_api)), + ) } #[cfg(all(feature = "oltp", feature = "v2"))] { @@ -1091,10 +1095,6 @@ impl Customers { .route(web::get().to(customers::customers_retrieve)) .route(web::delete().to(customers::customers_delete)), ) - .service( - web::resource("/{id}/saved-payment-methods") - .route(web::get().to(payment_methods::list_customer_payment_method_api)), - ) } route }
2025-06-10T08:28:04Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Moved customer saved PML route to OLAP in v2 ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #8302 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Verified as working. No change in response. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
713c85d25d29259672da6efbfed0862e843ec542
713c85d25d29259672da6efbfed0862e843ec542
juspay/hyperswitch
juspay__hyperswitch-8325
Bug: feat(recovery-events): add revenue recovery topic and vector config to push these events to s3 Add new event for revenue recovery and write vector config to send data to aws s3.
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index 8dc81cdc9a7..206c4bbe812 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -15695,7 +15695,9 @@ "type": "object", "required": [ "id", - "status" + "status", + "amount", + "created_at" ], "properties": { "id": { @@ -15705,6 +15707,20 @@ "status": { "$ref": "#/components/schemas/AttemptStatus" }, + "amount": { + "type": "integer", + "format": "int64", + "description": "The amount of the payment attempt", + "example": 6540 + }, + "error_details": { + "allOf": [ + { + "$ref": "#/components/schemas/RecordAttemptErrorDetails" + } + ], + "nullable": true + }, "payment_intent_feature_metadata": { "allOf": [ { @@ -15720,6 +15736,11 @@ } ], "nullable": true + }, + "created_at": { + "type": "string", + "format": "date-time", + "description": "attempt created at timestamp" } } }, @@ -18105,6 +18126,12 @@ "description": "Invoice Next billing time", "nullable": true }, + "invoice_billing_started_at_time": { + "type": "string", + "format": "date-time", + "description": "Invoice Next billing time", + "nullable": true + }, "first_payment_attempt_pg_error_code": { "type": "string", "description": "First Payment Attempt Payment Gateway Error Code", @@ -21904,6 +21931,39 @@ "disabled" ] }, + "RecordAttemptErrorDetails": { + "type": "object", + "description": "Error details for the payment", + "required": [ + "code", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "error code sent by billing connector." + }, + "message": { + "type": "string", + "description": "error message sent by billing connector." + }, + "network_advice_code": { + "type": "string", + "description": "This field can be returned for both approved and refused Mastercard payments.\nThis code provides additional information about the type of transaction or the reason why the payment failed.\nIf the payment failed, the network advice code gives guidance on if and when you can retry the payment.", + "nullable": true + }, + "network_decline_code": { + "type": "string", + "description": "For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed.", + "nullable": true + }, + "network_error_message": { + "type": "string", + "description": "A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better.", + "nullable": true + } + } + }, "RecurringDetails": { "oneOf": [ { diff --git a/config/config.example.toml b/config/config.example.toml index d90be9cae0a..36ab1d1713e 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -994,6 +994,7 @@ payout_analytics_topic = "topic" # Kafka topic to be used for Payouts an consolidated_events_topic = "topic" # Kafka topic to be used for Consolidated events authentication_analytics_topic = "topic" # Kafka topic to be used for Authentication events routing_logs_topic = "topic" # Kafka topic to be used for Routing events +revenue_recovery_topic = "topic" # Kafka topic to be used for revenue recovery events # File storage configuration [file_storage] diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 4428b508017..23ff9f16e70 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -94,6 +94,7 @@ consolidated_events_topic = "topic" # Kafka topic to be used for Consolidat authentication_analytics_topic = "topic" # Kafka topic to be used for Authentication events fraud_check_analytics_topic = "topic" # Kafka topic to be used for Fraud Check events routing_logs_topic = "topic" # Kafka topic to be used for Routing events +revenue_recovery_topic = "topic" # Kafka topic to be used for Revenue Recovery Events # File storage configuration [file_storage] diff --git a/config/development.toml b/config/development.toml index ee66404e638..658b9b21684 100644 --- a/config/development.toml +++ b/config/development.toml @@ -1097,6 +1097,7 @@ payout_analytics_topic = "hyperswitch-payout-events" consolidated_events_topic = "hyperswitch-consolidated-events" authentication_analytics_topic = "hyperswitch-authentication-events" routing_logs_topic = "hyperswitch-routing-api-events" +revenue_recovery_topic = "hyperswitch-revenue-recovery-events" [debit_routing_config] supported_currencies = "USD" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index e6885ab39ae..7737a295220 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -955,6 +955,7 @@ payout_analytics_topic = "hyperswitch-payout-events" consolidated_events_topic = "hyperswitch-consolidated-events" authentication_analytics_topic = "hyperswitch-authentication-events" routing_logs_topic = "hyperswitch-routing-api-events" +revenue_recovery_topic = "hyperswitch-revenue-recovery-events" [analytics] source = "sqlx" diff --git a/config/vector.yaml b/config/vector.yaml index 4b801935ae5..89e33da57ba 100644 --- a/config/vector.yaml +++ b/config/vector.yaml @@ -1,15 +1,5 @@ acknowledgements: enabled: true -enrichment_tables: - sdk_map: - type: file - file: - path: /etc/vector/config/sdk_map.csv - encoding: - type: csv - schema: - publishable_key: string - merchant_id: string api: @@ -28,6 +18,15 @@ sources: - hyperswitch-dispute-events decoding: codec: json + + revenue_events: + type: kafka + bootstrap_servers: kafka0:29092 + group_id: hyperswitch_revenue_recovery + topics: + - hyperswitch-revenue-recovery-events + decoding: + codec: json sessionized_kafka_tx_events: type: kafka @@ -98,19 +97,6 @@ transforms: key_field: "{{ .payment_id }}{{ .merchant_id }}" threshold: 1000 window_secs: 60 - - amend_sdk_logs: - type: remap - inputs: - - sdk_transformed - source: | - .before_transform = now() - - merchant_id = .merchant_id - row = get_enrichment_table_record!("sdk_map", { "publishable_key" : merchant_id }, case_sensitive: true) - .merchant_id = row.merchant_id - - .after_transform = now() @@ -256,7 +242,54 @@ sinks: - "path" - "source_type" inputs: - - "amend_sdk_logs" + - "sdk_transformed" bootstrap_servers: kafka0:29092 topic: hyper-sdk-logs key_field: ".merchant_id" + + revenue_recovery_s3: + type: aws_s3 + inputs: + - revenue_events + bucket: BUCKET_NAME + region: us-east-1 + content_type: json + batch: + max_events: 1000 + timeout_secs: 86400 + encoding: + codec: csv + csv: + fields: + - merchant_id + - invoice_id + - invoice_amount + - invoice_currency + - invoice_due_date + - invoice_date + - billing_city + - billing_country + - billing_state + - attempt_id + - attempt_amount + - attempt_currency + - attempt_status + - pg_error_code + - network_advice_code + - network_error_code + - first_pg_error_code + - first_network_advice_code + - first_network_error_code + - attempt_created_at + - payment_method_type + - payment_method_subtype + - card_network + - card_issuer + - retry_count + - payment_gateway + key_prefix: "{{ .merchant_id }}/" + timezone: "Europe/London" + + filename_append_uuid: false + filename_time_format: "%Y/%m/%+" + filename_extension: csv diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 6cddf9430b9..72519b541bb 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1562,11 +1562,14 @@ pub struct PaymentAttemptResponse { /// The global identifier for the payment attempt #[schema(value_type = String)] pub id: id_type::GlobalAttemptId, + /// /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, + /// Amount related information for this payment and attempt pub amount: PaymentAttemptAmountDetails, + /// Name of the connector that was used for the payment attempt. #[schema(example = "stripe")] pub connector: Option<String>, @@ -1624,6 +1627,7 @@ pub struct PaymentAttemptResponse { /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, + /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, @@ -1643,12 +1647,21 @@ pub struct PaymentAttemptRecordResponse { /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, + /// The amount of the payment attempt + #[schema(value_type = i64, example = 6540)] + pub amount: MinorUnit, + /// Error details for the payment attempt, if any. + /// This includes fields like error code, network advice code, and network decline code. + pub error_details: Option<RecordAttemptErrorDetails>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub payment_intent_feature_metadata: Option<FeatureMetadata>, /// Additional data that might be required by hyperswitch, to enable some specific features. pub payment_attempt_feature_metadata: Option<PaymentAttemptFeatureMetadata>, + /// attempt created at timestamp + pub created_at: PrimitiveDateTime, } + #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptFeatureMetadata { @@ -8800,6 +8813,9 @@ pub struct PaymentRevenueRecoveryMetadata { /// Invoice Next billing time #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub invoice_next_billing_time: Option<PrimitiveDateTime>, + /// Invoice Next billing time + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + pub invoice_billing_started_at_time: Option<PrimitiveDateTime>, /// First Payment Attempt Payment Gateway Error Code #[schema(value_type = Option<String>, example = "card_declined")] pub first_payment_attempt_pg_error_code: Option<String>, @@ -8829,6 +8845,15 @@ pub struct BillingConnectorAdditionalCardInfo { pub card_issuer: Option<String>, } +#[cfg(feature = "v2")] +impl BillingConnectorPaymentMethodDetails { + pub fn get_billing_connector_card_info(&self) -> Option<&BillingConnectorAdditionalCardInfo> { + match self { + Self::Card(card_details) => Some(card_details), + } + } +} + #[cfg(feature = "v2")] impl PaymentRevenueRecoveryMetadata { pub fn set_payment_transmission_field_for_api_request( @@ -8939,6 +8964,11 @@ pub struct PaymentsAttemptRecordRequest { #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub invoice_next_billing_time: Option<PrimitiveDateTime>, + /// Next Billing time of the Invoice + #[schema(example = "2022-09-10T10:11:12Z")] + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + pub invoice_billing_started_at_time: Option<PrimitiveDateTime>, + /// source where the payment was triggered by #[schema(value_type = TriggeredBy, example = "internal" )] pub triggered_by: common_enums::TriggeredBy, diff --git a/crates/diesel_models/src/types.rs b/crates/diesel_models/src/types.rs index e3efd3dae2d..8f795d67eab 100644 --- a/crates/diesel_models/src/types.rs +++ b/crates/diesel_models/src/types.rs @@ -174,6 +174,8 @@ pub struct PaymentRevenueRecoveryMetadata { pub connector: common_enums::connector_enums::Connector, /// Time at which next invoice will be created pub invoice_next_billing_time: Option<time::PrimitiveDateTime>, + /// Time at which invoice started + pub invoice_billing_started_at_time: Option<time::PrimitiveDateTime>, /// Extra Payment Method Details that are needed to be stored pub billing_connector_payment_method_details: Option<BillingConnectorPaymentMethodDetails>, /// First Payment Attempt Payment Gateway Error Code diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs index e0c84b4b459..5a3ec2f96f9 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs @@ -280,6 +280,8 @@ pub struct ChargebeeWebhookContent { #[derive(Serialize, Deserialize, Debug)] pub struct ChargebeeSubscriptionData { + #[serde(default, with = "common_utils::custom_serde::timestamp::option")] + pub current_term_start: Option<PrimitiveDateTime>, #[serde(default, with = "common_utils::custom_serde::timestamp::option")] pub next_billing_at: Option<PrimitiveDateTime>, } @@ -488,6 +490,11 @@ impl TryFrom<ChargebeeWebhookBody> for revenue_recovery::RevenueRecoveryAttemptD .subscription .as_ref() .and_then(|subscription| subscription.next_billing_at); + let invoice_billing_started_at_time = item + .content + .subscription + .as_ref() + .and_then(|subscription| subscription.current_term_start); Ok(Self { amount, currency, @@ -507,6 +514,7 @@ impl TryFrom<ChargebeeWebhookBody> for revenue_recovery::RevenueRecoveryAttemptD network_error_message: None, retry_count, invoice_next_billing_time, + invoice_billing_started_at_time, card_network: Some(payment_method_details.card.brand), card_isin: Some(payment_method_details.card.iin), // This field is none because it is specific to stripebilling. @@ -576,6 +584,11 @@ impl TryFrom<ChargebeeInvoiceBody> for revenue_recovery::RevenueRecoveryInvoiceD .subscription .as_ref() .and_then(|subscription| subscription.next_billing_at); + let billing_started_at = item + .content + .subscription + .as_ref() + .and_then(|subscription| subscription.current_term_start); Ok(Self { amount: item.content.invoice.total, currency: item.content.invoice.currency_code, @@ -583,6 +596,7 @@ impl TryFrom<ChargebeeInvoiceBody> for revenue_recovery::RevenueRecoveryInvoiceD billing_address: Some(api_models::payments::Address::from(item.content.invoice)), retry_count, next_billing_at: invoice_next_billing_time, + billing_started_at, }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs index ca0875ba4ce..ae80cb48ea1 100644 --- a/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs @@ -402,6 +402,13 @@ impl TryFrom<StripebillingInvoiceBody> for revenue_recovery::RevenueRecoveryInvo .data .first() .map(|linedata| linedata.period.end); + let billing_started_at = item + .data + .object + .lines + .data + .first() + .map(|linedata| linedata.period.start); Ok(Self { amount: item.data.object.amount, currency: item.data.object.currency, @@ -413,6 +420,7 @@ impl TryFrom<StripebillingInvoiceBody> for revenue_recovery::RevenueRecoveryInvo .map(api_models::payments::Address::from), retry_count: Some(item.data.object.attempt_count), next_billing_at, + billing_started_at, }) } } diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs index 1f9dee68632..c7df1e3749b 100644 --- a/crates/hyperswitch_domain_models/src/lib.rs +++ b/crates/hyperswitch_domain_models/src/lib.rs @@ -335,6 +335,7 @@ impl ApiModelToDieselModelConvertor<ApiRevenueRecoveryMetadata> for PaymentReven first_payment_attempt_network_decline_code: from .first_payment_attempt_network_decline_code, first_payment_attempt_pg_error_code: from.first_payment_attempt_pg_error_code, + invoice_billing_started_at_time: from.invoice_billing_started_at_time, } } @@ -359,6 +360,7 @@ impl ApiModelToDieselModelConvertor<ApiRevenueRecoveryMetadata> for PaymentReven first_payment_attempt_network_decline_code: self .first_payment_attempt_network_decline_code, first_payment_attempt_pg_error_code: self.first_payment_attempt_pg_error_code, + invoice_billing_started_at_time: self.invoice_billing_started_at_time, } } } diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index 0445b2b9a22..e9b234eb46a 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -744,6 +744,7 @@ impl PaymentIntent { network_error_message: None, retry_count: None, invoice_next_billing_time: None, + invoice_billing_started_at_time: None, card_isin: None, card_network: None, // No charge id is present here since it is an internal payment and we didn't call connector yet. @@ -1068,6 +1069,9 @@ where errors::api_error_response::ApiErrorResponse::InternalServerError })?, invoice_next_billing_time: self.revenue_recovery_data.invoice_next_billing_time, + invoice_billing_started_at_time: self + .revenue_recovery_data + .invoice_next_billing_time, billing_connector_payment_method_details, first_payment_attempt_network_advice_code: first_network_advice_code, first_payment_attempt_network_decline_code: first_network_decline_code, diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index 3baddfa98c5..e16285e3df2 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -373,6 +373,19 @@ pub struct ErrorDetails { pub network_error_message: Option<String>, } +#[cfg(feature = "v2")] +impl From<ErrorDetails> for api_models::payments::RecordAttemptErrorDetails { + fn from(error_details: ErrorDetails) -> Self { + Self { + code: error_details.code, + message: error_details.message, + network_decline_code: error_details.network_decline_code, + network_advice_code: error_details.network_advice_code, + network_error_message: error_details.network_error_message, + } + } +} + /// Domain model for the payment attempt. /// Few fields which are related are grouped together for better readability and understandability. /// These fields will be flattened and stored in the database in individual columns diff --git a/crates/hyperswitch_domain_models/src/revenue_recovery.rs b/crates/hyperswitch_domain_models/src/revenue_recovery.rs index 0485644628a..6481a81d536 100644 --- a/crates/hyperswitch_domain_models/src/revenue_recovery.rs +++ b/crates/hyperswitch_domain_models/src/revenue_recovery.rs @@ -3,8 +3,12 @@ use common_enums::enums as common_enums; use common_utils::{id_type, types as util_types}; use time::PrimitiveDateTime; -use crate::router_response_types::revenue_recovery::{ - BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse, +use crate::{ + payments, + router_response_types::revenue_recovery::{ + BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse, + }, + ApiModelToDieselModelConvertor, }; /// Recovery payload is unified struct constructed from billing connectors @@ -48,6 +52,8 @@ pub struct RevenueRecoveryAttemptData { pub retry_count: Option<u16>, /// Time when next invoice will be generated which will be equal to the end time of the current invoice pub invoice_next_billing_time: Option<PrimitiveDateTime>, + /// Time at which the invoice created + pub invoice_billing_started_at_time: Option<PrimitiveDateTime>, /// card network type pub card_network: Option<common_enums::CardNetwork>, /// card isin @@ -71,6 +77,8 @@ pub struct RevenueRecoveryInvoiceData { pub retry_count: Option<u16>, /// Ending date of the invoice or the Next billing time of the Subscription pub next_billing_at: Option<PrimitiveDateTime>, + /// Invoice Starting Time + pub billing_started_at: Option<PrimitiveDateTime>, } /// type of action that needs to taken after consuming recovery payload @@ -89,17 +97,30 @@ pub enum RecoveryAction { /// Invalid event has been received. InvalidAction, } -#[derive(Clone)] + +#[derive(Clone, Debug)] pub struct RecoveryPaymentIntent { pub payment_id: id_type::GlobalPaymentId, pub status: common_enums::IntentStatus, pub feature_metadata: Option<api_payments::FeatureMetadata>, + pub merchant_id: id_type::MerchantId, + pub merchant_reference_id: Option<id_type::PaymentReferenceId>, + pub invoice_amount: util_types::MinorUnit, + pub invoice_currency: common_enums::Currency, + pub created_at: Option<PrimitiveDateTime>, + pub billing_address: Option<api_payments::Address>, } +#[derive(Clone, Debug)] pub struct RecoveryPaymentAttempt { pub attempt_id: id_type::GlobalAttemptId, pub attempt_status: common_enums::AttemptStatus, pub feature_metadata: Option<api_payments::PaymentAttemptFeatureMetadata>, + pub amount: util_types::MinorUnit, + pub network_advice_code: Option<String>, + pub network_decline_code: Option<String>, + pub error_code: Option<String>, + pub created_at: PrimitiveDateTime, } impl RecoveryPaymentAttempt { @@ -231,6 +252,7 @@ impl From<&BillingConnectorInvoiceSyncResponse> for RevenueRecoveryInvoiceData { billing_address: data.billing_address.clone(), retry_count: data.retry_count, next_billing_at: data.ends_at, + billing_started_at: data.created_at, } } } @@ -281,6 +303,7 @@ impl card_network: billing_connector_payment_details.card_network.clone(), card_isin: billing_connector_payment_details.card_isin.clone(), charge_id: billing_connector_payment_details.charge_id.clone(), + invoice_billing_started_at_time: invoice_details.billing_started_at, } } } @@ -313,3 +336,61 @@ impl From<&RevenueRecoveryAttemptData> for Option<api_payments::RecordAttemptErr }) } } + +impl From<&payments::PaymentIntent> for RecoveryPaymentIntent { + fn from(payment_intent: &payments::PaymentIntent) -> Self { + Self { + payment_id: payment_intent.id.clone(), + status: payment_intent.status, + feature_metadata: payment_intent + .feature_metadata + .clone() + .map(|feature_metadata| feature_metadata.convert_back()), + merchant_reference_id: payment_intent.merchant_reference_id.clone(), + invoice_amount: payment_intent.amount_details.order_amount, + invoice_currency: payment_intent.amount_details.currency, + billing_address: payment_intent + .billing_address + .clone() + .map(|address| api_payments::Address::from(address.into_inner())), + merchant_id: payment_intent.merchant_id.clone(), + created_at: Some(payment_intent.created_at), + } + } +} + +impl From<&payments::payment_attempt::PaymentAttempt> for RecoveryPaymentAttempt { + fn from(payment_attempt: &payments::payment_attempt::PaymentAttempt) -> Self { + Self { + attempt_id: payment_attempt.id.clone(), + attempt_status: payment_attempt.status, + feature_metadata: payment_attempt + .feature_metadata + .clone() + .map( + |feature_metadata| api_payments::PaymentAttemptFeatureMetadata { + revenue_recovery: feature_metadata.revenue_recovery.map(|recovery| { + api_payments::PaymentAttemptRevenueRecoveryData { + attempt_triggered_by: recovery.attempt_triggered_by, + charge_id: recovery.charge_id, + } + }), + }, + ), + amount: payment_attempt.amount_details.get_net_amount(), + network_advice_code: payment_attempt + .error + .clone() + .and_then(|error| error.network_advice_code), + network_decline_code: payment_attempt + .error + .clone() + .and_then(|error| error.network_decline_code), + error_code: payment_attempt + .error + .as_ref() + .map(|error| error.code.clone()), + created_at: payment_attempt.created_at, + } + } +} diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 4b88ec4c1ab..81e8f10dcdc 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -360,6 +360,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::PaymentAttemptFeatureMetadata, api_models::payments::PaymentAttemptRevenueRecoveryData, api_models::payments::BillingConnectorPaymentMethodDetails, + api_models::payments::RecordAttemptErrorDetails, api_models::payments::BillingConnectorAdditionalCardInfo, api_models::payments::AliPayRedirection, api_models::payments::MomoRedirection, diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 1974fd3e428..c59682fa982 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -2144,8 +2144,9 @@ where let payment_attempt = self.payment_attempt; let payment_intent = self.payment_intent; let response = api_models::payments::PaymentAttemptRecordResponse { - id: payment_attempt.get_id().to_owned(), + id: payment_attempt.id.clone(), status: payment_attempt.status, + amount: payment_attempt.amount_details.get_net_amount(), payment_intent_feature_metadata: payment_intent .feature_metadata .as_ref() @@ -2154,6 +2155,10 @@ where .feature_metadata .as_ref() .map(api_models::payments::PaymentAttemptFeatureMetadata::foreign_from), + error_details: payment_attempt + .error + .map(api_models::payments::RecordAttemptErrorDetails::from), + created_at: payment_attempt.created_at, }; Ok(services::ApplicationResponse::JsonWithHeaders(( response, @@ -5213,6 +5218,8 @@ impl ForeignFrom<&diesel_models::types::FeatureMetadata> for api_models::payment first_payment_attempt_pg_error_code: payment_revenue_recovery_metadata .first_payment_attempt_pg_error_code .clone(), + invoice_billing_started_at_time: payment_revenue_recovery_metadata + .invoice_billing_started_at_time, } }); let apple_pay_details = feature_metadata diff --git a/crates/router/src/core/revenue_recovery/types.rs b/crates/router/src/core/revenue_recovery/types.rs index 65bdbaa628e..c043641dabd 100644 --- a/crates/router/src/core/revenue_recovery/types.rs +++ b/crates/router/src/core/revenue_recovery/types.rs @@ -34,6 +34,7 @@ use crate::{ errors::{self, RouterResult}, payments::{self, helpers, operations::Operation}, revenue_recovery::{self as revenue_recovery_core}, + webhooks::recovery_incoming as recovery_incoming_flow, }, db::StorageInterface, logger, @@ -101,6 +102,23 @@ impl RevenueRecoveryPaymentsAttemptStatus { ) -> Result<(), errors::ProcessTrackerError> { let db = &*state.store; + let recovery_payment_intent = + hyperswitch_domain_models::revenue_recovery::RecoveryPaymentIntent::from( + payment_intent, + ); + + let recovery_payment_attempt = + hyperswitch_domain_models::revenue_recovery::RecoveryPaymentAttempt::from( + &payment_attempt, + ); + + let recovery_payment_tuple = recovery_incoming_flow::RecoveryPaymentTuple::new( + &recovery_payment_intent, + &recovery_payment_attempt, + ); + + let retry_count = process_tracker.retry_count; + match self { Self::Succeeded => { // finish psync task as the payment was a success @@ -110,6 +128,19 @@ impl RevenueRecoveryPaymentsAttemptStatus { business_status::PSYNC_WORKFLOW_COMPLETE, ) .await?; + // publish events to kafka + if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka( + state, + &recovery_payment_tuple, + Some(retry_count+1) + ) + .await{ + router_env::logger::error!( + "Failed to publish revenue recovery event to kafka: {:?}", + e + ); + }; + // Record a successful transaction back to Billing Connector // TODO: Add support for retrying failed outgoing recordback webhooks record_back_to_billing_connector( @@ -130,6 +161,17 @@ impl RevenueRecoveryPaymentsAttemptStatus { business_status::PSYNC_WORKFLOW_COMPLETE, ) .await?; + // publish events to kafka + if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka( + state, + &recovery_payment_tuple, + Some(retry_count+1) + ) + .await{ + router_env::logger::error!( + "Failed to publish revenue recovery event to kafka : {:?}", e + ); + }; // get a reschedule time let schedule_time = get_schedule_time_to_retry_mit_payments( @@ -291,13 +333,66 @@ impl Action { revenue_recovery_metadata, ) .await; + let recovery_payment_intent = + hyperswitch_domain_models::revenue_recovery::RecoveryPaymentIntent::from( + payment_intent, + ); + // handle proxy api's response match response { Ok(payment_data) => match payment_data.payment_attempt.status.foreign_into() { - RevenueRecoveryPaymentsAttemptStatus::Succeeded => Ok(Self::SuccessfulPayment( - payment_data.payment_attempt.clone(), - )), + RevenueRecoveryPaymentsAttemptStatus::Succeeded => { + let recovery_payment_attempt = + hyperswitch_domain_models::revenue_recovery::RecoveryPaymentAttempt::from( + &payment_data.payment_attempt, + ); + + let recovery_payment_tuple = recovery_incoming_flow::RecoveryPaymentTuple::new( + &recovery_payment_intent, + &recovery_payment_attempt, + ); + + // publish events to kafka + if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka( + state, + &recovery_payment_tuple, + Some(process.retry_count+1) + ) + .await{ + router_env::logger::error!( + "Failed to publish revenue recovery event to kafka: {:?}", + e + ); + }; + + Ok(Self::SuccessfulPayment( + payment_data.payment_attempt.clone(), + )) + } RevenueRecoveryPaymentsAttemptStatus::Failed => { + let recovery_payment_attempt = + hyperswitch_domain_models::revenue_recovery::RecoveryPaymentAttempt::from( + &payment_data.payment_attempt, + ); + + let recovery_payment_tuple = recovery_incoming_flow::RecoveryPaymentTuple::new( + &recovery_payment_intent, + &recovery_payment_attempt, + ); + + // publish events to kafka + if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka( + state, + &recovery_payment_tuple, + Some(process.retry_count+1) + ) + .await{ + router_env::logger::error!( + "Failed to publish revenue recovery event to kafka: {:?}", + e + ); + }; + Self::decide_retry_failure_action( db, merchant_id, diff --git a/crates/router/src/core/webhooks/recovery_incoming.rs b/crates/router/src/core/webhooks/recovery_incoming.rs index b46b0651e6e..fe5613af882 100644 --- a/crates/router/src/core/webhooks/recovery_incoming.rs +++ b/crates/router/src/core/webhooks/recovery_incoming.rs @@ -13,7 +13,9 @@ use hyperswitch_domain_models::{ router_response_types::revenue_recovery as revenue_recovery_response, types as router_types, }; use hyperswitch_interfaces::webhooks as interface_webhooks; +use masking::{PeekInterface, Secret}; use router_env::{instrument, tracing}; +use services::kafka; use crate::{ core::{ @@ -133,6 +135,25 @@ pub async fn recovery_incoming_webhook_flow( ) .await?; + // Publish event to Kafka + if let Some(ref attempt) = recovery_attempt_from_payment_attempt { + // Passing `merchant_context` here + let recovery_payment_tuple = + &RecoveryPaymentTuple::new(&recovery_intent_from_payment_attempt, attempt); + if let Err(e) = RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka( + &state, + recovery_payment_tuple, + None, + ) + .await + { + router_env::logger::error!( + "Failed to publish revenue recovery event to kafka : {:?}", + e + ); + }; + } + let attempt_triggered_by = recovery_attempt_from_payment_attempt .as_ref() .and_then(|attempt| attempt.get_attempt_triggered_by()); @@ -342,10 +363,20 @@ impl RevenueRecoveryInvoice { let payment_id = payments_response.id.clone(); let status = payments_response.status; let feature_metadata = payments_response.feature_metadata; + let merchant_id = merchant_context.get_merchant_account().get_id().clone(); + let revenue_recovery_invoice_data = &self.0; Ok(Some(revenue_recovery::RecoveryPaymentIntent { payment_id, status, feature_metadata, + merchant_id, + merchant_reference_id: Some( + revenue_recovery_invoice_data.merchant_reference_id.clone(), + ), + invoice_amount: revenue_recovery_invoice_data.amount, + invoice_currency: revenue_recovery_invoice_data.currency, + created_at: revenue_recovery_invoice_data.billing_started_at, + billing_address: revenue_recovery_invoice_data.billing_address.clone(), })) } Err(err) @@ -402,10 +433,21 @@ impl RevenueRecoveryInvoice { .change_context(errors::RevenueRecoveryError::PaymentIntentCreateFailed) .attach_printable("expected json response")?; + let merchant_id = merchant_context.get_merchant_account().get_id().clone(); + let revenue_recovery_invoice_data = &self.0; + Ok(revenue_recovery::RecoveryPaymentIntent { payment_id: response.id, status: response.status, feature_metadata: response.feature_metadata, + merchant_id, + merchant_reference_id: Some( + revenue_recovery_invoice_data.merchant_reference_id.clone(), + ), + invoice_amount: revenue_recovery_invoice_data.amount, + invoice_currency: revenue_recovery_invoice_data.currency, + created_at: revenue_recovery_invoice_data.billing_started_at, + billing_address: revenue_recovery_invoice_data.billing_address.clone(), }) } } @@ -511,10 +553,18 @@ impl RevenueRecoveryAttempt { }) }); let payment_attempt = - final_attempt.map(|attempt_res| revenue_recovery::RecoveryPaymentAttempt { - attempt_id: attempt_res.id.to_owned(), - attempt_status: attempt_res.status.to_owned(), - feature_metadata: attempt_res.feature_metadata.to_owned(), + final_attempt.map(|res| revenue_recovery::RecoveryPaymentAttempt { + attempt_id: res.id.to_owned(), + attempt_status: res.status.to_owned(), + feature_metadata: res.feature_metadata.to_owned(), + amount: res.amount.net_amount, + network_advice_code: res.error.clone().and_then(|e| e.network_advice_code), // Placeholder, to be populated if available + network_decline_code: res + .error + .clone() + .and_then(|e| e.network_decline_code), // Placeholder, to be populated if available + error_code: res.error.clone().map(|error| error.code), + created_at: res.created_at, }); // If we have an attempt, combine it with payment_intent in a tuple. let res_with_payment_intent_and_attempt = @@ -579,11 +629,31 @@ impl RevenueRecoveryAttempt { attempt_id: attempt_response.id.clone(), attempt_status: attempt_response.status, feature_metadata: attempt_response.payment_attempt_feature_metadata, + amount: attempt_response.amount, + network_advice_code: attempt_response + .error_details + .clone() + .and_then(|error| error.network_decline_code), // Placeholder, to be populated if available + network_decline_code: attempt_response + .error_details + .clone() + .and_then(|error| error.network_decline_code), // Placeholder, to be populated if available + error_code: attempt_response + .error_details + .clone() + .map(|error| error.code), + created_at: attempt_response.created_at, }, revenue_recovery::RecoveryPaymentIntent { payment_id: payment_intent.payment_id.clone(), status: attempt_response.status.into(), // Using status from attempt_response feature_metadata: attempt_response.payment_intent_feature_metadata, // Using feature_metadata from attempt_response + merchant_id: payment_intent.merchant_id.clone(), + merchant_reference_id: payment_intent.merchant_reference_id.clone(), + invoice_amount: payment_intent.invoice_amount, + invoice_currency: payment_intent.invoice_currency, + created_at: payment_intent.created_at, + billing_address: payment_intent.billing_address.clone(), }, )) } @@ -665,6 +735,8 @@ impl RevenueRecoveryAttempt { connector_customer_id: revenue_recovery_attempt_data.connector_customer_id.clone(), retry_count: revenue_recovery_attempt_data.retry_count, invoice_next_billing_time: revenue_recovery_attempt_data.invoice_next_billing_time, + invoice_billing_started_at_time: revenue_recovery_attempt_data + .invoice_billing_started_at_time, triggered_by, card_network: revenue_recovery_attempt_data.card_network.clone(), card_issuer, @@ -1180,3 +1252,104 @@ impl BillingConnectorInvoiceSyncFlowRouterData { self.0 } } + +#[derive(Clone, Debug)] +pub struct RecoveryPaymentTuple( + revenue_recovery::RecoveryPaymentIntent, + revenue_recovery::RecoveryPaymentAttempt, +); + +impl RecoveryPaymentTuple { + pub fn new( + payment_intent: &revenue_recovery::RecoveryPaymentIntent, + payment_attempt: &revenue_recovery::RecoveryPaymentAttempt, + ) -> Self { + Self(payment_intent.clone(), payment_attempt.clone()) + } + + pub async fn publish_revenue_recovery_event_to_kafka( + state: &SessionState, + recovery_payment_tuple: &Self, + retry_count: Option<i32>, + ) -> CustomResult<(), errors::RevenueRecoveryError> { + let recovery_payment_intent = &recovery_payment_tuple.0; + let recovery_payment_attempt = &recovery_payment_tuple.1; + let revenue_recovery_feature_metadata = recovery_payment_intent + .feature_metadata + .as_ref() + .and_then(|metadata| metadata.revenue_recovery.as_ref()); + + let billing_city = recovery_payment_intent + .billing_address + .as_ref() + .and_then(|billing_address| billing_address.address.as_ref()) + .and_then(|address| address.city.clone()) + .map(Secret::new); + + let billing_state = recovery_payment_intent + .billing_address + .as_ref() + .and_then(|billing_address| billing_address.address.as_ref()) + .and_then(|address| address.state.clone()); + + let billing_country = recovery_payment_intent + .billing_address + .as_ref() + .and_then(|billing_address| billing_address.address.as_ref()) + .and_then(|address| address.country); + + let card_info = revenue_recovery_feature_metadata.and_then(|metadata| { + metadata + .billing_connector_payment_method_details + .as_ref() + .and_then(|details| details.get_billing_connector_card_info()) + }); + + #[allow(clippy::as_conversions)] + let retry_count = Some(retry_count.unwrap_or_else(|| { + revenue_recovery_feature_metadata + .map(|data| data.total_retry_count as i32) + .unwrap_or(0) + })); + + let event = kafka::revenue_recovery::RevenueRecovery { + merchant_id: &recovery_payment_intent.merchant_id, + invoice_amount: recovery_payment_intent.invoice_amount, + invoice_currency: &recovery_payment_intent.invoice_currency, + invoice_date: revenue_recovery_feature_metadata.and_then(|data| { + data.invoice_billing_started_at_time + .map(|time| time.assume_utc()) + }), + invoice_due_date: revenue_recovery_feature_metadata + .and_then(|data| data.invoice_next_billing_time.map(|time| time.assume_utc())), + billing_city, + billing_country: billing_country.as_ref(), + billing_state, + attempt_amount: recovery_payment_attempt.amount, + attempt_currency: &recovery_payment_intent.invoice_currency.clone(), + attempt_status: &recovery_payment_attempt.attempt_status.clone(), + pg_error_code: recovery_payment_attempt.error_code.clone(), + network_advice_code: recovery_payment_attempt.network_advice_code.clone(), + network_error_code: recovery_payment_attempt.network_decline_code.clone(), + first_pg_error_code: revenue_recovery_feature_metadata + .and_then(|data| data.first_payment_attempt_pg_error_code.clone()), + first_network_advice_code: revenue_recovery_feature_metadata + .and_then(|data| data.first_payment_attempt_network_advice_code.clone()), + first_network_error_code: revenue_recovery_feature_metadata + .and_then(|data| data.first_payment_attempt_network_decline_code.clone()), + attempt_created_at: recovery_payment_attempt.created_at.assume_utc(), + payment_method_type: revenue_recovery_feature_metadata + .map(|data| &data.payment_method_type), + payment_method_subtype: revenue_recovery_feature_metadata + .map(|data| &data.payment_method_subtype), + card_network: card_info + .as_ref() + .and_then(|info| info.card_network.as_ref()), + card_issuer: card_info.and_then(|data| data.card_issuer.clone()), + retry_count, + payment_gateway: revenue_recovery_feature_metadata.map(|data| data.connector), + }; + state.event_handler.log_event(&event); + Ok(()) + } +} diff --git a/crates/router/src/events.rs b/crates/router/src/events.rs index 7d77df6871f..b7bf1b9f0fb 100644 --- a/crates/router/src/events.rs +++ b/crates/router/src/events.rs @@ -39,6 +39,7 @@ pub enum EventType { Consolidated, Authentication, RoutingApiLogs, + RevenueRecovery, } #[derive(Debug, Default, Deserialize, Clone)] diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs index 2da6cc66ff4..8a7613f344f 100644 --- a/crates/router/src/services/kafka.rs +++ b/crates/router/src/services/kafka.rs @@ -28,6 +28,7 @@ mod payment_intent; mod payment_intent_event; mod refund; mod refund_event; +pub mod revenue_recovery; use diesel_models::{authentication::Authentication, refund::Refund}; use hyperswitch_domain_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent}; use serde::Serialize; @@ -162,6 +163,7 @@ pub struct KafkaSettings { consolidated_events_topic: String, authentication_analytics_topic: String, routing_logs_topic: String, + revenue_recovery_topic: String, } impl KafkaSettings { @@ -277,6 +279,7 @@ pub struct KafkaProducer { authentication_analytics_topic: String, ckh_database_name: Option<String>, routing_logs_topic: String, + revenue_recovery_topic: String, } struct RdKafkaProducer(ThreadedProducer<DefaultProducerContext>); @@ -327,6 +330,7 @@ impl KafkaProducer { authentication_analytics_topic: conf.authentication_analytics_topic.clone(), ckh_database_name: None, routing_logs_topic: conf.routing_logs_topic.clone(), + revenue_recovery_topic: conf.revenue_recovery_topic.clone(), }) } @@ -665,6 +669,7 @@ impl KafkaProducer { EventType::Consolidated => &self.consolidated_events_topic, EventType::Authentication => &self.authentication_analytics_topic, EventType::RoutingApiLogs => &self.routing_logs_topic, + EventType::RevenueRecovery => &self.revenue_recovery_topic, } } } diff --git a/crates/router/src/services/kafka/revenue_recovery.rs b/crates/router/src/services/kafka/revenue_recovery.rs new file mode 100644 index 00000000000..93294dca4c9 --- /dev/null +++ b/crates/router/src/services/kafka/revenue_recovery.rs @@ -0,0 +1,43 @@ +use common_utils::{id_type, types::MinorUnit}; +use masking::Secret; +use time::OffsetDateTime; +#[derive(serde::Serialize, Debug)] +pub struct RevenueRecovery<'a> { + pub merchant_id: &'a id_type::MerchantId, + pub invoice_amount: MinorUnit, + pub invoice_currency: &'a common_enums::Currency, + #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] + pub invoice_due_date: Option<OffsetDateTime>, + #[serde(with = "time::serde::timestamp::nanoseconds::option")] + pub invoice_date: Option<OffsetDateTime>, + pub billing_country: Option<&'a common_enums::CountryAlpha2>, + pub billing_state: Option<Secret<String>>, + pub billing_city: Option<Secret<String>>, + pub attempt_amount: MinorUnit, + pub attempt_currency: &'a common_enums::Currency, + pub attempt_status: &'a common_enums::AttemptStatus, + pub pg_error_code: Option<String>, + pub network_advice_code: Option<String>, + pub network_error_code: Option<String>, + pub first_pg_error_code: Option<String>, + pub first_network_advice_code: Option<String>, + pub first_network_error_code: Option<String>, + #[serde(default, with = "time::serde::timestamp::nanoseconds")] + pub attempt_created_at: OffsetDateTime, + pub payment_method_type: Option<&'a common_enums::PaymentMethod>, + pub payment_method_subtype: Option<&'a common_enums::PaymentMethodType>, + pub card_network: Option<&'a common_enums::CardNetwork>, + pub card_issuer: Option<String>, + pub retry_count: Option<i32>, + pub payment_gateway: Option<common_enums::connector_enums::Connector>, +} + +impl super::KafkaMessage for RevenueRecovery<'_> { + fn key(&self) -> String { + self.merchant_id.get_string_repr().to_string() + } + + fn event_type(&self) -> crate::events::EventType { + crate::events::EventType::RevenueRecovery + } +} diff --git a/crates/storage_impl/src/errors.rs b/crates/storage_impl/src/errors.rs index 2260a0528fe..89326d9a71c 100644 --- a/crates/storage_impl/src/errors.rs +++ b/crates/storage_impl/src/errors.rs @@ -289,7 +289,6 @@ pub enum RecoveryError { #[error("Failed to fetch billing connector account id")] BillingMerchantConnectorAccountIdNotFound, } - #[derive(Debug, Clone, thiserror::Error)] pub enum HealthCheckDecisionEngineError { #[error("Failed to establish Decision Engine connection")]
2025-06-09T10:54:43Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This new Kafka Event consume the revenue recovery related events which will be constructed from both `RecoveryPaymentIntent` and `RecoveryPaymentAttempt` in revenue recovery flow. The events form Kafka will be picked up by vector and this be eventually batched and pushed to s3 based on the set config. They file path will look like this `merchant_id/Year/month/timestamp.csv`. The events will be recorded at two places. `Webhook Flow`(External Payments done by billing processor) and `Internal Proxy Flow`(Internal Done by Hyperswitch as a part of retrying). The event structure is mentioned in the kafka message in code. The estimated size of each event is around 1000bytes. We want to keep the config at 1000 batches and one day(86400s) timeout in vector. So that vector collects all the events till the end of the time out or till it hits 1000 events and push them to s3 file in the designated file path in a csv format in the order mentioned in the config. Based on the above config vector needs 10mb size buffer to support this. S3 auth will be done using the IAM Instance profile which will be taken care off at the time of the deployment. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [x] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context As for the Revenue Recovery System we needed a pipeline which can move transaction based data to s3 where we store the entire transactional data which can be further used to train models. The transactional data consists of various parameters from both payment intent and payment attempt. So we created a new topic to facilitate this requirement. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> At the time of this pr getting merged, Kafka is not enabled for V2 . So we cannot test it. It can be tested by the following steps once kafka is enabled for v2. Follow the steps in this pr #7461 and check the s3 attached to that kafka topic to find a file after waiting for one day. Sample Kafka Event : <img width="1723" alt="Screenshot 2025-07-07 at 4 57 59 PM" src="https://github.com/user-attachments/assets/f61040e1-2def-46ea-aee6-4652418ebdfb" /> Here is the S3 File Path: <img width="897" alt="Screenshot 2025-06-11 at 7 20 08 PM" src="https://github.com/user-attachments/assets/7f89d1c9-1af4-4edf-b051-2371d5198ce9" /> Here is the AWS File sample <img width="1643" alt="Screenshot 2025-07-07 at 5 01 25 PM" src="https://github.com/user-attachments/assets/64e64767-fa72-48e8-a885-2a4db7d45cf7" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.115.0
20b37bdb7a25ec053e7671332d4837a0ad743983
20b37bdb7a25ec053e7671332d4837a0ad743983
juspay/hyperswitch
juspay__hyperswitch-8324
Bug: [REFACTOR] Refactor routing events core ### Feature Description Refactor routing events core to include a framework for routing events ### Possible Implementation Refactor routing events core to include a framework for routing events ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/api_models/src/open_router.rs b/crates/api_models/src/open_router.rs index 33719e8a41b..af91ece3f12 100644 --- a/crates/api_models/src/open_router.rs +++ b/crates/api_models/src/open_router.rs @@ -58,14 +58,14 @@ pub struct PaymentInfo { // cardSwitchProvider: Option<Secret<String>>, } -#[derive(Debug, Serialize, Deserialize, PartialEq)] +#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] pub struct DecidedGateway { pub gateway_priority_map: Option<HashMap<String, f64>>, pub debit_routing_output: Option<DebitRoutingOutput>, pub routing_approach: String, } -#[derive(Debug, Serialize, Deserialize, PartialEq)] +#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] pub struct DebitRoutingOutput { pub co_badged_card_networks: Vec<common_enums::CardNetwork>, pub issuer_country: common_enums::CountryAlpha2, @@ -121,7 +121,7 @@ pub struct DebitRoutingRequestData { pub card_type: common_enums::CardType, } -#[derive(Debug, Serialize, Deserialize)] +#[derive(Debug, Serialize, Deserialize, Clone)] pub struct ErrorResponse { pub status: String, pub error_code: String, @@ -132,7 +132,7 @@ pub struct ErrorResponse { pub is_dynamic_mga_enabled: bool, } -#[derive(Debug, Serialize, Deserialize)] +#[derive(Debug, Serialize, Deserialize, Clone)] pub struct UnifiedError { pub code: String, pub user_message: String, diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index 75bb67ba493..3e312769e07 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -1384,160 +1384,6 @@ impl std::fmt::Display for RoutingApproach { } } } - -#[derive(Clone, Debug, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub struct BucketInformationEventResponse { - pub is_eliminated: bool, - pub bucket_name: Vec<String>, -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub struct EliminationInformationEventResponse { - pub entity: Option<BucketInformationEventResponse>, - pub global: Option<BucketInformationEventResponse>, -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub struct LabelWithStatusEliminationEventResponse { - pub label: String, - pub elimination_information: Option<EliminationInformationEventResponse>, -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub struct EliminationEventResponse { - pub labels_with_status: Vec<LabelWithStatusEliminationEventResponse>, -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub struct ScoreDataEventResponse { - pub score: f64, - pub label: String, - pub current_count: u64, -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub struct CalContractScoreEventResponse { - pub labels_with_score: Vec<ScoreDataEventResponse>, -} - -#[derive(Clone, Copy, Debug, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub struct CalGlobalSuccessRateConfigEventRequest { - pub entity_min_aggregates_size: u32, - pub entity_default_success_rate: f64, -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub struct CalGlobalSuccessRateEventRequest { - pub entity_id: String, - pub entity_params: String, - pub entity_labels: Vec<String>, - pub global_labels: Vec<String>, - pub config: Option<CalGlobalSuccessRateConfigEventRequest>, -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub struct UpdateSuccessRateWindowConfig { - pub max_aggregates_size: Option<u32>, - pub current_block_threshold: Option<CurrentBlockThreshold>, -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub struct UpdateLabelWithStatusEventRequest { - pub label: String, - pub status: bool, -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub struct UpdateSuccessRateWindowEventRequest { - pub id: String, - pub params: String, - pub labels_with_status: Vec<UpdateLabelWithStatusEventRequest>, - pub config: Option<UpdateSuccessRateWindowConfig>, - pub global_labels_with_status: Vec<UpdateLabelWithStatusEventRequest>, -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub struct UpdateSuccessRateWindowEventResponse { - pub status: UpdationStatusEventResponse, -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum UpdationStatusEventResponse { - WindowUpdationSucceeded, - WindowUpdationFailed, -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub struct LabelWithBucketNameEventRequest { - pub label: String, - pub bucket_name: String, -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub struct UpdateEliminationBucketEventRequest { - pub id: String, - pub params: String, - pub labels_with_bucket_name: Vec<LabelWithBucketNameEventRequest>, - pub config: Option<EliminationRoutingEventBucketConfig>, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub struct UpdateEliminationBucketEventResponse { - pub status: EliminationUpdationStatusEventResponse, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum EliminationUpdationStatusEventResponse { - BucketUpdationSucceeded, - BucketUpdationFailed, -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub struct ContractLabelInformationEventRequest { - pub label: String, - pub target_count: u64, - pub target_time: u64, - pub current_count: u64, -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub struct UpdateContractRequestEventRequest { - pub id: String, - pub params: String, - pub labels_information: Vec<ContractLabelInformationEventRequest>, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub struct UpdateContractEventResponse { - pub status: ContractUpdationStatusEventResponse, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum ContractUpdationStatusEventResponse { - ContractUpdationSucceeded, - ContractUpdationFailed, -} #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct RuleMigrationQuery { pub profile_id: common_utils::id_type::ProfileId, diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index 3037c1d4e6b..93d4414a5b4 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -388,6 +388,8 @@ pub enum RoutingError { DecisionEngineValidationError(String), #[error("Invalid transaction type")] InvalidTransactionType, + #[error("Routing events error: {message}, status code: {status_code}")] + RoutingEventsError { message: String, status_code: u16 }, } #[derive(Debug, Clone, thiserror::Error)] diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index f08e76469dc..53a657c2e6c 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -17,8 +17,6 @@ use api_models::{ }; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use common_utils::ext_traits::AsyncExt; -#[cfg(all(feature = "v1", feature = "dynamic_routing"))] -use common_utils::{ext_traits::BytesExt, request}; use diesel_models::enums as storage_enums; use error_stack::ResultExt; use euclid::{ @@ -30,13 +28,12 @@ use euclid::{ #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use external_services::grpc_client::dynamic_routing::{ contract_routing_client::ContractBasedDynamicRouting, - elimination_based_client::{EliminationBasedRouting, EliminationResponse}, - success_rate_client::SuccessBasedDynamicRouting, - DynamicRoutingError, + elimination_based_client::EliminationBasedRouting, + success_rate_client::SuccessBasedDynamicRouting, DynamicRoutingError, }; use hyperswitch_domain_models::address::Address; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] -use hyperswitch_interfaces::events::routing_api_logs::{ApiMethod, RoutingEngine, RoutingEvent}; +use hyperswitch_interfaces::events::routing_api_logs::{ApiMethod, RoutingEngine}; use kgraph_utils::{ mca as mca_graph, transformers::{IntoContext, IntoDirValue}, @@ -59,8 +56,6 @@ use crate::core::payouts; #[cfg(feature = "v1")] use crate::core::routing::transformers::OpenRouterDecideGatewayRequestExt; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] -use crate::headers; -#[cfg(all(feature = "v1", feature = "dynamic_routing"))] use crate::routes::app::SessionStateInfo; use crate::{ core::{ @@ -482,10 +477,36 @@ pub async fn perform_static_routing_v1( } }; + let payment_id = match transaction_data { + routing::TransactionData::Payment(payment_data) => payment_data + .payment_attempt + .payment_id + .clone() + .get_string_repr() + .to_string(), + #[cfg(feature = "payouts")] + routing::TransactionData::Payout(payout_data) => { + payout_data.payout_attempt.payout_id.clone() + } + }; + + let routing_events_wrapper = utils::RoutingEventsWrapper::new( + state.tenant.tenant_id.clone(), + state.request_id, + payment_id, + business_profile.get_id().to_owned(), + business_profile.merchant_id.to_owned(), + "DecisionEngine: Euclid Static Routing".to_string(), + None, + true, + false, + ); + let de_euclid_connectors = perform_decision_euclid_routing( state, backend_input.clone(), business_profile.get_id().get_string_repr().to_string(), + routing_events_wrapper ) .await .map_err(|e| @@ -497,8 +518,12 @@ pub async fn perform_static_routing_v1( .iter() .map(|c| c.connector.to_string()) .collect::<Vec<String>>(); + let de_connectors = de_euclid_connectors + .iter() + .map(|c| c.gateway_name.to_string()) + .collect::<Vec<String>>(); utils::compare_and_log_result( - de_euclid_connectors, + de_connectors, connectors, "evaluate_routing".to_string(), ); @@ -1646,19 +1671,36 @@ pub async fn perform_open_routing_for_debit_routing( Some(or_types::RankingAlgorithm::NtwBasedRouting), ); - let response: RoutingResult<DecidedGateway> = + let routing_events_wrapper = utils::RoutingEventsWrapper::new( + state.tenant.tenant_id.clone(), + state.request_id, + payment_attempt.payment_id.get_string_repr().to_string(), + payment_attempt.profile_id.to_owned(), + payment_attempt.merchant_id.to_owned(), + "DecisionEngine: Debit Routing".to_string(), + Some(open_router_req_body.clone()), + true, + true, + ); + + let response: RoutingResult<utils::RoutingEventsResponse<DecidedGateway>> = utils::EuclidApiClient::send_decision_engine_request( state, services::Method::Post, "decide-gateway", Some(open_router_req_body), None, + Some(routing_events_wrapper), ) .await; let output = match response { - Ok(decided_gateway) => { - let debit_routing_output = decided_gateway + Ok(events_response) => { + let debit_routing_output = events_response + .response + .ok_or(errors::RoutingError::OpenRouterError( + "Response from decision engine API is empty".to_string(), + ))? .debit_routing_output .get_required_value("debit_routing_output") .change_context(errors::RoutingError::OpenRouterError( @@ -1797,57 +1839,45 @@ pub async fn perform_decide_gateway_call_with_open_router( is_elimination_enabled, ); - let serialized_request = serde_json::to_value(&open_router_req_body) - .change_context(errors::RoutingError::OpenRouterCallFailed) - .attach_printable("Failed to serialize open_router request body")?; - - let url = format!("{}/{}", &state.conf.open_router.url, "decide-gateway"); - let mut request = request::Request::new(services::Method::Post, &url); - request.add_header(headers::CONTENT_TYPE, "application/json".into()); - request.add_header( - headers::X_TENANT_ID, - state.tenant.tenant_id.get_string_repr().to_owned().into(), - ); - request.set_body(request::RequestContent::Json(Box::new( - open_router_req_body, - ))); - - let mut routing_event = RoutingEvent::new( + let routing_events_wrapper = utils::RoutingEventsWrapper::new( state.tenant.tenant_id.clone(), - "".to_string(), - "open_router_decide_gateway_call", - serialized_request, - url.clone(), - ApiMethod::Rest(services::Method::Post), + state.request_id, payment_attempt.payment_id.get_string_repr().to_string(), - profile_id.to_owned(), + payment_attempt.profile_id.to_owned(), payment_attempt.merchant_id.to_owned(), - state.request_id, - RoutingEngine::DecisionEngine, + "DecisionEngine: SuccessRate decide_gateway".to_string(), + Some(open_router_req_body.clone()), + true, + false, ); - let response = services::call_connector_api(state, request, "open_router_decide_gateway_call") - .await - .inspect_err(|err| { - routing_event - .set_error(serde_json::json!({"error": err.current_context().to_string()})); - state.event_handler().log_event(&routing_event); - }) - .change_context(errors::RoutingError::OpenRouterCallFailed)?; + let response: RoutingResult<utils::RoutingEventsResponse<DecidedGateway>> = + utils::SRApiClient::send_decision_engine_request( + state, + services::Method::Post, + "decide-gateway", + Some(open_router_req_body), + None, + Some(routing_events_wrapper), + ) + .await; let sr_sorted_connectors = match response { Ok(resp) => { - let decided_gateway: DecidedGateway = resp - .response - .parse_struct("DecidedGateway") - .change_context(errors::RoutingError::OpenRouterError( - "Failed to parse the response from open_router".into(), + let decided_gateway: DecidedGateway = + resp.response.ok_or(errors::RoutingError::OpenRouterError( + "Empty response received from open_router".into(), ))?; - routing_event.set_status_code(resp.status_code); + let mut routing_event = resp.event.ok_or(errors::RoutingError::RoutingEventsError { + message: "Decision-Engine: RoutingEvent not found in RoutingEventsResponse" + .to_string(), + status_code: 500, + })?; + routing_event.set_response_body(&decided_gateway); routing_event.set_routing_approach( - api_routing::RoutingApproach::from_decision_engine_approach( + utils::RoutingApproach::from_decision_engine_approach( &decided_gateway.routing_approach, ) .to_string(), @@ -1876,18 +1906,7 @@ pub async fn perform_decide_gateway_call_with_open_router( Ok(routable_connectors) } Err(err) => { - let err_resp: or_types::ErrorResponse = err - .response - .parse_struct("ErrorResponse") - .change_context(errors::RoutingError::OpenRouterError( - "Failed to parse the response from open_router".into(), - ))?; - logger::error!("open_router_error_response: {:?}", err_resp); - - routing_event.set_status_code(err.status_code); - routing_event.set_error(serde_json::json!({"error": err_resp.error_message})); - routing_event.set_error_response_body(&err_resp); - state.event_handler().log_event(&routing_event); + logger::error!("open_router_error_response: {:?}", err); Err(errors::RoutingError::OpenRouterError( "Failed to perform decide_gateway call in open_router".into(), @@ -1915,81 +1934,55 @@ pub async fn update_gateway_score_with_open_router( payment_id: payment_id.clone(), }; - let serialized_request = serde_json::to_value(&open_router_req_body) - .change_context(errors::RoutingError::OpenRouterCallFailed) - .attach_printable("Failed to serialize open_router request body")?; - - let url = format!("{}/{}", &state.conf.open_router.url, "update-gateway-score"); - let mut request = request::Request::new(services::Method::Post, &url); - request.add_header(headers::CONTENT_TYPE, "application/json".into()); - request.add_header( - headers::X_TENANT_ID, - state.tenant.tenant_id.get_string_repr().to_owned().into(), - ); - request.set_body(request::RequestContent::Json(Box::new( - open_router_req_body, - ))); - - let mut routing_event = RoutingEvent::new( + let routing_events_wrapper = utils::RoutingEventsWrapper::new( state.tenant.tenant_id.clone(), - "".to_string(), - "open_router_update_gateway_score_call", - serialized_request, - url.clone(), - ApiMethod::Rest(services::Method::Post), + state.request_id, payment_id.get_string_repr().to_string(), profile_id.to_owned(), merchant_id.to_owned(), - state.request_id, - RoutingEngine::DecisionEngine, + "DecisionEngine: SuccessRate update_gateway_score".to_string(), + Some(open_router_req_body.clone()), + true, + false, ); - let response = - services::call_connector_api(state, request, "open_router_update_gateway_score_call") - .await - .inspect_err(|err| { - routing_event - .set_error(serde_json::json!({"error": err.current_context().to_string()})); - state.event_handler().log_event(&routing_event); - }) - .change_context(errors::RoutingError::OpenRouterCallFailed)?; - - routing_event.set_payment_connector(payment_connector.clone()); // check this in review + let response: RoutingResult<utils::RoutingEventsResponse<or_types::UpdateScoreResponse>> = + utils::SRApiClient::send_decision_engine_request( + state, + services::Method::Post, + "update-gateway-score", + Some(open_router_req_body), + None, + Some(routing_events_wrapper), + ) + .await; match response { Ok(resp) => { - let update_score_resp = resp - .response - .parse_struct::<or_types::UpdateScoreResponse>("UpdateScoreResponse") - .change_context(errors::RoutingError::OpenRouterError( - "Failed to parse the response from open_router".into(), - ))?; + let update_score_resp = resp.response.ok_or(errors::RoutingError::OpenRouterError( + "Failed to parse the response from open_router".into(), + ))?; + + let mut routing_event = resp.event.ok_or(errors::RoutingError::RoutingEventsError { + message: "Decision-Engine: RoutingEvent not found in RoutingEventsResponse" + .to_string(), + status_code: 500, + })?; logger::debug!( "open_router update_gateway_score response for gateway with id {}: {:?}", payment_connector, - update_score_resp + update_score_resp.message ); - routing_event.set_status_code(resp.status_code); routing_event.set_response_body(&update_score_resp); + routing_event.set_payment_connector(payment_connector.clone()); // check this in review state.event_handler().log_event(&routing_event); Ok(()) } Err(err) => { - let err_resp: or_types::ErrorResponse = err - .response - .parse_struct("ErrorResponse") - .change_context(errors::RoutingError::OpenRouterError( - "Failed to parse the response from open_router".into(), - ))?; - logger::error!("open_router_update_gateway_score_error: {:?}", err_resp); - - routing_event.set_status_code(err.status_code); - routing_event.set_error(serde_json::json!({"error": err_resp.error_message})); - routing_event.set_error_response_body(&err_resp); - state.event_handler().log_event(&routing_event); + logger::error!("open_router_update_gateway_score_error: {:?}", err); Err(errors::RoutingError::OpenRouterError( "Failed to update gateway score in open_router".into(), @@ -2052,88 +2045,96 @@ pub async fn perform_success_based_routing( .ok_or(errors::RoutingError::SuccessBasedRoutingParamsNotFoundError)?, ); - let event_request = api_routing::CalSuccessRateEventRequest { + let event_request = utils::CalSuccessRateEventRequest { id: profile_id.get_string_repr().to_string(), params: success_based_routing_config_params.clone(), labels: routable_connectors .iter() .map(|conn_choice| conn_choice.to_string()) .collect::<Vec<_>>(), - config: success_based_routing_configs.config.as_ref().map(|conf| { - api_routing::CalSuccessRateConfigEventRequest { - min_aggregates_size: conf.min_aggregates_size, - default_success_rate: conf.default_success_rate, - specificity_level: conf.specificity_level, - exploration_percent: conf.exploration_percent, - } - }), + config: success_based_routing_configs + .config + .as_ref() + .map(utils::CalSuccessRateConfigEventRequest::from), }; - let serialized_request = serde_json::to_value(&event_request) - .change_context(errors::RoutingError::SuccessBasedRoutingConfigError) - .attach_printable("unable to serialize success_based_routing_config_params")?; - - let mut routing_event = RoutingEvent::new( + let routing_events_wrapper = utils::RoutingEventsWrapper::new( state.tenant.tenant_id.clone(), - "".to_string(), - "Intelligent-router FetchSuccessRate", - serialized_request, - "SuccessRateCalculator.FetchSuccessRate".to_string(), - ApiMethod::Grpc, + state.request_id, payment_id.get_string_repr().to_string(), profile_id.to_owned(), merchant_id.to_owned(), - state.request_id, - RoutingEngine::IntelligentRouter, + "IntelligentRouter: CalculateSuccessRate".to_string(), + Some(event_request.clone()), + true, + false, ); - let success_based_connectors = client - .calculate_success_rate( - profile_id.get_string_repr().into(), - success_based_routing_configs, - success_based_routing_config_params, - routable_connectors, - state.get_grpc_headers(), - ) - .await - .inspect_err(|e| { - routing_event - .set_error(serde_json::json!({"error": e.current_context().to_string()})); - state.event_handler().log_event(&routing_event); - }) - .change_context(errors::RoutingError::SuccessRateCalculationError) - .attach_printable( - "unable to calculate/fetch success rate from dynamic routing service", - )?; - - let event_response = api_routing::CalSuccessRateEventResponse { - labels_with_score: success_based_connectors - .labels_with_score - .iter() - .map( - |label_with_score| api_routing::LabelWithScoreEventResponse { - label: label_with_score.label.clone(), - score: label_with_score.score, - }, + let closure = || async { + let success_based_connectors_result = client + .calculate_success_rate( + profile_id.get_string_repr().into(), + success_based_routing_configs, + success_based_routing_config_params, + routable_connectors, + state.get_grpc_headers(), ) - .collect(), - routing_approach: match success_based_connectors.routing_approach { - 0 => api_routing::RoutingApproach::Exploration, - 1 => api_routing::RoutingApproach::Exploitation, - _ => { - return Err(errors::RoutingError::GenericNotFoundError { - field: "routing_approach".to_string(), - }) - .change_context(errors::RoutingError::GenericNotFoundError { - field: "unknown routing approach from dynamic routing service".to_string(), - }) - .attach_printable("unknown routing approach from dynamic routing service") + .await + .change_context(errors::RoutingError::SuccessRateCalculationError) + .attach_printable( + "unable to calculate/fetch success rate from dynamic routing service", + ); + + match success_based_connectors_result { + Ok(success_response) => { + let updated_resp = utils::CalSuccessRateEventResponse::try_from( + &success_response, + ) + .change_context(errors::RoutingError::RoutingEventsError { message: "unable to convert SuccessBasedConnectors to CalSuccessRateEventResponse".to_string(), status_code: 500 }) + .attach_printable( + "unable to convert SuccessBasedConnectors to CalSuccessRateEventResponse", + )?; + + Ok(Some(updated_resp)) } - }, + Err(e) => { + logger::error!( + "unable to calculate/fetch success rate from dynamic routing service: {:?}", + e.current_context() + ); + + Err(error_stack::report!( + errors::RoutingError::SuccessRateCalculationError + )) + } + } }; - routing_event.set_response_body(&event_response); - routing_event.set_routing_approach(event_response.routing_approach.to_string()); + let events_response = routing_events_wrapper + .construct_event_builder( + "SuccessRateCalculator.FetchSuccessRate".to_string(), + RoutingEngine::IntelligentRouter, + ApiMethod::Grpc, + )? + .trigger_event(state, closure) + .await?; + + let success_based_connectors: utils::CalSuccessRateEventResponse = events_response + .response + .ok_or(errors::RoutingError::SuccessRateCalculationError)?; + + // Need to log error case + let mut routing_event = + events_response + .event + .ok_or(errors::RoutingError::RoutingEventsError { + message: + "SR-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse" + .to_string(), + status_code: 500, + })?; + + routing_event.set_routing_approach(success_based_connectors.routing_approach.to_string()); let mut connectors = Vec::with_capacity(success_based_connectors.labels_with_score.len()); for label_with_score in success_based_connectors.labels_with_score { @@ -2227,7 +2228,7 @@ pub async fn perform_elimination_routing( .ok_or(errors::RoutingError::EliminationBasedRoutingParamsNotFoundError)?, ); - let event_request = api_routing::EliminationRoutingEventRequest { + let event_request = utils::EliminationRoutingEventRequest { id: profile_id.get_string_repr().to_string(), params: elimination_routing_config_params.clone(), labels: routable_connectors @@ -2237,80 +2238,76 @@ pub async fn perform_elimination_routing( config: elimination_routing_config .elimination_analyser_config .as_ref() - .map(|conf| api_routing::EliminationRoutingEventBucketConfig { - bucket_leak_interval_in_secs: conf.bucket_leak_interval_in_secs, - bucket_size: conf.bucket_size, - }), + .map(utils::EliminationRoutingEventBucketConfig::from), }; - let serialized_request = serde_json::to_value(&event_request) - .change_context(errors::RoutingError::SuccessBasedRoutingConfigError) - .attach_printable("unable to serialize EliminationRoutingEventRequest")?; - - let mut routing_event = RoutingEvent::new( + let routing_events_wrapper = utils::RoutingEventsWrapper::new( state.tenant.tenant_id.clone(), - "".to_string(), - "Intelligent-router GetEliminationStatus", - serialized_request, - "EliminationAnalyser.GetEliminationStatus".to_string(), - ApiMethod::Grpc, + state.request_id, payment_id.get_string_repr().to_string(), profile_id.to_owned(), merchant_id.to_owned(), - state.request_id, - RoutingEngine::IntelligentRouter, + "IntelligentRouter: PerformEliminationRouting".to_string(), + Some(event_request.clone()), + true, + false, ); - let elimination_based_connectors: EliminationResponse = client - .perform_elimination_routing( - profile_id.get_string_repr().to_string(), - elimination_routing_config_params, - routable_connectors.clone(), - elimination_routing_config.elimination_analyser_config, - state.get_grpc_headers(), - ) - .await - .inspect_err(|e| { - routing_event - .set_error(serde_json::json!({"error": e.current_context().to_string()})); - state.event_handler().log_event(&routing_event); - }) - .change_context(errors::RoutingError::EliminationRoutingCalculationError) - .attach_printable( - "unable to analyze/fetch elimination routing from dynamic routing service", - )?; - - let event_response = api_routing::EliminationEventResponse { - labels_with_status: elimination_based_connectors - .labels_with_status - .iter() - .map( - |label_with_status| api_routing::LabelWithStatusEliminationEventResponse { - label: label_with_status.label.clone(), - elimination_information: label_with_status - .elimination_information - .as_ref() - .map(|info| api_routing::EliminationInformationEventResponse { - entity: info.entity.as_ref().map(|entity_info| { - api_routing::BucketInformationEventResponse { - is_eliminated: entity_info.is_eliminated, - bucket_name: entity_info.bucket_name.clone(), - } - }), - global: info.global.as_ref().map(|global_info| { - api_routing::BucketInformationEventResponse { - is_eliminated: global_info.is_eliminated, - bucket_name: global_info.bucket_name.clone(), - } - }), - }), - }, + let closure = || async { + let elimination_based_connectors_result = client + .perform_elimination_routing( + profile_id.get_string_repr().to_string(), + elimination_routing_config_params, + routable_connectors.clone(), + elimination_routing_config.elimination_analyser_config, + state.get_grpc_headers(), ) - .collect(), + .await + .change_context(errors::RoutingError::EliminationRoutingCalculationError) + .attach_printable( + "unable to analyze/fetch elimination routing from dynamic routing service", + ); + + match elimination_based_connectors_result { + Ok(elimination_response) => Ok(Some(utils::EliminationEventResponse::from( + &elimination_response, + ))), + Err(e) => { + logger::error!( + "unable to analyze/fetch elimination routing from dynamic routing service: {:?}", + e.current_context() + ); + + Err(error_stack::report!( + errors::RoutingError::EliminationRoutingCalculationError + )) + } + } }; - routing_event.set_response_body(&event_response); - routing_event.set_routing_approach(api_routing::RoutingApproach::Elimination.to_string()); + let events_response = routing_events_wrapper + .construct_event_builder( + "EliminationAnalyser.GetEliminationStatus".to_string(), + RoutingEngine::IntelligentRouter, + ApiMethod::Grpc, + )? + .trigger_event(state, closure) + .await?; + + let elimination_based_connectors: utils::EliminationEventResponse = events_response + .response + .ok_or(errors::RoutingError::EliminationRoutingCalculationError)?; + + let mut routing_event = events_response + .event + .ok_or(errors::RoutingError::RoutingEventsError { + message: + "Elimination-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse" + .to_string(), + status_code: 500, + })?; + + routing_event.set_routing_approach(utils::RoutingApproach::Elimination.to_string()); let mut connectors = Vec::with_capacity(elimination_based_connectors.labels_with_status.len()); @@ -2440,7 +2437,7 @@ pub async fn perform_contract_based_routing( }) .collect::<Vec<_>>(); - let event_request = api_routing::CalContractScoreEventRequest { + let event_request = utils::CalContractScoreEventRequest { id: profile_id.get_string_repr().to_string(), params: "".to_string(), labels: contract_based_connectors @@ -2450,66 +2447,37 @@ pub async fn perform_contract_based_routing( config: Some(contract_based_routing_configs.clone()), }; - let serialized_request = serde_json::to_value(&event_request) - .change_context(errors::RoutingError::SuccessBasedRoutingConfigError) - .attach_printable("unable to serialize EliminationRoutingEventRequest")?; - - let mut routing_event = RoutingEvent::new( + let routing_events_wrapper = utils::RoutingEventsWrapper::new( state.tenant.tenant_id.clone(), - "".to_string(), - "Intelligent-router CalContractScore", - serialized_request, - "ContractScoreCalculator.FetchContractScore".to_string(), - ApiMethod::Grpc, + state.request_id, payment_id.get_string_repr().to_string(), profile_id.to_owned(), merchant_id.to_owned(), - state.request_id, - RoutingEngine::IntelligentRouter, + "IntelligentRouter: PerformContractRouting".to_string(), + Some(event_request.clone()), + true, + false, ); - let contract_based_connectors_result = client - .calculate_contract_score( - profile_id.get_string_repr().into(), - contract_based_routing_configs.clone(), - "".to_string(), - contract_based_connectors, - state.get_grpc_headers(), - ) - .await - .inspect_err(|e| { - routing_event - .set_error(serde_json::json!({"error": e.current_context().to_string()})); - routing_event - .set_routing_approach(api_routing::RoutingApproach::ContractBased.to_string()); - state.event_handler().log_event(&routing_event); - }) - .attach_printable( - "unable to calculate/fetch contract score from dynamic routing service", - ); - - let contract_based_connectors = match contract_based_connectors_result { - Ok(resp) => { - let event_response = api_routing::CalContractScoreEventResponse { - labels_with_score: resp - .labels_with_score - .iter() - .map(|label_with_score| api_routing::ScoreDataEventResponse { - score: label_with_score.score, - label: label_with_score.label.clone(), - current_count: label_with_score.current_count, - }) - .collect(), - }; - - routing_event.set_response_body(&event_response); - routing_event - .set_routing_approach(api_routing::RoutingApproach::ContractBased.to_string()); - resp - } - Err(err) => match err.current_context() { - DynamicRoutingError::ContractNotFound => { - client + let closure = || async { + let contract_based_connectors_result = client + .calculate_contract_score( + profile_id.get_string_repr().into(), + contract_based_routing_configs.clone(), + "".to_string(), + contract_based_connectors, + state.get_grpc_headers(), + ) + .await + .attach_printable( + "unable to calculate/fetch contract score from dynamic routing service", + ); + + let contract_based_connectors = match contract_based_connectors_result { + Ok(resp) => Some(utils::CalContractScoreEventResponse::from(&resp)), + Err(err) => match err.current_context() { + DynamicRoutingError::ContractNotFound => { + client .update_contracts( profile_id.get_string_repr().into(), label_info, @@ -2523,20 +2491,47 @@ pub async fn perform_contract_based_routing( .attach_printable( "unable to update contract based routing window in dynamic routing service", )?; - return Err((errors::RoutingError::ContractScoreCalculationError { - err: err.to_string(), - }) - .into()); - } - _ => { - return Err((errors::RoutingError::ContractScoreCalculationError { - err: err.to_string(), - }) - .into()) - } - }, + return Err((errors::RoutingError::ContractScoreCalculationError { + err: err.to_string(), + }) + .into()); + } + _ => { + return Err((errors::RoutingError::ContractScoreCalculationError { + err: err.to_string(), + }) + .into()) + } + }, + }; + + Ok(contract_based_connectors) }; + let events_response = routing_events_wrapper + .construct_event_builder( + "ContractScoreCalculator.FetchContractScore".to_string(), + RoutingEngine::IntelligentRouter, + ApiMethod::Grpc, + )? + .trigger_event(state, closure) + .await?; + + let contract_based_connectors: utils::CalContractScoreEventResponse = events_response + .response + .ok_or(errors::RoutingError::ContractScoreCalculationError { + err: "CalContractScoreEventResponse not found".to_string(), + })?; + + let mut routing_event = events_response + .event + .ok_or(errors::RoutingError::RoutingEventsError { + message: + "ContractRouting-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse" + .to_string(), + status_code: 500, + })?; + let mut connectors = Vec::with_capacity(contract_based_connectors.labels_with_score.len()); for label_with_score in contract_based_connectors.labels_with_score { diff --git a/crates/router/src/core/payments/routing/utils.rs b/crates/router/src/core/payments/routing/utils.rs index 0478091936e..d49aada7076 100644 --- a/crates/router/src/core/payments/routing/utils.rs +++ b/crates/router/src/core/payments/routing/utils.rs @@ -1,20 +1,27 @@ -use std::collections::{HashMap, HashSet}; +use std::{ + collections::{HashMap, HashSet}, + str::FromStr, +}; use api_models::{ - routing as api_routing, + open_router as or_types, routing as api_routing, routing::{ConnectorSelection, RoutableConnectorChoice}, }; use async_trait::async_trait; -use common_utils::id_type; +use common_utils::{ext_traits::BytesExt, id_type}; use diesel_models::{enums, routing_algorithm}; use error_stack::ResultExt; use euclid::{backend::BackendInput, frontend::ast}; +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +use external_services::grpc_client::dynamic_routing as ir_client; +use hyperswitch_interfaces::events::routing_api_logs as routing_events; +use router_env::tracing_actix_web::RequestId; use serde::{Deserialize, Serialize}; use super::RoutingResult; use crate::{ core::errors, - routes::SessionState, + routes::{app::SessionStateInfo, SessionState}, services::{self, logger}, types::transformers::ForeignInto, }; @@ -28,10 +35,11 @@ pub trait DecisionEngineApiHandler { path: &str, request_body: Option<Req>, // Option to handle GET/DELETE requests without body timeout: Option<u64>, - ) -> RoutingResult<Res> + events_wrapper: Option<RoutingEventsWrapper<Req>>, + ) -> RoutingResult<RoutingEventsResponse<Res>> where - Req: Serialize + Send + Sync + 'static, - Res: serde::de::DeserializeOwned + Send + 'static + std::fmt::Debug; + Req: Serialize + Send + Sync + 'static + Clone, + Res: Serialize + serde::de::DeserializeOwned + Send + 'static + std::fmt::Debug + Clone; async fn send_decision_engine_request_without_response_parsing<Req>( state: &SessionState, @@ -39,9 +47,10 @@ pub trait DecisionEngineApiHandler { path: &str, request_body: Option<Req>, timeout: Option<u64>, + events_wrapper: Option<RoutingEventsWrapper<Req>>, ) -> RoutingResult<()> where - Req: Serialize + Send + Sync + 'static; + Req: Serialize + Send + Sync + 'static + Clone; } // Struct to implement the DecisionEngineApiHandler trait @@ -49,16 +58,21 @@ pub struct EuclidApiClient; pub struct ConfigApiClient; -pub async fn build_and_send_decision_engine_http_request<Req>( +pub struct SRApiClient; + +pub async fn build_and_send_decision_engine_http_request<Req, Res, ErrRes>( state: &SessionState, http_method: services::Method, path: &str, request_body: Option<Req>, - timeout: Option<u64>, + _timeout: Option<u64>, context_message: &str, -) -> RoutingResult<reqwest::Response> + events_wrapper: Option<RoutingEventsWrapper<Req>>, +) -> RoutingResult<RoutingEventsResponse<Res>> where - Req: Serialize + Send + Sync + 'static, + Req: Serialize + Send + Sync + 'static + Clone, + Res: Serialize + serde::de::DeserializeOwned + std::fmt::Debug + Clone, + ErrRes: serde::de::DeserializeOwned + std::fmt::Debug + Clone + DecisionEngineErrorsInterface, { let decision_engine_base_url = &state.conf.open_router.url; let url = format!("{}/{}", decision_engine_base_url, path); @@ -75,18 +89,88 @@ where let http_request = request_builder.build(); logger::info!(?http_request, decision_engine_request_path = %path, "decision_engine: Constructed Decision Engine API request details ({})", context_message); + let should_parse_response = events_wrapper + .as_ref() + .map(|wrapper| wrapper.parse_response) + .unwrap_or(true); + + let closure = || async { + let response = + services::call_connector_api(state, http_request, "Decision Engine API call") + .await + .change_context(errors::RoutingError::OpenRouterCallFailed)?; + + match response { + Ok(resp) => { + logger::debug!( + "decision_engine: Received response from Decision Engine API ({:?})", + String::from_utf8_lossy(&resp.response) // For logging + ); + + let resp = should_parse_response + .then(|| { + let response_type: Res = resp + .response + .parse_struct(std::any::type_name::<Res>()) + .change_context(errors::RoutingError::OpenRouterError( + "Failed to parse the response from open_router".into(), + ))?; + + Ok::<_, error_stack::Report<errors::RoutingError>>(response_type) + }) + .transpose()?; + + logger::debug!("decision_engine_success_response: {:?}", resp); + + Ok(resp) + } + Err(err) => { + logger::debug!( + "decision_engine: Received response from Decision Engine API ({:?})", + String::from_utf8_lossy(&err.response) // For logging + ); + + let err_resp: ErrRes = err + .response + .parse_struct(std::any::type_name::<ErrRes>()) + .change_context(errors::RoutingError::OpenRouterError( + "Failed to parse the response from open_router".into(), + ))?; + + logger::error!( + decision_engine_error_code = %err_resp.get_error_code(), + decision_engine_error_message = %err_resp.get_error_message(), + decision_engine_raw_response = ?err_resp.get_error_data(), + ); + + Err(error_stack::report!( + errors::RoutingError::RoutingEventsError { + message: err_resp.get_error_message(), + status_code: err.status_code, + } + )) + } + } + }; - state - .api_client - .send_request(state, http_request, timeout, false) - .await - .change_context(errors::RoutingError::DslExecutionError) - .attach_printable_lazy(|| { - format!( - "Decision Engine API call to path '{}' unresponsive ({})", - path, context_message - ) - }) + let events_response = if let Some(wrapper) = events_wrapper { + wrapper + .construct_event_builder( + url, + routing_events::RoutingEngine::DecisionEngine, + routing_events::ApiMethod::Rest(http_method), + )? + .trigger_event(state, closure) + .await? + } else { + let resp = closure() + .await + .change_context(errors::RoutingError::OpenRouterCallFailed)?; + + RoutingEventsResponse::new(None, resp) + }; + + Ok(events_response) } #[async_trait] @@ -97,83 +181,33 @@ impl DecisionEngineApiHandler for EuclidApiClient { path: &str, request_body: Option<Req>, // Option to handle GET/DELETE requests without body timeout: Option<u64>, - ) -> RoutingResult<Res> + events_wrapper: Option<RoutingEventsWrapper<Req>>, + ) -> RoutingResult<RoutingEventsResponse<Res>> where - Req: Serialize + Send + Sync + 'static, - Res: serde::de::DeserializeOwned + Send + 'static + std::fmt::Debug, + Req: Serialize + Send + Sync + 'static + Clone, + Res: Serialize + serde::de::DeserializeOwned + Send + 'static + std::fmt::Debug + Clone, { - let response = build_and_send_decision_engine_http_request( + let event_response = build_and_send_decision_engine_http_request::<_, _, DeErrorResponse>( state, http_method, path, request_body, timeout, "parsing response", + events_wrapper, ) .await?; - let status = response.status(); - let response_bytes = response.bytes().await.unwrap_or_default(); - - let body_str = String::from_utf8_lossy(&response_bytes); // For logging - - if !status.is_success() { - match serde_json::from_slice::<DeErrorResponse>(&response_bytes) { - Ok(parsed) => { - logger::error!( - decision_engine_error_code = %parsed.code, - decision_engine_error_message = %parsed.message, - decision_engine_raw_response = ?parsed.data, - "decision_engine_euclid: validation failed" - ); - - return Err(errors::RoutingError::DecisionEngineValidationError( - parsed.message, - ) - .into()); - } - Err(_) => { - logger::error!( - decision_engine_raw_response = %body_str, - "decision_engine_euclid: failed to deserialize validation error response" - ); - - return Err(errors::RoutingError::DecisionEngineValidationError( - "decision_engine_euclid: Failed to parse validation error from decision engine".to_string(), - ) - .into()); - } - } - } - - logger::debug!( - euclid_response_body = %body_str, - response_status = ?status, - euclid_request_path = %path, - "decision_engine_euclid: Received raw response from Euclid API" - ); - - let parsed_response = serde_json::from_slice::<Res>(&response_bytes) - .map_err(|_| errors::RoutingError::GenericConversionError { - from: "ApiResponse".to_string(), - to: std::any::type_name::<Res>().to_string(), - }) - .attach_printable_lazy(|| { - format!( - "Unable to parse response of type '{}' received from Euclid API path: {}", - std::any::type_name::<Res>(), - path - ) - })?; - - logger::debug!( - parsed_response = ?parsed_response, - response_type = %std::any::type_name::<Res>(), - euclid_request_path = %path, - "decision_engine_euclid: Successfully parsed response from Euclid API" - ); + let parsed_response = + event_response + .response + .as_ref() + .ok_or(errors::RoutingError::OpenRouterError( + "Response from decision engine API is empty".to_string(), + ))?; - Ok(parsed_response) + logger::debug!(parsed_response = ?parsed_response, response_type = %std::any::type_name::<Res>(), euclid_request_path = %path, "decision_engine_euclid: Successfully parsed response from Euclid API"); + Ok(event_response) } async fn send_decision_engine_request_without_response_parsing<Req>( @@ -182,19 +216,24 @@ impl DecisionEngineApiHandler for EuclidApiClient { path: &str, request_body: Option<Req>, timeout: Option<u64>, + events_wrapper: Option<RoutingEventsWrapper<Req>>, ) -> RoutingResult<()> where - Req: Serialize + Send + Sync + 'static, + Req: Serialize + Send + Sync + 'static + Clone, { - let response = build_and_send_decision_engine_http_request( - state, - http_method, - path, - request_body, - timeout, - "not parsing response", - ) - .await?; + let event_response = + build_and_send_decision_engine_http_request::<Req, (), DeErrorResponse>( + state, + http_method, + path, + request_body, + timeout, + "not parsing response", + events_wrapper, + ) + .await?; + + let response = event_response.response; logger::debug!(euclid_response = ?response, euclid_request_path = %path, "decision_engine_routing: Received raw response from Euclid API"); Ok(()) @@ -209,38 +248,32 @@ impl DecisionEngineApiHandler for ConfigApiClient { path: &str, request_body: Option<Req>, timeout: Option<u64>, - ) -> RoutingResult<Res> + events_wrapper: Option<RoutingEventsWrapper<Req>>, + ) -> RoutingResult<RoutingEventsResponse<Res>> where - Req: Serialize + Send + Sync + 'static, - Res: serde::de::DeserializeOwned + Send + 'static + std::fmt::Debug, + Req: Serialize + Send + Sync + 'static + Clone, + Res: Serialize + serde::de::DeserializeOwned + Send + 'static + std::fmt::Debug + Clone, { - let response = build_and_send_decision_engine_http_request( + let events_response = build_and_send_decision_engine_http_request::<_, _, DeErrorResponse>( state, http_method, path, request_body, timeout, "parsing response", + events_wrapper, ) .await?; - logger::debug!(decision_engine_config_response = ?response, decision_engine_request_path = %path, "decision_engine_config: Received raw response from Decision Engine config API"); - let parsed_response = response - .json::<Res>() - .await - .change_context(errors::RoutingError::GenericConversionError { - from: "ApiResponse".to_string(), - to: std::any::type_name::<Res>().to_string(), - }) - .attach_printable_lazy(|| { - format!( - "Unable to parse response of type '{}' received from Decision Engine config API path: {}", - std::any::type_name::<Res>(), - path - ) - })?; + let parsed_response = + events_response + .response + .as_ref() + .ok_or(errors::RoutingError::OpenRouterError( + "Response from decision engine API is empty".to_string(), + ))?; logger::debug!(parsed_response = ?parsed_response, response_type = %std::any::type_name::<Res>(), decision_engine_request_path = %path, "decision_engine_config: Successfully parsed response from Decision Engine config API"); - Ok(parsed_response) + Ok(events_response) } async fn send_decision_engine_request_without_response_parsing<Req>( @@ -249,19 +282,91 @@ impl DecisionEngineApiHandler for ConfigApiClient { path: &str, request_body: Option<Req>, timeout: Option<u64>, + events_wrapper: Option<RoutingEventsWrapper<Req>>, ) -> RoutingResult<()> where - Req: Serialize + Send + Sync + 'static, + Req: Serialize + Send + Sync + 'static + Clone, { - let response = build_and_send_decision_engine_http_request( - state, - http_method, - path, - request_body, - timeout, - "not parsing response", - ) - .await?; + let event_response = + build_and_send_decision_engine_http_request::<Req, (), DeErrorResponse>( + state, + http_method, + path, + request_body, + timeout, + "not parsing response", + events_wrapper, + ) + .await?; + + let response = event_response.response; + + logger::debug!(decision_engine_response = ?response, decision_engine_request_path = %path, "decision_engine_config: Received raw response from Decision Engine config API"); + Ok(()) + } +} + +#[async_trait] +impl DecisionEngineApiHandler for SRApiClient { + async fn send_decision_engine_request<Req, Res>( + state: &SessionState, + http_method: services::Method, + path: &str, + request_body: Option<Req>, + timeout: Option<u64>, + events_wrapper: Option<RoutingEventsWrapper<Req>>, + ) -> RoutingResult<RoutingEventsResponse<Res>> + where + Req: Serialize + Send + Sync + 'static + Clone, + Res: Serialize + serde::de::DeserializeOwned + Send + 'static + std::fmt::Debug + Clone, + { + let events_response = + build_and_send_decision_engine_http_request::<_, _, or_types::ErrorResponse>( + state, + http_method, + path, + request_body, + timeout, + "parsing response", + events_wrapper, + ) + .await?; + + let parsed_response = + events_response + .response + .as_ref() + .ok_or(errors::RoutingError::OpenRouterError( + "Response from decision engine API is empty".to_string(), + ))?; + logger::debug!(parsed_response = ?parsed_response, response_type = %std::any::type_name::<Res>(), decision_engine_request_path = %path, "decision_engine_config: Successfully parsed response from Decision Engine config API"); + Ok(events_response) + } + + async fn send_decision_engine_request_without_response_parsing<Req>( + state: &SessionState, + http_method: services::Method, + path: &str, + request_body: Option<Req>, + timeout: Option<u64>, + events_wrapper: Option<RoutingEventsWrapper<Req>>, + ) -> RoutingResult<()> + where + Req: Serialize + Send + Sync + 'static + Clone, + { + let event_response = + build_and_send_decision_engine_http_request::<Req, (), or_types::ErrorResponse>( + state, + http_method, + path, + request_body, + timeout, + "not parsing response", + events_wrapper, + ) + .await?; + + let response = event_response.response; logger::debug!(decision_engine_response = ?response, decision_engine_request_path = %path, "decision_engine_config: Received raw response from Decision Engine config API"); Ok(()) @@ -274,20 +379,85 @@ pub async fn perform_decision_euclid_routing( state: &SessionState, input: BackendInput, created_by: String, -) -> RoutingResult<Vec<String>> { + events_wrapper: RoutingEventsWrapper<RoutingEvaluateRequest>, +) -> RoutingResult<Vec<ConnectorInfo>> { logger::debug!("decision_engine_euclid: evaluate api call for euclid routing evaluation"); + let mut events_wrapper = events_wrapper; + let routing_request = convert_backend_input_to_routing_eval(created_by, input)?; + events_wrapper.set_request_body(routing_request.clone()); - let euclid_response: RoutingEvaluateResponse = EuclidApiClient::send_decision_engine_request( + let event_response = EuclidApiClient::send_decision_engine_request( state, services::Method::Post, "routing/evaluate", Some(routing_request), Some(EUCLID_API_TIMEOUT), + Some(events_wrapper), ) .await?; + let euclid_response: RoutingEvaluateResponse = + event_response + .response + .ok_or(errors::RoutingError::OpenRouterError( + "Response from decision engine API is empty".to_string(), + ))?; + + let mut routing_event = + event_response + .event + .ok_or(errors::RoutingError::RoutingEventsError { + message: "Routing event not found in EventsResponse".to_string(), + status_code: 500, + })?; + + let connector_info = euclid_response.evaluated_output.clone(); + let mut routable_connectors = Vec::new(); + for conn in &connector_info { + let connector = common_enums::RoutableConnectors::from_str(conn.gateway_name.as_str()) + .change_context(errors::RoutingError::GenericConversionError { + from: "String".to_string(), + to: "RoutableConnectors".to_string(), + }) + .attach_printable( + "decision_engine_euclid: unable to convert String to RoutableConnectors", + ) + .ok(); + let mca_id = conn + .gateway_id + .as_ref() + .map(|id| { + id_type::MerchantConnectorAccountId::wrap(id.to_string()) + .change_context(errors::RoutingError::GenericConversionError { + from: "String".to_string(), + to: "MerchantConnectorAccountId".to_string(), + }) + .attach_printable( + "decision_engine_euclid: unable to convert MerchantConnectorAccountId from string", + ) + }) + .transpose() + .ok() + .flatten(); + + if let Some(conn) = connector { + let connector = RoutableConnectorChoice { + choice_kind: api_routing::RoutableChoiceKind::FullStruct, + connector: conn, + merchant_connector_id: mca_id, + }; + routable_connectors.push(connector); + } + } + + routing_event.set_routing_approach(RoutingApproach::StaticRouting.to_string()); + routing_event.set_routable_connectors(routable_connectors); + state.event_handler.log_event(&routing_event); + + // Need to log euclid response event here + logger::debug!(decision_engine_euclid_response=?euclid_response,"decision_engine_euclid"); logger::debug!(decision_engine_euclid_selected_connector=?euclid_response.evaluated_output,"decision_engine_euclid"); @@ -301,15 +471,23 @@ pub async fn create_de_euclid_routing_algo( logger::debug!("decision_engine_euclid: create api call for euclid routing rule creation"); logger::debug!(decision_engine_euclid_request=?routing_request,"decision_engine_euclid"); - let euclid_response: RoutingDictionaryRecord = EuclidApiClient::send_decision_engine_request( + let events_response = EuclidApiClient::send_decision_engine_request( state, services::Method::Post, "routing/create", Some(routing_request.clone()), Some(EUCLID_API_TIMEOUT), + None, ) .await?; + let euclid_response: RoutingDictionaryRecord = + events_response + .response + .ok_or(errors::RoutingError::OpenRouterError( + "Response from decision engine API is empty".to_string(), + ))?; + logger::debug!(decision_engine_euclid_parsed_response=?euclid_response,"decision_engine_euclid"); Ok(euclid_response.rule_id) } @@ -326,6 +504,7 @@ pub async fn link_de_euclid_routing_algorithm( "routing/activate", Some(routing_request.clone()), Some(EUCLID_API_TIMEOUT), + None, ) .await?; @@ -339,16 +518,24 @@ pub async fn list_de_euclid_routing_algorithms( ) -> RoutingResult<Vec<api_routing::RoutingDictionaryRecord>> { logger::debug!("decision_engine_euclid: list api call for euclid routing algorithms"); let created_by = routing_list_request.created_by; - let response: Vec<RoutingAlgorithmRecord> = EuclidApiClient::send_decision_engine_request( + let events_response = EuclidApiClient::send_decision_engine_request( state, services::Method::Post, format!("routing/list/{created_by}").as_str(), None::<()>, Some(EUCLID_API_TIMEOUT), + None, ) .await?; - Ok(response + let euclid_response: Vec<RoutingAlgorithmRecord> = + events_response + .response + .ok_or(errors::RoutingError::OpenRouterError( + "Response from decision engine API is empty".to_string(), + ))?; + + Ok(euclid_response .into_iter() .map(routing_algorithm::RoutingProfileMetadata::from) .map(ForeignInto::foreign_into) @@ -543,6 +730,37 @@ struct DeErrorResponse { data: Option<serde_json::Value>, } +impl DecisionEngineErrorsInterface for DeErrorResponse { + fn get_error_message(&self) -> String { + self.message.clone() + } + + fn get_error_code(&self) -> String { + self.code.clone() + } + + fn get_error_data(&self) -> Option<String> { + self.data.as_ref().map(|data| data.to_string()) + } +} + +impl DecisionEngineErrorsInterface for or_types::ErrorResponse { + fn get_error_message(&self) -> String { + self.error_message.clone() + } + + fn get_error_code(&self) -> String { + self.error_code.clone() + } + + fn get_error_data(&self) -> Option<String> { + Some(format!( + "decision_engine Error: {}", + self.error_message.clone() + )) + } +} + //TODO: temporary change will be refactored afterwards #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq)] pub struct RoutingEvaluateRequest { @@ -550,12 +768,12 @@ pub struct RoutingEvaluateRequest { pub parameters: HashMap<String, Option<ValueType>>, } -#[derive(Debug, serde::Serialize, serde::Deserialize)] +#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)] pub struct RoutingEvaluateResponse { pub status: String, pub output: serde_json::Value, - pub evaluated_output: Vec<String>, - pub eligible_connectors: Vec<String>, + pub evaluated_output: Vec<ConnectorInfo>, + pub eligible_connectors: Vec<ConnectorInfo>, } #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] @@ -686,13 +904,16 @@ pub struct VolumeSplit<T> { #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct ConnectorInfo { - pub connector: String, - pub mca_id: Option<String>, + pub gateway_name: String, + pub gateway_id: Option<String>, } impl ConnectorInfo { - pub fn new(connector: String, mca_id: Option<String>) -> Self { - Self { connector, mca_id } + pub fn new(gateway_name: String, gateway_id: Option<String>) -> Self { + Self { + gateway_name, + gateway_id, + } } } @@ -914,3 +1135,654 @@ fn stringify_choice(c: RoutableConnectorChoice) -> ConnectorInfo { .map(|mca_id| mca_id.get_string_repr().to_string()), ) } + +pub trait DecisionEngineErrorsInterface { + fn get_error_message(&self) -> String; + fn get_error_code(&self) -> String; + fn get_error_data(&self) -> Option<String>; +} + +#[derive(Debug)] +pub struct RoutingEventsWrapper<Req> +where + Req: Serialize + Clone, +{ + pub tenant_id: id_type::TenantId, + pub request_id: Option<RequestId>, + pub payment_id: String, + pub profile_id: id_type::ProfileId, + pub merchant_id: id_type::MerchantId, + pub flow: String, + pub request: Option<Req>, + pub parse_response: bool, + pub log_event: bool, + pub routing_event: Option<routing_events::RoutingEvent>, +} + +#[derive(Debug)] +pub enum EventResponseType<Res> +where + Res: Serialize + serde::de::DeserializeOwned + Clone, +{ + Structured(Res), + String(String), +} + +#[derive(Debug)] +pub struct RoutingEventsResponse<Res> +where + Res: Serialize + serde::de::DeserializeOwned + Clone, +{ + pub event: Option<routing_events::RoutingEvent>, + pub response: Option<Res>, +} + +impl<Res> RoutingEventsResponse<Res> +where + Res: Serialize + serde::de::DeserializeOwned + Clone, +{ + pub fn new(event: Option<routing_events::RoutingEvent>, response: Option<Res>) -> Self { + Self { event, response } + } + + pub fn set_response(&mut self, response: Res) { + self.response = Some(response); + } + + pub fn set_event(&mut self, event: routing_events::RoutingEvent) { + self.event = Some(event); + } +} + +impl<Req> RoutingEventsWrapper<Req> +where + Req: Serialize + Clone, +{ + #[allow(clippy::too_many_arguments)] + pub fn new( + tenant_id: id_type::TenantId, + request_id: Option<RequestId>, + payment_id: String, + profile_id: id_type::ProfileId, + merchant_id: id_type::MerchantId, + flow: String, + request: Option<Req>, + parse_response: bool, + log_event: bool, + ) -> Self { + Self { + tenant_id, + request_id, + payment_id, + profile_id, + merchant_id, + flow, + request, + parse_response, + log_event, + routing_event: None, + } + } + + pub fn construct_event_builder( + self, + url: String, + routing_engine: routing_events::RoutingEngine, + method: routing_events::ApiMethod, + ) -> RoutingResult<Self> { + let mut wrapper = self; + let request = wrapper + .request + .clone() + .ok_or(errors::RoutingError::RoutingEventsError { + message: "Request body is missing".to_string(), + status_code: 400, + })?; + + let serialized_request = serde_json::to_value(&request) + .change_context(errors::RoutingError::RoutingEventsError { + message: "Failed to serialize RoutingRequest".to_string(), + status_code: 500, + }) + .attach_printable("Failed to serialize request body")?; + + let routing_event = routing_events::RoutingEvent::new( + wrapper.tenant_id.clone(), + "".to_string(), + &wrapper.flow, + serialized_request, + url, + method, + wrapper.payment_id.clone(), + wrapper.profile_id.clone(), + wrapper.merchant_id.clone(), + wrapper.request_id, + routing_engine, + ); + + wrapper.set_routing_event(routing_event); + + Ok(wrapper) + } + + pub async fn trigger_event<Res, F, Fut>( + self, + state: &SessionState, + func: F, + ) -> RoutingResult<RoutingEventsResponse<Res>> + where + F: FnOnce() -> Fut + Send, + Res: Serialize + serde::de::DeserializeOwned + Clone, + Fut: futures::Future<Output = RoutingResult<Option<Res>>> + Send, + { + let mut routing_event = + self.routing_event + .ok_or(errors::RoutingError::RoutingEventsError { + message: "Routing event is missing".to_string(), + status_code: 500, + })?; + + let mut response = RoutingEventsResponse::new(None, None); + + let resp = func().await; + match resp { + Ok(ok_resp) => { + if let Some(resp) = ok_resp { + routing_event.set_response_body(&resp); + // routing_event + // .set_routable_connectors(ok_resp.get_routable_connectors().unwrap_or_default()); + // routing_event.set_payment_connector(ok_resp.get_payment_connector()); + routing_event.set_status_code(200); + + response.set_response(resp.clone()); + self.log_event + .then(|| state.event_handler().log_event(&routing_event)); + } + } + Err(err) => { + // Need to figure out a generic way to log errors + routing_event + .set_error(serde_json::json!({"error": err.current_context().to_string()})); + + match err.current_context() { + errors::RoutingError::RoutingEventsError { status_code, .. } => { + routing_event.set_status_code(*status_code); + } + _ => { + routing_event.set_status_code(500); + } + } + state.event_handler().log_event(&routing_event) + } + } + + response.set_event(routing_event); + + Ok(response) + } + + pub fn set_log_event(&mut self, log_event: bool) { + self.log_event = log_event; + } + + pub fn set_request_body(&mut self, request: Req) { + self.request = Some(request); + } + + pub fn set_routing_event(&mut self, routing_event: routing_events::RoutingEvent) { + self.routing_event = Some(routing_event); + } +} + +pub trait RoutingEventsInterface { + fn get_routable_connectors(&self) -> Option<Vec<RoutableConnectorChoice>>; + fn get_payment_connector(&self) -> Option<RoutableConnectorChoice>; +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct CalSuccessRateConfigEventRequest { + pub min_aggregates_size: Option<u32>, + pub default_success_rate: Option<f64>, + pub specificity_level: api_routing::SuccessRateSpecificityLevel, + pub exploration_percent: Option<f64>, +} + +impl From<&api_routing::SuccessBasedRoutingConfigBody> for CalSuccessRateConfigEventRequest { + fn from(value: &api_routing::SuccessBasedRoutingConfigBody) -> Self { + Self { + min_aggregates_size: value.min_aggregates_size, + default_success_rate: value.default_success_rate, + specificity_level: value.specificity_level, + exploration_percent: value.exploration_percent, + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct CalSuccessRateEventRequest { + pub id: String, + pub params: String, + pub labels: Vec<String>, + pub config: Option<CalSuccessRateConfigEventRequest>, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct EliminationRoutingEventBucketConfig { + pub bucket_size: Option<u64>, + pub bucket_leak_interval_in_secs: Option<u64>, +} + +impl From<&api_routing::EliminationAnalyserConfig> for EliminationRoutingEventBucketConfig { + fn from(value: &api_routing::EliminationAnalyserConfig) -> Self { + Self { + bucket_size: value.bucket_size, + bucket_leak_interval_in_secs: value.bucket_leak_interval_in_secs, + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct EliminationRoutingEventRequest { + pub id: String, + pub params: String, + pub labels: Vec<String>, + pub config: Option<EliminationRoutingEventBucketConfig>, +} + +/// API-1 types +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct CalContractScoreEventRequest { + pub id: String, + pub params: String, + pub labels: Vec<String>, + pub config: Option<api_routing::ContractBasedRoutingConfig>, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct LabelWithScoreEventResponse { + pub score: f64, + pub label: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct CalSuccessRateEventResponse { + pub labels_with_score: Vec<LabelWithScoreEventResponse>, + pub routing_approach: RoutingApproach, +} + +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +impl TryFrom<&ir_client::success_rate_client::CalSuccessRateResponse> + for CalSuccessRateEventResponse +{ + type Error = errors::RoutingError; + + fn try_from( + value: &ir_client::success_rate_client::CalSuccessRateResponse, + ) -> Result<Self, Self::Error> { + Ok(Self { + labels_with_score: value + .labels_with_score + .iter() + .map(|l| LabelWithScoreEventResponse { + score: l.score, + label: l.label.clone(), + }) + .collect(), + routing_approach: match value.routing_approach { + 0 => RoutingApproach::Exploration, + 1 => RoutingApproach::Exploitation, + _ => { + return Err(errors::RoutingError::GenericNotFoundError { + field: "unknown routing approach from dynamic routing service".to_string(), + }) + } + }, + }) + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum RoutingApproach { + Exploitation, + Exploration, + Elimination, + ContractBased, + StaticRouting, + Default, +} + +impl RoutingApproach { + pub fn from_decision_engine_approach(approach: &str) -> Self { + match approach { + "SR_SELECTION_V3_ROUTING" => Self::Exploitation, + "SR_V3_HEDGING" => Self::Exploration, + _ => Self::Default, + } + } +} + +impl std::fmt::Display for RoutingApproach { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Exploitation => write!(f, "Exploitation"), + Self::Exploration => write!(f, "Exploration"), + Self::Elimination => write!(f, "Elimination"), + Self::ContractBased => write!(f, "ContractBased"), + Self::StaticRouting => write!(f, "StaticRouting"), + Self::Default => write!(f, "Default"), + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct BucketInformationEventResponse { + pub is_eliminated: bool, + pub bucket_name: Vec<String>, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct EliminationInformationEventResponse { + pub entity: Option<BucketInformationEventResponse>, + pub global: Option<BucketInformationEventResponse>, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct LabelWithStatusEliminationEventResponse { + pub label: String, + pub elimination_information: Option<EliminationInformationEventResponse>, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct EliminationEventResponse { + pub labels_with_status: Vec<LabelWithStatusEliminationEventResponse>, +} + +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +impl From<&ir_client::elimination_based_client::EliminationResponse> for EliminationEventResponse { + fn from(value: &ir_client::elimination_based_client::EliminationResponse) -> Self { + Self { + labels_with_status: value + .labels_with_status + .iter() + .map( + |label_with_status| LabelWithStatusEliminationEventResponse { + label: label_with_status.label.clone(), + elimination_information: label_with_status + .elimination_information + .as_ref() + .map(|info| EliminationInformationEventResponse { + entity: info.entity.as_ref().map(|entity_info| { + BucketInformationEventResponse { + is_eliminated: entity_info.is_eliminated, + bucket_name: entity_info.bucket_name.clone(), + } + }), + global: info.global.as_ref().map(|global_info| { + BucketInformationEventResponse { + is_eliminated: global_info.is_eliminated, + bucket_name: global_info.bucket_name.clone(), + } + }), + }), + }, + ) + .collect(), + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct ScoreDataEventResponse { + pub score: f64, + pub label: String, + pub current_count: u64, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct CalContractScoreEventResponse { + pub labels_with_score: Vec<ScoreDataEventResponse>, +} + +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +impl From<&ir_client::contract_routing_client::CalContractScoreResponse> + for CalContractScoreEventResponse +{ + fn from(value: &ir_client::contract_routing_client::CalContractScoreResponse) -> Self { + Self { + labels_with_score: value + .labels_with_score + .iter() + .map(|label_with_score| ScoreDataEventResponse { + score: label_with_score.score, + label: label_with_score.label.clone(), + current_count: label_with_score.current_count, + }) + .collect(), + } + } +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct CalGlobalSuccessRateConfigEventRequest { + pub entity_min_aggregates_size: u32, + pub entity_default_success_rate: f64, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct CalGlobalSuccessRateEventRequest { + pub entity_id: String, + pub entity_params: String, + pub entity_labels: Vec<String>, + pub global_labels: Vec<String>, + pub config: Option<CalGlobalSuccessRateConfigEventRequest>, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct UpdateSuccessRateWindowConfig { + pub max_aggregates_size: Option<u32>, + pub current_block_threshold: Option<api_routing::CurrentBlockThreshold>, +} + +impl From<&api_routing::SuccessBasedRoutingConfigBody> for UpdateSuccessRateWindowConfig { + fn from(value: &api_routing::SuccessBasedRoutingConfigBody) -> Self { + Self { + max_aggregates_size: value.max_aggregates_size, + current_block_threshold: value.current_block_threshold.clone(), + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct UpdateLabelWithStatusEventRequest { + pub label: String, + pub status: bool, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct UpdateSuccessRateWindowEventRequest { + pub id: String, + pub params: String, + pub labels_with_status: Vec<UpdateLabelWithStatusEventRequest>, + pub config: Option<UpdateSuccessRateWindowConfig>, + pub global_labels_with_status: Vec<UpdateLabelWithStatusEventRequest>, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct UpdateSuccessRateWindowEventResponse { + pub status: UpdationStatusEventResponse, +} + +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +impl TryFrom<&ir_client::success_rate_client::UpdateSuccessRateWindowResponse> + for UpdateSuccessRateWindowEventResponse +{ + type Error = errors::RoutingError; + + fn try_from( + value: &ir_client::success_rate_client::UpdateSuccessRateWindowResponse, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: match value.status { + 0 => UpdationStatusEventResponse::WindowUpdationSucceeded, + 1 => UpdationStatusEventResponse::WindowUpdationFailed, + _ => { + return Err(errors::RoutingError::GenericNotFoundError { + field: "unknown updation status from dynamic routing service".to_string(), + }) + } + }, + }) + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum UpdationStatusEventResponse { + WindowUpdationSucceeded, + WindowUpdationFailed, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct LabelWithBucketNameEventRequest { + pub label: String, + pub bucket_name: String, +} + +impl From<&api_routing::RoutableConnectorChoiceWithBucketName> for LabelWithBucketNameEventRequest { + fn from(value: &api_routing::RoutableConnectorChoiceWithBucketName) -> Self { + Self { + label: value.routable_connector_choice.to_string(), + bucket_name: value.bucket_name.clone(), + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct UpdateEliminationBucketEventRequest { + pub id: String, + pub params: String, + pub labels_with_bucket_name: Vec<LabelWithBucketNameEventRequest>, + pub config: Option<EliminationRoutingEventBucketConfig>, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct UpdateEliminationBucketEventResponse { + pub status: EliminationUpdationStatusEventResponse, +} + +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +impl TryFrom<&ir_client::elimination_based_client::UpdateEliminationBucketResponse> + for UpdateEliminationBucketEventResponse +{ + type Error = errors::RoutingError; + + fn try_from( + value: &ir_client::elimination_based_client::UpdateEliminationBucketResponse, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: match value.status { + 0 => EliminationUpdationStatusEventResponse::BucketUpdationSucceeded, + 1 => EliminationUpdationStatusEventResponse::BucketUpdationFailed, + _ => { + return Err(errors::RoutingError::GenericNotFoundError { + field: "unknown updation status from dynamic routing service".to_string(), + }) + } + }, + }) + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum EliminationUpdationStatusEventResponse { + BucketUpdationSucceeded, + BucketUpdationFailed, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct ContractLabelInformationEventRequest { + pub label: String, + pub target_count: u64, + pub target_time: u64, + pub current_count: u64, +} + +impl From<&api_routing::LabelInformation> for ContractLabelInformationEventRequest { + fn from(value: &api_routing::LabelInformation) -> Self { + Self { + label: value.label.clone(), + target_count: value.target_count, + target_time: value.target_time, + current_count: 1, + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct UpdateContractRequestEventRequest { + pub id: String, + pub params: String, + pub labels_information: Vec<ContractLabelInformationEventRequest>, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct UpdateContractEventResponse { + pub status: ContractUpdationStatusEventResponse, +} + +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +impl TryFrom<&ir_client::contract_routing_client::UpdateContractResponse> + for UpdateContractEventResponse +{ + type Error = errors::RoutingError; + + fn try_from( + value: &ir_client::contract_routing_client::UpdateContractResponse, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: match value.status { + 0 => ContractUpdationStatusEventResponse::ContractUpdationSucceeded, + 1 => ContractUpdationStatusEventResponse::ContractUpdationFailed, + _ => { + return Err(errors::RoutingError::GenericNotFoundError { + field: "unknown updation status from dynamic routing service".to_string(), + }) + } + }, + }) + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ContractUpdationStatusEventResponse { + ContractUpdationSucceeded, + ContractUpdationFailed, +} diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 12e6923a4f9..6573a17025e 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -1091,78 +1091,110 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( .attach_printable("Unable to push dynamic routing stats to db")?; }; - let label_with_status = routing_types::UpdateLabelWithStatusEventRequest { + let label_with_status = routing_utils::UpdateLabelWithStatusEventRequest { label: routable_connector.clone().to_string(), status: payment_status_attribute == common_enums::AttemptStatus::Charged, }; - let event_request = routing_types::UpdateSuccessRateWindowEventRequest { + let event_request = routing_utils::UpdateSuccessRateWindowEventRequest { id: payment_attempt.profile_id.get_string_repr().to_string(), params: success_based_routing_config_params.clone(), labels_with_status: vec![label_with_status.clone()], global_labels_with_status: vec![label_with_status], - config: success_based_routing_configs.config.as_ref().map(|conf| { - routing_types::UpdateSuccessRateWindowConfig { - max_aggregates_size: conf.max_aggregates_size, - current_block_threshold: conf.current_block_threshold.clone(), - } - }), + config: success_based_routing_configs + .config + .as_ref() + .map(routing_utils::UpdateSuccessRateWindowConfig::from), }; - let serialized_request = serde_json::to_value(&event_request) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("unable to serialize success_based_routing_config_params")?; - - let mut routing_event = routing_events::RoutingEvent::new( + let routing_events_wrapper = routing_utils::RoutingEventsWrapper::new( state.tenant.tenant_id.clone(), - "".to_string(), - "Intelligent-router UpdateSuccessRateWindow", - serialized_request, - "SuccessRateCalculator.UpdateSuccessRateWindow".to_string(), - routing_events::ApiMethod::Grpc, + state.request_id, payment_attempt.payment_id.get_string_repr().to_string(), profile_id.to_owned(), payment_attempt.merchant_id.to_owned(), - state.request_id, - routing_events::RoutingEngine::IntelligentRouter, + "IntelligentRouter: UpdateSuccessRateWindow".to_string(), + Some(event_request.clone()), + true, + false, ); - let update_response = client - .update_success_rate( - profile_id.get_string_repr().into(), - success_based_routing_configs, - success_based_routing_config_params, - vec![routing_types::RoutableConnectorChoiceWithStatus::new( - routable_connector.clone(), - payment_status_attribute == common_enums::AttemptStatus::Charged, - )], - state.get_grpc_headers(), + let closure = || async { + let update_response_result = client + .update_success_rate( + profile_id.get_string_repr().into(), + success_based_routing_configs, + success_based_routing_config_params, + vec![routing_types::RoutableConnectorChoiceWithStatus::new( + routable_connector.clone(), + payment_status_attribute == common_enums::AttemptStatus::Charged, + )], + state.get_grpc_headers(), + ) + .await + .change_context(errors::RoutingError::SuccessRateCalculationError) + .attach_printable( + "unable to update success based routing window in dynamic routing service", + ); + + match update_response_result { + Ok(update_response) => { + let updated_resp = + routing_utils::UpdateSuccessRateWindowEventResponse::try_from( + &update_response, + ) + .change_context(errors::RoutingError::RoutingEventsError { message: "Unable to convert to UpdateSuccessRateWindowEventResponse from UpdateSuccessRateWindowResponse".to_string(), status_code: 500 })?; + Ok(Some(updated_resp)) + } + Err(err) => { + logger::error!( + "unable to update connector score in dynamic routing service: {:?}", + err.current_context() + ); + + Err(err) + } + } + }; + + let events_response = routing_events_wrapper + .construct_event_builder( + "SuccessRateCalculator.UpdateSuccessRateWindow".to_string(), + routing_events::RoutingEngine::IntelligentRouter, + routing_events::ApiMethod::Grpc, ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "SR-Intelligent-Router: Failed to update success rate in Intelligent-Router", + )? + .trigger_event(state, closure) .await - .inspect_err(|e| { - routing_event - .set_error(serde_json::json!({"error": e.current_context().to_string()})); - state.event_handler().log_event(&routing_event); - }) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( - "unable to update success based routing window in dynamic routing service", + "SR-Intelligent-Router: Failed to update success rate in Intelligent-Router", )?; - let event_response = routing_types::UpdateSuccessRateWindowEventResponse { - status: match update_response.status { - 0 => routing_types::UpdationStatusEventResponse::WindowUpdationSucceeded, - 1 => routing_types::UpdationStatusEventResponse::WindowUpdationFailed, - _ => { - return Err(errors::ApiErrorResponse::InternalServerError) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("unknown status code from dynamic routing service") - } - }, - }; + let _response: routing_utils::UpdateSuccessRateWindowEventResponse = events_response + .response + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "UpdateSuccessRateWindowEventResponse not found in RoutingEventResponse", + )?; + + let mut routing_event = events_response + .event + .ok_or(errors::RoutingError::RoutingEventsError { + message: + "SR-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse" + .to_string(), + status_code: 500, + }) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "SR-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse", + )?; - routing_event.set_response_body(&event_response); routing_event.set_status_code(200); - routing_event.set_payment_connector(routable_connector); + routing_event.set_payment_connector(routable_connector); // we can do this inside the event wrap by implementing an interface on the req type state.event_handler().log_event(&routing_event); Ok(()) @@ -1246,45 +1278,35 @@ pub async fn update_window_for_elimination_routing( gsm_error_category.to_string(), )]; - let event_request = routing_types::UpdateEliminationBucketEventRequest { + let event_request = routing_utils::UpdateEliminationBucketEventRequest { id: profile_id.get_string_repr().to_string(), params: elimination_routing_config_params.clone(), labels_with_bucket_name: labels_with_bucket_name .iter() - .map( - |conn_choice| routing_types::LabelWithBucketNameEventRequest { - label: conn_choice.routable_connector_choice.to_string(), - bucket_name: conn_choice.bucket_name.clone(), - }, - ) + .map(|conn_choice| { + routing_utils::LabelWithBucketNameEventRequest::from(conn_choice) + }) .collect(), config: elimination_routing_config .elimination_analyser_config - .map(|conf| routing_types::EliminationRoutingEventBucketConfig { - bucket_leak_interval_in_secs: conf.bucket_leak_interval_in_secs, - bucket_size: conf.bucket_size, - }), + .as_ref() + .map(routing_utils::EliminationRoutingEventBucketConfig::from), }; - let serialized_request = serde_json::to_value(&event_request) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("unable to serialize success_based_routing_config_params")?; - - let mut routing_event = routing_events::RoutingEvent::new( + let routing_events_wrapper = routing_utils::RoutingEventsWrapper::new( state.tenant.tenant_id.clone(), - "".to_string(), - "Intelligent-router UpdateEliminationBucket", - serialized_request, - "EliminationAnalyser.UpdateEliminationBucket".to_string(), - routing_events::ApiMethod::Grpc, + state.request_id, payment_attempt.payment_id.get_string_repr().to_string(), profile_id.to_owned(), payment_attempt.merchant_id.to_owned(), - state.request_id, - routing_events::RoutingEngine::IntelligentRouter, + "IntelligentRouter: UpdateEliminationBucket".to_string(), + Some(event_request.clone()), + true, + false, ); - let update_response = client + let closure = || async { + let update_response_result = client .update_elimination_bucket_config( profile_id.get_string_repr().to_string(), elimination_routing_config_params, @@ -1293,29 +1315,58 @@ pub async fn update_window_for_elimination_routing( state.get_grpc_headers(), ) .await - .inspect_err(|e| { - routing_event - .set_error(serde_json::json!({"error": e.current_context().to_string()})); - state.event_handler().log_event(&routing_event); - }) - .change_context(errors::ApiErrorResponse::InternalServerError) + .change_context(errors::RoutingError::EliminationRoutingCalculationError) .attach_printable( "unable to update elimination based routing buckets in dynamic routing service", + ); + + match update_response_result { + Ok(resp) => { + let updated_resp = + routing_utils::UpdateEliminationBucketEventResponse::try_from(&resp) + .change_context(errors::RoutingError::RoutingEventsError { message: "Unable to convert to UpdateEliminationBucketEventResponse from UpdateEliminationBucketResponse".to_string(), status_code: 500 })?; + + Ok(Some(updated_resp)) + } + Err(err) => { + logger::error!( + "unable to update elimination score in dynamic routing service: {:?}", + err.current_context() + ); + + Err(err) + } + } + }; + + let events_response = routing_events_wrapper.construct_event_builder( "EliminationAnalyser.UpdateEliminationBucket".to_string(), + routing_events::RoutingEngine::IntelligentRouter, + routing_events::ApiMethod::Grpc) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Elimination-Intelligent-Router: Failed to update elimination bucket in Intelligent-Router")? + .trigger_event(state, closure) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Elimination-Intelligent-Router: Failed to update elimination bucket in Intelligent-Router")?; + + let _response: routing_utils::UpdateEliminationBucketEventResponse = events_response + .response + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "UpdateEliminationBucketEventResponse not found in RoutingEventResponse", )?; - let event_response = routing_types::UpdateEliminationBucketEventResponse { - status: match update_response.status { - 0 => routing_types::EliminationUpdationStatusEventResponse::BucketUpdationSucceeded, - 1 => routing_types::EliminationUpdationStatusEventResponse::BucketUpdationFailed, - _ => { - return Err(errors::ApiErrorResponse::InternalServerError) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("unknown status code from dynamic routing service") - } - }, - }; + let mut routing_event = events_response + .event + .ok_or(errors::RoutingError::RoutingEventsError { + message: + "Elimination-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse" + .to_string(), + status_code: 500, + }) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Elimination-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse")?; - routing_event.set_response_body(&event_response); routing_event.set_status_code(200); routing_event.set_payment_connector(routing_types::RoutableConnectorChoice { choice_kind: api_models::routing::RoutableChoiceKind::FullStruct, @@ -1423,36 +1474,30 @@ pub async fn push_metrics_with_update_window_for_contract_based_routing( get_desired_payment_status_for_dynamic_routing_metrics(payment_attempt.status); if payment_status_attribute == common_enums::AttemptStatus::Charged { - let event_request = routing_types::UpdateContractRequestEventRequest { + let event_request = routing_utils::UpdateContractRequestEventRequest { id: profile_id.get_string_repr().to_string(), params: "".to_string(), - labels_information: vec![routing_types::ContractLabelInformationEventRequest { - label: request_label_info.label.clone(), - target_count: request_label_info.target_count, - target_time: request_label_info.target_time, - current_count: 1, - }], + labels_information: vec![ + routing_utils::ContractLabelInformationEventRequest::from( + &request_label_info, + ), + ], }; - let serialized_request = serde_json::to_value(&event_request) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("unable to serialize success_based_routing_config_params")?; - - let mut routing_event = routing_events::RoutingEvent::new( + let routing_events_wrapper = routing_utils::RoutingEventsWrapper::new( state.tenant.tenant_id.clone(), - "".to_string(), - "Intelligent-router UpdateContract", - serialized_request, - "ContractScoreCalculator.UpdateContract".to_string(), - routing_events::ApiMethod::Grpc, + state.request_id, payment_attempt.payment_id.get_string_repr().to_string(), profile_id.to_owned(), payment_attempt.merchant_id.to_owned(), - state.request_id, - routing_events::RoutingEngine::IntelligentRouter, + "IntelligentRouter: UpdateContractScore".to_string(), + Some(event_request.clone()), + true, + false, ); - let update_response = client + let closure = || async { + let update_response_result = client .update_contracts( profile_id.get_string_repr().into(), vec![request_label_info], @@ -1462,30 +1507,60 @@ pub async fn push_metrics_with_update_window_for_contract_based_routing( state.get_grpc_headers(), ) .await - .inspect_err(|e| { - routing_event.set_error( - serde_json::json!({"error": e.current_context().to_string()}), - ); - state.event_handler().log_event(&routing_event); - }) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "unable to update contract based routing window in dynamic routing service", + ); + + match update_response_result { + Ok(resp) => { + let updated_resp = + routing_utils::UpdateContractEventResponse::try_from(&resp) + .change_context(errors::RoutingError::RoutingEventsError { message: "Unable to convert to UpdateContractEventResponse from UpdateContractResponse".to_string(), status_code: 500 })?; + Ok(Some(updated_resp)) + } + Err(err) => { + logger::error!( + "unable to update elimination score in dynamic routing service: {:?}", + err.current_context() + ); + + // have to refactor errors + Err(error_stack::report!( + errors::RoutingError::ContractScoreUpdationError + )) + } + } + }; + + let events_response = routing_events_wrapper.construct_event_builder( "ContractScoreCalculator.UpdateContract".to_string(), + routing_events::RoutingEngine::IntelligentRouter, + routing_events::ApiMethod::Grpc) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("ContractRouting-Intelligent-Router: Failed to contruct RoutingEventsBuilder")? + .trigger_event(state, closure) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("ContractRouting-Intelligent-Router: Failed to update contract scores in Intelligent-Router")?; + + let _response: routing_utils::UpdateContractEventResponse = events_response + .response + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "UpdateContractEventResponse not found in RoutingEventResponse", )?; - let event_response = routing_types::UpdateContractEventResponse { - status: match update_response.status { - 0 => routing_types::ContractUpdationStatusEventResponse::ContractUpdationSucceeded, - 1 => routing_types::ContractUpdationStatusEventResponse::ContractUpdationFailed, - _ => { - return Err(errors::ApiErrorResponse::InternalServerError) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("unknown status code from dynamic routing service") - } - }, - }; + let mut routing_event = events_response + .event + .ok_or(errors::RoutingError::RoutingEventsError { + message: + "ContractRouting-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse" + .to_string(), + status_code: 500, + }) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("ContractRouting-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse")?; - routing_event.set_response_body(&event_response); routing_event.set_payment_connector(routing_types::RoutableConnectorChoice { choice_kind: api_models::routing::RoutableChoiceKind::FullStruct, connector: common_enums::RoutableConnectors::from_str( @@ -2269,6 +2344,7 @@ pub async fn enable_decision_engine_dynamic_routing_setup( DECISION_ENGINE_RULE_CREATE_ENDPOINT, Some(default_engine_config_request), None, + None, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -2346,6 +2422,7 @@ pub async fn update_decision_engine_dynamic_routing_setup( DECISION_ENGINE_RULE_UPDATE_ENDPOINT, Some(decision_engine_request), None, + None, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -2395,6 +2472,7 @@ pub async fn disable_decision_engine_dynamic_routing_setup( DECISION_ENGINE_RULE_DELETE_ENDPOINT, Some(decision_engine_request), None, + None, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -2445,6 +2523,7 @@ pub async fn create_decision_engine_merchant( DECISION_ENGINE_MERCHANT_CREATE_ENDPOINT, Some(merchant_account_req), None, + None, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -2470,6 +2549,7 @@ pub async fn delete_decision_engine_merchant( &path, None, None, + None, ) .await .change_context(errors::ApiErrorResponse::InternalServerError)
2025-06-11T13:58:14Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - Refactored routing events in dynamic_routing core. - have also added routing events for Euclid and Debit Routing ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> SR routing dynamo- <img width="1490" alt="image" src="https://github.com/user-attachments/assets/4877f130-136f-4d75-bb71-fe8a17445e52" /> Elimination and Contract based on dynamo - <img width="1728" alt="image" src="https://github.com/user-attachments/assets/ab090dae-8abb-4b02-99ce-a5a50aa9bf7d" /> <img width="1728" alt="image" src="https://github.com/user-attachments/assets/b0cabbf9-a911-494b-9f61-c28ff4613f7c" /> SR routing on DE - <img width="1728" alt="image" src="https://github.com/user-attachments/assets/a7344a76-381b-4f03-95f9-a3744aea3d5c" /> Euclid DE evaluate rule <img width="1539" alt="image" src="https://github.com/user-attachments/assets/f444dec7-097f-4b71-bf97-64f63cd2bdf8" /> <img width="1728" alt="image" src="https://github.com/user-attachments/assets/dca48eaf-9d38-4d6e-896a-8946a63cc8f7" /> Debit Routing DE - <img width="1728" alt="image" src="https://github.com/user-attachments/assets/0dbbf853-909c-4ea8-9201-70e4d00e4d07" /> <img width="1728" alt="image" src="https://github.com/user-attachments/assets/16d2a113-b160-40cf-bfa2-5e346bc009ed" /> Hit the analytics API - ``` curl --location 'http://localhost:8080/analytics/v1/profile/routing_event_logs?type=Payment&payment_id=pay_6GDjoYAiko8BmxoThD0u' \ --header 'api-key: dev_BNOaWRzwyZ3hMAbhRNtp9t6Mx7ZSVyK5gPvd1bavl0FWehvrHlre1eMifYA244TE' ``` Response - ``` [{"merchant_id":"merchant_1749723893","profile_id":"pro_EfD8EtQQSPZxXStG6B7x","payment_id":"pay_6GDjoYAiko8BmxoThD0u","routable_connectors":"","payment_connector":null,"request_id":"01976967-fd01-7c03-be4b-2a4f20ebf510","flow":"DecisionEngine: Euclid Static Routing","url":"http://localhost:8000/routing/evaluate","request":"{\"created_by\":\"pro_EfD8EtQQSPZxXStG6B7x\",\"parameters\":{\"payment_type\":{\"type\":\"enum_variant\",\"value\":\"non_mandate\"},\"currency\":{\"type\":\"enum_variant\",\"value\":\"USD\"},\"card_bin\":{\"type\":\"str_value\",\"value\":\"424242\"},\"capture_method\":{\"type\":\"enum_variant\",\"value\":\"automatic\"},\"login_date\":{\"type\":\"metadata_variant\",\"value\":{\"key\":\"login_date\",\"value\":\"2019-09-10T10:11:12Z\"}},\"udf1\":{\"type\":\"metadata_variant\",\"value\":{\"key\":\"udf1\",\"value\":\"value1\"}},\"new_customer\":{\"type\":\"metadata_variant\",\"value\":{\"key\":\"new_customer\",\"value\":\"true\"}},\"billing_country\":{\"type\":\"enum_variant\",\"value\":\"Netherlands\"},\"authentication_type\":{\"type\":\"enum_variant\",\"value\":\"no_three_ds\"},\"amount\":{\"type\":\"number\",\"value\":6540},\"business_label\":{\"type\":\"str_value\",\"value\":\"default\"},\"payment_method\":{\"type\":\"enum_variant\",\"value\":\"card\"},\"payment_method_type\":{\"type\":\"enum_variant\",\"value\":\"credit\"}}}","response":"{\"status\":\"success\",\"output\":{\"type\":\"priority\",\"connectors\":[\"stripe\"]},\"evaluated_output\":[\"stripe\"],\"eligible_connectors\":[]}","error":null,"status_code":200,"created_at":"2025-06-13T13:08:32.175Z","method":"Rest (POST)","routing_engine":"decision_engine","routing_approach":null},{"merchant_id":"merchant_1749723893","profile_id":"pro_EfD8EtQQSPZxXStG6B7x","payment_id":"pay_6GDjoYAiko8BmxoThD0u","routable_connectors":"Stripe:\"mca_SdftCCtpClu32qA6oijC\",Adyen:\"mca_Du0BKvXFphUeC5CZ4vb8\"","payment_connector":null,"request_id":"01976967-fd01-7c03-be4b-2a4f20ebf510","flow":"DecisionEngine: SuccessRate decide_gateway","url":"http://localhost:8000/decide-gateway","request":"{\"paymentInfo\":{\"paymentId\":\"pay_6GDjoYAiko8BmxoThD0u\",\"amount\":6540,\"currency\":\"USD\",\"paymentType\":\"ORDER_PAYMENT\",\"metadata\":null,\"paymentMethodType\":\"UPI\",\"paymentMethod\":\"card\",\"cardIsin\":null},\"merchantId\":\"pro_EfD8EtQQSPZxXStG6B7x\",\"eligibleGatewayList\":[\"stripe:mca_SdftCCtpClu32qA6oijC\",\"adyen:mca_Du0BKvXFphUeC5CZ4vb8\"],\"rankingAlgorithm\":\"SR_BASED_ROUTING\",\"eliminationEnabled\":false}","response":"{\"gateway_priority_map\":{\"stripe:mca_SdftCCtpClu32qA6oijC\":0.995,\"adyen:mca_Du0BKvXFphUeC5CZ4vb8\":0.995},\"debit_routing_output\":null,\"routing_approach\":\"SR_SELECTION_V3_ROUTING\"}","error":null,"status_code":200,"created_at":"2025-06-13T13:08:32.184Z","method":"Rest (POST)","routing_engine":"decision_engine","routing_approach":"Exploitation"},{"merchant_id":"merchant_1749723893","profile_id":"pro_EfD8EtQQSPZxXStG6B7x","payment_id":"pay_6GDjoYAiko8BmxoThD0u","routable_connectors":"","payment_connector":"Stripe:\"mca_SdftCCtpClu32qA6oijC\"","request_id":"01976967-fd01-7c03-be4b-2a4f20ebf510","flow":"DecisionEngine: SuccessRate update_gateway_score","url":"http://localhost:8000/update-gateway-score","request":"{\"merchantId\":\"pro_EfD8EtQQSPZxXStG6B7x\",\"gateway\":\"stripe:mca_SdftCCtpClu32qA6oijC\",\"status\":\"CHARGED\",\"paymentId\":\"pay_6GDjoYAiko8BmxoThD0u\"}","response":"{\"message\":\"Success\"}","error":null,"status_code":200,"created_at":"2025-06-13T13:08:33.661Z","method":"Rest (POST)","routing_engine":"decision_engine","routing_approach":null}] ``` ![2025-06-17_17-42-33](https://github.com/user-attachments/assets/aea386ba-5816-4bea-869a-e72964708ee8) ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
1ed2f210b2fec95696b98cfbe67c620c8fe716ff
1ed2f210b2fec95696b98cfbe67c620c8fe716ff
juspay/hyperswitch
juspay__hyperswitch-8295
Bug: add `merchant_category_code` in business profile Add support to accept `merchant_category_code` as input in the business profile. This is the four-digit code assigned based on business type to determine processing fees and risk level. This code can be used to make various decision during a payment flow. One such use case is network interchange fee calculation in debit routing.
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 2e337c1f560..f1260390795 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -13195,6 +13195,18 @@ }, "additionalProperties": false }, + "MerchantCategoryCode": { + "type": "string", + "enum": [ + "5411", + "7011", + "0763", + "8111", + "5021", + "4816", + "5661" + ] + }, "MerchantConnectorAccountFeatureMetadata": { "type": "object", "description": "Feature metadata for merchant connector account", @@ -20977,6 +20989,14 @@ } ], "nullable": true + }, + "merchant_category_code": { + "allOf": [ + { + "$ref": "#/components/schemas/MerchantCategoryCode" + } + ], + "nullable": true } }, "additionalProperties": false @@ -21246,6 +21266,14 @@ } ], "nullable": true + }, + "merchant_category_code": { + "allOf": [ + { + "$ref": "#/components/schemas/MerchantCategoryCode" + } + ], + "nullable": true } } }, diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index c63c5485c5a..c80a698d624 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -16133,6 +16133,18 @@ }, "additionalProperties": false }, + "MerchantCategoryCode": { + "type": "string", + "enum": [ + "5411", + "7011", + "0763", + "8111", + "5021", + "4816", + "5661" + ] + }, "MerchantConnectorCreate": { "type": "object", "description": "Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc.\"", @@ -25777,6 +25789,14 @@ "type": "boolean", "description": "Indicates if pre network tokenization is enabled or not", "nullable": true + }, + "merchant_category_code": { + "allOf": [ + { + "$ref": "#/components/schemas/MerchantCategoryCode" + } + ], + "nullable": true } }, "additionalProperties": false @@ -26075,6 +26095,14 @@ "description": "Indicates if the redirection has to open in the iframe", "example": false, "nullable": true + }, + "merchant_category_code": { + "allOf": [ + { + "$ref": "#/components/schemas/MerchantCategoryCode" + } + ], + "nullable": true } } }, diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 07f3e2431fa..d30abfe813f 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -2121,6 +2121,10 @@ pub struct ProfileCreate { /// Indicates if pre network tokenization is enabled or not pub is_pre_network_tokenization_enabled: Option<bool>, + + /// Four-digit code assigned based on business type to determine processing fees and risk level + #[schema(value_type = Option<MerchantCategoryCode>, example = "5411")] + pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, } #[nutype::nutype( @@ -2263,6 +2267,10 @@ pub struct ProfileCreate { /// External Vault Connector Details pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, + + /// Four-digit code assigned based on business type to determine processing fees and risk level + #[schema(value_type = Option<MerchantCategoryCode>, example = "5411")] + pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, } #[cfg(feature = "v1")] @@ -2434,6 +2442,10 @@ pub struct ProfileResponse { /// Indicates if the redirection has to open in the iframe #[schema(example = false)] pub is_iframe_redirection_enabled: Option<bool>, + + /// Four-digit code assigned based on business type to determine processing fees and risk level + #[schema(value_type = Option<MerchantCategoryCode>, example = "5411")] + pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, } #[cfg(feature = "v2")] @@ -2584,6 +2596,10 @@ pub struct ProfileResponse { /// External Vault Connector Details pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, + + /// Four-digit code assigned based on business type to determine processing fees and risk level + #[schema(value_type = Option<MerchantCategoryCode>, example = "5411")] + pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, } #[cfg(feature = "v1")] @@ -2740,6 +2756,10 @@ pub struct ProfileUpdate { /// Indicates if pre network tokenization is enabled or not #[schema(default = false, example = false)] pub is_pre_network_tokenization_enabled: Option<bool>, + + /// Four-digit code assigned based on business type to determine processing fees and risk level + #[schema(value_type = Option<MerchantCategoryCode>, example = "5411")] + pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, } #[cfg(feature = "v2")] @@ -2872,6 +2892,10 @@ pub struct ProfileUpdate { /// External Vault Connector Details pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, + + /// Four-digit code assigned based on business type to determine processing fees and risk level + #[schema(value_type = Option<MerchantCategoryCode>, example = "5411")] + pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] diff --git a/crates/api_models/src/open_router.rs b/crates/api_models/src/open_router.rs index 08607e1469b..33719e8a41b 100644 --- a/crates/api_models/src/open_router.rs +++ b/crates/api_models/src/open_router.rs @@ -107,7 +107,7 @@ impl TryFrom<(payment_methods::CoBadgedCardData, String)> for DebitRoutingReques #[derive(Debug, Clone, Serialize, Deserialize)] pub struct CoBadgedCardRequest { - pub merchant_category_code: common_enums::MerchantCategoryCode, + pub merchant_category_code: common_enums::DecisionEngineMerchantCategoryCode, pub acquirer_country: common_enums::CountryAlpha2, pub co_badged_card_data: Option<DebitRoutingRequestData>, } diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 893a3b7dafa..5daabd0bc78 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -2412,7 +2412,7 @@ pub enum CardType { #[derive(Debug, Clone, Serialize, Deserialize, strum::EnumString, strum::Display)] #[serde(rename_all = "snake_case")] -pub enum MerchantCategoryCode { +pub enum DecisionEngineMerchantCategoryCode { #[serde(rename = "merchant_category_code_0001")] Mcc0001, } @@ -2515,6 +2515,98 @@ pub enum DisputeStatus { DisputeLost, } +#[derive( + Clone, + Copy, + Debug, + Eq, + Hash, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, + strum::EnumIter, + strum::VariantNames, + ToSchema, +)] +pub enum MerchantCategory { + #[serde(rename = "Grocery Stores, Supermarkets (5411)")] + GroceryStoresSupermarkets, + #[serde(rename = "Lodging-Hotels, Motels, Resorts-not elsewhere classified (7011)")] + LodgingHotelsMotelsResorts, + #[serde(rename = "Agricultural Cooperatives (0763)")] + AgriculturalCooperatives, + #[serde(rename = "Attorneys, Legal Services (8111)")] + AttorneysLegalServices, + #[serde(rename = "Office and Commercial Furniture (5021)")] + OfficeAndCommercialFurniture, + #[serde(rename = "Computer Network/Information Services (4816)")] + ComputerNetworkInformationServices, + #[serde(rename = "Shoe Stores (5661)")] + ShoeStores, +} + +#[derive( + Clone, + Copy, + Debug, + Eq, + Hash, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, + strum::EnumIter, + strum::VariantNames, + ToSchema, +)] +#[router_derive::diesel_enum(storage_type = "text")] +pub enum MerchantCategoryCode { + #[serde(rename = "5411")] + #[strum(serialize = "5411")] + Mcc5411, + #[serde(rename = "7011")] + #[strum(serialize = "7011")] + Mcc7011, + #[serde(rename = "0763")] + #[strum(serialize = "0763")] + Mcc0763, + #[serde(rename = "8111")] + #[strum(serialize = "8111")] + Mcc8111, + #[serde(rename = "5021")] + #[strum(serialize = "5021")] + Mcc5021, + #[serde(rename = "4816")] + #[strum(serialize = "4816")] + Mcc4816, + #[serde(rename = "5661")] + #[strum(serialize = "5661")] + Mcc5661, +} + +impl MerchantCategoryCode { + pub fn to_merchant_category_name(&self) -> MerchantCategory { + match self { + Self::Mcc5411 => MerchantCategory::GroceryStoresSupermarkets, + Self::Mcc7011 => MerchantCategory::LodgingHotelsMotelsResorts, + Self::Mcc0763 => MerchantCategory::AgriculturalCooperatives, + Self::Mcc8111 => MerchantCategory::AttorneysLegalServices, + Self::Mcc5021 => MerchantCategory::OfficeAndCommercialFurniture, + Self::Mcc4816 => MerchantCategory::ComputerNetworkInformationServices, + Self::Mcc5661 => MerchantCategory::ShoeStores, + } + } +} + +#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)] +pub struct MerchantCategoryCodeWithName { + pub code: MerchantCategoryCode, + pub name: MerchantCategory, +} + #[derive( Clone, Debug, diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs index a93bab30a49..e2543e3b431 100644 --- a/crates/diesel_models/src/business_profile.rs +++ b/crates/diesel_models/src/business_profile.rs @@ -75,6 +75,7 @@ pub struct Profile { pub is_pre_network_tokenization_enabled: Option<bool>, pub three_ds_decision_rule_algorithm: Option<serde_json::Value>, pub acquirer_config_map: Option<common_types::domain::AcquirerConfigMap>, + pub merchant_category_code: Option<common_enums::MerchantCategoryCode>, } #[cfg(feature = "v1")] @@ -130,6 +131,7 @@ pub struct ProfileNew { pub id: Option<common_utils::id_type::ProfileId>, pub is_iframe_redirection_enabled: Option<bool>, pub is_pre_network_tokenization_enabled: Option<bool>, + pub merchant_category_code: Option<common_enums::MerchantCategoryCode>, } #[cfg(feature = "v1")] @@ -185,6 +187,7 @@ pub struct ProfileUpdateInternal { pub is_pre_network_tokenization_enabled: Option<bool>, pub three_ds_decision_rule_algorithm: Option<serde_json::Value>, pub acquirer_config_map: Option<common_types::domain::AcquirerConfigMap>, + pub merchant_category_code: Option<common_enums::MerchantCategoryCode>, } #[cfg(feature = "v1")] @@ -237,6 +240,7 @@ impl ProfileUpdateInternal { is_pre_network_tokenization_enabled, three_ds_decision_rule_algorithm, acquirer_config_map, + merchant_category_code, } = self; Profile { profile_id: source.profile_id, @@ -320,6 +324,7 @@ impl ProfileUpdateInternal { three_ds_decision_rule_algorithm: three_ds_decision_rule_algorithm .or(source.three_ds_decision_rule_algorithm), acquirer_config_map: acquirer_config_map.or(source.acquirer_config_map), + merchant_category_code: merchant_category_code.or(source.merchant_category_code), } } } @@ -381,6 +386,7 @@ pub struct Profile { pub is_iframe_redirection_enabled: Option<bool>, pub three_ds_decision_rule_algorithm: Option<serde_json::Value>, pub acquirer_config_map: Option<common_types::domain::AcquirerConfigMap>, + pub merchant_category_code: Option<common_enums::MerchantCategoryCode>, pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub order_fulfillment_time: Option<i64>, pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>, @@ -452,6 +458,7 @@ pub struct ProfileNew { pub is_clear_pan_retries_enabled: Option<bool>, pub is_debit_routing_enabled: bool, pub merchant_business_country: Option<common_enums::CountryAlpha2>, + pub merchant_category_code: Option<common_enums::MerchantCategoryCode>, pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub order_fulfillment_time: Option<i64>, pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>, @@ -510,6 +517,7 @@ pub struct ProfileUpdateInternal { pub is_clear_pan_retries_enabled: Option<bool>, pub is_debit_routing_enabled: Option<bool>, pub merchant_business_country: Option<common_enums::CountryAlpha2>, + pub merchant_category_code: Option<common_enums::MerchantCategoryCode>, pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub order_fulfillment_time: Option<i64>, pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>, @@ -578,6 +586,7 @@ impl ProfileUpdateInternal { is_iframe_redirection_enabled, is_external_vault_enabled, external_vault_connector_details, + merchant_category_code, } = self; Profile { id: source.id, @@ -671,6 +680,7 @@ impl ProfileUpdateInternal { .or(source.external_vault_connector_details), three_ds_decision_rule_algorithm: None, acquirer_config_map: None, + merchant_category_code: merchant_category_code.or(source.merchant_category_code), } } } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 4e93ecab944..522ad271be9 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -229,6 +229,8 @@ diesel::table! { is_pre_network_tokenization_enabled -> Nullable<Bool>, three_ds_decision_rule_algorithm -> Nullable<Jsonb>, acquirer_config_map -> Nullable<Jsonb>, + #[max_length = 16] + merchant_category_code -> Nullable<Varchar>, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 882c620d9fb..6ea3b49bb0c 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -224,6 +224,8 @@ diesel::table! { is_iframe_redirection_enabled -> Nullable<Bool>, three_ds_decision_rule_algorithm -> Nullable<Jsonb>, acquirer_config_map -> Nullable<Jsonb>, + #[max_length = 16] + merchant_category_code -> Nullable<Varchar>, #[max_length = 64] routing_algorithm_id -> Nullable<Varchar>, order_fulfillment_time -> Nullable<Int8>, diff --git a/crates/euclid_wasm/src/lib.rs b/crates/euclid_wasm/src/lib.rs index 6e8c327b7e4..25d1da385ad 100644 --- a/crates/euclid_wasm/src/lib.rs +++ b/crates/euclid_wasm/src/lib.rs @@ -34,7 +34,7 @@ use wasm_bindgen::prelude::*; use crate::utils::JsResultExt; type JsResult = Result<JsValue, JsValue>; use api_models::payment_methods::CountryCodeWithName; -use common_enums::CountryAlpha2; +use common_enums::{CountryAlpha2, MerchantCategoryCode, MerchantCategoryCodeWithName}; use strum::IntoEnumIterator; struct SeedData { @@ -91,6 +91,22 @@ pub fn get_two_letter_country_code() -> JsResult { Ok(serde_wasm_bindgen::to_value(&country_code_with_name)?) } +/// This function can be used by the frontend to get all the merchant category codes +/// along with their names. +#[wasm_bindgen(js_name=getMerchantCategoryCodeWithName)] +pub fn get_merchant_category_code_with_name() -> JsResult { + let merchant_category_codes_with_name = MerchantCategoryCode::iter() + .map(|mcc_value| MerchantCategoryCodeWithName { + code: mcc_value, + name: mcc_value.to_merchant_category_name(), + }) + .collect::<Vec<_>>(); + + Ok(serde_wasm_bindgen::to_value( + &merchant_category_codes_with_name, + )?) +} + /// This function can be used by the frontend to provide the WASM with information about /// all the merchant's connector accounts. The input argument is a vector of all the merchant's /// connector accounts from the API. diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs index 6c95af4f149..93ed2af4945 100644 --- a/crates/hyperswitch_domain_models/src/business_profile.rs +++ b/crates/hyperswitch_domain_models/src/business_profile.rs @@ -77,6 +77,7 @@ pub struct Profile { pub is_pre_network_tokenization_enabled: bool, pub three_ds_decision_rule_algorithm: Option<serde_json::Value>, pub acquirer_config_map: Option<common_types::domain::AcquirerConfigMap>, + pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, } #[cfg(feature = "v1")] @@ -130,6 +131,7 @@ pub struct ProfileSetter { pub merchant_business_country: Option<api_enums::CountryAlpha2>, pub is_iframe_redirection_enabled: Option<bool>, pub is_pre_network_tokenization_enabled: bool, + pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, } #[cfg(feature = "v1")] @@ -190,6 +192,7 @@ impl From<ProfileSetter> for Profile { is_pre_network_tokenization_enabled: value.is_pre_network_tokenization_enabled, three_ds_decision_rule_algorithm: None, // three_ds_decision_rule_algorithm is not yet created during profile creation acquirer_config_map: None, + merchant_category_code: value.merchant_category_code, } } } @@ -250,6 +253,7 @@ pub struct ProfileGeneralUpdate { pub merchant_business_country: Option<api_enums::CountryAlpha2>, pub is_iframe_redirection_enabled: Option<bool>, pub is_pre_network_tokenization_enabled: Option<bool>, + pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, } #[cfg(feature = "v1")] @@ -329,6 +333,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { merchant_business_country, is_iframe_redirection_enabled, is_pre_network_tokenization_enabled, + merchant_category_code, } = *update; Self { @@ -379,6 +384,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { is_pre_network_tokenization_enabled, three_ds_decision_rule_algorithm: None, acquirer_config_map: None, + merchant_category_code, } } ProfileUpdate::RoutingAlgorithmUpdate { @@ -432,6 +438,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { is_pre_network_tokenization_enabled: None, three_ds_decision_rule_algorithm, acquirer_config_map: None, + merchant_category_code: None, }, ProfileUpdate::DynamicRoutingAlgorithmUpdate { dynamic_routing_algorithm, @@ -482,6 +489,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { is_pre_network_tokenization_enabled: None, three_ds_decision_rule_algorithm: None, acquirer_config_map: None, + merchant_category_code: None, }, ProfileUpdate::ExtendedCardInfoUpdate { is_extended_card_info_enabled, @@ -532,6 +540,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { is_pre_network_tokenization_enabled: None, three_ds_decision_rule_algorithm: None, acquirer_config_map: None, + merchant_category_code: None, }, ProfileUpdate::ConnectorAgnosticMitUpdate { is_connector_agnostic_mit_enabled, @@ -582,6 +591,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { is_pre_network_tokenization_enabled: None, three_ds_decision_rule_algorithm: None, acquirer_config_map: None, + merchant_category_code: None, }, ProfileUpdate::NetworkTokenizationUpdate { is_network_tokenization_enabled, @@ -632,6 +642,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { is_pre_network_tokenization_enabled: None, three_ds_decision_rule_algorithm: None, acquirer_config_map: None, + merchant_category_code: None, }, ProfileUpdate::CardTestingSecretKeyUpdate { card_testing_secret_key, @@ -682,6 +693,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { is_pre_network_tokenization_enabled: None, three_ds_decision_rule_algorithm: None, acquirer_config_map: None, + merchant_category_code: None, }, ProfileUpdate::AcquirerConfigMapUpdate { acquirer_config_map, @@ -732,6 +744,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { is_pre_network_tokenization_enabled: None, three_ds_decision_rule_algorithm: None, acquirer_config_map, + merchant_category_code: None, }, } } @@ -802,6 +815,7 @@ impl super::behaviour::Conversion for Profile { is_pre_network_tokenization_enabled: Some(self.is_pre_network_tokenization_enabled), three_ds_decision_rule_algorithm: self.three_ds_decision_rule_algorithm, acquirer_config_map: self.acquirer_config_map, + merchant_category_code: self.merchant_category_code, }) } @@ -898,6 +912,7 @@ impl super::behaviour::Conversion for Profile { .unwrap_or(false), three_ds_decision_rule_algorithm: item.three_ds_decision_rule_algorithm, acquirer_config_map: item.acquirer_config_map, + merchant_category_code: item.merchant_category_code, }) } .await @@ -961,6 +976,7 @@ impl super::behaviour::Conversion for Profile { merchant_business_country: self.merchant_business_country, is_iframe_redirection_enabled: self.is_iframe_redirection_enabled, is_pre_network_tokenization_enabled: Some(self.is_pre_network_tokenization_enabled), + merchant_category_code: self.merchant_category_code, }) } } @@ -1020,6 +1036,7 @@ pub struct Profile { pub is_iframe_redirection_enabled: Option<bool>, pub is_external_vault_enabled: Option<bool>, pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, + pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, } #[cfg(feature = "v2")] @@ -1075,6 +1092,7 @@ pub struct ProfileSetter { pub is_iframe_redirection_enabled: Option<bool>, pub is_external_vault_enabled: Option<bool>, pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, + pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, } #[cfg(feature = "v2")] @@ -1135,6 +1153,7 @@ impl From<ProfileSetter> for Profile { is_iframe_redirection_enabled: value.is_iframe_redirection_enabled, is_external_vault_enabled: value.is_external_vault_enabled, external_vault_connector_details: value.external_vault_connector_details, + merchant_category_code: value.merchant_category_code, } } } @@ -1214,6 +1233,7 @@ pub struct ProfileGeneralUpdate { pub is_iframe_redirection_enabled: Option<bool>, pub is_external_vault_enabled: Option<bool>, pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, + pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, } #[cfg(feature = "v2")] @@ -1292,6 +1312,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { is_iframe_redirection_enabled, is_external_vault_enabled, external_vault_connector_details, + merchant_category_code, } = *update; Self { profile_name, @@ -1343,6 +1364,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { is_iframe_redirection_enabled: None, is_external_vault_enabled, external_vault_connector_details, + merchant_category_code, } } ProfileUpdate::RoutingAlgorithmUpdate { @@ -1397,6 +1419,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { is_iframe_redirection_enabled: None, is_external_vault_enabled: None, external_vault_connector_details: None, + merchant_category_code: None, }, ProfileUpdate::ExtendedCardInfoUpdate { is_extended_card_info_enabled, @@ -1449,6 +1472,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { is_iframe_redirection_enabled: None, is_external_vault_enabled: None, external_vault_connector_details: None, + merchant_category_code: None, }, ProfileUpdate::ConnectorAgnosticMitUpdate { is_connector_agnostic_mit_enabled, @@ -1501,6 +1525,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { is_iframe_redirection_enabled: None, is_external_vault_enabled: None, external_vault_connector_details: None, + merchant_category_code: None, }, ProfileUpdate::DefaultRoutingFallbackUpdate { default_fallback_routing, @@ -1553,6 +1578,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { is_iframe_redirection_enabled: None, is_external_vault_enabled: None, external_vault_connector_details: None, + merchant_category_code: None, }, ProfileUpdate::NetworkTokenizationUpdate { is_network_tokenization_enabled, @@ -1605,6 +1631,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { is_iframe_redirection_enabled: None, is_external_vault_enabled: None, external_vault_connector_details: None, + merchant_category_code: None, }, ProfileUpdate::CollectCvvDuringPaymentUpdate { should_collect_cvv_during_payment, @@ -1657,6 +1684,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { is_iframe_redirection_enabled: None, is_external_vault_enabled: None, external_vault_connector_details: None, + merchant_category_code: None, }, ProfileUpdate::DecisionManagerRecordUpdate { three_ds_decision_manager_config, @@ -1709,6 +1737,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { is_iframe_redirection_enabled: None, is_external_vault_enabled: None, external_vault_connector_details: None, + merchant_category_code: None, }, ProfileUpdate::CardTestingSecretKeyUpdate { card_testing_secret_key, @@ -1761,6 +1790,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { is_iframe_redirection_enabled: None, is_external_vault_enabled: None, external_vault_connector_details: None, + merchant_category_code: None, }, ProfileUpdate::RevenueRecoveryAlgorithmUpdate { revenue_recovery_retry_algorithm_type, @@ -1814,6 +1844,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { is_iframe_redirection_enabled: None, is_external_vault_enabled: None, external_vault_connector_details: None, + merchant_category_code: None, }, } } @@ -1890,6 +1921,7 @@ impl super::behaviour::Conversion for Profile { external_vault_connector_details: self.external_vault_connector_details, three_ds_decision_rule_algorithm: None, acquirer_config_map: None, + merchant_category_code: self.merchant_category_code, }) } @@ -1983,6 +2015,7 @@ impl super::behaviour::Conversion for Profile { is_iframe_redirection_enabled: item.is_iframe_redirection_enabled, is_external_vault_enabled: item.is_external_vault_enabled, external_vault_connector_details: item.external_vault_connector_details, + merchant_category_code: item.merchant_category_code, }) } .await @@ -2051,6 +2084,7 @@ impl super::behaviour::Conversion for Profile { is_iframe_redirection_enabled: self.is_iframe_redirection_enabled, is_external_vault_enabled: self.is_external_vault_enabled, external_vault_connector_details: self.external_vault_connector_details, + merchant_category_code: self.merchant_category_code, }) } } diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 171f37cca19..6738824b054 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -324,6 +324,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::enums::BankType, api_models::enums::BankHolderType, api_models::enums::CardNetwork, + api_models::enums::MerchantCategoryCode, api_models::enums::DisputeStage, api_models::enums::DisputeStatus, api_models::enums::CountryAlpha2, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 9a624c12a90..5b5ed7a83e4 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -285,6 +285,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::enums::BankType, api_models::enums::BankHolderType, api_models::enums::CardNetwork, + api_models::enums::MerchantCategoryCode, api_models::enums::TokenDataType, api_models::enums::DisputeStage, api_models::enums::DisputeStatus, diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index b8d24573c34..be009c127df 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -4052,6 +4052,7 @@ impl ProfileCreateBridge for api::ProfileCreate { is_pre_network_tokenization_enabled: self .is_pre_network_tokenization_enabled .unwrap_or_default(), + merchant_category_code: self.merchant_category_code, })) } @@ -4200,6 +4201,7 @@ impl ProfileCreateBridge for api::ProfileCreate { external_vault_connector_details: self .external_vault_connector_details .map(ForeignInto::foreign_into), + merchant_category_code: self.merchant_category_code, })) } } @@ -4533,6 +4535,7 @@ impl ProfileUpdateBridge for api::ProfileUpdate { merchant_business_country: self.merchant_business_country, is_iframe_redirection_enabled: self.is_iframe_redirection_enabled, is_pre_network_tokenization_enabled: self.is_pre_network_tokenization_enabled, + merchant_category_code: self.merchant_category_code, }, ))) } @@ -4672,6 +4675,7 @@ impl ProfileUpdateBridge for api::ProfileUpdate { external_vault_connector_details: self .external_vault_connector_details .map(ForeignInto::foreign_into), + merchant_category_code: self.merchant_category_code, }, ))) } diff --git a/crates/router/src/core/debit_routing.rs b/crates/router/src/core/debit_routing.rs index adbd663c5c1..26505171fc3 100644 --- a/crates/router/src/core/debit_routing.rs +++ b/crates/router/src/core/debit_routing.rs @@ -315,7 +315,7 @@ pub async fn get_debit_routing_output< } let co_badged_card_request = open_router::CoBadgedCardRequest { - merchant_category_code: enums::MerchantCategoryCode::Mcc0001, + merchant_category_code: enums::DecisionEngineMerchantCategoryCode::Mcc0001, acquirer_country, co_badged_card_data, }; diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index 41069a784b8..ac46c1dde00 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -199,6 +199,7 @@ impl ForeignTryFrom<domain::Profile> for ProfileResponse { is_pre_network_tokenization_enabled: item.is_pre_network_tokenization_enabled, acquirer_configs: item.acquirer_config_map, is_iframe_redirection_enabled: item.is_iframe_redirection_enabled, + merchant_category_code: item.merchant_category_code, }) } } @@ -283,6 +284,7 @@ impl ForeignTryFrom<domain::Profile> for ProfileResponse { external_vault_connector_details: item .external_vault_connector_details .map(ForeignInto::foreign_into), + merchant_category_code: item.merchant_category_code, }) } } @@ -450,5 +452,6 @@ pub async fn create_profile_from_merchant_account( is_pre_network_tokenization_enabled: request .is_pre_network_tokenization_enabled .unwrap_or_default(), + merchant_category_code: request.merchant_category_code, })) } diff --git a/migrations/2025-06-09-080126_add_merchant_category_code_in_business_profile/down.sql b/migrations/2025-06-09-080126_add_merchant_category_code_in_business_profile/down.sql new file mode 100644 index 00000000000..532bb667ff2 --- /dev/null +++ b/migrations/2025-06-09-080126_add_merchant_category_code_in_business_profile/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE business_profile DROP COLUMN IF EXISTS merchant_category_code; \ No newline at end of file diff --git a/migrations/2025-06-09-080126_add_merchant_category_code_in_business_profile/up.sql b/migrations/2025-06-09-080126_add_merchant_category_code_in_business_profile/up.sql new file mode 100644 index 00000000000..125634a30e1 --- /dev/null +++ b/migrations/2025-06-09-080126_add_merchant_category_code_in_business_profile/up.sql @@ -0,0 +1,3 @@ +-- Your SQL goes here +ALTER TABLE business_profile +ADD COLUMN merchant_category_code VARCHAR(16) DEFAULT NULL; \ No newline at end of file
2025-06-10T06:34:54Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This pull request introduces `merchant_category_code` field in the business profile. This is the four-digit code assigned based on business type to determine processing fees and risk level. This code can be used to make various decision during a payment flow. One such use case is network interchange fee calculation in debit routing. * **Enum Enhancements**: Introduced two new enums, `MerchantCategory` and `MerchantCategoryCode`, to represent MCCs and their corresponding human-readable names. Implemented a mapping function `to_merchant_category_name` to convert MCCs to their names. ### WASM Functionality * **Frontend Integration**: Added a new WASM function `getMerchantCategoryCodeWithName` to retrieve all MCCs along with their names for frontend use. This function iterates over the `MerchantCategoryCode` enum and constructs a list of MCCs and their human-readable names. ### Code Refactoring * **Enum Renaming**: Renamed `MerchantCategoryCode` to `DecisionEngineMerchantCategoryCode` in specific contexts to clarify usage in decision engine logic. This is struct will be removed once the new struct is introduced in decision engine. -> Supported Merchant Category Codes 1. 5411 2. 7011 3. 0763 4. 8111 5. 5021 6. 4816 7. 5661 ### Additional Changes - [x] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Update a business profile by passing merchant category code ``` curl --location 'http://localhost:8080/account/merchant_1749476401/business_profile/pro_1RkvEPVmDc3K9FSyjOOS' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: ' \ --data '{ "merchant_category_code": "5411" }' ``` ``` { "merchant_id": "merchant_1749476401", "profile_id": "pro_1RkvEPVmDc3K9FSyjOOS", "profile_name": "US_default", "return_url": "https://google.com/success", "enable_payment_response_hash": true, "payment_response_hash_key": "IfRVqwhR9vFVlA7sYWqPZvy6xNbM6wToe8N0WCEGykmFkTc7hYyycIbOCbGw3Hxo", "redirect_to_merchant_with_http_post": false, "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "webhook_url": null, "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "metadata": null, "routing_algorithm": null, "intent_fulfillment_time": 900, "frm_routing_algorithm": null, "payout_routing_algorithm": null, "applepay_verified_domains": null, "session_expiry": 900, "payment_link_config": null, "authentication_connector_details": null, "use_billing_as_payment_method_billing": true, "extended_card_info_config": null, "collect_shipping_details_from_wallet_connector": false, "collect_billing_details_from_wallet_connector": false, "always_collect_shipping_details_from_wallet_connector": false, "always_collect_billing_details_from_wallet_connector": false, "is_connector_agnostic_mit_enabled": false, "payout_link_config": null, "outgoing_webhook_custom_http_headers": null, "tax_connector_id": null, "is_tax_connector_enabled": false, "is_network_tokenization_enabled": false, "is_auto_retries_enabled": false, "max_auto_retries_enabled": null, "always_request_extended_authorization": null, "is_click_to_pay_enabled": false, "authentication_product_ids": null, "card_testing_guard_config": { "card_ip_blocking_status": "disabled", "card_ip_blocking_threshold": 3, "guest_user_card_blocking_status": "disabled", "guest_user_card_blocking_threshold": 10, "customer_id_blocking_status": "disabled", "customer_id_blocking_threshold": 5, "card_testing_guard_expiry": 3600 }, "is_clear_pan_retries_enabled": false, "force_3ds_challenge": false, "is_debit_routing_enabled": true, "merchant_business_country": null, "is_pre_network_tokenization_enabled": false, "merchant_category_code": "5411" } ``` -> Db entry ![image](https://github.com/user-attachments/assets/1fd22d9e-ed8e-4ea1-9d9e-7d5a5f58afdf) -> Wasm testing <img width="737" alt="image" src="https://github.com/user-attachments/assets/e19488f1-f726-4522-b89d-6733a9f8504b" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Introduced support for merchant category codes across payment and profile APIs, enabling optional inclusion of standardized merchant category codes in payment intent requests and merchant profiles. - Added a public function to retrieve merchant category codes with their descriptive names via WebAssembly. - **Database** - Added a new nullable column for merchant category codes to the business profile table. - **API Documentation** - Updated API schemas and documentation to include merchant category code fields and enumerations. - **Refactor** - Standardized and extended merchant category code enums for improved mapping and integration. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
v1.114.0
713c85d25d29259672da6efbfed0862e843ec542
713c85d25d29259672da6efbfed0862e843ec542
juspay/hyperswitch
juspay__hyperswitch-8306
Bug: [REFACTOR] change the response type of update gateway score api in open router
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index bb4db422556..d43ddadc54c 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -9482,6 +9482,7 @@ "customer_id", "payment_method_type", "payment_method_subtype", + "recurring_enabled", "created", "requires_cvv", "last_used_at", @@ -9513,9 +9514,8 @@ }, "recurring_enabled": { "type": "boolean", - "description": "Indicates whether the payment method supports recurring payments. Optional.", - "example": true, - "nullable": true + "description": "Indicates whether the payment method is eligible for recurring payments", + "example": true }, "payment_method_data": { "allOf": [ @@ -17142,7 +17142,6 @@ "customer_id", "payment_method_type", "payment_method_subtype", - "recurring_enabled", "created", "requires_cvv", "is_default", @@ -17169,8 +17168,9 @@ }, "recurring_enabled": { "type": "boolean", - "description": "Indicates whether the payment method is eligible for recurring payments", - "example": true + "description": "Indicates whether the payment method supports recurring payments. Optional.", + "example": true, + "nullable": true }, "payment_method_data": { "allOf": [ diff --git a/crates/api_models/src/open_router.rs b/crates/api_models/src/open_router.rs index cfcb45ef97b..08607e1469b 100644 --- a/crates/api_models/src/open_router.rs +++ b/crates/api_models/src/open_router.rs @@ -148,6 +148,11 @@ pub struct UpdateScorePayload { pub payment_id: id_type::PaymentId, } +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct UpdateScoreResponse { + pub message: String, +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum TxnStatus { diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index c36de4fb633..f08e76469dc 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -1958,11 +1958,12 @@ pub async fn update_gateway_score_with_open_router( match response { Ok(resp) => { - let update_score_resp = String::from_utf8(resp.response.to_vec()).change_context( - errors::RoutingError::OpenRouterError( + let update_score_resp = resp + .response + .parse_struct::<or_types::UpdateScoreResponse>("UpdateScoreResponse") + .change_context(errors::RoutingError::OpenRouterError( "Failed to parse the response from open_router".into(), - ), - )?; + ))?; logger::debug!( "open_router update_gateway_score response for gateway with id {}: {:?}",
2025-06-10T13:16:06Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description A new struct, UpdateScoreResponse, was introduced in the API models to represent responses from the Open Router. The payment routing logic was updated to parse responses directly into this struct, replacing the previous manual string conversion and error handling with structured deserialization. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Cannot be tested until open_router is enabled in runtime. Tested locally - Response is getting deserialized ![image](https://github.com/user-attachments/assets/51117d21-74b2-4a34-811f-99d9c95e226f) ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit ## Summary by CodeRabbit - **New Features** - Introduced a new response format for score updates, providing clear messaging after updating gateway scores. - Updated payment method responses to clarify recurring payment eligibility and support. - **Refactor** - Improved the way score update responses are processed for greater reliability and clarity. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
v1.114.0
67a42f0c27157f876698982a6b5f0a1cd3e15ffb
67a42f0c27157f876698982a6b5f0a1cd3e15ffb
juspay/hyperswitch
juspay__hyperswitch-8298
Bug: [REFCTOR]: Move CustomerAcceptance type to `common_types` `CustomerAcceptance` is currently defined separately in `api_models` and `hyperswitch_domain_models`. These types are exactly the same, so they can be moved to `common_types`. Additionally, in V2, we can use this strict type in `diesel_models` as well, instead of having a `SecretSerdeValue`
diff --git a/Cargo.lock b/Cargo.lock index 42add100ade..d6037be06fd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1794,8 +1794,10 @@ dependencies = [ "common_utils", "diesel", "euclid", + "masking", "serde", "serde_json", + "time", "utoipa", ] diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json index 6045147a050..013008e8536 100644 --- a/api-reference/v1/openapi_spec_v1.json +++ b/api-reference/v1/openapi_spec_v1.json @@ -17969,6 +17969,7 @@ }, "OnlineMandate": { "type": "object", + "description": "Details of online mandate", "required": [ "ip_address", "user_agent" diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index 65d1b847f3d..2537ae0fcc0 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -14701,6 +14701,7 @@ }, "OnlineMandate": { "type": "object", + "description": "Details of online mandate", "required": [ "ip_address", "user_agent" diff --git a/crates/api_models/src/mandates.rs b/crates/api_models/src/mandates.rs index 2d61a630988..67852326642 100644 --- a/crates/api_models/src/mandates.rs +++ b/crates/api_models/src/mandates.rs @@ -1,9 +1,10 @@ +use common_types::payments as common_payments_types; use masking::Secret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; -use crate::{enums as api_enums, payments}; +use crate::enums as api_enums; #[derive(Default, Debug, Deserialize, Serialize)] pub struct MandateId { @@ -42,7 +43,7 @@ pub struct MandateResponse { pub card: Option<MandateCardDetails>, /// Details about the customer’s acceptance #[schema(value_type = Option<CustomerAcceptance>)] - pub customer_acceptance: Option<payments::CustomerAcceptance>, + pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, } #[derive(Default, Debug, Deserialize, Serialize, ToSchema, Clone)] diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 648df7b05a5..c251d78af5d 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -10,6 +10,7 @@ use cards::CardNumber; #[cfg(feature = "v2")] use common_enums::enums::PaymentConnectorTransmission; use common_enums::ProductType; +use common_types::payments as common_payments_types; #[cfg(feature = "v1")] use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool, @@ -1045,7 +1046,7 @@ pub struct PaymentsRequest { /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] - pub customer_acceptance: Option<CustomerAcceptance>, + pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, /// A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data #[schema(max_length = 64, example = "mandate_iwer89rnjef349dni3")] @@ -1876,7 +1877,8 @@ pub struct MandateData { /// A way to update the mandate's payment method details pub update_mandate_id: Option<String>, /// A consent from the customer to store the payment method - pub customer_acceptance: Option<CustomerAcceptance>, + #[schema(value_type = Option<CustomerAcceptance>)] + pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, /// A way to select the type of mandate used pub mandate_type: Option<MandateType>, } @@ -1925,40 +1927,6 @@ impl Default for MandateType { } } -/// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. -#[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] -#[serde(deny_unknown_fields)] -pub struct CustomerAcceptance { - /// Type of acceptance provided by the - #[schema(example = "online")] - pub acceptance_type: AcceptanceType, - /// Specifying when the customer acceptance was provided - #[schema(example = "2022-09-10T10:11:12Z")] - #[serde(default, with = "common_utils::custom_serde::iso8601::option")] - pub accepted_at: Option<PrimitiveDateTime>, - /// Information required for online mandate generation - pub online: Option<OnlineMandate>, -} - -#[derive(Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone, ToSchema)] -#[serde(rename_all = "lowercase")] -/// This is used to indicate if the mandate was accepted online or offline -pub enum AcceptanceType { - Online, - #[default] - Offline, -} - -#[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] -#[serde(deny_unknown_fields)] -pub struct OnlineMandate { - /// Ip address of the customer machine from which the mandate was created - #[schema(value_type = String, example = "123.32.25.123")] - pub ip_address: Option<Secret<String, pii::IpAddress>>, - /// The user-agent of the customer's browser - pub user_agent: String, -} - #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Card { /// The card number @@ -5370,7 +5338,7 @@ pub struct PaymentsConfirmIntentRequest { /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] - pub customer_acceptance: Option<CustomerAcceptance>, + pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] @@ -5542,7 +5510,7 @@ pub struct PaymentsRequest { /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] - pub customer_acceptance: Option<CustomerAcceptance>, + pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] diff --git a/crates/common_types/Cargo.toml b/crates/common_types/Cargo.toml index 0734a8860ae..7aec0314706 100644 --- a/crates/common_types/Cargo.toml +++ b/crates/common_types/Cargo.toml @@ -17,10 +17,12 @@ diesel = "2.2.10" serde = { version = "1.0.219", features = ["derive"] } serde_json = "1.0.140" utoipa = { version = "4.2.3", features = ["preserve_order", "preserve_path_order"] } +time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] } common_enums = { version = "0.1.0", path = "../common_enums" } common_utils = { version = "0.1.0", path = "../common_utils"} euclid = { version = "0.1.0", path = "../euclid" } +masking = { version = "0.1.0", path = "../masking" } [lints] workspace = true diff --git a/crates/common_types/src/payments.rs b/crates/common_types/src/payments.rs index 1a73e2f9787..e0ea52abc79 100644 --- a/crates/common_types/src/payments.rs +++ b/crates/common_types/src/payments.rs @@ -3,13 +3,15 @@ use std::collections::HashMap; use common_enums::enums; -use common_utils::{errors, events, impl_to_sql_from_sql_json, types::MinorUnit}; +use common_utils::{date_time, errors, events, impl_to_sql_from_sql_json, pii, types::MinorUnit}; use diesel::{sql_types::Jsonb, AsExpression, FromSqlRow}; use euclid::frontend::{ ast::Program, dir::{DirKeyKind, EuclidDirFilter}, }; +use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; +use time::PrimitiveDateTime; use utoipa::ToSchema; use crate::domain::{AdyenSplitData, XenditSplitSubMerchantData}; @@ -100,6 +102,92 @@ impl EuclidDirFilter for ConditionalConfigs { impl_to_sql_from_sql_json!(ConditionalConfigs); +/// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. +#[derive( + Default, + Eq, + PartialEq, + Debug, + serde::Deserialize, + serde::Serialize, + Clone, + AsExpression, + ToSchema, +)] +#[serde(deny_unknown_fields)] +#[diesel(sql_type = Jsonb)] +pub struct CustomerAcceptance { + /// Type of acceptance provided by the + #[schema(example = "online")] + pub acceptance_type: AcceptanceType, + /// Specifying when the customer acceptance was provided + #[schema(example = "2022-09-10T10:11:12Z")] + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + pub accepted_at: Option<PrimitiveDateTime>, + /// Information required for online mandate generation + pub online: Option<OnlineMandate>, +} + +impl_to_sql_from_sql_json!(CustomerAcceptance); + +impl CustomerAcceptance { + /// Get the IP address + pub fn get_ip_address(&self) -> Option<String> { + self.online + .as_ref() + .and_then(|data| data.ip_address.as_ref().map(|ip| ip.peek().to_owned())) + } + + /// Get the User Agent + pub fn get_user_agent(&self) -> Option<String> { + self.online.as_ref().map(|data| data.user_agent.clone()) + } + + /// Get when the customer acceptance was provided + pub fn get_accepted_at(&self) -> PrimitiveDateTime { + self.accepted_at.unwrap_or_else(date_time::now) + } +} + +impl masking::SerializableSecret for CustomerAcceptance {} + +#[derive( + Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone, Copy, ToSchema, +)] +#[serde(rename_all = "lowercase")] +/// This is used to indicate if the mandate was accepted online or offline +pub enum AcceptanceType { + /// Online + Online, + /// Offline + #[default] + Offline, +} + +#[derive( + Default, + Eq, + PartialEq, + Debug, + serde::Deserialize, + serde::Serialize, + AsExpression, + Clone, + ToSchema, +)] +#[serde(deny_unknown_fields)] +/// Details of online mandate +#[diesel(sql_type = Jsonb)] +pub struct OnlineMandate { + /// Ip address of the customer machine from which the mandate was created + #[schema(value_type = String, example = "123.32.25.123")] + pub ip_address: Option<Secret<String, pii::IpAddress>>, + /// The user-agent of the customer's browser + pub user_agent: String, +} + +impl_to_sql_from_sql_json!(OnlineMandate); + #[derive(Serialize, Deserialize, Debug, Clone, FromSqlRow, AsExpression, ToSchema)] #[diesel(sql_type = Jsonb)] /// DecisionManagerRecord diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index 473502ad746..9a2e76b5fd3 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -1,3 +1,5 @@ +#[cfg(feature = "v2")] +use common_types::payments as common_payments_types; use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool, }; @@ -78,7 +80,7 @@ pub struct PaymentAttempt { pub fingerprint_id: Option<String>, pub client_source: Option<String>, pub client_version: Option<String>, - pub customer_acceptance: Option<pii::SecretSerdeValue>, + pub customer_acceptance: Option<masking::Secret<common_payments_types::CustomerAcceptance>>, pub profile_id: id_type::ProfileId, pub organization_id: id_type::OrganizationId, pub card_network: Option<String>, @@ -318,7 +320,7 @@ pub struct PaymentAttemptNew { pub payment_method_billing_address: Option<common_utils::encryption::Encryption>, pub client_source: Option<String>, pub client_version: Option<String>, - pub customer_acceptance: Option<pii::SecretSerdeValue>, + pub customer_acceptance: Option<masking::Secret<common_payments_types::CustomerAcceptance>>, pub profile_id: id_type::ProfileId, pub organization_id: id_type::OrganizationId, pub card_network: Option<String>, diff --git a/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs index 353d941ca6c..b6f263373bb 100644 --- a/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs @@ -2,7 +2,7 @@ use std::{collections::HashMap, ops::Deref}; use api_models::{self, enums as api_enums, payments}; use common_enums::{enums, AttemptStatus, PaymentChargeType, StripeChargeType}; -use common_types::payments::SplitPaymentsRequest; +use common_types::payments::{AcceptanceType, SplitPaymentsRequest}; use common_utils::{ collect_missing_value_keys, errors::CustomResult, @@ -13,7 +13,6 @@ use common_utils::{ }; use error_stack::ResultExt; use hyperswitch_domain_models::{ - mandates::AcceptanceType, payment_method_data::{ self, BankRedirectData, Card, CardRedirectData, GiftCardData, GooglePayWalletData, PayLaterData, PaymentMethodData, VoucherData, WalletData, diff --git a/crates/hyperswitch_domain_models/src/mandates.rs b/crates/hyperswitch_domain_models/src/mandates.rs index 5e5b9e18287..264ed0c6d81 100644 --- a/crates/hyperswitch_domain_models/src/mandates.rs +++ b/crates/hyperswitch_domain_models/src/mandates.rs @@ -1,11 +1,10 @@ use std::collections::HashMap; use api_models::payments::{ - AcceptanceType as ApiAcceptanceType, CustomerAcceptance as ApiCustomerAcceptance, MandateAmountData as ApiMandateAmountData, MandateData as ApiMandateData, MandateType, - OnlineMandate as ApiOnlineMandate, }; use common_enums::Currency; +use common_types::payments as common_payments_types; use common_utils::{ date_time, errors::{CustomResult, ParsingError}, @@ -13,7 +12,6 @@ use common_utils::{ types::MinorUnit, }; use error_stack::ResultExt; -use masking::{PeekInterface, Secret}; use time::PrimitiveDateTime; #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)] @@ -61,39 +59,11 @@ pub struct MandateData { /// A way to update the mandate's payment method details pub update_mandate_id: Option<String>, /// A consent from the customer to store the payment method - pub customer_acceptance: Option<CustomerAcceptance>, + pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, /// A way to select the type of mandate used pub mandate_type: Option<MandateDataType>, } -#[derive(Default, Eq, PartialEq, Debug, Clone, serde::Deserialize, serde::Serialize)] -pub struct CustomerAcceptance { - /// Type of acceptance provided by the - pub acceptance_type: AcceptanceType, - /// Specifying when the customer acceptance was provided - #[serde(with = "common_utils::custom_serde::iso8601::option")] - pub accepted_at: Option<PrimitiveDateTime>, - /// Information required for online mandate generation - pub online: Option<OnlineMandate>, -} - -#[derive(Default, Debug, PartialEq, Eq, Clone, serde::Deserialize, serde::Serialize)] -#[serde(rename_all = "lowercase")] -pub enum AcceptanceType { - Online, - #[default] - Offline, -} - -#[derive(Default, Eq, PartialEq, Debug, Clone, serde::Deserialize, serde::Serialize)] -pub struct OnlineMandate { - /// Ip address of the customer machine from which the mandate was created - #[serde(skip_deserializing)] - pub ip_address: Option<Secret<String, pii::IpAddress>>, - /// The user-agent of the customer's browser - pub user_agent: String, -} - impl From<MandateType> for MandateDataType { fn from(mandate_type: MandateType) -> Self { match mandate_type { @@ -168,83 +138,13 @@ impl From<diesel_models::enums::MandateAmountData> for MandateAmountData { impl From<ApiMandateData> for MandateData { fn from(value: ApiMandateData) -> Self { Self { - customer_acceptance: value.customer_acceptance.map(|d| d.into()), + customer_acceptance: value.customer_acceptance, mandate_type: value.mandate_type.map(|d| d.into()), update_mandate_id: value.update_mandate_id, } } } -impl From<ApiCustomerAcceptance> for CustomerAcceptance { - fn from(value: ApiCustomerAcceptance) -> Self { - Self { - acceptance_type: value.acceptance_type.into(), - accepted_at: value.accepted_at, - online: value.online.map(|d| d.into()), - } - } -} - -impl From<CustomerAcceptance> for ApiCustomerAcceptance { - fn from(value: CustomerAcceptance) -> Self { - Self { - acceptance_type: value.acceptance_type.into(), - accepted_at: value.accepted_at, - online: value.online.map(|d| d.into()), - } - } -} - -impl From<ApiAcceptanceType> for AcceptanceType { - fn from(value: ApiAcceptanceType) -> Self { - match value { - ApiAcceptanceType::Online => Self::Online, - ApiAcceptanceType::Offline => Self::Offline, - } - } -} -impl From<AcceptanceType> for ApiAcceptanceType { - fn from(value: AcceptanceType) -> Self { - match value { - AcceptanceType::Online => Self::Online, - AcceptanceType::Offline => Self::Offline, - } - } -} - -impl From<ApiOnlineMandate> for OnlineMandate { - fn from(value: ApiOnlineMandate) -> Self { - Self { - ip_address: value.ip_address, - user_agent: value.user_agent, - } - } -} -impl From<OnlineMandate> for ApiOnlineMandate { - fn from(value: OnlineMandate) -> Self { - Self { - ip_address: value.ip_address, - user_agent: value.user_agent, - } - } -} - -impl CustomerAcceptance { - pub fn get_ip_address(&self) -> Option<String> { - self.online - .as_ref() - .and_then(|data| data.ip_address.as_ref().map(|ip| ip.peek().to_owned())) - } - - pub fn get_user_agent(&self) -> Option<String> { - self.online.as_ref().map(|data| data.user_agent.clone()) - } - - pub fn get_accepted_at(&self) -> PrimitiveDateTime { - self.accepted_at.unwrap_or_else(date_time::now) - } -} - impl MandateAmountData { pub fn get_end_date( &self, diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index cdc9103c86c..76434c50b4c 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -1,6 +1,8 @@ #[cfg(all(feature = "v1", feature = "olap"))] use api_models::enums::Connector; use common_enums as storage_enums; +#[cfg(feature = "v2")] +use common_types::payments as common_payments_types; #[cfg(feature = "v1")] use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool, @@ -440,8 +442,7 @@ pub struct PaymentAttempt { pub fingerprint_id: Option<String>, pub client_source: Option<String>, pub client_version: Option<String>, - // TODO: use a type here instead of value - pub customer_acceptance: Option<pii::SecretSerdeValue>, + pub customer_acceptance: Option<Secret<common_payments_types::CustomerAcceptance>>, /// The profile id for the payment attempt. This will be derived from payment intent. pub profile_id: id_type::ProfileId, /// The organization id for the payment attempt. This will be derived from payment intent. @@ -590,14 +591,7 @@ impl PaymentAttempt { charges: None, client_source: None, client_version: None, - customer_acceptance: request - .customer_acceptance - .as_ref() - .map(Encode::encode_to_value) - .transpose() - .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError) - .attach_printable("Unable to encode customer_acceptance")? - .map(Secret::new), + customer_acceptance: request.customer_acceptance.clone().map(Secret::new), profile_id: payment_intent.profile_id.clone(), organization_id: payment_intent.organization_id.clone(), payment_method_type: request.payment_method_type, diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index 06932fb1265..e811b872c8c 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -3,6 +3,7 @@ pub mod fraud_check; pub mod revenue_recovery; pub mod unified_authentication_service; use api_models::payments::{AdditionalPaymentData, RequestSurchargeDetails}; +use common_types::payments as common_payments_types; use common_utils::{consts, errors, ext_traits::OptionExt, id_type, pii, types::MinorUnit}; use diesel_models::{enums as storage_enums, types::OrderDetailsWithAmount}; use error_stack::ResultExt; @@ -46,7 +47,7 @@ pub struct PaymentsAuthorizeData { pub setup_future_usage: Option<storage_enums::FutureUsage>, pub mandate_id: Option<api_models::payments::MandateIds>, pub off_session: Option<bool>, - pub customer_acceptance: Option<mandates::CustomerAcceptance>, + pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, pub setup_mandate_details: Option<mandates::MandateData>, pub browser_info: Option<BrowserInformation>, pub order_details: Option<Vec<OrderDetailsWithAmount>>, @@ -478,7 +479,7 @@ pub struct CompleteAuthorizeData { pub connector_meta: Option<serde_json::Value>, pub complete_authorize_url: Option<String>, pub metadata: Option<serde_json::Value>, - pub customer_acceptance: Option<mandates::CustomerAcceptance>, + pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, // New amount for amount frame work pub minor_amount: MinorUnit, pub merchant_account_id: Option<Secret<String>>, @@ -969,7 +970,7 @@ pub struct SetupMandateRequestData { pub amount: Option<i64>, pub confirm: bool, pub statement_descriptor_suffix: Option<String>, - pub customer_acceptance: Option<mandates::CustomerAcceptance>, + pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, pub mandate_id: Option<api_models::payments::MandateIds>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 8ce212dd09b..e6c4ad8514f 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -230,6 +230,9 @@ Never share your secret api keys. Keep them guarded and secure. common_types::payments::StripeSplitPaymentRequest, common_types::domain::AdyenSplitData, common_types::domain::AdyenSplitItem, + common_types::payments::AcceptanceType, + common_types::payments::CustomerAcceptance, + common_types::payments::OnlineMandate, common_types::payments::XenditSplitRequest, common_types::payments::XenditSplitRoute, common_types::payments::XenditChargeResponseData, @@ -446,13 +449,10 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::PaymentMethodData, api_models::payments::PaymentMethodDataRequest, api_models::payments::MandateType, - api_models::payments::AcceptanceType, api_models::payments::MandateAmountData, - api_models::payments::OnlineMandate, api_models::payments::Card, api_models::payments::CardRedirectData, api_models::payments::CardToken, - api_models::payments::CustomerAcceptance, api_models::payments::PaymentsRequest, api_models::payments::PaymentsCreateRequest, api_models::payments::PaymentsUpdateRequest, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index d55d5829bd9..bdf63e1a1ee 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -181,6 +181,9 @@ Never share your secret api keys. Keep them guarded and secure. common_types::payments::SplitPaymentsRequest, common_types::payments::StripeSplitPaymentRequest, common_types::domain::AdyenSplitData, + common_types::payments::AcceptanceType, + common_types::payments::CustomerAcceptance, + common_types::payments::OnlineMandate, common_types::payments::XenditSplitRequest, common_types::payments::XenditSplitRoute, common_types::payments::XenditChargeResponseData, @@ -412,13 +415,10 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::PaymentMethodData, api_models::payments::PaymentMethodDataRequest, api_models::payments::MandateType, - api_models::payments::AcceptanceType, api_models::payments::MandateAmountData, - api_models::payments::OnlineMandate, api_models::payments::Card, api_models::payments::CardRedirectData, api_models::payments::CardToken, - api_models::payments::CustomerAcceptance, api_models::payments::ConnectorTokenDetails, api_models::payments::PaymentsRequest, api_models::payments::PaymentsResponse, diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index c2d2b33b28e..e8813fad688 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -1,6 +1,7 @@ use std::str::FromStr; use api_models::payments; +use common_types::payments as common_payments_types; use common_utils::{ crypto::Encryptable, date_time, @@ -765,16 +766,15 @@ impl ForeignTryFrom<(Option<MandateData>, Option<String>)> for Option<payments:: }, ))), }, - customer_acceptance: Some(payments::CustomerAcceptance { - acceptance_type: payments::AcceptanceType::Online, + customer_acceptance: Some(common_payments_types::CustomerAcceptance { + acceptance_type: common_payments_types::AcceptanceType::Online, accepted_at: mandate.customer_acceptance.accepted_at, - online: mandate - .customer_acceptance - .online - .map(|online| payments::OnlineMandate { + online: mandate.customer_acceptance.online.map(|online| { + common_payments_types::OnlineMandate { ip_address: Some(online.ip_address), user_agent: online.user_agent, - }), + } + }), }), update_mandate_id: None, }); diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index fc66f6489fe..1ff35bb5b7d 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -1,6 +1,7 @@ pub mod helpers; pub mod utils; use api_models::payments; +use common_types::payments as common_payments_types; use common_utils::{ext_traits::Encode, id_type}; use diesel_models::enums as storage_enums; use error_stack::{report, ResultExt}; @@ -445,5 +446,5 @@ pub trait MandateBehaviour { fn get_setup_mandate_details( &self, ) -> Option<&hyperswitch_domain_models::mandates::MandateData>; - fn get_customer_acceptance(&self) -> Option<payments::CustomerAcceptance>; + fn get_customer_acceptance(&self) -> Option<common_payments_types::CustomerAcceptance>; } diff --git a/crates/router/src/core/mandate/helpers.rs b/crates/router/src/core/mandate/helpers.rs index 14a733d2ebc..298c737c6db 100644 --- a/crates/router/src/core/mandate/helpers.rs +++ b/crates/router/src/core/mandate/helpers.rs @@ -1,5 +1,6 @@ use api_models::payments as api_payments; use common_enums::enums; +use common_types::payments as common_payments_types; use common_utils::errors::CustomResult; use diesel_models::Mandate; use error_stack::ResultExt; @@ -49,7 +50,7 @@ pub fn get_mandate_type( mandate_data: Option<api_payments::MandateData>, off_session: Option<bool>, setup_future_usage: Option<enums::FutureUsage>, - customer_acceptance: Option<api_payments::CustomerAcceptance>, + customer_acceptance: Option<common_payments_types::CustomerAcceptance>, token: Option<String>, payment_method: Option<enums::PaymentMethod>, ) -> CustomResult<Option<api::MandateTransactionType>, errors::ValidationError> { diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index e3fdf6e1cac..f10cabe4fbf 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -33,6 +33,7 @@ use api_models::{ payments::{self as payments_api}, }; pub use common_enums::enums::CallConnectorAction; +use common_types::payments as common_payments_types; use common_utils::{ ext_traits::{AsyncExt, StringExt}, id_type, pii, @@ -51,7 +52,7 @@ use hyperswitch_domain_models::payments::{ #[cfg(feature = "v2")] use hyperswitch_domain_models::router_response_types::RedirectForm; pub use hyperswitch_domain_models::{ - mandates::{CustomerAcceptance, MandateData}, + mandates::MandateData, payment_address::PaymentAddress, payments::{self as domain_payments, HeaderPayload}, router_data::{PaymentMethodToken, RouterData}, @@ -5959,7 +5960,7 @@ where pub mandate_connector: Option<MandateConnectorDetails>, pub currency: storage_enums::Currency, pub setup_mandate: Option<MandateData>, - pub customer_acceptance: Option<CustomerAcceptance>, + pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, pub address: PaymentAddress, pub token: Option<String>, pub token_data: Option<storage::PaymentTokenData>, diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index fa951af010d..2b681202743 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -13,13 +13,12 @@ pub mod setup_mandate_flow; pub mod update_metadata_flow; use async_trait::async_trait; +use common_types::payments::CustomerAcceptance; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] use hyperswitch_domain_models::router_flow_types::{ BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, RecoveryRecordBack, }; -use hyperswitch_domain_models::{ - mandates::CustomerAcceptance, router_request_types::PaymentsCaptureData, -}; +use hyperswitch_domain_models::router_request_types::PaymentsCaptureData; use crate::{ core::{ diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index ee27620917b..318e69d7aca 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -1,5 +1,6 @@ use async_trait::async_trait; use common_enums as enums; +use common_types::payments as common_payments_types; use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse; #[cfg(feature = "v2")] use hyperswitch_domain_models::payments::PaymentConfirmData; @@ -498,8 +499,8 @@ impl mandate::MandateBehaviour for types::PaymentsAuthorizeData { fn set_mandate_id(&mut self, new_mandate_id: Option<api_models::payments::MandateIds>) { self.mandate_id = new_mandate_id; } - fn get_customer_acceptance(&self) -> Option<api_models::payments::CustomerAcceptance> { - self.customer_acceptance.clone().map(From::from) + fn get_customer_acceptance(&self) -> Option<common_payments_types::CustomerAcceptance> { + self.customer_acceptance.clone() } } diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs index d4722a05c8d..a5bcdb4f55e 100644 --- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs +++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs @@ -1,4 +1,5 @@ use async_trait::async_trait; +use common_types::payments as common_payments_types; use router_env::logger; use super::{ConstructFlowSpecificData, Feature}; @@ -247,7 +248,7 @@ impl mandate::MandateBehaviour for types::SetupMandateRequestData { ) -> Option<&hyperswitch_domain_models::mandates::MandateData> { self.setup_mandate_details.as_ref() } - fn get_customer_acceptance(&self) -> Option<api_models::payments::CustomerAcceptance> { - self.customer_acceptance.clone().map(From::from) + fn get_customer_acceptance(&self) -> Option<common_payments_types::CustomerAcceptance> { + self.customer_acceptance.clone() } } diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs index 199b4faf629..3ce888e6574 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -11,16 +11,13 @@ use crate::{ core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, mandate::helpers as m_helpers, - payments::{ - self, helpers, operations, CustomerAcceptance, CustomerDetails, PaymentAddress, - PaymentData, - }, + payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, }, events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, services, types::{ - api::{self, PaymentIdTypeExt}, + api::{self, CustomerAcceptance, PaymentIdTypeExt}, domain, storage::{self, enums as storage_enums}, }, @@ -139,11 +136,8 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> payment_intent.customer_id.as_ref(), )) .await?; - let customer_acceptance: Option<CustomerAcceptance> = request - .customer_acceptance - .clone() - .map(From::from) - .or(payment_method_info + let customer_acceptance: Option<CustomerAcceptance> = + request.customer_acceptance.clone().or(payment_method_info .clone() .map(|pm| { pm.customer_acceptance diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 944f2852b18..4ee639f5f42 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -788,7 +788,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> mandate_id: mandate_id.clone(), mandate_connector, setup_mandate, - customer_acceptance: customer_acceptance.map(From::from), + customer_acceptance, token, address: unified_address, token_data, diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 68f1b9d9c15..bc88a4e0019 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -5,6 +5,7 @@ use api_models::{ payments::GetAddressFromPaymentMethodData, }; use async_trait::async_trait; +use common_types::payments as common_payments_types; use common_utils::{ ext_traits::{AsyncExt, Encode, ValueExt}, type_name, @@ -143,7 +144,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> id: profile_id.get_string_repr().to_owned(), })? }; - let customer_acceptance = request.customer_acceptance.clone().map(From::from); + let customer_acceptance = request.customer_acceptance.clone(); let recurring_details = request.recurring_details.clone(); @@ -1116,7 +1117,7 @@ impl PaymentCreate { payment_method_info: &Option<domain::PaymentMethod>, key_store: &domain::MerchantKeyStore, profile_id: common_utils::id_type::ProfileId, - customer_acceptance: &Option<payments::CustomerAcceptance>, + customer_acceptance: &Option<common_payments_types::CustomerAcceptance>, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<( storage::PaymentAttemptNew, diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index eaae9514912..ca8bef361c0 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -129,7 +129,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - let customer_acceptance = request.customer_acceptance.clone().map(From::from); + let customer_acceptance = request.customer_acceptance.clone(); let recurring_details = request.recurring_details.clone(); let mandate_type = m_helpers::get_mandate_type( diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 2ab004cccd1..59acc0c7d7a 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -15,6 +15,7 @@ use api_models::{ enums::{self as api_enums, CountryAlpha2}, routing::ConnectorSelection, }; +use common_types::payments as common_payments_types; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use common_utils::ext_traits::AsyncExt; use diesel_models::enums as storage_enums; @@ -208,10 +209,10 @@ pub fn make_dsl_input( .customer_acceptance .as_ref() .map(|customer_accept| match customer_accept.acceptance_type { - hyperswitch_domain_models::mandates::AcceptanceType::Online => { + common_payments_types::AcceptanceType::Online => { euclid_enums::MandateAcceptanceType::Online } - hyperswitch_domain_models::mandates::AcceptanceType::Offline => { + common_payments_types::AcceptanceType::Offline => { euclid_enums::MandateAcceptanceType::Offline } }) @@ -323,10 +324,10 @@ pub fn make_dsl_input( .customer_acceptance .as_ref() .map(|cat| match cat.acceptance_type { - hyperswitch_domain_models::mandates::AcceptanceType::Online => { + common_payments_types::AcceptanceType::Online => { euclid_enums::MandateAcceptanceType::Online } - hyperswitch_domain_models::mandates::AcceptanceType::Offline => { + common_payments_types::AcceptanceType::Offline => { euclid_enums::MandateAcceptanceType::Offline } }) diff --git a/crates/router/src/core/payments/routing/transformers.rs b/crates/router/src/core/payments/routing/transformers.rs index 026807f3976..7e667732249 100644 --- a/crates/router/src/core/payments/routing/transformers.rs +++ b/crates/router/src/core/payments/routing/transformers.rs @@ -1,6 +1,7 @@ use std::collections::HashMap; use api_models::{self, routing as routing_types}; +use common_types::payments as common_payments_types; use diesel_models::enums as storage_enums; use euclid::{enums as dsl_enums, frontend::ast as dsl_ast}; use kgraph_utils::types; @@ -31,11 +32,11 @@ impl ForeignFrom<storage_enums::CaptureMethod> for Option<dsl_enums::CaptureMeth } } -impl ForeignFrom<api_models::payments::AcceptanceType> for dsl_enums::MandateAcceptanceType { - fn foreign_from(from: api_models::payments::AcceptanceType) -> Self { +impl ForeignFrom<common_payments_types::AcceptanceType> for dsl_enums::MandateAcceptanceType { + fn foreign_from(from: common_payments_types::AcceptanceType) -> Self { match from { - api_models::payments::AcceptanceType::Online => Self::Online, - api_models::payments::AcceptanceType::Offline => Self::Offline, + common_payments_types::AcceptanceType::Online => Self::Online, + common_payments_types::AcceptanceType::Offline => Self::Offline, } } } diff --git a/crates/router/src/core/payments/session_operation.rs b/crates/router/src/core/payments/session_operation.rs index 3ed015309ea..d24845d4b59 100644 --- a/crates/router/src/core/payments/session_operation.rs +++ b/crates/router/src/core/payments/session_operation.rs @@ -4,7 +4,7 @@ pub use common_enums::enums::CallConnectorAction; use common_utils::id_type; use error_stack::ResultExt; pub use hyperswitch_domain_models::{ - mandates::{CustomerAcceptance, MandateData}, + mandates::MandateData, payment_address::PaymentAddress, payments::{HeaderPayload, PaymentIntentData}, router_data::{PaymentMethodToken, RouterData}, diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index f758066207f..b88476e19d8 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -168,7 +168,7 @@ where let customer_acceptance = save_payment_method_data .request .get_customer_acceptance() - .or(mandate_data_customer_acceptance.clone().map(From::from)) + .or(mandate_data_customer_acceptance.clone()) .map(|ca| ca.encode_to_value()) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 65f526af2e3..959c201bc7a 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -2754,24 +2754,8 @@ where }); let mandate_data = payment_data.get_setup_mandate().map(|d| api::MandateData { - customer_acceptance: d - .customer_acceptance - .clone() - .map(|d| api::CustomerAcceptance { - acceptance_type: match d.acceptance_type { - hyperswitch_domain_models::mandates::AcceptanceType::Online => { - api::AcceptanceType::Online - } - hyperswitch_domain_models::mandates::AcceptanceType::Offline => { - api::AcceptanceType::Offline - } - }, - accepted_at: d.accepted_at, - online: d.online.map(|d| api::OnlineMandate { - ip_address: d.ip_address, - user_agent: d.user_agent, - }), - }), + customer_acceptance: d.customer_acceptance.clone(), + mandate_type: d.mandate_type.clone().map(|d| match d { hyperswitch_domain_models::mandates::MandateDataType::MultiUse(Some(i)) => { api::MandateType::MultiUse(Some(api::MandateAmountData { diff --git a/crates/router/src/core/payments/vault_session.rs b/crates/router/src/core/payments/vault_session.rs index db77d6a9997..10b965786e5 100644 --- a/crates/router/src/core/payments/vault_session.rs +++ b/crates/router/src/core/payments/vault_session.rs @@ -4,7 +4,7 @@ pub use common_enums::enums::CallConnectorAction; use common_utils::id_type; use error_stack::ResultExt; pub use hyperswitch_domain_models::{ - mandates::{CustomerAcceptance, MandateData}, + mandates::MandateData, payment_address::PaymentAddress, payments::{HeaderPayload, PaymentIntentData}, router_data::{PaymentMethodToken, RouterData}, diff --git a/crates/router/src/services/kafka/payment_attempt.rs b/crates/router/src/services/kafka/payment_attempt.rs index f2c18ae9302..e7f55c51c0f 100644 --- a/crates/router/src/services/kafka/payment_attempt.rs +++ b/crates/router/src/services/kafka/payment_attempt.rs @@ -189,7 +189,7 @@ pub struct KafkaPaymentAttempt<'a> { pub authentication_connector: Option<String>, pub authentication_id: Option<String>, pub fingerprint_id: Option<String>, - pub customer_acceptance: Option<&'a masking::Secret<serde_json::Value>>, + pub customer_acceptance: Option<&'a masking::Secret<payments::CustomerAcceptance>>, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub charges: Option<payments::ConnectorChargeResponseData>, diff --git a/crates/router/src/services/kafka/payment_attempt_event.rs b/crates/router/src/services/kafka/payment_attempt_event.rs index e06f4e014dd..4fd411dfcf5 100644 --- a/crates/router/src/services/kafka/payment_attempt_event.rs +++ b/crates/router/src/services/kafka/payment_attempt_event.rs @@ -191,7 +191,7 @@ pub struct KafkaPaymentAttemptEvent<'a> { pub authentication_connector: Option<String>, pub authentication_id: Option<String>, pub fingerprint_id: Option<String>, - pub customer_acceptance: Option<&'a masking::Secret<serde_json::Value>>, + pub customer_acceptance: Option<&'a masking::Secret<payments::CustomerAcceptance>>, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub charges: Option<payments::ConnectorChargeResponseData>, diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs index 725a821eba1..62738680b1b 100644 --- a/crates/router/src/types/api/payments.rs +++ b/crates/router/src/types/api/payments.rs @@ -12,26 +12,27 @@ pub use api_models::{ ConnectorFeatureMatrixResponse, FeatureMatrixListResponse, FeatureMatrixRequest, }, payments::{ - AcceptanceType, Address, AddressDetails, Amount, AuthenticationForStartResponse, Card, - CryptoData, CustomerAcceptance, CustomerDetails, CustomerDetailsResponse, - HyperswitchVaultSessionDetails, MandateAmountData, MandateData, MandateTransactionType, - MandateType, MandateValidationFields, NextActionType, OnlineMandate, - OpenBankingSessionToken, PayLaterData, PaymentIdType, PaymentListConstraints, - PaymentListFilters, PaymentListFiltersV2, PaymentMethodData, PaymentMethodDataRequest, - PaymentMethodDataResponse, PaymentOp, PaymentRetrieveBody, - PaymentRetrieveBodyWithCredentials, PaymentsAggregateResponse, PaymentsApproveRequest, - PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsCompleteAuthorizeRequest, - PaymentsDynamicTaxCalculationRequest, PaymentsDynamicTaxCalculationResponse, - PaymentsExternalAuthenticationRequest, PaymentsIncrementalAuthorizationRequest, - PaymentsManualUpdateRequest, PaymentsPostSessionTokensRequest, - PaymentsPostSessionTokensResponse, PaymentsRedirectRequest, PaymentsRedirectionResponse, - PaymentsRejectRequest, PaymentsRequest, PaymentsResponse, PaymentsResponseForm, - PaymentsRetrieveRequest, PaymentsSessionRequest, PaymentsSessionResponse, - PaymentsStartRequest, PaymentsUpdateMetadataRequest, PaymentsUpdateMetadataResponse, - PgRedirectResponse, PhoneDetails, RedirectionResponse, SessionToken, UrlDetails, - VaultSessionDetails, VerifyRequest, VerifyResponse, VgsSessionDetails, WalletData, + Address, AddressDetails, Amount, AuthenticationForStartResponse, Card, CryptoData, + CustomerDetails, CustomerDetailsResponse, HyperswitchVaultSessionDetails, + MandateAmountData, MandateData, MandateTransactionType, MandateType, + MandateValidationFields, NextActionType, OpenBankingSessionToken, PayLaterData, + PaymentIdType, PaymentListConstraints, PaymentListFilters, PaymentListFiltersV2, + PaymentMethodData, PaymentMethodDataRequest, PaymentMethodDataResponse, PaymentOp, + PaymentRetrieveBody, PaymentRetrieveBodyWithCredentials, PaymentsAggregateResponse, + PaymentsApproveRequest, PaymentsCancelRequest, PaymentsCaptureRequest, + PaymentsCompleteAuthorizeRequest, PaymentsDynamicTaxCalculationRequest, + PaymentsDynamicTaxCalculationResponse, PaymentsExternalAuthenticationRequest, + PaymentsIncrementalAuthorizationRequest, PaymentsManualUpdateRequest, + PaymentsPostSessionTokensRequest, PaymentsPostSessionTokensResponse, + PaymentsRedirectRequest, PaymentsRedirectionResponse, PaymentsRejectRequest, + PaymentsRequest, PaymentsResponse, PaymentsResponseForm, PaymentsRetrieveRequest, + PaymentsSessionRequest, PaymentsSessionResponse, PaymentsStartRequest, + PaymentsUpdateMetadataRequest, PaymentsUpdateMetadataResponse, PgRedirectResponse, + PhoneDetails, RedirectionResponse, SessionToken, UrlDetails, VaultSessionDetails, + VerifyRequest, VerifyResponse, VgsSessionDetails, WalletData, }, }; +pub use common_types::payments::{AcceptanceType, CustomerAcceptance, OnlineMandate}; use error_stack::ResultExt; pub use hyperswitch_domain_models::router_flow_types::payments::{ Approve, Authorize, AuthorizeSessionToken, Balance, CalculateTax, Capture, CompleteAuthorize, diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 2e64b10c284..3a1c89a0168 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -398,25 +398,7 @@ impl ForeignFrom<storage_enums::MandateAmountData> for payments::MandateAmountDa impl ForeignFrom<payments::MandateData> for hyperswitch_domain_models::mandates::MandateData { fn foreign_from(d: payments::MandateData) -> Self { Self { - customer_acceptance: d.customer_acceptance.map(|d| { - hyperswitch_domain_models::mandates::CustomerAcceptance { - acceptance_type: match d.acceptance_type { - payments::AcceptanceType::Online => { - hyperswitch_domain_models::mandates::AcceptanceType::Online - } - payments::AcceptanceType::Offline => { - hyperswitch_domain_models::mandates::AcceptanceType::Offline - } - }, - accepted_at: d.accepted_at, - online: d - .online - .map(|d| hyperswitch_domain_models::mandates::OnlineMandate { - ip_address: d.ip_address, - user_agent: d.user_agent, - }), - } - }), + customer_acceptance: d.customer_acceptance, mandate_type: d.mandate_type.map(|d| match d { payments::MandateType::MultiUse(Some(i)) => { hyperswitch_domain_models::mandates::MandateDataType::MultiUse(Some(
2025-06-10T07:59:02Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - Moved `CustomerAcceptance`, `AcceptanceType`, `OnlineMandate` to `common_types` - Removed unnecessary conversions from the code - Changed `payment_attempt` domain model and diesel model in v2 to use strict type ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #8298 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> V1 Payments Create + Confirm Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_YYBHtW1Ed85InL1L2TfWTZRUY7LCQxWotVQnOt5WjlMF6pMzEakhdpCzkj1AYaIa' \ --data-raw '{ "amount": 180000, "currency": "EUR", "confirm": true, "capture_method": "automatic", "customer_id": "klarna", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "return_url": "https://google.com", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "setup_future_usage": "off_session", "business_country": "NL", "payment_method": "bank_redirect", "payment_method_type": "ideal", "payment_method_data": { "bank_redirect": { "ideal": { "country": "NL", "bank_name": "rabobank", "billing_details": { "billing_name": "John Doe", "email": "[email protected]" } } } }, "mandate_data": { "customer_acceptance": { "acceptance_type": "online", "accepted_at": "2022-09-10T10:11:12Z", "online": { "ip_address": "123.32.25.123", "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" } }, "mandate_type": { "single_use": { "amount": 6540, "currency": "EUR" } } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1, "account_name": "transaction_processing" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "en-GB", "color_depth": 24, "screen_height": 1117, "screen_width": 1728, "time_zone": -330, "java_enabled": true, "java_script_enabled": true, "device_model": "Macintosh", "os_type": "macOS", "os_version": "10.15.7" } }' ``` Response: ```json { "payment_id": "pay_8LTgSVkhEmehgtu1eIuJ", "merchant_id": "merchant_1750233210", "status": "requires_customer_action", "amount": 180000, "net_amount": 180000, "shipping_cost": null, "amount_capturable": 180000, "amount_received": 0, "connector": "stripe", "client_secret": "pay_8LTgSVkhEmehgtu1eIuJ_secret_kALuNnmlbaNEzyQJkeP5", "created": "2025-06-18T07:53:54.544Z", "currency": "EUR", "customer_id": "klarna", "customer": { "id": "klarna", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": "man_dotLdCpwGUyqeE3bJhvj", "mandate_data": { "update_mandate_id": null, "customer_acceptance": { "acceptance_type": "online", "accepted_at": "2022-09-10T10:11:12.000Z", "online": { "ip_address": "123.32.25.123", "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" } }, "mandate_type": { "single_use": { "amount": 6540, "currency": "EUR", "start_date": null, "end_date": null, "metadata": null } } }, ... } ``` V2 Payments Confirm Request: ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_0197821d2b14713291386704613637ad/confirm-intent' \ --header 'x-profile-id: pro_GiWMG7VDcuWfIrlReElL' \ --header 'x-client-secret: cs_0197821d2b227603bd66e184fe946484' \ --header 'Authorization: publishable-key=pk_dev_c28ad8ebb32e4f9c8ac1a84f221ec3e4,client-secret=cs_0197821d2b227603bd66e184fe946484' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_c28ad8ebb32e4f9c8ac1a84f221ec3e4' \ --data '{ "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "01", "card_exp_year": "26", "card_holder_name": "John Doe", "card_cvc": "123" } }, "payment_method_type": "card", "payment_method_subtype": "card", "customer_acceptance": { "acceptance_type": "online", "accepted_at": "2022-09-10T10:11:12Z", "online": { "ip_address": "123.32.25.123", "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" } } }' ``` Response ```json { "id": "12345_pay_0197821d2b14713291386704613637ad", "status": "succeeded", "amount": { "order_amount": 1000, "currency": "EUR", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 1000, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": 1000 }, "customer_id": "12345_cus_0197821d18d77ee183767e2baec9dc80", "connector": "stripe", "created": "2025-06-18T08:17:19.135Z", "payment_method_data": { "billing": null }, "payment_method_type": "card", "payment_method_subtype": "card", "connector_transaction_id": "pi_3RbHBPCuXDMKrYZe1NDYJ7TC", "connector_reference_id": null, "merchant_connector_id": "mca_uUOvCLZKNXK5LT8Ghr6T", "browser_info": null, "error": null, "shipping": null, "billing": null, "attempts": null, "connector_token_details": { "token": "pm_1RbHBPCuXDMKrYZeHuVQG7NM", "connector_token_request_reference_id": "lRI0TlJZTT5OjItgR2" }, "payment_method_id": "12345_pm_0197821d37f47203a783e419365ff252", "next_action": null, "return_url": "https://google.com/success", "authentication_type": "no_three_ds", "authentication_type_applied": "no_three_ds", "is_iframe_redirection_enabled": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
7338a8db8562bae749e32437fa36d8f036655fcd
7338a8db8562bae749e32437fa36d8f036655fcd
juspay/hyperswitch
juspay__hyperswitch-8297
Bug: [FEATURE] add Click To Pay feature for Trustpay Connector ### Feature Description add Click To Pay feature for Trustpay Connector ### Possible Implementation add Click To Pay feature for Trustpay Connector ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs index f59cbe3313d..de40805ad4e 100644 --- a/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs @@ -10,6 +10,7 @@ use common_utils::{ }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ + network_tokenization::NetworkTokenNumber, payment_method_data::{BankRedirectData, BankTransferData, Card, PaymentMethodData}, router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_request_types::{BrowserInformation, PaymentsPreProcessingData, ResponseId}, @@ -29,8 +30,9 @@ use serde::{Deserialize, Serialize}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{ - self, AddressDetailsData, BrowserInformationData, CardData, PaymentsAuthorizeRequestData, - PaymentsPreProcessingRequestData, RouterData as OtherRouterData, + self, AddressDetailsData, BrowserInformationData, CardData, NetworkTokenData, + PaymentsAuthorizeRequestData, PaymentsPreProcessingRequestData, + RouterData as OtherRouterData, }, }; @@ -226,6 +228,26 @@ pub enum TrustpayPaymentsRequest { CardsPaymentRequest(Box<PaymentRequestCards>), BankRedirectPaymentRequest(Box<PaymentRequestBankRedirect>), BankTransferPaymentRequest(Box<PaymentRequestBankTransfer>), + NetworkTokenPaymentRequest(Box<PaymentRequestNetworkToken>), +} + +#[derive(Debug, Serialize, PartialEq)] +pub struct PaymentRequestNetworkToken { + pub amount: StringMajorUnit, + pub currency: enums::Currency, + pub pan: NetworkTokenNumber, + #[serde(rename = "exp")] + pub expiry_date: Secret<String>, + #[serde(rename = "RedirectUrl")] + pub redirect_url: String, + #[serde(rename = "threeDSecureEnrollmentStatus")] + pub enrollment_status: char, + #[serde(rename = "threeDSecureEci")] + pub eci: String, + #[serde(rename = "threeDSecureAuthenticationStatus")] + pub authentication_status: char, + #[serde(rename = "threeDSecureVerificationId")] + pub verification_id: Secret<String>, } #[derive(Debug, Serialize, PartialEq)] @@ -538,6 +560,28 @@ impl TryFrom<&TrustpayRouterData<&PaymentsAuthorizeRouterData>> for TrustpayPaym auth, ) } + PaymentMethodData::NetworkToken(ref token_data) => { + Ok(Self::NetworkTokenPaymentRequest(Box::new( + PaymentRequestNetworkToken { + amount: item.amount.to_owned(), + currency: item.router_data.request.currency, + pan: token_data.get_network_token(), + expiry_date: token_data + .get_token_expiry_month_year_2_digit_with_delimiter("/".to_owned())?, + redirect_url: item.router_data.request.get_router_return_url()?, + enrollment_status: 'Y', // Set to 'Y' as network provider not providing this value in response + eci: token_data.eci.clone().ok_or_else(|| { + errors::ConnectorError::MissingRequiredField { field_name: "eci" } + })?, + authentication_status: 'Y', // Set to 'Y' since presence of token_cryptogram is already validated + verification_id: token_data.get_cryptogram().ok_or_else(|| { + errors::ConnectorError::MissingRequiredField { + field_name: "verification_id", + } + })?, + }, + ))) + } PaymentMethodData::CardRedirect(_) | PaymentMethodData::Wallet(_) | PaymentMethodData::PayLater(_) @@ -552,7 +596,6 @@ impl TryFrom<&TrustpayRouterData<&PaymentsAuthorizeRouterData>> for TrustpayPaym | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) - | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("trustpay"), diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index e23960e0566..165eb41f76a 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -5970,6 +5970,11 @@ pub trait NetworkTokenData { fn get_network_token_expiry_month(&self) -> Secret<String>; fn get_network_token_expiry_year(&self) -> Secret<String>; fn get_cryptogram(&self) -> Option<Secret<String>>; + fn get_token_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError>; + fn get_token_expiry_month_year_2_digit_with_delimiter( + &self, + delimiter: String, + ) -> Result<Secret<String>, errors::ConnectorError>; } impl NetworkTokenData for payment_method_data::NetworkTokenData { @@ -6040,6 +6045,56 @@ impl NetworkTokenData for payment_method_data::NetworkTokenData { fn get_cryptogram(&self) -> Option<Secret<String>> { self.cryptogram.clone() } + + #[cfg(feature = "v1")] + fn get_token_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> { + let binding = self.token_exp_year.clone(); + let year = binding.peek(); + Ok(Secret::new( + year.get(year.len() - 2..) + .ok_or(errors::ConnectorError::RequestEncodingFailed)? + .to_string(), + )) + } + + #[cfg(feature = "v2")] + fn get_token_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> { + let binding = self.network_token_exp_year.clone(); + let year = binding.peek(); + Ok(Secret::new( + year.get(year.len() - 2..) + .ok_or(errors::ConnectorError::RequestEncodingFailed)? + .to_string(), + )) + } + + #[cfg(feature = "v1")] + fn get_token_expiry_month_year_2_digit_with_delimiter( + &self, + delimiter: String, + ) -> Result<Secret<String>, errors::ConnectorError> { + let year = self.get_token_expiry_year_2_digit()?; + Ok(Secret::new(format!( + "{}{}{}", + self.token_exp_month.peek(), + delimiter, + year.peek() + ))) + } + + #[cfg(feature = "v2")] + fn get_token_expiry_month_year_2_digit_with_delimiter( + &self, + delimiter: String, + ) -> Result<Secret<String>, errors::ConnectorError> { + let year = self.get_token_expiry_year_2_digit()?; + Ok(Secret::new(format!( + "{}{}{}", + self.network_token_exp_month.peek(), + delimiter, + year.peek() + ))) + } } pub fn convert_uppercase<'de, D, T>(v: D) -> Result<T, D::Error>
2025-06-10T10:07:34Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD Closes this [issue](https://github.com/juspay/hyperswitch/issues/8297) ## Description <!-- Describe your changes in detail --> Added click to pay feature for Trustpay. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Postman Test 1. Payment Connector - Create (Trustpay) Request: ``` curl --location 'http://localhost:8080/account/merchant_1749546439/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: {{api-key}}' \ --data '{ "connector_type": "payment_processor", "connector_name": "trustpay", "connector_account_details": { "auth_type": "SignatureKey", "api_key": "API KEY", "key1": "KEY1", "api_secret": "API SECRET" }, "test_mode": true, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true, "accepted_countries": { "type": "disable_only", "list": [ "HK" ] }, "accepted_currencies": { "type": "enable_only", "list": [ "USD", "GBP", "INR" ] } }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true, "accepted_countries": { "type": "disable_only", "list": [ "HK" ] }, "accepted_currencies": { "type": "enable_only", "list": [ "USD", "GBP", "INR" ] } } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "city": "NY", "unit": "245" }, "connector_webhook_details": { "merchant_secret": "***" }, "business_country": "US", "business_label": "default" }' ``` Response: ``` { "connector_type": "payment_processor", "connector_name": "trustpay", "connector_label": "trustpay_US_default", "merchant_connector_id": "mca_v8hmmeB14qT4cMdRVueZ", "profile_id": "pro_xxUlbqufnXVCUkRP97xs", "connector_account_details": { "auth_type": "SignatureKey", "api_key": "****************************************************", "key1": "******", "api_secret": "****************************" }, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": { "type": "enable_only", "list": [ "USD", "GBP", "INR" ] }, "accepted_countries": { "type": "disable_only", "list": [ "HK" ] }, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": { "type": "enable_only", "list": [ "USD", "GBP", "INR" ] }, "accepted_countries": { "type": "disable_only", "list": [ "HK" ] }, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "connector_webhook_details": { "merchant_secret": "***", "additional_secret": null }, "metadata": { "city": "NY", "unit": "245" }, "test_mode": true, "disabled": false, "frm_configs": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "applepay_verified_domains": null, "pm_auth_config": null, "status": "active", "additional_merchant_data": null, "connector_wallets_details": null } ``` 2. Configs Request: ``` curl --location 'http://localhost:8080/configs' \ --header 'Content-Type: application/json' \ --header 'api-key: {{api-key}}' \ --data '{ "key": "merchants_eligible_for_authentication_service", "value": "[\"xyz\", \"merchant_1749546439\", \"dqwdwljildwduoqwhduwqcqwjd\"]" }' ``` 3. Create Merchant connector account for mastercard click to pay Request: ``` curl --location 'http://localhost:8080/account/dqwdwljildwduoqwhduwqcqwjd/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: {{api-key}}' \ --data ' { "connector_type": "authentication_processor", "connector_name": "ctp_mastercard", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "API-KEY" }, "test_mode": true, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "business_country": "US", "business_label": "default", "metadata": { "dpa_id": "DPA ID", "dpa_name": "TestMerchant", "locale": "en_AU", "card_brands": ["mastercard", "visa"], "acquirer_bin": "ACQUIRER BIN", "acquirer_merchant_id": "ACQUIRER MERCHANT ID", "merchant_category_code": "0001", "merchant_country_code": "US" } } ' ``` Response: ``` { "connector_type": "authentication_processor", "connector_name": "ctp_mastercard", "connector_label": "ctp_mastercard_US_default", "merchant_connector_id": "mca_yHkNx6WMa6GXtoVq3ezk", "profile_id": "pro_xxUlbqufnXVCUkRP97xs", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "********************************" }, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "connector_webhook_details": null, "metadata": { "dpa_id": "DPA ID", "locale": "en_AU", "dpa_name": "TestMerchant", "card_brands": [ "mastercard", "visa" ], "acquirer_bin": "ACQUIRER BIN", "acquirer_merchant_id": "ACQUIRER MERCHANT ID", "merchant_country_code": "US", "merchant_category_code": "0001" }, "test_mode": true, "disabled": false, "frm_configs": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "applepay_verified_domains": null, "pm_auth_config": null, "status": "active", "additional_merchant_data": null, "connector_wallets_details": null } ``` 4. Update business profile with ctp_mastercard mca_id Request: ``` curl --location 'http://localhost:8080/account/merchant_1749546439/business_profile/pro_xxUlbqufnXVCUkRP97xs' \ --header 'Content-Type: application/json' \ --header 'api-key: {{api-key}}' \ --data '{ "is_click_to_pay_enabled": true, "authentication_product_ids": {"click_to_pay": "mca_yHkNx6WMa6GXtoVq3ezk"} }' ``` Response: ``` { "merchant_id": "merchant_1749546439", "profile_id": "pro_xxUlbqufnXVCUkRP97xs", "profile_name": "US_default", "return_url": "https://google.com/success", "enable_payment_response_hash": true, "payment_response_hash_key": "***", "redirect_to_merchant_with_http_post": false, "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "***", "webhook_password": "***", "webhook_url": "https://webhook.site", "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "metadata": null, "routing_algorithm": null, "intent_fulfillment_time": 900, "frm_routing_algorithm": null, "payout_routing_algorithm": null, "applepay_verified_domains": null, "session_expiry": 900, "payment_link_config": null, "authentication_connector_details": null, "use_billing_as_payment_method_billing": true, "extended_card_info_config": null, "collect_shipping_details_from_wallet_connector": false, "collect_billing_details_from_wallet_connector": false, "always_collect_shipping_details_from_wallet_connector": false, "always_collect_billing_details_from_wallet_connector": false, "is_connector_agnostic_mit_enabled": false, "payout_link_config": null, "outgoing_webhook_custom_http_headers": null, "tax_connector_id": null, "is_tax_connector_enabled": false, "is_network_tokenization_enabled": false, "is_auto_retries_enabled": false, "max_auto_retries_enabled": null, "always_request_extended_authorization": null, "is_click_to_pay_enabled": true, "authentication_product_ids": { "click_to_pay": "mca_yHkNx6WMa6GXtoVq3ezk" }, "card_testing_guard_config": { "card_ip_blocking_status": "disabled", "card_ip_blocking_threshold": 3, "guest_user_card_blocking_status": "disabled", "guest_user_card_blocking_threshold": 10, "customer_id_blocking_status": "disabled", "customer_id_blocking_threshold": 5, "card_testing_guard_expiry": 3600 }, "is_clear_pan_retries_enabled": false, "force_3ds_challenge": false, "is_debit_routing_enabled": false, "merchant_business_country": null, "is_pre_network_tokenization_enabled": false } ``` 5. Payments - Create Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: {{api-key}}' \ --data-raw '{ "amount": 1130, "currency": "USD", "confirm": false, "return_url": "https://hyperswitch.io", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" } } ' ``` Response: ``` { "payment_id": "pay_1vu2W3eLWiCYnvO4xw9V", "merchant_id": "merchant_1749541493", "status": "requires_payment_method", "amount": 1130, "net_amount": 1130, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_1vu2W3eLWiCYnvO4xw9V_secret_nnQEs4RBqKBpiajfzOyx", "created": "2025-06-10T07:46:31.636Z", "currency": "USD", "customer_id": null, "customer": null, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://hyperswitch.io/", "authentication_type": null, "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_MhKcVLclOBPMduS23UEE", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-06-10T08:01:31.635Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-06-10T07:46:31.689Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` 6. Payments - Confirm Request: ``` curl --location 'http://localhost:8080/payments/pay_1vu2W3eLWiCYnvO4xw9V/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: {{publishable-key}}' \ --data ' { "payment_method": "card", "payment_method_type": "debit", "client_secret": "pay_1vu2W3eLWiCYnvO4xw9V_secret_nnQEs4RBqKBpiajfzOyx", "ctp_service_details" : { "merchant_transaction_id": "MERCHANT TRANSACTION ID", "correlation_id": "CORRELATION ID", "x_src_flow_id" : "X SRC FLOW ID" }, "browser_info": { "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "color_depth": 24, "java_enabled":true, "java_script_enabled": true, "language": "en-GB", "screen_height": 1440, "screen_width": 2560, "time_zone": -330, "user_agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Mobile Safari/537.36" } }' ``` Response: ``` { "payment_id": "pay_1vu2W3eLWiCYnvO4xw9V", "merchant_id": "merchant_1749541493", "status": "succeeded", "amount": 1130, "net_amount": 1130, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1130, "connector": "trustpay", "client_secret": "pay_1vu2W3eLWiCYnvO4xw9V_secret_nnQEs4RBqKBpiajfzOyx", "created": "2025-06-10T07:46:31.636Z", "currency": "USD", "customer_id": null, "customer": null, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": null, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://hyperswitch.io/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "***", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_MhKcVLclOBPMduS23UEE", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_IlgCBX2F3GYYHdL0gqGj", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": { "authentication_flow": null, "electronic_commerce_indicator": "06", "status": "success", "ds_transaction_id": null, "version": null, "error_code": null, "error_message": null }, "external_3ds_authentication_attempted": false, "expires_on": "2025-06-10T08:01:31.635Z", "fingerprint": null, "browser_info": { "os_type": null, "language": "en-GB", "time_zone": -330, "ip_address": "::1", "os_version": null, "user_agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Mobile Safari/537.36", "color_depth": 24, "device_model": null, "java_enabled": true, "screen_width": 2560, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 1440, "accept_language": "en", "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-06-10T07:47:18.148Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "click_to_pay", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Added support for network token payments through Trustpay, including 3DSecure authentication and expiry date handling. - Introduced standardized methods to format and retrieve two-digit expiry year and combined expiry month-year for network tokens. - **Bug Fixes** - Enhanced error handling for missing required fields in network token payment requests. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
v1.114.0
bc767b9131e2637ce90997da9018085d2dadb80b
bc767b9131e2637ce90997da9018085d2dadb80b
juspay/hyperswitch
juspay__hyperswitch-8288
Bug: [REFACTOR] Change refunds v2 list request verb Change refunds v2 list request verb from GET to POST
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index ab487354acd..0d27c061dc9 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -3365,7 +3365,7 @@ } }, "/v2/refunds/list": { - "get": { + "post": { "tags": [ "Refunds" ], diff --git a/crates/openapi/src/routes/refunds.rs b/crates/openapi/src/routes/refunds.rs index 6628d432203..f33369d3888 100644 --- a/crates/openapi/src/routes/refunds.rs +++ b/crates/openapi/src/routes/refunds.rs @@ -272,7 +272,7 @@ pub async fn refunds_retrieve() {} /// /// To list the refunds associated with a payment_id or with the merchant, if payment_id is not provided #[utoipa::path( - get, + post, path = "/v2/refunds/list", request_body=RefundListRequest, responses( diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 82c3e10105e..09e32e702bb 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1213,7 +1213,7 @@ impl Refunds { #[cfg(feature = "olap")] { route = - route.service(web::resource("/list").route(web::get().to(refunds::refunds_list))); + route.service(web::resource("/list").route(web::post().to(refunds::refunds_list))); } #[cfg(feature = "oltp")] {
2025-06-09T13:05:01Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Currently to list refunds in v2, we are using GET verb, but we are passing filters through body which is not correct. Since listing requests are generally GET requests, we pass filters through query params. In the current scenario, passing filters through query params may result in url length violation. Hence we are changing the route verb from GET to POST request. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Follow correct and semantic approach to list refunds in v2 apis. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Create some payments and refunds before hand. - List all refunds API call ``` curl --location 'http://localhost:8080/v2/refunds/list' \ --header 'x-profile-id: pro_hB6oV5vfIHyqUVw1aetw' \ --header 'Content-Type: application/json' \ --header 'Authorization: api-key=dev_iNC2eYPgqnHNYoFG44nlmpp3ofzZqQ4wPOcx9r7IONCidqNmbVRLwXZwgctSQn4m' \ --data '{ }' ``` - Response from the above call ``` { "count": 3, "total_count": 3, "data": [ { "id": "12345_ref_019754aecbb47921a9947612563466bd", "payment_id": "12345_pay_019754aeb06771c38815608e367ed6a2", "merchant_reference_id": "1749472431", "amount": 70, "currency": "EUR", "status": "pending", "reason": "CUSTOMER REQUEST", "metadata": { "foo": "bar" }, "error_details": { "code": "", "message": "" }, "created_at": "2025-06-09T12:33:51.053Z", "updated_at": "2025-06-09T12:33:51.363Z", "connector": "adyen", "profile_id": "pro_hB6oV5vfIHyqUVw1aetw", "merchant_connector_id": "mca_76RN9eoOT1pKjdBC8wU7", "connector_refund_reference_id": null }, { "id": "12345_ref_019754ad614b7122b3f9c2b7c0af3ffa", "payment_id": "12345_pay_019754acd9797072ad358e2ddc41594f", "merchant_reference_id": "1749472338", "amount": 720, "currency": "USD", "status": "pending", "reason": "CUSTOMER REQUEST", "metadata": { "foo": "bar" }, "error_details": { "code": "", "message": "" }, "created_at": "2025-06-09T12:32:18.275Z", "updated_at": "2025-06-09T12:33:11.264Z", "connector": "adyen", "profile_id": "pro_hB6oV5vfIHyqUVw1aetw", "merchant_connector_id": "mca_76RN9eoOT1pKjdBC8wU7", "connector_refund_reference_id": null }, { "id": "12345_ref_019754ad1149783385dda1328a50d9c9", "payment_id": "12345_pay_019754acd9797072ad358e2ddc41594f", "merchant_reference_id": "1749472318", "amount": 720, "currency": "USD", "status": "failed", "reason": "Paid by mistake", "metadata": { "foo": "bar" }, "error_details": { "code": "000", "message": "Invalid merchant refund reason, the only valid values are : [OTHER, RETURN, DUPLICATE, FRAUD, CUSTOMER REQUEST]" }, "created_at": "2025-06-09T12:31:57.817Z", "updated_at": "2025-06-09T12:31:58.211Z", "connector": "adyen", "profile_id": "pro_hB6oV5vfIHyqUVw1aetw", "merchant_connector_id": "mca_76RN9eoOT1pKjdBC8wU7", "connector_refund_reference_id": null } ] } ``` - List refund by payment id API Call ``` curl --location 'http://localhost:8080/v2/refunds/list' \ --header 'x-profile-id: pro_hB6oV5vfIHyqUVw1aetw' \ --header 'Content-Type: application/json' \ --header 'Authorization: api-key=dev_iNC2eYPgqnHNYoFG44nlmpp3ofzZqQ4wPOcx9r7IONCidqNmbVRLwXZwgctSQn4m' \ --data '{ "payment_id":"12345_pay_019754aeb06771c38815608e367ed6a2" }' ``` - Response from the above call ``` { "count": 1, "total_count": 1, "data": [ { "id": "12345_ref_019754aecbb47921a9947612563466bd", "payment_id": "12345_pay_019754aeb06771c38815608e367ed6a2", "merchant_reference_id": "1749472431", "amount": 70, "currency": "EUR", "status": "pending", "reason": "CUSTOMER REQUEST", "metadata": { "foo": "bar" }, "error_details": { "code": "", "message": "" }, "created_at": "2025-06-09T12:33:51.053Z", "updated_at": "2025-06-09T12:33:51.363Z", "connector": "adyen", "profile_id": "pro_hB6oV5vfIHyqUVw1aetw", "merchant_connector_id": "mca_76RN9eoOT1pKjdBC8wU7", "connector_refund_reference_id": null } ] } ``` - List refund by currencies API Call ``` curl --location 'http://localhost:8080/v2/refunds/list' \ --header 'x-profile-id: pro_hB6oV5vfIHyqUVw1aetw' \ --header 'Content-Type: application/json' \ --header 'Authorization: api-key=dev_iNC2eYPgqnHNYoFG44nlmpp3ofzZqQ4wPOcx9r7IONCidqNmbVRLwXZwgctSQn4m' \ --data '{ "currency":["EUR","USD"] }' ``` - Response from the above call ``` { "count": 3, "total_count": 3, "data": [ { "id": "12345_ref_019754aecbb47921a9947612563466bd", "payment_id": "12345_pay_019754aeb06771c38815608e367ed6a2", "merchant_reference_id": "1749472431", "amount": 70, "currency": "EUR", "status": "pending", "reason": "CUSTOMER REQUEST", "metadata": { "foo": "bar" }, "error_details": { "code": "", "message": "" }, "created_at": "2025-06-09T12:33:51.053Z", "updated_at": "2025-06-09T12:33:51.363Z", "connector": "adyen", "profile_id": "pro_hB6oV5vfIHyqUVw1aetw", "merchant_connector_id": "mca_76RN9eoOT1pKjdBC8wU7", "connector_refund_reference_id": null }, { "id": "12345_ref_019754ad614b7122b3f9c2b7c0af3ffa", "payment_id": "12345_pay_019754acd9797072ad358e2ddc41594f", "merchant_reference_id": "1749472338", "amount": 720, "currency": "USD", "status": "pending", "reason": "CUSTOMER REQUEST", "metadata": { "foo": "bar" }, "error_details": { "code": "", "message": "" }, "created_at": "2025-06-09T12:32:18.275Z", "updated_at": "2025-06-09T12:33:11.264Z", "connector": "adyen", "profile_id": "pro_hB6oV5vfIHyqUVw1aetw", "merchant_connector_id": "mca_76RN9eoOT1pKjdBC8wU7", "connector_refund_reference_id": null }, { "id": "12345_ref_019754ad1149783385dda1328a50d9c9", "payment_id": "12345_pay_019754acd9797072ad358e2ddc41594f", "merchant_reference_id": "1749472318", "amount": 720, "currency": "USD", "status": "failed", "reason": "Paid by mistake", "metadata": { "foo": "bar" }, "error_details": { "code": "000", "message": "Invalid merchant refund reason, the only valid values are : [OTHER, RETURN, DUPLICATE, FRAUD, CUSTOMER REQUEST]" }, "created_at": "2025-06-09T12:31:57.817Z", "updated_at": "2025-06-09T12:31:58.211Z", "connector": "adyen", "profile_id": "pro_hB6oV5vfIHyqUVw1aetw", "merchant_connector_id": "mca_76RN9eoOT1pKjdBC8wU7", "connector_refund_reference_id": null } ] } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
4c73d74889472c1185fa85658ab462ea37f31f84
4c73d74889472c1185fa85658ab462ea37f31f84
juspay/hyperswitch
juspay__hyperswitch-8281
Bug: [BUG] [JPMORGAN] 5xx during Payments Authorize and Void - Card expiry should be be `i32` and not `String` - Void has a set of enum values to be passed and not random String values
diff --git a/crates/hyperswitch_connectors/src/connectors/jpmorgan.rs b/crates/hyperswitch_connectors/src/connectors/jpmorgan.rs index 00e9fb35e8e..9783324c042 100644 --- a/crates/hyperswitch_connectors/src/connectors/jpmorgan.rs +++ b/crates/hyperswitch_connectors/src/connectors/jpmorgan.rs @@ -306,6 +306,16 @@ impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Jpmorgan { + fn build_request( + &self, + _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Err( + errors::ConnectorError::NotImplemented("Setup Mandate flow for JPMorgan".to_string()) + .into(), + ) + } } impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Jpmorgan { diff --git a/crates/hyperswitch_connectors/src/connectors/jpmorgan/transformers.rs b/crates/hyperswitch_connectors/src/connectors/jpmorgan/transformers.rs index 8497443fbb8..9f253c0ffb7 100644 --- a/crates/hyperswitch_connectors/src/connectors/jpmorgan/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/jpmorgan/transformers.rs @@ -1,5 +1,8 @@ +use std::str::FromStr; + use common_enums::enums::CaptureMethod; use common_utils::types::MinorUnit; +use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{AccessToken, ConnectorAuthType, RouterData}, @@ -12,7 +15,7 @@ use hyperswitch_domain_models::{ }, }; use hyperswitch_interfaces::errors; -use masking::Secret; +use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ @@ -102,8 +105,8 @@ pub struct JpmorganPaymentMethodType { #[derive(Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Expiry { - month: Secret<String>, - year: Secret<String>, + month: Secret<i32>, + year: Secret<i32>, } #[derive(Serialize, Debug, Default, Deserialize)] @@ -159,8 +162,15 @@ impl TryFrom<&JpmorganRouterData<&PaymentsAuthorizeRouterData>> for JpmorganPaym let merchant = JpmorganMerchant { merchant_software }; let expiry: Expiry = Expiry { - month: req_card.card_exp_month.clone(), - year: req_card.get_expiry_year_4_digit(), + month: Secret::new( + req_card + .card_exp_month + .peek() + .clone() + .parse::<i32>() + .change_context(errors::ConnectorError::RequestEncodingFailed)?, + ), + year: req_card.get_expiry_year_as_4_digit_i32()?, }; let account_number = Secret::new(req_card.card_number.to_string()); @@ -637,12 +647,47 @@ impl TryFrom<RefundsResponseRouterData<RSync, JpmorganRefundSyncResponse>> } } +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum ReversalReason { + NoResponse, + LateResponse, + UnableToDeliver, + CardDeclined, + MacNotVerified, + MacSyncError, + ZekSyncError, + SystemMalfunction, + SuspectedFraud, +} + +impl FromStr for ReversalReason { + type Err = error_stack::Report<errors::ConnectorError>; + + fn from_str(s: &str) -> Result<Self, Self::Err> { + match s.to_uppercase().as_str() { + "NO_RESPONSE" => Ok(Self::NoResponse), + "LATE_RESPONSE" => Ok(Self::LateResponse), + "UNABLE_TO_DELIVER" => Ok(Self::UnableToDeliver), + "CARD_DECLINED" => Ok(Self::CardDeclined), + "MAC_NOT_VERIFIED" => Ok(Self::MacNotVerified), + "MAC_SYNC_ERROR" => Ok(Self::MacSyncError), + "ZEK_SYNC_ERROR" => Ok(Self::ZekSyncError), + "SYSTEM_MALFUNCTION" => Ok(Self::SystemMalfunction), + "SUSPECTED_FRAUD" => Ok(Self::SuspectedFraud), + _ => Err(report!(errors::ConnectorError::InvalidDataFormat { + field_name: "cancellation_reason", + })), + } + } +} + #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct JpmorganCancelRequest { pub amount: Option<i64>, pub is_void: Option<bool>, - pub reversal_reason: Option<String>, + pub reversal_reason: Option<ReversalReason>, } impl TryFrom<JpmorganRouterData<&PaymentsCancelRouterData>> for JpmorganCancelRequest { @@ -651,7 +696,13 @@ impl TryFrom<JpmorganRouterData<&PaymentsCancelRouterData>> for JpmorganCancelRe Ok(Self { amount: item.router_data.request.amount, is_void: Some(true), - reversal_reason: item.router_data.request.cancellation_reason.clone(), + reversal_reason: item + .router_data + .request + .cancellation_reason + .as_ref() + .map(|reason| ReversalReason::from_str(reason)) + .transpose()?, }) } }
2025-06-08T17:53:11Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR fixes 5xx thrown by JPMorgan connector during payments authorize and void call. Connector expects the expiry month and year to be `i32` and not a `String` which is why it used to a 5xx due to deserialization failure. And for Void, the connector expects a limited set of values as cancellation reason. Passing values outside of those limited values results in a 5xx being thrown. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> This bug fix is done as a part of connector auditing for JPMorgan connector. Closes https://github.com/juspay/hyperswitch/issues/8281 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Fixed and ran Cypress tests against the connector. ![image](https://github.com/user-attachments/assets/036fb788-9d6d-4575-adf7-9e724556ae60) ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `just clippy && just clippy_v2` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
e58eeb1aa964c035af2e4fc54ad35adcc4dac157
e58eeb1aa964c035af2e4fc54ad35adcc4dac157
juspay/hyperswitch
juspay__hyperswitch-8277
Bug: [BUG] Unwanted country PM filters in Authorizedotnet ### Bug Description Country PM filters for payment processor authorizedotnet need to be removed as it is a global payment processor. ### Expected Behavior Payments with any billing country should be possible for authorizedotnet ### Actual Behavior Payments with billing country other than US or Canada lead to a payment failure. ### Steps To Reproduce Test Card Payments for authorizedotnet. ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 10038b3aca7..e5b8c09a1d9 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -366,11 +366,11 @@ debit = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, crypto_currency = { country = "US, CA, GB, AU, BR, MX, SG, PH, NZ, ZA, JP, AT, BE, HR, CY, EE, FI, FR, DE, GR, IE, IT, LV, LT, LU, MT, NL, PT, SK, SI, ES", currency = "USD, CAD, GBP, AUD, BRL, MXN, SGD, PHP, NZD, ZAR, JPY, EUR" } [pm_filters.authorizedotnet] -credit = { country = "US, CA", currency = "CAD,USD"} -debit = { country = "US, CA", currency = "CAD,USD"} -google_pay = {country = "AL,DZ,AS,AO,AG,AR,AU,AT,AZ,BH,BY,BE,BR,BG,CA,CL,CO,HR,CZ,DK,DO,EG,EE,FI,FR,DE,GR,HK,HU,IN,ID,IE,IL,IT,JP,JO,KZ,KE,KW,LV,LB,LT,LU,MY,MX,NL,NZ,NO,OM,PK,PA,PE,PH,PL,PT,QA,RO,RU,SA,SG,SK,ZA,ES,LK,SE,CH,TW,TH,TR,UA,AE,GB,US,UY,VN", currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD"} -apple_pay = {country = "AL,AR,AM,AU,AT,AZ,BH,BE,BG,BR,CA,CL,CO,CR,HR,CY,CZ,DK,DO,EC,SV,EE,FO,FI,FR,GE,DE,GR,GL,GG,GT,HN,HK,HU,IS,IE,IM,IL,IT,JP,KZ,KW,LV,LI,LT,LU,MO,MY,MT,MX,MD,MC,ME,MA,NL,NZ,NO,PA,PY,PE,PL,PT,QA,RO,RS,SA,SG,SK,SI,ZA,ES,SE,CH,TW,UA,AE,GB,US,UY,VN", currency = "EUR,GBP,ISK,USD,AUD,CAD,BRL,CLP,COP,CRC,CZK,DKK,EGP,GEL,GHS,GTQ,HNL,HKD,HUF,ILS,INR,JPY,KZT,KRW,KWD,MAD,MXN,MYR,NOK,NZD,PEN,PLN,PYG,QAR,RON,SAR,SEK,SGD,THB,TWD,UAH,AED,VND,ZAR"} -paypal = {country = "AD,AE,AG,AL,AM,AO,AR,AT,AU,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BM,BN,BO,BR,BS,BT,BW,BY,BZ,CA,CD,CF,CG,CH,CI,CL,CM,CN,CO,CR,CU,CV,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GH,GI,GM,GN,GP,GQ,GR,GT,GU,GW,GY,HK,HN,HR,HU,ID,IE,IL,IN,IO,IQ,IS,IT,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SY,SZ,TC,TD,TF,TG,TH,TJ,TK,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "AUD,BRL,CAD,CHF,CNY,CZK,DKK,EUR,GBP,HKD,HUF,ILS,JPY,MXN,MYR,NOK,NZD,PHP,PLN,SEK,SGD,THB,TWD,USD"} +credit = {currency = "CAD,USD"} +debit = {currency = "CAD,USD"} +google_pay = {currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD"} +apple_pay = {currency = "EUR,GBP,ISK,USD,AUD,CAD,BRL,CLP,COP,CRC,CZK,DKK,EGP,GEL,GHS,GTQ,HNL,HKD,HUF,ILS,INR,JPY,KZT,KRW,KWD,MAD,MXN,MYR,NOK,NZD,PEN,PLN,PYG,QAR,RON,SAR,SEK,SGD,THB,TWD,UAH,AED,VND,ZAR"} +paypal = {currency = "AUD,BRL,CAD,CHF,CNY,CZK,DKK,EUR,GBP,HKD,HUF,ILS,JPY,MXN,MYR,NOK,NZD,PHP,PLN,SEK,SGD,THB,TWD,USD"} [pm_filters.bambora] credit = { country = "US,CA", currency = "USD" } diff --git a/config/deployments/production.toml b/config/deployments/production.toml index f747d1f4518..9a0270fe500 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -380,11 +380,11 @@ debit = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, crypto_currency = { country = "US, CA, GB, AU, BR, MX, SG, PH, NZ, ZA, JP, AT, BE, HR, CY, EE, FI, FR, DE, GR, IE, IT, LV, LT, LU, MT, NL, PT, SK, SI, ES", currency = "USD, CAD, GBP, AUD, BRL, MXN, SGD, PHP, NZD, ZAR, JPY, EUR" } [pm_filters.authorizedotnet] -credit = { country = "US, CA", currency = "CAD,USD"} -debit = { country = "US, CA", currency = "CAD,USD"} -google_pay = {country = "AL,DZ,AS,AO,AG,AR,AU,AT,AZ,BH,BY,BE,BR,BG,CA,CL,CO,HR,CZ,DK,DO,EG,EE,FI,FR,DE,GR,HK,HU,IN,ID,IE,IL,IT,JP,JO,KZ,KE,KW,LV,LB,LT,LU,MY,MX,NL,NZ,NO,OM,PK,PA,PE,PH,PL,PT,QA,RO,RU,SA,SG,SK,ZA,ES,LK,SE,CH,TW,TH,TR,UA,AE,GB,US,UY,VN", currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD"} -apple_pay = {country = "AL,AR,AM,AU,AT,AZ,BH,BE,BG,BR,CA,CL,CO,CR,HR,CY,CZ,DK,DO,EC,SV,EE,FO,FI,FR,GE,DE,GR,GL,GG,GT,HN,HK,HU,IS,IE,IM,IL,IT,JP,KZ,KW,LV,LI,LT,LU,MO,MY,MT,MX,MD,MC,ME,MA,NL,NZ,NO,PA,PY,PE,PL,PT,QA,RO,RS,SA,SG,SK,SI,ZA,ES,SE,CH,TW,UA,AE,GB,US,UY,VN", currency = "EUR,GBP,ISK,USD,AUD,CAD,BRL,CLP,COP,CRC,CZK,DKK,EGP,GEL,GHS,GTQ,HNL,HKD,HUF,ILS,INR,JPY,KZT,KRW,KWD,MAD,MXN,MYR,NOK,NZD,PEN,PLN,PYG,QAR,RON,SAR,SEK,SGD,THB,TWD,UAH,AED,VND,ZAR"} -paypal = {country = "AD,AE,AG,AL,AM,AO,AR,AT,AU,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BM,BN,BO,BR,BS,BT,BW,BY,BZ,CA,CD,CF,CG,CH,CI,CL,CM,CN,CO,CR,CU,CV,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GH,GI,GM,GN,GP,GQ,GR,GT,GU,GW,GY,HK,HN,HR,HU,ID,IE,IL,IN,IO,IQ,IS,IT,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SY,SZ,TC,TD,TF,TG,TH,TJ,TK,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "AUD,BRL,CAD,CHF,CNY,CZK,DKK,EUR,GBP,HKD,HUF,ILS,JPY,MXN,MYR,NOK,NZD,PHP,PLN,SEK,SGD,THB,TWD,USD"} +credit = {currency = "CAD,USD"} +debit = {currency = "CAD,USD"} +google_pay = {currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD"} +apple_pay = {currency = "EUR,GBP,ISK,USD,AUD,CAD,BRL,CLP,COP,CRC,CZK,DKK,EGP,GEL,GHS,GTQ,HNL,HKD,HUF,ILS,INR,JPY,KZT,KRW,KWD,MAD,MXN,MYR,NOK,NZD,PEN,PLN,PYG,QAR,RON,SAR,SEK,SGD,THB,TWD,UAH,AED,VND,ZAR"} +paypal = {currency = "AUD,BRL,CAD,CHF,CNY,CZK,DKK,EUR,GBP,HKD,HUF,ILS,JPY,MXN,MYR,NOK,NZD,PHP,PLN,SEK,SGD,THB,TWD,USD"} [pm_filters.bambora] credit = { country = "US,CA", currency = "USD" } diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 13624a12e7c..4522e128707 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -389,11 +389,11 @@ debit = { country = "AE, AF, AL, AO, AR, AT, AU, AW, AZ, BA, BB, BD, BE, BG, BH, crypto_currency = { country = "US, CA, GB, AU, BR, MX, SG, PH, NZ, ZA, JP, AT, BE, HR, CY, EE, FI, FR, DE, GR, IE, IT, LV, LT, LU, MT, NL, PT, SK, SI, ES", currency = "USD, CAD, GBP, AUD, BRL, MXN, SGD, PHP, NZD, ZAR, JPY, EUR" } [pm_filters.authorizedotnet] -credit = { country = "US, CA", currency = "CAD,USD"} -debit = { country = "US, CA", currency = "CAD,USD"} -google_pay = {country = "AL,DZ,AS,AO,AG,AR,AU,AT,AZ,BH,BY,BE,BR,BG,CA,CL,CO,HR,CZ,DK,DO,EG,EE,FI,FR,DE,GR,HK,HU,IN,ID,IE,IL,IT,JP,JO,KZ,KE,KW,LV,LB,LT,LU,MY,MX,NL,NZ,NO,OM,PK,PA,PE,PH,PL,PT,QA,RO,RU,SA,SG,SK,ZA,ES,LK,SE,CH,TW,TH,TR,UA,AE,GB,US,UY,VN", currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD"} -apple_pay = {country = "AL,AR,AM,AU,AT,AZ,BH,BE,BG,BR,CA,CL,CO,CR,HR,CY,CZ,DK,DO,EC,SV,EE,FO,FI,FR,GE,DE,GR,GL,GG,GT,HN,HK,HU,IS,IE,IM,IL,IT,JP,KZ,KW,LV,LI,LT,LU,MO,MY,MT,MX,MD,MC,ME,MA,NL,NZ,NO,PA,PY,PE,PL,PT,QA,RO,RS,SA,SG,SK,SI,ZA,ES,SE,CH,TW,UA,AE,GB,US,UY,VN", currency = "EUR,GBP,ISK,USD,AUD,CAD,BRL,CLP,COP,CRC,CZK,DKK,EGP,GEL,GHS,GTQ,HNL,HKD,HUF,ILS,INR,JPY,KZT,KRW,KWD,MAD,MXN,MYR,NOK,NZD,PEN,PLN,PYG,QAR,RON,SAR,SEK,SGD,THB,TWD,UAH,AED,VND,ZAR"} -paypal = {country = "AD,AE,AG,AL,AM,AO,AR,AT,AU,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BM,BN,BO,BR,BS,BT,BW,BY,BZ,CA,CD,CF,CG,CH,CI,CL,CM,CN,CO,CR,CU,CV,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GH,GI,GM,GN,GP,GQ,GR,GT,GU,GW,GY,HK,HN,HR,HU,ID,IE,IL,IN,IO,IQ,IS,IT,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SY,SZ,TC,TD,TF,TG,TH,TJ,TK,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "AUD,BRL,CAD,CHF,CNY,CZK,DKK,EUR,GBP,HKD,HUF,ILS,JPY,MXN,MYR,NOK,NZD,PHP,PLN,SEK,SGD,THB,TWD,USD"} +credit = {currency = "CAD,USD"} +debit = {currency = "CAD,USD"} +google_pay = {currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD"} +apple_pay = {currency = "EUR,GBP,ISK,USD,AUD,CAD,BRL,CLP,COP,CRC,CZK,DKK,EGP,GEL,GHS,GTQ,HNL,HKD,HUF,ILS,INR,JPY,KZT,KRW,KWD,MAD,MXN,MYR,NOK,NZD,PEN,PLN,PYG,QAR,RON,SAR,SEK,SGD,THB,TWD,UAH,AED,VND,ZAR"} +paypal = {currency = "AUD,BRL,CAD,CHF,CNY,CZK,DKK,EUR,GBP,HKD,HUF,ILS,JPY,MXN,MYR,NOK,NZD,PHP,PLN,SEK,SGD,THB,TWD,USD"} [pm_filters.bambora] credit = { country = "US,CA", currency = "USD" } diff --git a/config/development.toml b/config/development.toml index a72dd2a1614..1194e0dbdef 100644 --- a/config/development.toml +++ b/config/development.toml @@ -745,11 +745,11 @@ instant_bank_transfer = { country = "CZ,SK,GB,AT,DE,IT", currency = "CZK, EUR, G sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT,GB", currency = "EUR" } [pm_filters.authorizedotnet] -credit = { country = "US, CA", currency = "CAD,USD"} -debit = { country = "US, CA", currency = "CAD,USD"} -google_pay = {country = "AL,DZ,AS,AO,AG,AR,AU,AT,AZ,BH,BY,BE,BR,BG,CA,CL,CO,HR,CZ,DK,DO,EG,EE,FI,FR,DE,GR,HK,HU,IN,ID,IE,IL,IT,JP,JO,KZ,KE,KW,LV,LB,LT,LU,MY,MX,NL,NZ,NO,OM,PK,PA,PE,PH,PL,PT,QA,RO,RU,SA,SG,SK,ZA,ES,LK,SE,CH,TW,TH,TR,UA,AE,GB,US,UY,VN", currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD"} -apple_pay = {country = "AL,AR,AM,AU,AT,AZ,BH,BE,BG,BR,CA,CL,CO,CR,HR,CY,CZ,DK,DO,EC,SV,EE,FO,FI,FR,GE,DE,GR,GL,GG,GT,HN,HK,HU,IS,IE,IM,IL,IT,JP,KZ,KW,LV,LI,LT,LU,MO,MY,MT,MX,MD,MC,ME,MA,NL,NZ,NO,PA,PY,PE,PL,PT,QA,RO,RS,SA,SG,SK,SI,ZA,ES,SE,CH,TW,UA,AE,GB,US,UY,VN", currency = "EUR,GBP,ISK,USD,AUD,CAD,BRL,CLP,COP,CRC,CZK,DKK,EGP,GEL,GHS,GTQ,HNL,HKD,HUF,ILS,INR,JPY,KZT,KRW,KWD,MAD,MXN,MYR,NOK,NZD,PEN,PLN,PYG,QAR,RON,SAR,SEK,SGD,THB,TWD,UAH,AED,VND,ZAR"} -paypal = {country = "AD,AE,AG,AL,AM,AO,AR,AT,AU,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BM,BN,BO,BR,BS,BT,BW,BY,BZ,CA,CD,CF,CG,CH,CI,CL,CM,CN,CO,CR,CU,CV,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GH,GI,GM,GN,GP,GQ,GR,GT,GU,GW,GY,HK,HN,HR,HU,ID,IE,IL,IN,IO,IQ,IS,IT,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SY,SZ,TC,TD,TF,TG,TH,TJ,TK,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "AUD,BRL,CAD,CHF,CNY,CZK,DKK,EUR,GBP,HKD,HUF,ILS,JPY,MXN,MYR,NOK,NZD,PHP,PLN,SEK,SGD,THB,TWD,USD"} +credit = {currency = "CAD,USD"} +debit = {currency = "CAD,USD"} +google_pay = {currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD"} +apple_pay = {currency = "EUR,GBP,ISK,USD,AUD,CAD,BRL,CLP,COP,CRC,CZK,DKK,EGP,GEL,GHS,GTQ,HNL,HKD,HUF,ILS,INR,JPY,KZT,KRW,KWD,MAD,MXN,MYR,NOK,NZD,PEN,PLN,PYG,QAR,RON,SAR,SEK,SGD,THB,TWD,UAH,AED,VND,ZAR"} +paypal = {currency = "AUD,BRL,CAD,CHF,CNY,CZK,DKK,EUR,GBP,HKD,HUF,ILS,JPY,MXN,MYR,NOK,NZD,PHP,PLN,SEK,SGD,THB,TWD,USD"} [pm_filters.worldpay] debit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" } diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 40ce9b8e68a..798b0952bfd 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -783,11 +783,11 @@ credit = {country = "AU,NZ,CN,HK,IN,LK,KR,MY,SG,GB,BE,FR,DE,IT,ME,NL,PL,ES,ZA,AR debit = {country = "AU,NZ,CN,HK,IN,LK,KR,MY,SG,GB,BE,FR,DE,IT,ME,NL,PL,ES,ZA,AR,BR,CO,MX,PA,UY,US,CA", currency = "AFN,ALL,DZD,AOA,ARS,AMD,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BYN,BZD,BMD,BTN,BOB,VES,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XAF,CLP,CNY,COP,KMF,CDF,CRC,HRK,CUP,CZK,DKK,DJF,DOP,XCD,EGP,ERN,ETB,EUR,FKP,FJD,XPF,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KGS,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,ANG,NZD,NIO,NGN,VUV,KPW,NOK,OMR,PKR,PAB,PGK,PYG,PEN,PHP,PLN,GBP,QAR,RON,RUB,RWF,SHP,SVC,WST,STN,SAR,RSD,SCR,SLL,SGD,SBD,SOS,ZAR,KRW,SSP,LKR,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,UGX,UAH,AED,USD,UYU,UZS,VND,XOF,YER,ZMW,ZWL"} [pm_filters.authorizedotnet] -credit = { country = "US, CA", currency = "CAD,USD"} -debit = { country = "US, CA", currency = "CAD,USD"} -google_pay = {country = "AL,DZ,AS,AO,AG,AR,AU,AT,AZ,BH,BY,BE,BR,BG,CA,CL,CO,HR,CZ,DK,DO,EG,EE,FI,FR,DE,GR,HK,HU,IN,ID,IE,IL,IT,JP,JO,KZ,KE,KW,LV,LB,LT,LU,MY,MX,NL,NZ,NO,OM,PK,PA,PE,PH,PL,PT,QA,RO,RU,SA,SG,SK,ZA,ES,LK,SE,CH,TW,TH,TR,UA,AE,GB,US,UY,VN", currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD"} -apple_pay = {country = "AL,AR,AM,AU,AT,AZ,BH,BE,BG,BR,CA,CL,CO,CR,HR,CY,CZ,DK,DO,EC,SV,EE,FO,FI,FR,GE,DE,GR,GL,GG,GT,HN,HK,HU,IS,IE,IM,IL,IT,JP,KZ,KW,LV,LI,LT,LU,MO,MY,MT,MX,MD,MC,ME,MA,NL,NZ,NO,PA,PY,PE,PL,PT,QA,RO,RS,SA,SG,SK,SI,ZA,ES,SE,CH,TW,UA,AE,GB,US,UY,VN", currency = "EUR,GBP,ISK,USD,AUD,CAD,BRL,CLP,COP,CRC,CZK,DKK,EGP,GEL,GHS,GTQ,HNL,HKD,HUF,ILS,INR,JPY,KZT,KRW,KWD,MAD,MXN,MYR,NOK,NZD,PEN,PLN,PYG,QAR,RON,SAR,SEK,SGD,THB,TWD,UAH,AED,VND,ZAR"} -paypal = {country = "AD,AE,AG,AL,AM,AO,AR,AT,AU,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BM,BN,BO,BR,BS,BT,BW,BY,BZ,CA,CD,CF,CG,CH,CI,CL,CM,CN,CO,CR,CU,CV,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GH,GI,GM,GN,GP,GQ,GR,GT,GU,GW,GY,HK,HN,HR,HU,ID,IE,IL,IN,IO,IQ,IS,IT,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SY,SZ,TC,TD,TF,TG,TH,TJ,TK,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "AUD,BRL,CAD,CHF,CNY,CZK,DKK,EUR,GBP,HKD,HUF,ILS,JPY,MXN,MYR,NOK,NZD,PHP,PLN,SEK,SGD,THB,TWD,USD"} +credit = {currency = "CAD,USD"} +debit = {currency = "CAD,USD"} +google_pay = {currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD"} +apple_pay = {currency = "EUR,GBP,ISK,USD,AUD,CAD,BRL,CLP,COP,CRC,CZK,DKK,EGP,GEL,GHS,GTQ,HNL,HKD,HUF,ILS,INR,JPY,KZT,KRW,KWD,MAD,MXN,MYR,NOK,NZD,PEN,PLN,PYG,QAR,RON,SAR,SEK,SGD,THB,TWD,UAH,AED,VND,ZAR"} +paypal = {currency = "AUD,BRL,CAD,CHF,CNY,CZK,DKK,EUR,GBP,HKD,HUF,ILS,JPY,MXN,MYR,NOK,NZD,PHP,PLN,SEK,SGD,THB,TWD,USD"} [pm_filters.braintree] credit = { country = "AD,AT,AU,BE,BG,CA,CH,CY,CZ,DE,DK,EE,ES,FI,FR,GB,GG,GI,GR,HK,HR,HU,IE,IM,IT,JE,LI,LT,LU,LV,MT,MC,MY,NL,NO,NZ,PL,PT,RO,SE,SG,SI,SK,SM,US", currency = "AED,AMD,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BIF,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CHF,CLP,CNY,COP,CRC,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,ISK,JMD,JPY,KES,KGS,KHR,KMF,KRW,KYD,KZT,LAK,LBP,LKR,LRD,LSL,MAD,MDL,MKD,MNT,MOP,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLL,SOS,SRD,STD,SVC,SYP,SZL,THB,TJS,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL"} diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 4e18ce3e43d..eb99fba72aa 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -512,11 +512,11 @@ trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NL,NZ,NO,PL,PT,ES,SE,CH,GB,US", currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" } [pm_filters.authorizedotnet] -credit = { country = "US, CA", currency = "CAD,USD"} -debit = { country = "US, CA", currency = "CAD,USD"} -google_pay = {country = "AL,DZ,AS,AO,AG,AR,AU,AT,AZ,BH,BY,BE,BR,BG,CA,CL,CO,HR,CZ,DK,DO,EG,EE,FI,FR,DE,GR,HK,HU,IN,ID,IE,IL,IT,JP,JO,KZ,KE,KW,LV,LB,LT,LU,MY,MX,NL,NZ,NO,OM,PK,PA,PE,PH,PL,PT,QA,RO,RU,SA,SG,SK,ZA,ES,LK,SE,CH,TW,TH,TR,UA,AE,GB,US,UY,VN", currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD"} -apple_pay = {country = "AL,AR,AM,AU,AT,AZ,BH,BE,BG,BR,CA,CL,CO,CR,HR,CY,CZ,DK,DO,EC,SV,EE,FO,FI,FR,GE,DE,GR,GL,GG,GT,HN,HK,HU,IS,IE,IM,IL,IT,JP,KZ,KW,LV,LI,LT,LU,MO,MY,MT,MX,MD,MC,ME,MA,NL,NZ,NO,PA,PY,PE,PL,PT,QA,RO,RS,SA,SG,SK,SI,ZA,ES,SE,CH,TW,UA,AE,GB,US,UY,VN", currency = "EUR,GBP,ISK,USD,AUD,CAD,BRL,CLP,COP,CRC,CZK,DKK,EGP,GEL,GHS,GTQ,HNL,HKD,HUF,ILS,INR,JPY,KZT,KRW,KWD,MAD,MXN,MYR,NOK,NZD,PEN,PLN,PYG,QAR,RON,SAR,SEK,SGD,THB,TWD,UAH,AED,VND,ZAR"} -paypal = {country = "AD,AE,AG,AL,AM,AO,AR,AT,AU,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BM,BN,BO,BR,BS,BT,BW,BY,BZ,CA,CD,CF,CG,CH,CI,CL,CM,CN,CO,CR,CU,CV,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GH,GI,GM,GN,GP,GQ,GR,GT,GU,GW,GY,HK,HN,HR,HU,ID,IE,IL,IN,IO,IQ,IS,IT,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SY,SZ,TC,TD,TF,TG,TH,TJ,TK,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "AUD,BRL,CAD,CHF,CNY,CZK,DKK,EUR,GBP,HKD,HUF,ILS,JPY,MXN,MYR,NOK,NZD,PHP,PLN,SEK,SGD,THB,TWD,USD"} +credit = {currency = "CAD,USD"} +debit = {currency = "CAD,USD"} +google_pay = {currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD"} +apple_pay = {currency = "EUR,GBP,ISK,USD,AUD,CAD,BRL,CLP,COP,CRC,CZK,DKK,EGP,GEL,GHS,GTQ,HNL,HKD,HUF,ILS,INR,JPY,KZT,KRW,KWD,MAD,MXN,MYR,NOK,NZD,PEN,PLN,PYG,QAR,RON,SAR,SEK,SGD,THB,TWD,UAH,AED,VND,ZAR"} +paypal = {currency = "AUD,BRL,CAD,CHF,CNY,CZK,DKK,EUR,GBP,HKD,HUF,ILS,JPY,MXN,MYR,NOK,NZD,PHP,PLN,SEK,SGD,THB,TWD,USD"} [pm_filters.forte] credit = { country = "US, CA", currency = "CAD,USD"}
2025-06-07T06:14:43Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Removed country PM filters for payment processor authorizedotnet. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [x] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/8277 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Test Any Payment on Authorizedotnet with Billing Country other than US/Canada Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "amount": 1234, "currency": "USD", "confirm": true, "customer_id": "Strustomewwr", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "02", "card_exp_year": "35", "card_holder_name": "John Doe", "card_cvc": "123" } }, "billing": { "address": { "first_name": "John", "last_name": "Doe", "line1": "Harrison Street", "city": "San Francisco", "state": "California", "zip": "94016", "country": "ID" } }, "metadata": { "count_tickets": 1, "transaction_number": "5590045" } }' ``` Response: ``` { "payment_id": "pay_WWS00coZ3l0Ka60YIRnR", "merchant_id": "merchant_1749276137", "status": "succeeded", "amount": 1234, "net_amount": 1234, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1234, "connector": "authorizedotnet", "client_secret": "pay_WWS00coZ3l0Ka60YIRnR_secret_wFydMj0boNTbiTmq839R", "created": "2025-06-07T06:16:14.824Z", "currency": "USD", "customer_id": "Strustomewwr", "customer": { "id": "Strustomewwr", "name": null, "email": null, "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "02", "card_exp_year": "35", "card_holder_name": "John Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Francisco", "country": "ID", "line1": "Harrison Street", "line2": null, "line3": null, "zip": "94016", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "Strustomewwr", "created_at": 1749276974, "expires": 1749280574, "secret": "epk_715cd374b7e8409fba550e3866c9dbc6" }, "manual_retry_allowed": false, "connector_transaction_id": "120064688104", "frm_message": null, "metadata": { "count_tickets": 1, "transaction_number": "5590045" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "120064688104", "payment_link": null, "profile_id": "pro_lZhF6us28eQOE1icJuYF", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_iQgBrM8isie20kKlZGth", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-06-07T06:31:14.824Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-06-07T06:16:15.357Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
cb3aba8d5a0ed7080af54d15d7690ad4115c8a3d
cb3aba8d5a0ed7080af54d15d7690ad4115c8a3d
juspay/hyperswitch
juspay__hyperswitch-8272
Bug: [BUG] styling for elements in payment links using dynamic classes ### Bug Description `payment_link_ui_rules` has a set of CSS selectors and CSS properties defined - which are selected using JS after rendering the elements and CSS styles are applied directly to the elements. This is only done once. Whenever something is added dynamically (after interaction with the elements) - it does not re-apply those styles. ### Expected Behavior Styling for UI elements in the payment links should work when using dynamic classes as well. ### Actual Behavior Styling for UI elements in the payment links does not work when using dynamic classes. ### Context For The Bug This bug exists since the `payment_link_ui_rules` are directly being applied to the elements which can be selected using the query selectors. Instead of doing this, these rules can directly be appended to the `style` tag. ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index c68771b7170..f3d1eb16998 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -15633,6 +15633,11 @@ "type": "boolean", "description": "Boolean to control payment button text for setup mandate calls", "nullable": true + }, + "color_icon_card_cvc_error": { + "type": "string", + "description": "Hex color for the CVC icon during error state", + "nullable": true } } }, @@ -15801,6 +15806,11 @@ "type": "boolean", "description": "Boolean to control payment button text for setup mandate calls", "nullable": true + }, + "color_icon_card_cvc_error": { + "type": "string", + "description": "Hex color for the CVC icon during error state", + "nullable": true } } }, diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index bf997d7feda..d67ea1ead23 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -17660,6 +17660,11 @@ "type": "boolean", "description": "Boolean to control payment button text for setup mandate calls", "nullable": true + }, + "color_icon_card_cvc_error": { + "type": "string", + "description": "Hex color for the CVC icon during error state", + "nullable": true } } }, @@ -17828,6 +17833,11 @@ "type": "boolean", "description": "Boolean to control payment button text for setup mandate calls", "nullable": true + }, + "color_icon_card_cvc_error": { + "type": "string", + "description": "Hex color for the CVC icon during error state", + "nullable": true } } }, diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index f4435b08fcd..1dbc372de79 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -2958,6 +2958,8 @@ pub struct PaymentLinkConfigRequest { pub show_card_terms: Option<api_enums::PaymentLinkShowSdkTerms>, /// Boolean to control payment button text for setup mandate calls pub is_setup_mandate_flow: Option<bool>, + /// Hex color for the CVC icon during error state + pub color_icon_card_cvc_error: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] @@ -3055,6 +3057,8 @@ pub struct PaymentLinkConfig { pub show_card_terms: Option<api_enums::PaymentLinkShowSdkTerms>, /// Boolean to control payment button text for setup mandate calls pub is_setup_mandate_flow: Option<bool>, + /// Hex color for the CVC icon during error state + pub color_icon_card_cvc_error: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)] diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index adbfb56c0fa..f9999ff25dc 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -8120,7 +8120,6 @@ pub struct PaymentLinkDetails { pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, - pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub status: api_enums::IntentStatus, pub enable_button_only_on_form_ready: bool, pub payment_form_header_text: Option<String>, @@ -8129,6 +8128,7 @@ pub struct PaymentLinkDetails { pub is_setup_mandate_flow: Option<bool>, pub capture_method: Option<common_enums::CaptureMethod>, pub setup_future_usage_applied: Option<common_enums::FutureUsage>, + pub color_icon_card_cvc_error: Option<String>, } #[derive(Debug, serde::Serialize, Clone)] @@ -8145,11 +8145,11 @@ pub struct SecurePaymentLinkDetails { pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, - pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub enable_button_only_on_form_ready: bool, pub payment_form_header_text: Option<String>, pub payment_form_label_type: Option<api_enums::PaymentLinkSdkLabelType>, pub show_card_terms: Option<api_enums::PaymentLinkShowSdkTerms>, + pub color_icon_card_cvc_error: Option<String>, } #[derive(Debug, serde::Serialize)] diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs index 0bc52b33189..9f13c720e49 100644 --- a/crates/diesel_models/src/business_profile.rs +++ b/crates/diesel_models/src/business_profile.rs @@ -770,6 +770,7 @@ pub struct PaymentLinkConfigRequest { pub payment_form_label_type: Option<common_enums::PaymentLinkSdkLabelType>, pub show_card_terms: Option<common_enums::PaymentLinkShowSdkTerms>, pub is_setup_mandate_flow: Option<bool>, + pub color_icon_card_cvc_error: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq)] diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index ae2710c50e9..fe28ee27369 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -209,6 +209,8 @@ pub struct PaymentLinkConfigRequestForPayments { pub show_card_terms: Option<common_enums::PaymentLinkShowSdkTerms>, /// Boolean to control payment button text for setup mandate calls pub is_setup_mandate_flow: Option<bool>, + /// Hex color for the CVC icon during error state + pub color_icon_card_cvc_error: Option<String>, } common_utils::impl_to_sql_from_sql_json!(PaymentLinkConfigRequestForPayments); diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs index eb37f8f45da..99ef5e3581f 100644 --- a/crates/hyperswitch_domain_models/src/lib.rs +++ b/crates/hyperswitch_domain_models/src/lib.rs @@ -432,6 +432,7 @@ impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkConfigRequest> payment_form_label_type: item.payment_form_label_type, show_card_terms: item.show_card_terms, is_setup_mandate_flow: item.is_setup_mandate_flow, + color_icon_card_cvc_error: item.color_icon_card_cvc_error, } } fn convert_back(self) -> api_models::admin::PaymentLinkConfigRequest { @@ -460,6 +461,7 @@ impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkConfigRequest> payment_form_label_type, show_card_terms, is_setup_mandate_flow, + color_icon_card_cvc_error, } = self; api_models::admin::PaymentLinkConfigRequest { theme, @@ -492,6 +494,7 @@ impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkConfigRequest> payment_form_label_type, show_card_terms, is_setup_mandate_flow, + color_icon_card_cvc_error, } } } diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rs index 545966968bd..923a7af9da8 100644 --- a/crates/router/src/core/payment_link.rs +++ b/crates/router/src/core/payment_link.rs @@ -1,4 +1,6 @@ pub mod validator; +use std::collections::HashMap; + use actix_web::http::header; use api_models::{ admin::PaymentLinkConfig, @@ -142,6 +144,7 @@ pub async fn form_payment_link_data( payment_form_label_type: None, show_card_terms: None, is_setup_mandate_flow: None, + color_icon_card_cvc_error: None, } }; @@ -316,13 +319,13 @@ pub async fn form_payment_link_data( background_colour: payment_link_config.background_colour.clone(), payment_button_text_colour: payment_link_config.payment_button_text_colour.clone(), sdk_ui_rules: payment_link_config.sdk_ui_rules.clone(), - payment_link_ui_rules: payment_link_config.payment_link_ui_rules.clone(), status: payment_intent.status, enable_button_only_on_form_ready: payment_link_config.enable_button_only_on_form_ready, payment_form_header_text: payment_link_config.payment_form_header_text.clone(), payment_form_label_type: payment_link_config.payment_form_label_type, show_card_terms: payment_link_config.show_card_terms, is_setup_mandate_flow: payment_link_config.is_setup_mandate_flow, + color_icon_card_cvc_error: payment_link_config.color_icon_card_cvc_error.clone(), capture_method: payment_attempt.capture_method, setup_future_usage_applied: payment_attempt.setup_future_usage_applied, }; @@ -350,7 +353,7 @@ pub async fn initiate_secure_payment_link_flow( &payment_link_config, )?; - let css_script = get_color_scheme_css(&payment_link_config); + let css_script = get_payment_link_css_script(&payment_link_config)?; match payment_link_details { PaymentLinkData::PaymentLinkStatusDetails(ref status_details) => { @@ -380,12 +383,12 @@ pub async fn initiate_secure_payment_link_flow( background_colour: payment_link_config.background_colour, payment_button_text_colour: payment_link_config.payment_button_text_colour, sdk_ui_rules: payment_link_config.sdk_ui_rules, - payment_link_ui_rules: payment_link_config.payment_link_ui_rules, enable_button_only_on_form_ready: payment_link_config .enable_button_only_on_form_ready, payment_form_header_text: payment_link_config.payment_form_header_text, payment_form_label_type: payment_link_config.payment_form_label_type, show_card_terms: payment_link_config.show_card_terms, + color_icon_card_cvc_error: payment_link_config.color_icon_card_cvc_error, }; let payment_details_str = serde_json::to_string(&secure_payment_link_details) .change_context(errors::ApiErrorResponse::InternalServerError) @@ -446,7 +449,7 @@ pub async fn initiate_payment_link_flow( let (_, payment_details, payment_link_config) = form_payment_link_data(&state, merchant_context, merchant_id, payment_id).await?; - let css_script = get_color_scheme_css(&payment_link_config); + let css_script = get_payment_link_css_script(&payment_link_config)?; let js_script = get_js_script(&payment_details)?; match payment_details { @@ -494,6 +497,85 @@ fn get_js_script(payment_details: &PaymentLinkData) -> RouterResult<String> { Ok(format!("window.__PAYMENT_DETAILS = '{url_encoded_str}';")) } +fn camel_to_kebab(s: &str) -> String { + let mut result = String::new(); + if s.is_empty() { + return result; + } + + let chars: Vec<char> = s.chars().collect(); + + for (i, &ch) in chars.iter().enumerate() { + if ch.is_uppercase() { + let should_add_dash = i > 0 + && (chars.get(i - 1).map(|c| c.is_lowercase()).unwrap_or(false) + || (i + 1 < chars.len() + && chars.get(i + 1).map(|c| c.is_lowercase()).unwrap_or(false) + && chars.get(i - 1).map(|c| c.is_uppercase()).unwrap_or(false))); + + if should_add_dash { + result.push('-'); + } + result.push(ch.to_ascii_lowercase()); + } else { + result.push(ch); + } + } + result +} + +fn generate_dynamic_css( + rules: &HashMap<String, HashMap<String, String>>, +) -> Result<String, errors::ApiErrorResponse> { + if rules.is_empty() { + return Ok(String::new()); + } + + let mut css_string = String::new(); + css_string.push_str("/* Dynamically Injected UI Rules */\n"); + + for (selector, styles_map) in rules { + if selector.trim().is_empty() { + return Err(errors::ApiErrorResponse::InvalidRequestData { + message: "CSS selector cannot be empty.".to_string(), + }); + } + + css_string.push_str(selector); + css_string.push_str(" {\n"); + + for (prop_camel_case, css_value) in styles_map { + let css_property = camel_to_kebab(prop_camel_case); + + css_string.push_str(" "); + css_string.push_str(&css_property); + css_string.push_str(": "); + css_string.push_str(css_value); + css_string.push_str(";\n"); + } + css_string.push_str("}\n"); + } + Ok(css_string) +} + +fn get_payment_link_css_script( + payment_link_config: &PaymentLinkConfig, +) -> Result<String, errors::ApiErrorResponse> { + let custom_rules_css_option = payment_link_config + .payment_link_ui_rules + .as_ref() + .map(generate_dynamic_css) + .transpose()?; + + let color_scheme_css = get_color_scheme_css(payment_link_config); + + if let Some(custom_rules_css) = custom_rules_css_option { + Ok(format!("{}\n{}", color_scheme_css, custom_rules_css)) + } else { + Ok(color_scheme_css) + } +} + fn get_color_scheme_css(payment_link_config: &PaymentLinkConfig) -> String { let background_primary_color = payment_link_config .background_colour @@ -706,6 +788,7 @@ pub fn get_payment_link_config_based_on_priority( payment_form_label_type, show_card_terms, is_setup_mandate_flow, + color_icon_card_cvc_error, ) = get_payment_link_config_value!( payment_create_link_config, business_theme_configs, @@ -724,6 +807,7 @@ pub fn get_payment_link_config_based_on_priority( (payment_form_label_type), (show_card_terms), (is_setup_mandate_flow), + (color_icon_card_cvc_error), ); let payment_link_config = @@ -756,6 +840,7 @@ pub fn get_payment_link_config_based_on_priority( payment_form_label_type, show_card_terms, is_setup_mandate_flow, + color_icon_card_cvc_error, }; Ok((payment_link_config, domain_name)) @@ -870,6 +955,7 @@ pub async fn get_payment_link_status( payment_form_label_type: None, show_card_terms: None, is_setup_mandate_flow: None, + color_icon_card_cvc_error: None, } }; diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.css b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.css index f58617261d6..37d132fff3a 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.css +++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.css @@ -653,7 +653,7 @@ body { } #submit.not-ready { - background-color: #C2C2C2 !important; + background-color: #C2C2C2; } #submit-spinner { diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js index 1e96731402f..81bda59a0d5 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js +++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js @@ -291,12 +291,6 @@ function boot() { // Add event listeners initializeEventListeners(paymentDetails); - // Update payment link styles - var paymentLinkUiRules = paymentDetails.payment_link_ui_rules; - if (isObject(paymentLinkUiRules)) { - updatePaymentLinkUi(paymentLinkUiRules); - } - // Initialize SDK // @ts-ignore if (window.Hyper) { @@ -358,11 +352,11 @@ function initializeEventListeners(paymentDetails) { if (payNowButtonText) { if (paymentDetails.payment_button_text) { payNowButtonText.textContent = paymentDetails.payment_button_text; - } else if (paymentDetails.is_setup_mandate_flow || (paymentDetails.amount==="0.00" && paymentDetails.setup_future_usage_applied ==="off_session")) { + } else if (paymentDetails.is_setup_mandate_flow || (paymentDetails.amount === "0.00" && paymentDetails.setup_future_usage_applied === "off_session")) { payNowButtonText.textContent = translations.addPaymentMethod; } else { - payNowButtonText.textContent = capture_type === "manual" ? translations.authorizePayment: translations.payNow; - + payNowButtonText.textContent = capture_type === "manual" ? translations.authorizePayment : translations.payNow; + } } @@ -1214,25 +1208,4 @@ function renderSDKHeader(paymentDetails) { // sdkHeaderNode.append(sdkHeaderLogoNode); sdkHeaderNode.append(sdkHeaderItemNode); } -} - -/** - * Trigger - post UI render - * Use - add CSS rules for the payment link - * @param {Object} paymentLinkUiRules - */ -function updatePaymentLinkUi(paymentLinkUiRules) { - Object.keys(paymentLinkUiRules).forEach(function (selector) { - try { - var node = document.querySelector(selector); - if (node instanceof HTMLElement) { - var styles = paymentLinkUiRules[selector]; - Object.keys(styles).forEach(function (property) { - node.style[property] = styles[property]; - }); - } - } catch (error) { - console.error("Failed to apply styles to selector", selector, error); - } - }) } \ No newline at end of file diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js index 33758131aa2..3c4e0d2549a 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js +++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js @@ -14,6 +14,7 @@ function initializeSDK() { var clientSecret = paymentDetails.client_secret; var sdkUiRules = paymentDetails.sdk_ui_rules; var labelType = paymentDetails.payment_form_label_type; + var colorIconCardCvcError = paymentDetails.color_icon_card_cvc_error; var appearance = { variables: { colorPrimary: paymentDetails.theme || "rgb(0, 109, 249)", @@ -33,6 +34,9 @@ function initializeSDK() { if (labelType !== null && typeof labelType === "string") { appearance.labels = labelType; } + if (colorIconCardCvcError !== null && typeof colorIconCardCvcError === "string") { + appearance.variables.colorIconCardCvcError = colorIconCardCvcError; + } // @ts-ignore hyper = window.Hyper(pub_key, { isPreloadEnabled: false, diff --git a/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js b/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js index 3db5eb94de2..c539363c102 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js +++ b/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js @@ -34,6 +34,7 @@ if (!isFramed) { var clientSecret = paymentDetails.client_secret; var sdkUiRules = paymentDetails.sdk_ui_rules; var labelType = paymentDetails.payment_form_label_type; + var colorIconCardCvcError = paymentDetails.color_icon_card_cvc_error; var appearance = { variables: { colorPrimary: paymentDetails.theme || "rgb(0, 109, 249)", @@ -53,6 +54,9 @@ if (!isFramed) { if (labelType !== null && typeof labelType === "string") { appearance.labels = labelType; } + if (colorIconCardCvcError !== null && typeof colorIconCardCvcError === "string") { + appearance.variables.colorIconCardCvcError = colorIconCardCvcError; + } // @ts-ignore hyper = window.Hyper(pub_key, { isPreloadEnabled: false, diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 4dff52acb4c..b9f6e6e5efe 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -4967,6 +4967,7 @@ impl ForeignFrom<api_models::admin::PaymentLinkConfigRequest> payment_form_label_type: config.payment_form_label_type, show_card_terms: config.show_card_terms, is_setup_mandate_flow: config.is_setup_mandate_flow, + color_icon_card_cvc_error: config.color_icon_card_cvc_error, } } } @@ -5042,6 +5043,7 @@ impl ForeignFrom<diesel_models::PaymentLinkConfigRequestForPayments> payment_form_label_type: config.payment_form_label_type, show_card_terms: config.show_card_terms, is_setup_mandate_flow: config.is_setup_mandate_flow, + color_icon_card_cvc_error: config.color_icon_card_cvc_error, } } } diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index e1607c3b6b2..7e504413e57 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -2235,6 +2235,7 @@ impl ForeignFrom<api_models::admin::PaymentLinkConfigRequest> payment_form_label_type: item.payment_form_label_type, show_card_terms: item.show_card_terms, is_setup_mandate_flow: item.is_setup_mandate_flow, + color_icon_card_cvc_error: item.color_icon_card_cvc_error, } } } @@ -2270,6 +2271,7 @@ impl ForeignFrom<diesel_models::business_profile::PaymentLinkConfigRequest> payment_form_label_type: item.payment_form_label_type, show_card_terms: item.show_card_terms, is_setup_mandate_flow: item.is_setup_mandate_flow, + color_icon_card_cvc_error: item.color_icon_card_cvc_error, } } }
2025-06-06T08:16:38Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR introduces - modification of the behavior of appending the `payment_link_ui_rules` to the CSS instead of selecting and applying it to the retrieved elements at runtime. - expose `color_icon_card_cvc_error` via API for SDK variables ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context This change allows for styling the payment link UI elements using CSS rules. ## How did you test it? Steps for testing - <details> <summary>1. Create a payment link with dynamic selectors in `payment_link_ui_rules`</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_mCD2MU1TfvKQkyMLkTKg6aeNkN8JHVGSllEqGrC0wbSnWNMtGmzrgYPFMwlx8Atl' \ --data-raw '{"authentication_type":"three_ds","customer_id":"cus_Qy5sr7VpE3tRoUh7M1W1","profile_id":"pro_A69LEikrut4ROWAXoTnm","customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"amount":0,"currency":"USD","confirm":false,"payment_link":true,"session_expiry":12600,"billing":{"address":{},"email":"[email protected]"},"return_url":"https://www.example.com","payment_link_config":{"logo":"https://hyperswitch.io/favicon.ico","display_sdk_only":true,"payment_button_text":"Save Card","enable_button_only_on_form_ready":true,"color_icon_card_cvc_error":"#CB4B40","payment_link_ui_rules":{"#submit":{"color":"#ffffff !important","border":"1px solid #b2b2b2 !important","borderRadius":"0 !important","fontSize":"13px !important","backgroundColor":"#b2b2b2 !important","height":"25px !important","width":"max-content !important","padding":"0 8px","margin":"0 4px 0 auto"},"#submit.not-ready":{"color":"#b2b2b2 !important","border":"1px solid #b2b2b2 !important","backgroundColor":"#ffffff !important"},"#submit-spinner":{"width":"20px !important","height":"20px !important","border":"2px solid #fff !important","borderBottomColor":"#c2c2c2 !important"}},"background_image":{"url":"https://img.freepik.com/free-photo/abstract-blue-geometric-shapes-background_24972-1841.jpg","position":"bottom","size":"cover"}}}' </details> <details> <summary>2. Open the payment link and fill in the form (Save Card button's color should update)</summary> <img width="589" alt="Screenshot 2025-06-06 at 1 49 47 PM" src="https://github.com/user-attachments/assets/918e152b-0ac0-4a81-860f-2a7740ef8d6b" /> <img width="605" alt="Screenshot 2025-06-06 at 1 49 53 PM" src="https://github.com/user-attachments/assets/e243b8a0-3be8-45b7-ae40-dd37dbacf15a" /> </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
4fa7b12400b31396de0ace295118dc7192245bb1
4fa7b12400b31396de0ace295118dc7192245bb1
juspay/hyperswitch
juspay__hyperswitch-8254
Bug: feat(router): Include `payment_experience` in PML for payments response (v2) Required by SDK
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index e3b41ce3899..6e1c321d250 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -21692,6 +21692,14 @@ "payment_method_subtype": { "$ref": "#/components/schemas/PaymentMethodType" }, + "payment_experience": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentExperience" + } + ], + "nullable": true + }, "required_fields": { "allOf": [ { diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 7ab8bc19361..adbfb56c0fa 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -7605,6 +7605,10 @@ pub struct ResponsePaymentMethodTypesForPayments { #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, + /// The payment experience for the payment method + #[schema(value_type = Option<PaymentExperience>)] + pub payment_experience: Option<common_enums::PaymentExperience>, + /// payment method subtype specific information #[serde(flatten)] #[schema(value_type = Option<PaymentMethodSubtypeSpecificData>)] diff --git a/crates/router/src/core/payments/payment_methods.rs b/crates/router/src/core/payments/payment_methods.rs index 887bd078914..208333ba0b2 100644 --- a/crates/router/src/core/payments/payment_methods.rs +++ b/crates/router/src/core/payments/payment_methods.rs @@ -87,6 +87,9 @@ impl FilteredPaymentMethodsEnabled { payment_method_subtype: payment_methods_enabled .payment_methods_enabled .payment_method_subtype, + payment_experience: payment_methods_enabled + .payment_methods_enabled + .payment_experience, }, ) .collect(); @@ -100,6 +103,7 @@ struct RequiredFieldsForEnabledPaymentMethod { required_field: Option<Vec<api_models::payment_methods::RequiredFieldInfo>>, payment_method_subtype: common_enums::PaymentMethodType, payment_method_type: common_enums::PaymentMethod, + payment_experience: Option<common_enums::PaymentExperience>, } /// Container to hold the filtered payment methods enabled with required fields @@ -110,6 +114,7 @@ struct RequiredFieldsAndSurchargeForEnabledPaymentMethodType { required_field: Option<Vec<api_models::payment_methods::RequiredFieldInfo>>, payment_method_subtype: common_enums::PaymentMethodType, payment_method_type: common_enums::PaymentMethod, + payment_experience: Option<common_enums::PaymentExperience>, surcharge: Option<api_models::payment_methods::SurchargeDetailsResponse>, } @@ -127,6 +132,7 @@ impl RequiredFieldsAndSurchargeForEnabledPaymentMethodTypes { api_models::payments::ResponsePaymentMethodTypesForPayments { payment_method_type: payment_methods_enabled.payment_method_type, payment_method_subtype: payment_methods_enabled.payment_method_subtype, + payment_experience: payment_methods_enabled.payment_experience, required_fields: payment_methods_enabled.required_field, surcharge_details: payment_methods_enabled.surcharge, extra_information: None, @@ -153,6 +159,7 @@ impl RequiredFieldsForEnabledPaymentMethodTypes { payment_method_type: payment_methods_enabled.payment_method_type, required_field: payment_methods_enabled.required_field, payment_method_subtype: payment_methods_enabled.payment_method_subtype, + payment_experience: payment_methods_enabled.payment_experience, surcharge: None, }, )
2025-06-05T05:56:25Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Added `payment_experience` in Payment Method List for Payments Response ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #8254 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Request: ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_019740919d6a72c2b6984f9b99be203f/payment-methods' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_GKx8bxieFB51Nk5FMCi6' \ --header 'Authorization: publishable-key=pk_dev_e2eec08c40444d8e862c444d3df67cd2,client-secret=cs_019740919d817810ad313fce9534793e' \ --header 'api-key: pk_dev_e2eec08c40444d8e862c444d3df67cd2' ``` Response: ```json { "payment_methods_enabled": [ { "payment_method_type": "card_redirect", "payment_method_subtype": "card_redirect", "payment_experience": "redirect_to_url", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "card", "payment_method_subtype": "card", "payment_experience": null, "required_fields": null, "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "google_pay", "payment_experience": null, "required_fields": null, "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "apple_pay", "payment_experience": null, "required_fields": null, "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "we_chat_pay", "payment_experience": null, "required_fields": null, "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "ali_pay", "payment_experience": null, "required_fields": null, "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "paypal", "payment_experience": null, "required_fields": null, "surcharge_details": null }, { "payment_method_type": "wallet", "payment_method_subtype": "mb_way", "payment_experience": null, "required_fields": null, "surcharge_details": null }, { "payment_method_type": "pay_later", "payment_method_subtype": "klarna", "payment_experience": "redirect_to_url", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "pay_later", "payment_method_subtype": "affirm", "payment_experience": "redirect_to_url", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "pay_later", "payment_method_subtype": "afterpay_clearpay", "payment_experience": "redirect_to_url", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "pay_later", "payment_method_subtype": "walley", "payment_experience": "redirect_to_url", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "giropay", "payment_experience": "redirect_to_url", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "ideal", "payment_experience": "redirect_to_url", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "eps", "payment_experience": "redirect_to_url", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "bancontact_card", "payment_experience": "redirect_to_url", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "przelewy24", "payment_experience": "redirect_to_url", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "sofort", "payment_experience": "redirect_to_url", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "blik", "payment_experience": "redirect_to_url", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "trustly", "payment_experience": "redirect_to_url", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "online_banking_finland", "payment_experience": "redirect_to_url", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_redirect", "payment_method_subtype": "online_banking_poland", "payment_experience": "redirect_to_url", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_transfer", "payment_method_subtype": "ach", "payment_experience": "redirect_to_url", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_transfer", "payment_method_subtype": "sepa", "payment_experience": "redirect_to_url", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_transfer", "payment_method_subtype": "bacs", "payment_experience": "redirect_to_url", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_debit", "payment_method_subtype": "ach", "payment_experience": null, "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_debit", "payment_method_subtype": "sepa", "payment_experience": null, "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_debit", "payment_method_subtype": "bacs", "payment_experience": null, "required_fields": null, "surcharge_details": null }, { "payment_method_type": "bank_debit", "payment_method_subtype": "becs", "payment_experience": null, "required_fields": null, "surcharge_details": null }, { "payment_method_type": "pay_later", "payment_method_subtype": "klarna", "payment_experience": "invoke_sdk_client", "required_fields": null, "surcharge_details": null }, { "payment_method_type": "pay_later", "payment_method_subtype": "klarna", "payment_experience": "redirect_to_url", "required_fields": null, "surcharge_details": null } ], "customer_payment_methods": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
4a7c08fbc57f9712f1ff478d01d4929b9576b448
4a7c08fbc57f9712f1ff478d01d4929b9576b448
juspay/hyperswitch
juspay__hyperswitch-8249
Bug: feat: migration api for migrating routing rules to decision_engine ## Description Create migration apis to move to decision-engine for PL routing.
diff --git a/config/development.toml b/config/development.toml index d7fb9578c98..1c83278b3fd 100644 --- a/config/development.toml +++ b/config/development.toml @@ -1176,4 +1176,4 @@ connector_names = "stripe, adyen" # Comma-separated list of allowe [infra_values] cluster = "CLUSTER" -version = "HOSTNAME" \ No newline at end of file +version = "HOSTNAME" diff --git a/crates/api_models/src/events/routing.rs b/crates/api_models/src/events/routing.rs index f1ba35bd9f3..62bc49dbe1b 100644 --- a/crates/api_models/src/events/routing.rs +++ b/crates/api_models/src/events/routing.rs @@ -7,7 +7,8 @@ use crate::routing::{ RoutingAlgorithmId, RoutingConfigRequest, RoutingDictionaryRecord, RoutingKind, RoutingLinkWrapper, RoutingPayloadWrapper, RoutingRetrieveLinkQuery, RoutingRetrieveLinkQueryWrapper, RoutingRetrieveQuery, RoutingVolumeSplit, - RoutingVolumeSplitResponse, RoutingVolumeSplitWrapper, SuccessBasedRoutingConfig, + RoutingVolumeSplitResponse, RoutingVolumeSplitWrapper, RuleMigrationError, RuleMigrationQuery, + RuleMigrationResponse, RuleMigrationResult, SuccessBasedRoutingConfig, SuccessBasedRoutingPayloadWrapper, ToggleDynamicRoutingPath, ToggleDynamicRoutingQuery, ToggleDynamicRoutingWrapper, }; @@ -153,3 +154,27 @@ impl ApiEventMetric for RoutingVolumeSplit { Some(ApiEventsType::Routing) } } + +impl ApiEventMetric for RuleMigrationQuery { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Routing) + } +} + +impl ApiEventMetric for RuleMigrationResponse { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Routing) + } +} + +impl ApiEventMetric for RuleMigrationResult { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Routing) + } +} + +impl ApiEventMetric for RuleMigrationError { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Routing) + } +} diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index ed1915764cb..064af45c13d 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -1533,3 +1533,50 @@ pub enum ContractUpdationStatusEventResponse { ContractUpdationSucceeded, ContractUpdationFailed, } +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +pub struct RuleMigrationQuery { + pub profile_id: common_utils::id_type::ProfileId, + pub merchant_id: common_utils::id_type::MerchantId, + pub limit: Option<u32>, + pub offset: Option<u32>, +} + +impl RuleMigrationQuery { + pub fn validated_limit(&self) -> u32 { + self.limit.unwrap_or(50).min(1000) + } +} + +#[derive(Debug, serde::Serialize)] +pub struct RuleMigrationResult { + pub success: Vec<RuleMigrationResponse>, + pub errors: Vec<RuleMigrationError>, +} + +#[derive(Debug, serde::Serialize)] +pub struct RuleMigrationResponse { + pub profile_id: common_utils::id_type::ProfileId, + pub euclid_algorithm_id: common_utils::id_type::RoutingId, + pub decision_engine_algorithm_id: String, +} + +#[derive(Debug, serde::Serialize)] +pub struct RuleMigrationError { + pub profile_id: common_utils::id_type::ProfileId, + pub algorithm_id: common_utils::id_type::RoutingId, + pub error: String, +} + +impl RuleMigrationResponse { + pub fn new( + profile_id: common_utils::id_type::ProfileId, + euclid_algorithm_id: common_utils::id_type::RoutingId, + decision_engine_algorithm_id: String, + ) -> Self { + Self { + profile_id, + euclid_algorithm_id, + decision_engine_algorithm_id, + } + } +} diff --git a/crates/diesel_models/src/routing_algorithm.rs b/crates/diesel_models/src/routing_algorithm.rs index 4e6e9212885..2844aeb16fd 100644 --- a/crates/diesel_models/src/routing_algorithm.rs +++ b/crates/diesel_models/src/routing_algorithm.rs @@ -30,6 +30,7 @@ pub struct RoutingAlgorithmMetadata { pub algorithm_for: enums::TransactionType, } +#[derive(Clone, Debug, Serialize, Deserialize)] pub struct RoutingProfileMetadata { pub profile_id: id_type::ProfileId, pub algorithm_id: id_type::RoutingId, @@ -40,3 +41,10 @@ pub struct RoutingProfileMetadata { pub modified_at: time::PrimitiveDateTime, pub algorithm_for: enums::TransactionType, } + +impl RoutingProfileMetadata { + pub fn metadata_is_advanced_rule_for_payments(&self) -> bool { + matches!(self.kind, enums::RoutingAlgorithmKind::Advanced) + && matches!(self.algorithm_for, enums::TransactionType::Payment) + } +} diff --git a/crates/router/src/core/payments/routing/utils.rs b/crates/router/src/core/payments/routing/utils.rs index 01d066e5cf2..d34e538747c 100644 --- a/crates/router/src/core/payments/routing/utils.rs +++ b/crates/router/src/core/payments/routing/utils.rs @@ -658,6 +658,7 @@ pub struct Program { #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct RoutingRule { + pub rule_id: Option<String>, pub name: String, pub description: Option<String>, pub metadata: Option<RoutingMetadata>, diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs index d5821666a18..975af0da4f0 100644 --- a/crates/router/src/core/routing.rs +++ b/crates/router/src/core/routing.rs @@ -6,7 +6,9 @@ use std::collections::HashSet; use api_models::routing::DynamicRoutingAlgoAccessor; use api_models::{ enums, mandates as mandates_api, routing, - routing::{self as routing_types, RoutingRetrieveQuery}, + routing::{ + self as routing_types, RoutingRetrieveQuery, RuleMigrationError, RuleMigrationResponse, + }, }; use async_trait::async_trait; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] @@ -22,6 +24,7 @@ use external_services::grpc_client::dynamic_routing::{ #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use helpers::update_decision_engine_dynamic_routing_setup; use hyperswitch_domain_models::{mandates, payment_address}; +use payment_methods::helpers::StorageErrorExt; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use router_env::logger; use rustc_hash::FxHashSet; @@ -46,7 +49,7 @@ use crate::utils::ValueExt; use crate::{core::admin, utils::ValueExt}; use crate::{ core::{ - errors::{self, CustomResult, RouterResponse, StorageErrorExt}, + errors::{self, CustomResult, RouterResponse}, metrics, utils as core_utils, }, db::StorageInterface, @@ -345,6 +348,7 @@ pub async fn create_routing_algorithm_under_profile( match program.try_into() { Ok(internal_program) => { let routing_rule = RoutingRule { + rule_id: None, name: name.clone(), description: Some(description.clone()), created_by: profile_id.get_string_repr().to_string(), @@ -2291,3 +2295,158 @@ impl RoutableConnectors { Ok(connector_data) } } + +pub async fn migrate_rules_for_profile( + state: SessionState, + merchant_context: domain::MerchantContext, + query_params: routing_types::RuleMigrationQuery, +) -> RouterResult<routing_types::RuleMigrationResult> { + use api_models::routing::StaticRoutingAlgorithm as EuclidAlgorithm; + + use crate::services::logger; + + let profile_id = query_params.profile_id.clone(); + let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); + let merchant_key_store = merchant_context.get_merchant_key_store(); + let merchant_id = merchant_context.get_merchant_account().get_id(); + + core_utils::validate_and_get_business_profile( + db, + key_manager_state, + merchant_key_store, + Some(&profile_id), + merchant_id, + ) + .await? + .get_required_value("Profile") + .change_context(errors::ApiErrorResponse::ProfileNotFound { + id: profile_id.get_string_repr().to_owned(), + })?; + + let routing_metadatas: Vec<diesel_models::routing_algorithm::RoutingProfileMetadata> = state + .store + .list_routing_algorithm_metadata_by_profile_id( + &profile_id, + i64::from(query_params.validated_limit()), + i64::from(query_params.offset.unwrap_or_default()), + ) + .await + .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; + + let mut response_list = Vec::new(); + let mut error_list = Vec::new(); + + for routing_metadata in routing_metadatas + .into_iter() + .filter(|algo| algo.metadata_is_advanced_rule_for_payments()) + { + match db + .find_routing_algorithm_by_profile_id_algorithm_id( + &profile_id, + &routing_metadata.algorithm_id, + ) + .await + { + Ok(algorithm) => { + let parsed_result = algorithm + .algorithm_data + .parse_value::<EuclidAlgorithm>("EuclidAlgorithm"); + + match parsed_result { + Ok(EuclidAlgorithm::Advanced(program)) => match program.try_into() { + Ok(internal_program) => { + let routing_rule = RoutingRule { + rule_id: Some( + algorithm.algorithm_id.clone().get_string_repr().to_string(), + ), + name: algorithm.name.clone(), + description: algorithm.description.clone(), + created_by: profile_id.get_string_repr().to_string(), + algorithm: internal_program, + metadata: None, + }; + + let result = create_de_euclid_routing_algo(&state, &routing_rule).await; + + match result { + Ok(decision_engine_routing_id) => { + let response = RuleMigrationResponse { + profile_id: profile_id.clone(), + euclid_algorithm_id: algorithm.algorithm_id.clone(), + decision_engine_algorithm_id: decision_engine_routing_id, + }; + response_list.push(response); + } + Err(err) => { + logger::error!( + decision_engine_rule_migration_error = ?err, + algorithm_id = ?algorithm.algorithm_id, + "Failed to insert into decision engine" + ); + error_list.push(RuleMigrationError { + profile_id: profile_id.clone(), + algorithm_id: algorithm.algorithm_id.clone(), + error: format!("Insertion error: {:?}", err), + }); + } + } + } + Err(e) => { + logger::error!( + decision_engine_rule_migration_error = ?e, + algorithm_id = ?algorithm.algorithm_id, + "Failed to convert program" + ); + error_list.push(RuleMigrationError { + profile_id: profile_id.clone(), + algorithm_id: algorithm.algorithm_id.clone(), + error: format!("Program conversion error: {:?}", e), + }); + } + }, + Err(e) => { + logger::error!( + decision_engine_rule_migration_error = ?e, + algorithm_id = ?algorithm.algorithm_id, + "Failed to parse EuclidAlgorithm" + ); + error_list.push(RuleMigrationError { + profile_id: profile_id.clone(), + algorithm_id: algorithm.algorithm_id.clone(), + error: format!("JSON parse error: {:?}", e), + }); + } + _ => { + logger::info!( + "decision_engine_rule_migration_error: Skipping non-advanced algorithm {:?}", + algorithm.algorithm_id + ); + error_list.push(RuleMigrationError { + profile_id: profile_id.clone(), + algorithm_id: algorithm.algorithm_id.clone(), + error: "Not an advanced algorithm".to_string(), + }); + } + } + } + Err(e) => { + logger::error!( + decision_engine_rule_migration_error = ?e, + algorithm_id = ?routing_metadata.algorithm_id, + "Failed to fetch routing algorithm" + ); + error_list.push(RuleMigrationError { + profile_id: profile_id.clone(), + algorithm_id: routing_metadata.algorithm_id.clone(), + error: format!("Fetch error: {:?}", e), + }); + } + } + } + + Ok(routing_types::RuleMigrationResult { + success: response_list, + errors: error_list, + }) +} diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 0ae900f50b0..1380379a2a9 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -3,6 +3,7 @@ use std::{collections::HashMap, sync::Arc}; use actix_web::{web, Scope}; #[cfg(all(feature = "olap", feature = "v1"))] use api_models::routing::RoutingRetrieveQuery; +use api_models::routing::RuleMigrationQuery; #[cfg(feature = "olap")] use common_enums::TransactionType; #[cfg(feature = "partial-auth")] @@ -905,6 +906,11 @@ impl Routing { ) })), ) + .service(web::resource("/rule/migrate").route(web::post().to( + |state, req, query: web::Query<RuleMigrationQuery>| { + routing::migrate_routing_rules_for_profile(state, req, query) + }, + ))) .service( web::resource("/deactivate").route(web::post().to(|state, req, payload| { routing::routing_unlink_config(state, req, payload, None) diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 1f67e3093fc..73f98ebc2a5 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -79,6 +79,7 @@ impl From<Flow> for ApiIdentifier { | Flow::ToggleDynamicRouting | Flow::UpdateDynamicRoutingConfigs | Flow::DecisionManagerUpsertConfig + | Flow::DecisionEngineRuleMigration | Flow::VolumeSplitOnRoutingType => Self::Routing, Flow::RetrieveForexFlow => Self::Forex, diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs index eddac5479ec..d247a8af6ea 100644 --- a/crates/router/src/routes/routing.rs +++ b/crates/router/src/routes/routing.rs @@ -4,7 +4,12 @@ //! of Routing configs. use actix_web::{web, HttpRequest, Responder}; -use api_models::{enums, routing as routing_types, routing::RoutingRetrieveQuery}; +use api_models::{ + enums, + routing::{self as routing_types, RoutingRetrieveQuery}, +}; +use hyperswitch_domain_models::merchant_context::MerchantKeyStore; +use payment_methods::core::errors::ApiErrorResponse; use router_env::{ tracing::{self, instrument}, Flow, @@ -12,6 +17,7 @@ use router_env::{ use crate::{ core::{api_locking, conditional_config, routing, surcharge_decision_config}, + db::errors::StorageErrorExt, routes::AppState, services::{api as oss_api, authentication as auth, authorization::permissions::Permission}, types::domain, @@ -1558,3 +1564,61 @@ pub async fn get_dynamic_routing_volume_split( )) .await } + +use actix_web::HttpResponse; +#[instrument(skip_all, fields(flow = ?Flow::DecisionEngineRuleMigration))] +pub async fn migrate_routing_rules_for_profile( + state: web::Data<AppState>, + req: HttpRequest, + query: web::Query<routing_types::RuleMigrationQuery>, +) -> HttpResponse { + let flow = Flow::DecisionEngineRuleMigration; + + Box::pin(oss_api::server_wrap( + flow, + state, + &req, + query.into_inner(), + |state, _, query_params, _| async move { + let merchant_id = query_params.merchant_id.clone(); + let (key_store, merchant_account) = get_merchant_account(&state, &merchant_id).await?; + let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( + domain::Context(merchant_account, key_store), + )); + let res = Box::pin(routing::migrate_rules_for_profile( + state, + merchant_context, + query_params, + )) + .await?; + Ok(crate::services::ApplicationResponse::Json(res)) + }, + &auth::AdminApiAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} + +async fn get_merchant_account( + state: &super::SessionState, + merchant_id: &common_utils::id_type::MerchantId, +) -> common_utils::errors::CustomResult<(MerchantKeyStore, domain::MerchantAccount), ApiErrorResponse> +{ + let key_manager_state = &state.into(); + let key_store = state + .store + .get_merchant_key_store_by_merchant_id( + key_manager_state, + merchant_id, + &state.store.get_master_key().to_vec().into(), + ) + .await + .to_not_found_response(ApiErrorResponse::MerchantAccountNotFound)?; + + let merchant_account = state + .store + .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) + .await + .to_not_found_response(ApiErrorResponse::MerchantAccountNotFound)?; + Ok((key_store, merchant_account)) +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 198b7d6bfdc..e353d2b28f4 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -249,6 +249,8 @@ pub enum Flow { RoutingRetrieveDefaultConfig, /// Routing retrieve dictionary RoutingRetrieveDictionary, + /// Rule migration for decision-engine + DecisionEngineRuleMigration, /// Routing update config RoutingUpdateConfig, /// Routing update default config
2025-06-03T19:01:23Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR introduces a new migration API that facilitates migrating routing rules defined in Euclid (legacy engine) to the new `decision_engine`. It extracts routing algorithm definitions associated with a `profile_id`, parses them, converts them to the `Program` format used by the decision engine, and then invokes the corresponding creation logic. It includes: - Definition of migration request/response models (`RuleMigrationQuery`, `RuleMigrationResponse`, `RuleMigrationResult`, and `RuleMigrationError`). - New Actix Web route (`/rule/migrate`) under the `Routing` service. - A migration handler `migrate_rules_for_profile` that batches the migration process. - Telemetry integration using `ApiEventMetric`. - Locking support added via `Flow::DecisionEngineRuleMigration`. --- ## Outcomes - Enables smooth and bulk migration of legacy routing configurations into the new decision engine. - Adds error tracking and partial success support via detailed response struct. - Improves observability and tracking with logging and metric tagging. - Supports pagination (`limit`, `offset`) for large-scale migrations. - Provides a maintainable and extensible migration pathway for future routing strategy upgrades. --- ## Diff Hunk Explanation ### `crates/api_models/src/routing.rs` - Added new structs for `RuleMigrationQuery`, `RuleMigrationResponse`, `RuleMigrationResult`, and `RuleMigrationError`. - Implemented a helper method `RuleMigrationResponse::new`. ### `crates/api_models/src/events/routing.rs` - Implemented `ApiEventMetric` for all new migration-related types to support telemetry logging. ### `crates/router/src/core/payments/routing/utils.rs` - Extended `RoutingRule` struct to include an optional `rule_id` field. ### `crates/router/src/core/routing.rs` - Core logic for `migrate_rules_for_profile` which performs: - Profile validation, - Fetching routing algorithm metadata, - Parsing and transforming each rule, - Inserting into decision engine or collecting migration errors. ### `crates/router/src/routes/app.rs` - Registered the `/rule/migrate` endpoint using the new migration handler. ### `crates/router/src/routes/routing.rs` - Defined `migrate_routing_rules_for_profile` as the wrapper function for authenticated, locked execution of migration API. ### `crates/router/src/routes/lock_utils.rs` - Added `Flow::DecisionEngineRuleMigration` under the `ApiIdentifier` mapping. ### `crates/router_env/src/logger/types.rs` - Defined a new `Flow` variant: `DecisionEngineRuleMigration` for logging and audit purposes. ### `crates/diesel_models/src/routing_algorithm.rs` - No logic change, but affected indirectly via usage of `RoutingProfileMetadata`. --- This migration mechanism is a crucial step toward fully deprecating legacy routing configurations and unifying them under the `decision_engine` infrastructure. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ``` curl --location --request POST 'http://127.0.0.1:8080/routing/rule/migrate?profile_id=pro_iqrbKSzgfIcVYUEwqy2J&limit=5&offset=0&merchant_id=merchant_1749113195' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' ``` Note: testing shouldn't be performed as this will trigger migration for that profile. <img width="907" alt="Screenshot 2025-06-11 at 18 48 33" src="https://github.com/user-attachments/assets/34826ac1-5a69-4bcd-9f55-1ab59728c923" /> <img width="1225" alt="Screenshot 2025-06-05 at 01 17 10" src="https://github.com/user-attachments/assets/8a9778f8-f769-4c7b-a39c-0b060074baae" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Introduced a new POST endpoint `/routing/rule/migrate` for migrating routing rules for a profile. - Added support for migrating advanced payment routing rules to the decision engine, with detailed success and error reporting. - Enhanced routing rule data structures to support migration and tracking, including new query, response, result, and error models. - **Improvements** - Added new logging and flow tracking for rule migration operations. - Improved metadata handling for advanced payment routing rules. - **Bug Fixes** - None. - **Documentation** - None. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
v1.114.0
953bace38c1509c95fc8c1e2426fda72c65e3bf8
953bace38c1509c95fc8c1e2426fda72c65e3bf8
juspay/hyperswitch
juspay__hyperswitch-8275
Bug: [BUG] CPF info not getting populated for Facilitapay required fields <img width="907" alt="Image" src="https://github.com/user-attachments/assets/67f28a99-bff3-41fd-a770-110aa19e1bcb" /> <img width="1158" alt="Image" src="https://github.com/user-attachments/assets/5ceb4cd2-db27-4ff2-8252-2719c7a755e5" /> <img width="1057" alt="Image" src="https://github.com/user-attachments/assets/54a1299b-727f-4441-b072-0b93d2a0468d" />
diff --git a/crates/payment_methods/src/configs/payment_connector_required_fields.rs b/crates/payment_methods/src/configs/payment_connector_required_fields.rs index 0a5dca9c0e2..478c2ea2448 100644 --- a/crates/payment_methods/src/configs/payment_connector_required_fields.rs +++ b/crates/payment_methods/src/configs/payment_connector_required_fields.rs @@ -3107,6 +3107,7 @@ fn get_bank_transfer_required_fields() -> HashMap<enums::PaymentMethodType, Conn RequiredField::BillingAddressCountries(vec!["BR"]).to_tuple(), RequiredField::BillingUserFirstName.to_tuple(), RequiredField::BillingUserLastName.to_tuple(), + RequiredField::PixCpf.to_tuple(), ]), }, ),
2025-06-06T11:06:04Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR fixes the required fields error in SDK. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> SDK throws `Missing Required Param: cpf`. Closes https://github.com/juspay/hyperswitch/issues/8275 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> CPF now gets populated: ```curl curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_1iYxKKzKMLFXthlD6iAO_secret_i2gpOEtZadPHnlUpKR1Z' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_9caa65826ff740e78fcf292b7d96f31f' ``` ```json { "redirect_url": "https://duck.com/", "currency": "BRL", "payment_methods": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ { "card_network": "Interac", "surcharge_details": null, "eligible_connectors": [ "facilitapay" ] }, { "card_network": "Discover", "surcharge_details": null, "eligible_connectors": [ "facilitapay" ] }, { "card_network": "AmericanExpress", "surcharge_details": null, "eligible_connectors": [ "facilitapay" ] }, { "card_network": "JCB", "surcharge_details": null, "eligible_connectors": [ "facilitapay" ] }, { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "facilitapay" ] }, { "card_network": "DinersClub", "surcharge_details": null, "eligible_connectors": [ "facilitapay" ] }, { "card_network": "Mastercard", "surcharge_details": null, "eligible_connectors": [ "facilitapay" ] }, { "card_network": "UnionPay", "surcharge_details": null, "eligible_connectors": [ "facilitapay" ] }, { "card_network": "RuPay", "surcharge_details": null, "eligible_connectors": [ "facilitapay" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": null, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ { "card_network": "AmericanExpress", "surcharge_details": null, "eligible_connectors": [ "facilitapay" ] }, { "card_network": "Interac", "surcharge_details": null, "eligible_connectors": [ "facilitapay" ] }, { "card_network": "JCB", "surcharge_details": null, "eligible_connectors": [ "facilitapay" ] }, { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "facilitapay" ] }, { "card_network": "Discover", "surcharge_details": null, "eligible_connectors": [ "facilitapay" ] }, { "card_network": "Mastercard", "surcharge_details": null, "eligible_connectors": [ "facilitapay" ] }, { "card_network": "UnionPay", "surcharge_details": null, "eligible_connectors": [ "facilitapay" ] }, { "card_network": "DinersClub", "surcharge_details": null, "eligible_connectors": [ "facilitapay" ] }, { "card_network": "RuPay", "surcharge_details": null, "eligible_connectors": [ "facilitapay" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": null, "surcharge_details": null, "pm_auth_connector": null } ] }, { "payment_method": "bank_transfer", "payment_method_types": [ { "payment_method_type": "pix", "payment_experience": null, "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": { "eligible_connectors": [ "facilitapay" ] }, "required_fields": { "billing.address.country": { "required_field": "payment_method_data.billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "BR" ] } }, "value": "BR" }, "payment_method_data.bank_transfer.pix.source_bank_account_id": { "required_field": "payment_method_data.bank_transfer.pix.source_bank_account_id", "display_name": "source_bank_account_id", "field_type": "user_source_bank_account_id", "value": null }, "payment_method_data.bank_transfer.pix.destination_bank_account_id": { "required_field": "payment_method_data.bank_transfer.pix.destination_bank_account_id", "display_name": "destination_bank_account_id", "field_type": "user_destination_bank_account_id", "value": null }, "payment_method_data.bank_transfer.pix.cpf": { "required_field": "payment_method_data.bank_transfer.pix.cpf", "display_name": "cpf", "field_type": "user_cpf", "value": null }, "billing.address.last_name": { "required_field": "payment_method_data.billing.address.last_name", "display_name": "card_holder_name", "field_type": "user_full_name", "value": "THE" }, "billing.address.first_name": { "required_field": "payment_method_data.billing.address.first_name", "display_name": "card_holder_name", "field_type": "user_full_name", "value": "PiX" } }, "surcharge_details": null, "pm_auth_connector": null } ] } ], "mandate_payment": null, "merchant_name": "NewAge Retailer", "show_surcharge_breakup_screen": false, "payment_type": "normal", "request_external_three_ds_authentication": false, "collect_shipping_details_from_wallets": false, "collect_billing_details_from_wallets": false, "is_tax_calculation_enabled": false } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `just clippy && just clippy_v2` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
45d4ebfde33c778d3d6063c1c8d45ef6373a5afd
45d4ebfde33c778d3d6063c1c8d45ef6373a5afd
juspay/hyperswitch
juspay__hyperswitch-8244
Bug: [FEATURE] Health check for Decision Engine service ### Feature Description Need health check for DE ### Possible Implementation Need health check for DE ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/api_models/src/health_check.rs b/crates/api_models/src/health_check.rs index 4a1c009e43e..a6261da1be0 100644 --- a/crates/api_models/src/health_check.rs +++ b/crates/api_models/src/health_check.rs @@ -12,6 +12,8 @@ pub struct RouterHealthCheckResponse { pub outgoing_request: bool, #[cfg(feature = "dynamic_routing")] pub grpc_health_check: HealthCheckMap, + #[cfg(feature = "dynamic_routing")] + pub decision_engine: bool, } impl common_utils::events::ApiEventMetric for RouterHealthCheckResponse {} diff --git a/crates/router/src/core/health_check.rs b/crates/router/src/core/health_check.rs index c4892c94d6f..49138d3bda0 100644 --- a/crates/router/src/core/health_check.rs +++ b/crates/router/src/core/health_check.rs @@ -35,6 +35,11 @@ pub trait HealthCheckInterface { async fn health_check_grpc( &self, ) -> CustomResult<HealthCheckMap, errors::HealthCheckGRPCServiceError>; + + #[cfg(feature = "dynamic_routing")] + async fn health_check_decision_engine( + &self, + ) -> CustomResult<HealthState, errors::HealthCheckDecisionEngineError>; } #[async_trait::async_trait] @@ -184,4 +189,25 @@ impl HealthCheckInterface for app::SessionState { logger::debug!("Health check successful"); Ok(health_check_map) } + + #[cfg(feature = "dynamic_routing")] + async fn health_check_decision_engine( + &self, + ) -> CustomResult<HealthState, errors::HealthCheckDecisionEngineError> { + if self.conf.open_router.enabled { + let url = format!("{}/{}", &self.conf.open_router.url, "health"); + let request = services::Request::new(services::Method::Get, &url); + let _ = services::call_connector_api(self, request, "health_check_for_decision_engine") + .await + .change_context( + errors::HealthCheckDecisionEngineError::FailedToCallDecisionEngineService, + )?; + + logger::debug!("Decision engine health check successful"); + Ok(HealthState::Running) + } else { + logger::debug!("Decision engine health check not applicable"); + Ok(HealthState::NotApplicable) + } + } } diff --git a/crates/router/src/routes/health.rs b/crates/router/src/routes/health.rs index 7e9de917be3..f2ed05030da 100644 --- a/crates/router/src/routes/health.rs +++ b/crates/router/src/routes/health.rs @@ -108,6 +108,23 @@ async fn deep_health_check_func( logger::debug!("gRPC health check end"); + logger::debug!("Decision Engine health check begin"); + + #[cfg(feature = "dynamic_routing")] + let decision_engine_health_check = + state + .health_check_decision_engine() + .await + .map_err(|error| { + let message = error.to_string(); + error.change_context(errors::ApiErrorResponse::HealthCheckError { + component: "Decision Engine service", + message, + }) + })?; + + logger::debug!("Decision Engine health check end"); + logger::debug!("Opensearch health check begin"); #[cfg(feature = "olap")] @@ -144,6 +161,8 @@ async fn deep_health_check_func( outgoing_request: outgoing_check.into(), #[cfg(feature = "dynamic_routing")] grpc_health_check, + #[cfg(feature = "dynamic_routing")] + decision_engine: decision_engine_health_check.into(), }; Ok(api::ApplicationResponse::Json(response)) diff --git a/crates/storage_impl/src/errors.rs b/crates/storage_impl/src/errors.rs index 6d48fbcddac..5bab662687d 100644 --- a/crates/storage_impl/src/errors.rs +++ b/crates/storage_impl/src/errors.rs @@ -280,3 +280,9 @@ pub enum RecoveryError { #[error("Failed to fetch billing connector account id")] BillingMerchantConnectorAccountIdNotFound, } + +#[derive(Debug, Clone, thiserror::Error)] +pub enum HealthCheckDecisionEngineError { + #[error("Failed to establish Decision Engine connection")] + FailedToCallDecisionEngineService, +}
2025-06-04T13:55:01Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Added health check for Decision engine service ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Hit the health endpoint ``` curl "http://localhost:8080/health/ready" ``` Response - ``` { "database": true, "redis": true, "analytics": true, "opensearch": false, "outgoing_request": true, "grpc_health_check": { "dynamic_routing_service": false }, "decision_engine": true } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
fd844c3dd50600a1b136ed2bf15db50048918275
fd844c3dd50600a1b136ed2bf15db50048918275
juspay/hyperswitch
juspay__hyperswitch-8262
Bug: feat(core): consume card details from billing connectors and first error codes and store them in payment intent table Consume the card network and card iin from billing connectors and add them ton payment intent feature metadata
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index 877fb89ca93..9a8bebc893b 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -6780,6 +6780,23 @@ } } }, + "BillingConnectorAdditionalCardInfo": { + "type": "object", + "required": [ + "card_network" + ], + "properties": { + "card_network": { + "$ref": "#/components/schemas/CardNetwork" + }, + "card_issuer": { + "type": "string", + "description": "Card Issuer", + "example": "JP MORGAN CHASE", + "nullable": true + } + } + }, "BillingConnectorPaymentDetails": { "type": "object", "required": [ @@ -6797,6 +6814,31 @@ } } }, + "BillingConnectorPaymentMethodDetails": { + "oneOf": [ + { + "type": "object", + "required": [ + "type", + "value" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "card" + ] + }, + "value": { + "$ref": "#/components/schemas/BillingConnectorAdditionalCardInfo" + } + } + } + ], + "discriminator": { + "propertyName": "type" + } + }, "BlikBankRedirectAdditionalData": { "type": "object", "properties": { @@ -17854,7 +17896,8 @@ "billing_connector_payment_details", "payment_method_type", "payment_method_subtype", - "connector" + "connector", + "billing_connector_payment_method_details" ], "properties": { "total_retry_count": { @@ -17894,11 +17937,32 @@ "connector": { "$ref": "#/components/schemas/Connector" }, + "billing_connector_payment_method_details": { + "$ref": "#/components/schemas/BillingConnectorPaymentMethodDetails" + }, "invoice_next_billing_time": { "type": "string", "format": "date-time", "description": "Invoice Next billing time", "nullable": true + }, + "first_payment_attempt_pg_error_code": { + "type": "string", + "description": "First Payment Attempt Payment Gateway Error Code", + "example": "card_declined", + "nullable": true + }, + "first_payment_attempt_network_decline_code": { + "type": "string", + "description": "First Payment Attempt Network Error Code", + "example": "05", + "nullable": true + }, + "first_payment_attempt_network_advice_code": { + "type": "string", + "description": "First Payment Attempt Network Advice Code", + "example": "02", + "nullable": true } } }, diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index c37690a9f5a..ef4d417ddc6 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -8694,9 +8694,41 @@ pub struct PaymentRevenueRecoveryMetadata { /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Connector, example = "stripe")] pub connector: common_enums::connector_enums::Connector, + #[schema(value_type = BillingConnectorPaymentMethodDetails)] + /// Extra Payment Method Details that are needed to be stored + pub billing_connector_payment_method_details: Option<BillingConnectorPaymentMethodDetails>, /// Invoice Next billing time + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub invoice_next_billing_time: Option<PrimitiveDateTime>, + /// First Payment Attempt Payment Gateway Error Code + #[schema(value_type = Option<String>, example = "card_declined")] + pub first_payment_attempt_pg_error_code: Option<String>, + /// First Payment Attempt Network Error Code + #[schema(value_type = Option<String>, example = "05")] + pub first_payment_attempt_network_decline_code: Option<String>, + /// First Payment Attempt Network Advice Code + #[schema(value_type = Option<String>, example = "02")] + pub first_payment_attempt_network_advice_code: Option<String>, +} + +#[cfg(feature = "v2")] +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ToSchema)] +#[serde(rename_all = "snake_case", tag = "type", content = "value")] +pub enum BillingConnectorPaymentMethodDetails { + Card(BillingConnectorAdditionalCardInfo), +} + +#[cfg(feature = "v2")] +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ToSchema)] +pub struct BillingConnectorAdditionalCardInfo { + #[schema(value_type = CardNetwork, example = "Visa")] + /// Card Network + pub card_network: Option<common_enums::enums::CardNetwork>, + #[schema(value_type = Option<String>, example = "JP MORGAN CHASE")] + /// Card Issuer + pub card_issuer: Option<String>, } + #[cfg(feature = "v2")] impl PaymentRevenueRecoveryMetadata { pub fn set_payment_transmission_field_for_api_request( @@ -8810,6 +8842,14 @@ pub struct PaymentsAttemptRecordRequest { /// source where the payment was triggered by #[schema(value_type = TriggeredBy, example = "internal" )] pub triggered_by: common_enums::TriggeredBy, + + #[schema(value_type = CardNetwork, example = "Visa" )] + /// card_network + pub card_network: Option<common_enums::CardNetwork>, + + #[schema(example = "Chase")] + /// Card Issuer + pub card_issuer: Option<String>, } /// Error details for the payment diff --git a/crates/diesel_models/src/types.rs b/crates/diesel_models/src/types.rs index 696cc22783d..e3efd3dae2d 100644 --- a/crates/diesel_models/src/types.rs +++ b/crates/diesel_models/src/types.rs @@ -174,6 +174,14 @@ pub struct PaymentRevenueRecoveryMetadata { pub connector: common_enums::connector_enums::Connector, /// Time at which next invoice will be created pub invoice_next_billing_time: Option<time::PrimitiveDateTime>, + /// Extra Payment Method Details that are needed to be stored + pub billing_connector_payment_method_details: Option<BillingConnectorPaymentMethodDetails>, + /// First Payment Attempt Payment Gateway Error Code + pub first_payment_attempt_pg_error_code: Option<String>, + /// First Payment Attempt Network Error Code + pub first_payment_attempt_network_decline_code: Option<String>, + /// First Payment Attempt Network Advice Code + pub first_payment_attempt_network_advice_code: Option<String>, } #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] @@ -184,3 +192,19 @@ pub struct BillingConnectorPaymentDetails { /// Billing Connector's Customer Id pub connector_customer_id: String, } + +#[cfg(feature = "v2")] +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "snake_case", tag = "type", content = "value")] +pub enum BillingConnectorPaymentMethodDetails { + Card(BillingConnectorAdditionalCardInfo), +} + +#[cfg(feature = "v2")] +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct BillingConnectorAdditionalCardInfo { + /// Card Network + pub card_network: Option<common_enums::enums::CardNetwork>, + /// Card Issuer + pub card_issuer: Option<String>, +} diff --git a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs index ed978d84903..6436cd952e7 100644 --- a/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs @@ -335,6 +335,8 @@ pub struct ChargebeePaymentMethodDetails { #[derive(Serialize, Deserialize, Debug)] pub struct ChargebeeCardDetails { funding_type: ChargebeeFundingType, + brand: common_enums::CardNetwork, + iin: String, } #[derive(Serialize, Deserialize, Debug)] @@ -505,6 +507,8 @@ impl TryFrom<ChargebeeWebhookBody> for revenue_recovery::RevenueRecoveryAttemptD network_error_message: None, retry_count, invoice_next_billing_time, + card_network: Some(payment_method_details.card.brand), + card_isin: Some(payment_method_details.card.iin), }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs b/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs index 673ba9d432f..9ffd900dc45 100644 --- a/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs @@ -136,6 +136,8 @@ pub struct PaymentMethod { pub gateway_token: String, pub funding_source: RecurlyFundingTypes, pub object: RecurlyPaymentObject, + pub card_type: common_enums::CardNetwork, + pub first_six: String, } #[derive(Debug, Serialize, Deserialize)] @@ -204,6 +206,8 @@ impl payment_method_type: common_enums::PaymentMethod::from( item.response.payment_method.object, ), + card_network: Some(item.response.payment_method.card_type), + card_isin: Some(item.response.payment_method.first_six), }, ), ..item.data diff --git a/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs index ffefb74e7ee..1352b874c8a 100644 --- a/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs @@ -439,6 +439,7 @@ pub struct StripebillingLatestChargeData { pub payment_method_details: StripePaymentMethodDetails, #[serde(rename = "invoice")] pub invoice_id: String, + pub payment_intent: String, } #[derive(Serialize, Deserialize, Debug, Clone)] @@ -446,7 +447,7 @@ pub struct StripePaymentMethodDetails { #[serde(rename = "type")] pub type_of_payment_method: StripebillingPaymentMethod, #[serde(rename = "card")] - pub card_funding_type: StripeCardFundingTypeDetails, + pub card_details: StripeBillingCardDetails, } #[derive(Serialize, Deserialize, Debug, Clone, Copy)] @@ -456,10 +457,31 @@ pub enum StripebillingPaymentMethod { } #[derive(Serialize, Deserialize, Debug, Clone)] -pub struct StripeCardFundingTypeDetails { +pub struct StripeBillingCardDetails { + pub network: StripebillingCardNetwork, pub funding: StripebillingFundingTypes, } +#[derive(Serialize, Deserialize, Debug, Clone, Copy)] +#[serde(rename_all = "snake_case")] +pub enum StripebillingCardNetwork { + Visa, + Mastercard, + AmericanExpress, + JCB, + DinersClub, + Discover, + CartesBancaires, + UnionPay, + Interac, + RuPay, + Maestro, + Star, + Pulse, + Accel, + Nyce, +} + #[derive(Serialize, Deserialize, Debug, Clone, Copy)] #[serde(rename = "snake_case")] pub enum StripebillingFundingTypes { @@ -509,7 +531,7 @@ impl field_name: "invoice_id", })?; let connector_transaction_id = Some(common_utils::types::ConnectorTransactionId::from( - charge_details.charge_id, + charge_details.payment_intent, )); Ok(Self { @@ -529,14 +551,16 @@ impl connector_customer_id: charge_details.customer, transaction_created_at: Some(charge_details.created), payment_method_sub_type: common_enums::PaymentMethodType::from( - charge_details - .payment_method_details - .card_funding_type - .funding, + charge_details.payment_method_details.card_details.funding, ), payment_method_type: common_enums::PaymentMethod::from( charge_details.payment_method_details.type_of_payment_method, ), + card_network: Some(common_enums::CardNetwork::from( + charge_details.payment_method_details.card_details.network, + )), + // Todo: Fetch Card issuer details. Generally in the other billing connector we are getting card_issuer using the card bin info. But stripe dosent provide any such details. We should find a way for stripe billing case + card_isin: None, }, ), ..item.data @@ -611,3 +635,25 @@ impl }) } } + +impl From<StripebillingCardNetwork> for enums::CardNetwork { + fn from(item: StripebillingCardNetwork) -> Self { + match item { + StripebillingCardNetwork::Visa => Self::Visa, + StripebillingCardNetwork::Mastercard => Self::Mastercard, + StripebillingCardNetwork::AmericanExpress => Self::AmericanExpress, + StripebillingCardNetwork::JCB => Self::JCB, + StripebillingCardNetwork::DinersClub => Self::DinersClub, + StripebillingCardNetwork::Discover => Self::Discover, + StripebillingCardNetwork::CartesBancaires => Self::CartesBancaires, + StripebillingCardNetwork::UnionPay => Self::UnionPay, + StripebillingCardNetwork::Interac => Self::Interac, + StripebillingCardNetwork::RuPay => Self::RuPay, + StripebillingCardNetwork::Maestro => Self::Maestro, + StripebillingCardNetwork::Star => Self::Star, + StripebillingCardNetwork::Pulse => Self::Pulse, + StripebillingCardNetwork::Accel => Self::Accel, + StripebillingCardNetwork::Nyce => Self::Nyce, + } + } +} diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs index 99ef5e3581f..4ee8620e35e 100644 --- a/crates/hyperswitch_domain_models/src/lib.rs +++ b/crates/hyperswitch_domain_models/src/lib.rs @@ -55,7 +55,9 @@ use api_models::payments::{ }; #[cfg(feature = "v2")] use api_models::payments::{ + BillingConnectorAdditionalCardInfo as ApiBillingConnectorAdditionalCardInfo, BillingConnectorPaymentDetails as ApiBillingConnectorPaymentDetails, + BillingConnectorPaymentMethodDetails as ApiBillingConnectorPaymentMethodDetails, PaymentRevenueRecoveryMetadata as ApiRevenueRecoveryMetadata, }; use diesel_models::types::{ @@ -63,7 +65,10 @@ use diesel_models::types::{ OrderDetailsWithAmount, RecurringPaymentIntervalUnit, RedirectResponse, }; #[cfg(feature = "v2")] -use diesel_models::types::{BillingConnectorPaymentDetails, PaymentRevenueRecoveryMetadata}; +use diesel_models::types::{ + BillingConnectorAdditionalCardInfo, BillingConnectorPaymentDetails, + BillingConnectorPaymentMethodDetails, PaymentRevenueRecoveryMetadata, +}; #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)] pub enum RemoteStorageObject<T: ForeignIDRef> { @@ -267,6 +272,44 @@ impl ApiModelToDieselModelConvertor<ApiApplePayRecurringDetails> for ApplePayRec } } +#[cfg(feature = "v2")] +impl ApiModelToDieselModelConvertor<ApiBillingConnectorAdditionalCardInfo> + for BillingConnectorAdditionalCardInfo +{ + fn convert_from(from: ApiBillingConnectorAdditionalCardInfo) -> Self { + Self { + card_issuer: from.card_issuer, + card_network: from.card_network, + } + } + + fn convert_back(self) -> ApiBillingConnectorAdditionalCardInfo { + ApiBillingConnectorAdditionalCardInfo { + card_issuer: self.card_issuer, + card_network: self.card_network, + } + } +} + +#[cfg(feature = "v2")] +impl ApiModelToDieselModelConvertor<ApiBillingConnectorPaymentMethodDetails> + for BillingConnectorPaymentMethodDetails +{ + fn convert_from(from: ApiBillingConnectorPaymentMethodDetails) -> Self { + match from { + ApiBillingConnectorPaymentMethodDetails::Card(data) => { + Self::Card(BillingConnectorAdditionalCardInfo::convert_from(data)) + } + } + } + + fn convert_back(self) -> ApiBillingConnectorPaymentMethodDetails { + match self { + Self::Card(data) => ApiBillingConnectorPaymentMethodDetails::Card(data.convert_back()), + } + } +} + #[cfg(feature = "v2")] impl ApiModelToDieselModelConvertor<ApiRevenueRecoveryMetadata> for PaymentRevenueRecoveryMetadata { fn convert_from(from: ApiRevenueRecoveryMetadata) -> Self { @@ -282,6 +325,14 @@ impl ApiModelToDieselModelConvertor<ApiRevenueRecoveryMetadata> for PaymentReven payment_method_subtype: from.payment_method_subtype, connector: from.connector, invoice_next_billing_time: from.invoice_next_billing_time, + billing_connector_payment_method_details: from + .billing_connector_payment_method_details + .map(BillingConnectorPaymentMethodDetails::convert_from), + first_payment_attempt_network_advice_code: from + .first_payment_attempt_network_advice_code, + first_payment_attempt_network_decline_code: from + .first_payment_attempt_network_decline_code, + first_payment_attempt_pg_error_code: from.first_payment_attempt_pg_error_code, } } @@ -298,6 +349,14 @@ impl ApiModelToDieselModelConvertor<ApiRevenueRecoveryMetadata> for PaymentReven payment_method_subtype: self.payment_method_subtype, connector: self.connector, invoice_next_billing_time: self.invoice_next_billing_time, + billing_connector_payment_method_details: self + .billing_connector_payment_method_details + .map(|data| data.convert_back()), + first_payment_attempt_network_advice_code: self + .first_payment_attempt_network_advice_code, + first_payment_attempt_network_decline_code: self + .first_payment_attempt_network_decline_code, + first_payment_attempt_pg_error_code: self.first_payment_attempt_pg_error_code, } } } diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index e8ec7041f60..d460cfa4662 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -743,6 +743,8 @@ impl PaymentIntent { network_error_message: None, retry_count: None, invoice_next_billing_time: None, + card_isin: None, + card_network: None, }) } @@ -951,6 +953,8 @@ pub struct RevenueRecoveryData { pub retry_count: Option<u16>, pub invoice_next_billing_time: Option<PrimitiveDateTime>, pub triggered_by: storage_enums::enums::TriggeredBy, + pub card_network: Option<common_enums::CardNetwork>, + pub card_issuer: Option<String>, } #[cfg(feature = "v2")] @@ -962,9 +966,57 @@ where &self, ) -> CustomResult<Option<FeatureMetadata>, errors::api_error_response::ApiErrorResponse> { let payment_intent_feature_metadata = self.payment_intent.get_feature_metadata(); - let revenue_recovery = self.payment_intent.get_revenue_recovery_metadata(); let payment_attempt_connector = self.payment_attempt.connector.clone(); + + let feature_metadata_first_pg_error_code = revenue_recovery + .as_ref() + .and_then(|data| data.first_payment_attempt_pg_error_code.clone()); + + let (first_pg_error_code, first_network_advice_code, first_network_decline_code) = + feature_metadata_first_pg_error_code.map_or_else( + || { + let first_pg_error_code = self + .payment_attempt + .error + .as_ref() + .map(|error| error.code.clone()); + let first_network_advice_code = self + .payment_attempt + .error + .as_ref() + .and_then(|error| error.network_advice_code.clone()); + let first_network_decline_code = self + .payment_attempt + .error + .as_ref() + .and_then(|error| error.network_decline_code.clone()); + ( + first_pg_error_code, + first_network_advice_code, + first_network_decline_code, + ) + }, + |pg_code| { + let advice_code = revenue_recovery + .as_ref() + .and_then(|data| data.first_payment_attempt_network_advice_code.clone()); + let decline_code = revenue_recovery + .as_ref() + .and_then(|data| data.first_payment_attempt_network_decline_code.clone()); + (Some(pg_code), advice_code, decline_code) + }, + ); + + let billing_connector_payment_method_details = Some( + diesel_models::types::BillingConnectorPaymentMethodDetails::Card( + diesel_models::types::BillingConnectorAdditionalCardInfo { + card_network: self.revenue_recovery_data.card_network.clone(), + card_issuer: self.revenue_recovery_data.card_issuer.clone(), + }, + ), + ); + let payment_revenue_recovery_metadata = match payment_attempt_connector { Some(connector) => Some(diesel_models::types::PaymentRevenueRecoveryMetadata { // Update retry count by one. @@ -999,6 +1051,10 @@ where errors::api_error_response::ApiErrorResponse::InternalServerError })?, invoice_next_billing_time: self.revenue_recovery_data.invoice_next_billing_time, + billing_connector_payment_method_details, + first_payment_attempt_network_advice_code: first_network_advice_code, + first_payment_attempt_network_decline_code: first_network_decline_code, + first_payment_attempt_pg_error_code: first_pg_error_code, }), None => Err(errors::api_error_response::ApiErrorResponse::InternalServerError) .attach_printable("Connector not found in payment attempt")?, diff --git a/crates/hyperswitch_domain_models/src/revenue_recovery.rs b/crates/hyperswitch_domain_models/src/revenue_recovery.rs index 82692047e4b..529c035eebc 100644 --- a/crates/hyperswitch_domain_models/src/revenue_recovery.rs +++ b/crates/hyperswitch_domain_models/src/revenue_recovery.rs @@ -48,6 +48,10 @@ pub struct RevenueRecoveryAttemptData { pub retry_count: Option<u16>, /// Time when next invoice will be generated which will be equal to the end time of the current invoice pub invoice_next_billing_time: Option<PrimitiveDateTime>, + /// card network type + pub card_network: Option<common_enums::CardNetwork>, + /// card isin + pub card_isin: Option<String>, } /// This is unified struct for Revenue Recovery Invoice Data and it is constructed from billing connectors @@ -271,6 +275,8 @@ impl network_error_message: None, retry_count: invoice_details.retry_count, invoice_next_billing_time: invoice_details.next_billing_at, + card_network: billing_connector_payment_details.card_network.clone(), + card_isin: billing_connector_payment_details.card_isin.clone(), } } } diff --git a/crates/hyperswitch_domain_models/src/router_response_types/revenue_recovery.rs b/crates/hyperswitch_domain_models/src/router_response_types/revenue_recovery.rs index 598795fa116..8dd6aa2e74c 100644 --- a/crates/hyperswitch_domain_models/src/router_response_types/revenue_recovery.rs +++ b/crates/hyperswitch_domain_models/src/router_response_types/revenue_recovery.rs @@ -28,6 +28,10 @@ pub struct BillingConnectorPaymentsSyncResponse { pub payment_method_type: common_enums::enums::PaymentMethod, /// payment method sub type of the payment attempt. pub payment_method_sub_type: common_enums::enums::PaymentMethodType, + /// card netword network + pub card_network: Option<common_enums::CardNetwork>, + /// card isin + pub card_isin: Option<String>, } #[derive(Debug, Clone)] diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 5b5ed7a83e4..d8e08a296d1 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -351,6 +351,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::AliPayQr, api_models::payments::PaymentAttemptFeatureMetadata, api_models::payments::PaymentAttemptRevenueRecoveryData, + api_models::payments::BillingConnectorPaymentMethodDetails, + api_models::payments::BillingConnectorAdditionalCardInfo, api_models::payments::AliPayRedirection, api_models::payments::MomoRedirection, api_models::payments::TouchNGoRedirection, diff --git a/crates/router/src/core/payments/operations/payment_attempt_record.rs b/crates/router/src/core/payments/operations/payment_attempt_record.rs index 33848e1c39a..b2834f0bfad 100644 --- a/crates/router/src/core/payments/operations/payment_attempt_record.rs +++ b/crates/router/src/core/payments/operations/payment_attempt_record.rs @@ -199,6 +199,8 @@ impl<F: Send + Clone + Sync> retry_count: request.retry_count, invoice_next_billing_time: request.invoice_next_billing_time, triggered_by: request.triggered_by, + card_network: request.card_network.clone(), + card_issuer: request.card_issuer.clone(), }; let payment_address = hyperswitch_domain_models::payment_address::PaymentAddress::new( payment_intent diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 042fb6ba94a..f467eb39dd4 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -4900,6 +4900,22 @@ impl ForeignFrom<&diesel_models::types::BillingConnectorPaymentDetails> } } +#[cfg(feature = "v2")] +impl ForeignFrom<&diesel_models::types::BillingConnectorPaymentMethodDetails> + for api_models::payments::BillingConnectorPaymentMethodDetails +{ + fn foreign_from(metadata: &diesel_models::types::BillingConnectorPaymentMethodDetails) -> Self { + match metadata { + diesel_models::types::BillingConnectorPaymentMethodDetails::Card(card_details) => { + Self::Card(api_models::payments::BillingConnectorAdditionalCardInfo { + card_issuer: card_details.card_issuer.clone(), + card_network: card_details.card_network.clone(), + }) + } + } + } +} + #[cfg(feature = "v2")] impl ForeignFrom<&hyperswitch_domain_models::payments::payment_attempt::ErrorDetails> for api_models::payments::ErrorDetails @@ -4965,6 +4981,17 @@ impl ForeignFrom<&diesel_models::types::FeatureMetadata> for api_models::payment ), invoice_next_billing_time: payment_revenue_recovery_metadata .invoice_next_billing_time, + billing_connector_payment_method_details:payment_revenue_recovery_metadata + .billing_connector_payment_method_details.as_ref().map(api_models::payments::BillingConnectorPaymentMethodDetails::foreign_from), + first_payment_attempt_network_advice_code: payment_revenue_recovery_metadata + .first_payment_attempt_network_advice_code + .clone(), + first_payment_attempt_network_decline_code: payment_revenue_recovery_metadata + .first_payment_attempt_network_decline_code + .clone(), + first_payment_attempt_pg_error_code: payment_revenue_recovery_metadata + .first_payment_attempt_pg_error_code + .clone(), } }); let apple_pay_details = feature_metadata diff --git a/crates/router/src/core/revenue_recovery.rs b/crates/router/src/core/revenue_recovery.rs index ee22507b8f7..235d57f96d7 100644 --- a/crates/router/src/core/revenue_recovery.rs +++ b/crates/router/src/core/revenue_recovery.rs @@ -69,14 +69,14 @@ pub async fn perform_execute_payment( match record_attempt { Ok(_) => { - let action = types::Action::execute_payment( + let action = Box::pin(types::Action::execute_payment( state, revenue_recovery_payment_data.merchant_account.get_id(), payment_intent, execute_task_process, revenue_recovery_payment_data, &revenue_recovery_metadata, - ) + )) .await?; Box::pin(action.execute_payment_task_response_handler( state, diff --git a/crates/router/src/core/revenue_recovery/api.rs b/crates/router/src/core/revenue_recovery/api.rs index 60465964856..b58d7166837 100644 --- a/crates/router/src/core/revenue_recovery/api.rs +++ b/crates/router/src/core/revenue_recovery/api.rs @@ -183,16 +183,22 @@ pub async fn record_internal_attempt_api( message: "get_revenue_recovery_attempt was not constructed".to_string(), })?; - let request_payload = revenue_recovery_attempt_data.create_payment_record_request( - &revenue_recovery_payment_data.billing_mca.id, - Some( - revenue_recovery_metadata - .active_attempt_payment_connector_id - .clone(), - ), - Some(revenue_recovery_metadata.connector), - common_enums::TriggeredBy::Internal, - ); + let request_payload = revenue_recovery_attempt_data + .create_payment_record_request( + state, + &revenue_recovery_payment_data.billing_mca.id, + Some( + revenue_recovery_metadata + .active_attempt_payment_connector_id + .clone(), + ), + Some(revenue_recovery_metadata.connector), + common_enums::TriggeredBy::Internal, + ) + .await + .change_context(errors::ApiErrorResponse::GenericNotFoundError { + message: "Cannot Create the payment record Request".to_string(), + })?; let merchant_context_from_revenue_recovery_payment_data = MerchantContext::NormalMerchant(Box::new(Context( diff --git a/crates/router/src/core/webhooks/recovery_incoming.rs b/crates/router/src/core/webhooks/recovery_incoming.rs index 87c1a79aa12..18a51c3e9bb 100644 --- a/crates/router/src/core/webhooks/recovery_incoming.rs +++ b/crates/router/src/core/webhooks/recovery_incoming.rs @@ -545,14 +545,17 @@ impl RevenueRecoveryAttempt { errors::RevenueRecoveryError, > { let payment_connector_id = payment_connector_account.as_ref().map(|account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount| account.id.clone()); - let request_payload = self.create_payment_record_request( - billing_connector_account_id, - payment_connector_id, - payment_connector_account - .as_ref() - .map(|account| account.connector_name), - common_enums::TriggeredBy::External, - ); + let request_payload = self + .create_payment_record_request( + state, + billing_connector_account_id, + payment_connector_id, + payment_connector_account + .as_ref() + .map(|account| account.connector_name), + common_enums::TriggeredBy::External, + ) + .await?; let attempt_response = Box::pin(payments::record_attempt_core( state.clone(), req_state.clone(), @@ -593,13 +596,15 @@ impl RevenueRecoveryAttempt { Ok(response) } - pub fn create_payment_record_request( + pub async fn create_payment_record_request( &self, + state: &SessionState, billing_merchant_connector_account_id: &id_type::MerchantConnectorAccountId, payment_merchant_connector_account_id: Option<id_type::MerchantConnectorAccountId>, payment_connector: Option<common_enums::connector_enums::Connector>, triggered_by: common_enums::TriggeredBy, - ) -> api_payments::PaymentsAttemptRecordRequest { + ) -> CustomResult<api_payments::PaymentsAttemptRecordRequest, errors::RevenueRecoveryError> + { let revenue_recovery_attempt_data = &self.0; let amount_details = api_payments::PaymentAttemptAmountDetails::from(revenue_recovery_attempt_data); @@ -609,9 +614,27 @@ impl RevenueRecoveryAttempt { attempt_triggered_by: triggered_by, }), }; + + let card_info = revenue_recovery_attempt_data + .card_isin + .clone() + .async_and_then(|isin| async move { + let issuer_identifier_number = isin.clone(); + state + .store + .get_card_info(issuer_identifier_number.as_str()) + .await + .map_err(|error| services::logger::warn!(card_info_error=?error)) + .ok() + }) + .await + .flatten(); + + let card_issuer = card_info.and_then(|info| info.card_issuer); + let error = Option::<api_payments::RecordAttemptErrorDetails>::from(revenue_recovery_attempt_data); - api_payments::PaymentsAttemptRecordRequest { + Ok(api_payments::PaymentsAttemptRecordRequest { amount_details, status: revenue_recovery_attempt_data.status, billing: None, @@ -637,7 +660,9 @@ impl RevenueRecoveryAttempt { retry_count: revenue_recovery_attempt_data.retry_count, invoice_next_billing_time: revenue_recovery_attempt_data.invoice_next_billing_time, triggered_by, - } + card_network: revenue_recovery_attempt_data.card_network.clone(), + card_issuer, + }) } pub async fn find_payment_merchant_connector_account(
2025-06-04T21:34:40Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description The following details are needed to be stored in the payment intent feature metadata as a part of transaction monitoring system for revenue recovery. 1. Card Network 2. Card Issuer 3. First Payment Gateway Error Code 4. First Network Error Code 5. First Network Advice Code These will be constant through out the lifecycle of the payment intent in revenue recovery system. We need to use these parameters further in revenue recovery system. We need this as training data and need these while Deciding optimal time for the retry. These information is stored in payment intent because this information will be constant throughout for payment intent and this information cannot be populated every time we retry this payment. ### Additional Changes - [x] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 7. `crates/router/src/configs` 8. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Can be tested by following the steps mentioned in this PR: #7461. Here are the test results: ``` { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "payment_revenue_recovery_metadata": { "total_retry_count": 2, "payment_connector_transmission": "ConnectorCallUnsuccessful", "billing_connector_id": "mca_MWigDQEKB7Du4L9YqeSe", "active_attempt_payment_connector_id": "mca_PY26kh9v0Kiu1hd7lTzL", "billing_connector_payment_details": { "payment_processor_token": "card_1RXkE8RpLdtbmMLFiOTVtzLI", "connector_customer_id": "cus_SSfYcZWkulAsCG" }, "payment_method_type": "card", "payment_method_subtype": "credit", "connector": "stripe", "invoice_next_billing_time": "2025-07-15 18:30:00.0", "card_network": "Visa", "card_issuer": null, "first_payment_attempt_pg_error_code": "card_declined", "first_payment_attempt_network_decline_code": "card_declined", "first_payment_attempt_network_advice_code": "card_declined" } } ``` Or Run this Curl by filling our: ``` curl --location 'http://localhost:8080/v2/payments/create-intent' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: Profile_id' \ --header 'Authorization: api-key=api-key' \ --header 'api-key: apikey' \ --data-raw '{ "amount_details": { "order_amount": 100, "currency": "USD" }, "capture_method":"manual", "authentication_type": "no_three_ds", "billing": { "address": { "first_name": "John", "last_name": "Dough" }, "email": "[email protected]" }, "shipping": { "address": { "first_name": "John", "last_name": "Dough", "city": "Karwar", "zip": "581301", "state": "Karnataka" }, "email": "[email protected]" }, "feature_metadata": { "payment_revenue_recovery_metadata": { "total_retry_count": 2, "payment_connector_transmission": "ConnectorCallUnsuccessful", "billing_connector_id": "bca_12345", "active_attempt_payment_connector_id": "pca_67890", "billing_connector_payment_details": { "payment_processor_token": "tok_abcdef123456", "connector_customer_id": "cust_98765" }, "payment_method_type": "card", "payment_method_subtype": "credit", "connector": "stripe", "invoice_next_billing_time": "2025-06-12T15:00:00Z", "billing_connector_payment_method_details": { "type": "Card", "value": { "card_network": "Visa", "card_issuer": "HDFC Bank" } }, "first_payment_attempt_pg_error_code": "PG001", "first_payment_attempt_network_decline_code": "ND002", "first_payment_attempt_network_advice_code": "AD003" } } }' ``` This is the expected response ``` { "id": "12345_pay_019763e442877b72aaa3b0a5304b2c4e", "status": "requires_payment_method", "amount_details": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null }, "client_secret": "cs_019763e442ad7ff1b735ca04e9810f2c", "profile_id": "pro_jhWJnFzJZ4tDqxGRrSbX", "merchant_reference_id": null, "routing_algorithm_id": null, "capture_method": "manual", "authentication_type": "no_three_ds", "billing": { "address": { "city": null, "country": null, "line1": null, "line2": null, "line3": null, "zip": null, "state": null, "first_name": "John", "last_name": "Dough" }, "phone": null, "email": "[email protected]" }, "shipping": { "address": { "city": "Karwar", "country": null, "line1": null, "line2": null, "line3": null, "zip": "581301", "state": "Karnataka", "first_name": "John", "last_name": "Dough" }, "phone": null, "email": "[email protected]" }, "customer_id": null, "customer_present": "present", "description": null, "return_url": null, "setup_future_usage": "on_session", "apply_mit_exemption": "Skip", "statement_descriptor": null, "order_details": null, "allowed_payment_method_types": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": null, "payment_revenue_recovery_metadata": { "total_retry_count": 2, "payment_connector_transmission": "ConnectorCallUnsuccessful", "billing_connector_id": "bca_12345", "active_attempt_payment_connector_id": "pca_67890", "billing_connector_payment_details": { "payment_processor_token": "tok_abcdef123456", "connector_customer_id": "cust_98765" }, "payment_method_type": "card", "payment_method_subtype": "credit", "connector": "stripe", "billing_connector_payment_method_details": { "type": "Card", "value": { "card_network": "Visa", "card_issuer": "HDFC Bank" } }, "invoice_next_billing_time": "2025-06-12T15:00:00.000Z", "first_payment_attempt_pg_error_code": "PG001", "first_payment_attempt_network_decline_code": "ND002", "first_payment_attempt_network_advice_code": "AD003" } }, "payment_link_enabled": "Skip", "payment_link_config": null, "request_incremental_authorization": "default", "expires_on": "2025-06-12T11:41:33.123Z", "frm_metadata": null, "request_external_three_ds_authentication": "Skip" } ``` Check the DB for feature metadata and verify the data. Sample log: <img width="1205" alt="Screenshot 2025-06-12 at 5 02 26 PM" src="https://github.com/user-attachments/assets/b93cdf63-b8fb-4ae8-be1e-8a11d8c66a96" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Added support for capturing and displaying additional card metadata, including card network, card issuer, and card ISIN, in payment and revenue recovery data. - Enhanced error reporting by including detailed error codes from the first payment attempt, such as payment gateway error codes, network decline codes, and advice codes. - **Bug Fixes** - Improved propagation and mapping of card and error information across payment and revenue recovery processes. - **Chores** - Updated internal processes to fetch and enrich card issuer information asynchronously during revenue recovery operations. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
v1.114.0
9045eb5b65c21ee0c9746ee591b5f00bbce3b890
9045eb5b65c21ee0c9746ee591b5f00bbce3b890
juspay/hyperswitch
juspay__hyperswitch-8252
Bug: Improve Readme for better navigation Improve the Readme so it improves the navigation and format.
diff --git a/README.md b/README.md index 05764933882..a46baab5244 100644 --- a/README.md +++ b/README.md @@ -3,11 +3,14 @@ <img src="./docs/imgs/hyperswitch-logo-light.svg#gh-light-mode-only" alt="Hyperswitch-Logo" width="40%" /> </p> -<h1 align="center">Open-Source Payments Orchestration</h1> +<h1 align="center">Composable Open-Source Payments Infrastructure</h1> + +<p align="center"> + <img src="https://raw.githubusercontent.com/juspay/hyperswitch/main/docs/gifs/quickstart.gif" alt="Quickstart demo" /> +</p> -<div align="center" > -Single API to access the payments ecosystem and its features -</div> + +<!-- @import "[TOC]" {cmd="toc" depthFrom=1 depthTo=6 orderedList=false} --> <p align="center"> <a href="https://github.com/juspay/hyperswitch/actions?query=workflow%3ACI+branch%3Amain"> @@ -19,11 +22,8 @@ Single API to access the payments ecosystem and its features <a href="https://github.com/juspay/hyperswitch/blob/main/LICENSE"> <img src="https://img.shields.io/badge/Made_in-Rust-orange" /> </a> - <!-- Uncomment when we reach >50% coverage --> - <!-- <a href="https://codecov.io/github/juspay/hyperswitch" > - <img src="https://codecov.io/github/juspay/hyperswitch/graph/badge.svg"/> - </a> --> </p> + <p align="center"> <a href="https://www.linkedin.com/company/hyperswitch/"> <img src="https://img.shields.io/badge/follow-hyperswitch-blue?logo=linkedin&labelColor=grey"/> @@ -34,158 +34,177 @@ Single API to access the payments ecosystem and its features <a href="https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2jqxmpsbm-WXUENx022HjNEy~Ark7Orw"> <img src="https://img.shields.io/badge/chat-on_slack-blue?logo=slack&labelColor=grey&color=%233f0e40"/> </a> - <a href="https://deepwiki.com/juspay/hyperswitch"> - <img src="https://deepwiki.com/badge.svg" alt="Ask DeepWiki"> - </a> </p> -<hr> +<hr/> -## Table of Contents +<details> +<summary><strong>📁 Table of Contents</strong></summary> -1. [Introduction](#introduction) -2. [Try Hyperswitch](#try-hyperswitch) -3. [Architectural Overview](#architectural-overview) -4. [Community & Contributions](#community-and-contributions) -5. [Feature requests & Bugs](#feature-requests) -6. [Our Vision](#our-vision) -7. [Versioning](#versioning) -8. [Copyright and License](#copyright-and-license) +- [What Can I Do with Hyperswitch?](#-what-can-i-do-with-hyperswitch) +- [Quickstart (Local Setup)](#-quickstart-local-setup) +- [Cloud Deployment](#cloud-deployment) +- [Hosted Sandbox (No Setup Required)](#hosted-sandbox-no-setup-required) +- [Why Hyperswitch?](#-why-hyperswitch) +- [Architectural Overview](#architectural-overview) +- [Our Vision](#our-vision) +- [Community & Contributions](#community--contributions) +- [Feature Requests & Bugs](#feature-requests--bugs) +- [Versioning](#versioning) +- [License](#copyright-and-license) +- [Team Behind Hyperswitch](#team-behind-hyperswitch) -<a href="#introduction"> - <h2 id="introduction">Introduction</h2> -</a> -Juspay, founded in 2012, is a global leader in payment orchestration and checkout solutions, trusted by 400+ leading enterprises and brands worldwide. Hyperswitch is Juspay's new generation of composable, commercial open-source payments platform for merchant and brands. It is an enterprise-grade, transparent and modular payments platform designed to provide digital businesses access to the best payments infrastructure. +</details> -Here are the key components of Hyperswitch that deliver the whole solution: +<summary><h2> What Can I Do with Hyperswitch?</h2></summary> -* [Hyperswitch Backend](https://github.com/juspay/hyperswitch): Hyperswitch backend enables seamless payment processing with comprehensive support for various payment flows - authorization, authentication, void and capture workflows along with robust management of post-payment processes like refunds and chargeback handling. Additionally, Hyperswitch supports non-payment use cases by enabling connections with external FRM or authentication providers as part of the payment flow. The backend optimizes payment routing with customizable workflows, including success rate-based routing, rule-based routing, volume distribution, fallback handling, and intelligent retry mechanisms for failed payments based on specific error codes. +Hyperswitch offers a modular, open-source payments infrastructure designed for flexibility and control. Apart from our Payment Suite offering, this solution allows businesses to pick and integrate only the modules they need on top of their existing payment stack — without unnecessary complexity or vendor lock-in. -* [SDK (Frontend)](https://github.com/juspay/hyperswitch-web): The SDK, available for web, [Android, and iOS](https://github.com/juspay/hyperswitch-client-core), unifies the payment experience across various methods such as cards, wallets, BNPL, bank transfers, and more, while supporting the diverse payment flows of underlying PSPs. When paired with the locker, it surfaces the user's saved payment methods. +Each module is independent and purpose-built to optimize different aspects of payment processing. -* [Control Center](https://github.com/juspay/hyperswitch-control-center): The Control Center enables users to manage the entire payments stack without any coding. It allows the creation of workflows for routing, payment retries, and defining conditions to invoke 3DS, fraud risk management (FRM), and surcharge modules. The Control Center provides access to transaction, refund, and chargeback operations across all integrated PSPs, transaction-level logs for initial debugging, and detailed analytics and insights into payment performance. +<h3> Learn More About The Payment Modules </h3> +<details> -Read more at [Hyperswitch docs](https://docs.hyperswitch.io/). +- **Cost Observability** + Advanced observability tools to audit, monitor, and optimize your payment costs. Detect hidden fees, downgrades, and penalties with self-serve dashboards and actionable insights. + _[Read more](https://docs.hyperswitch.io/about-hyperswitch/payments-modules/ai-powered-cost-observability)_ -<a href="#try-hyperswitch"> - <h2 id="try-hyperswitch">Try Hyperswitch</h2> -</a> +- **Revenue Recovery** + Combat passive churn with intelligent retry strategies tuned by card bin, region, method, and more. Offers fine-grained control over retry algorithms, penalty budgets, and recovery transparency. + _[Read more](https://docs.hyperswitch.io/about-hyperswitch/payments-modules/revenue-recovery)_ + +- **Vault** + A PCI-compliant vault service to store cards, tokens, wallets, and bank credentials. Provides a unified, secure, and reusable store of customer-linked payment methods. + _[Read more](https://docs.hyperswitch.io/about-hyperswitch/payments-modules/vault)_ -### 1. Local Setup +- **Intelligent Routing** + Route each transaction to the PSP with the highest predicted auth rate. Reduce retries, avoid downtime, and minimize latency while maximizing first attempt success. + _[Read more](https://docs.hyperswitch.io/about-hyperswitch/payments-modules/intelligent-routing)_ -#### One-Click Setup (Recommended) +- **Reconciliation** + Automate 2-way and 3-way reconciliation with backdated support, staggered scheduling, and customizable outputs. Reduces manual ops effort and increases audit confidence. + _[Read more](https://docs.hyperswitch.io/about-hyperswitch/payments-modules/reconciliation)_ -You can run Hyperswitch on your system with a single command using our one-click setup script: +- **Alternate Payment Methods** + Drop-in widgets for PayPal, Apple Pay, Google Pay, Samsung Pay, Pay by Bank, and BNPL providers like Klarna. Maximizes conversions with seamless one-click checkout. + _[Read more](https://docs.hyperswitch.io/about-hyperswitch/payments-modules/enable-alternate-payment-method-widgets)_ + +</details> + +## Quickstart + +<h3> Local Setup via Docker </h3> + +```bash +# One-click local setup -```shell git clone --depth 1 --branch latest https://github.com/juspay/hyperswitch + cd hyperswitch + scripts/setup.sh ``` +<details> + <summary><strong>This script: </strong></summary> + + - Detects Docker/Podman + - Offers multiple deployment profiles: + - **Standard**: App server + Control Center + - **Full**: Includes monitoring + schedulers + - **Minimal**: Standalone App server + - Provides access links when done + + If you need further help, check out our [video tutorial](https://docs.hyperswitch.io/hyperswitch-open-source/overview/unified-local-setup-using-docker). -The above script will: -- Check for prerequisites (Docker Compose/Podman) -- Set up necessary configurations -- Let you select a deployment profile: - - **Standard**: Recommended - App server + Control Center + Web SDK. - - **Full**: Standard + Monitoring + Scheduler. - - **Standalone App Server**: Core services only (Hyperswitch server, PostgreSQL, Redis) -- Start the selected services -- Check service health -- Provide access information + 👉 After setup, [configure a connector](https://docs.hyperswitch.io/hyperswitch-open-source/account-setup/using-hyperswitch-control-center#add-a-payment-processor) and [test a payment](https://docs.hyperswitch.io/hyperswitch-open-source/account-setup/test-a-payment). +</details> -The next step is to [configure a connector][configure-a-connector] with the Hyperswitch Control Center and [try a payment][try-a-payment]. -Check out the [local setup guide][local-setup-guide] for more details on setting up the entire stack or component wise. +<h3>Hosted Sandbox (No Setup Required)</h3> +Hyperswitch offers a fully hosted sandbox environment that requires no setup. You can explore the Control Center, configure payment connectors, and test payments directly from the UI. -### 2. Deployment on cloud + <a href="https://app.hyperswitch.io"> + <img src="https://github.com/juspay/hyperswitch/blob/main/docs/imgs/try-the-sandbox.png?raw=true" height="35"> + </a> -The fastest and easiest way to try Hyperswitch on AWS is via our CDK scripts -1. Click on the following button for a quick standalone deployment on AWS, suitable for prototyping. - No code or setup is required in your system and the deployment is covered within the AWS free-tier setup. +<details> + <summary><strong> What you can do in the Hosted Sandbox</strong></summary> - <a href="https://console.aws.amazon.com/cloudformation/home?region=us-east-1#/stacks/new?stackName=HyperswitchBootstarp&templateURL=https://hyperswitch-synth.s3.eu-central-1.amazonaws.com/hs-starter-config.yaml"><img src="https://github.com/juspay/hyperswitch/blob/main/docs/imgs/aws_button.png?raw=true" height="35"></a> + - Access the full Control Center + - Configure payment connectors + - View logs, routing rules, and retry strategies + - Try payments directly from the UI +</details> -2. Sign-in to your AWS console. +<h3><strong>Cloud Deployment</strong></h3> -3. Follow the instructions provided on the console to successfully deploy Hyperswitch. This takes 30-45mins and gives the following output +You can deploy to AWS, GCP, or Azure using Helm or CDK scripts. Fastest path: -| Service| Host| -|----------------------------------------------|----------------------------------------------| -| App server running on | `http://hyperswitch-<host-id.region>.elb.amazonaws.com` | -| HyperloaderJS Hosted at | `http://<cloudfront.host-id>/0.103.1/v0/HyperLoader.js` | -| Control center server running on | `http://hyperswitch-control-center-<host-id.region>.elb.amazonaws.com`, Login with Email: `[email protected]` | -| Hyperswitch Demo Store running on | `http://hyperswitch-sdk-demo-<host-id.region>.elb.amazonaws.com` | -| Logs server running on | `http://hyperswitch-logs-<host-id.region>.elb.amazonaws.com`, Login with username: `admin`, password: `admin` | +Click to deploy via AWS: -We support deployment on GCP and Azure via Helm charts which takes 30-45mins. You can read more at [Hyperswitch docs](https://docs.hyperswitch.io/hyperswitch-open-source/deploy-on-kubernetes-using-helm). + <a href="https://console.aws.amazon.com/cloudformation/home?region=us-east-1#/stacks/new?stackName=HyperswitchBootstarp&templateURL=https://hyperswitch-synth.s3.eu-central-1.amazonaws.com/hs-starter-config.yaml"> + <img src="https://github.com/juspay/hyperswitch/blob/main/docs/imgs/aws_button.png?raw=true" height="35"> + </a> -### 3. Hosted Sandbox +<details> + <summary><strong>Cloud Deployment Instructions</strong></summary> + + 1. Click the AWS deployment button above to launch the stack. + 2. Follow the guided steps in the AWS Console (approx. 30–45 mins). + + ✅ This setup provisions Hyperswitch on your cloud account using CloudFormation. + + 📘 For full instructions and Helm-based deployments, check out the + <a href="https://docs.hyperswitch.io/hyperswitch-open-source/deploy-on-kubernetes-using-helm">Cloud Install Guide</a>. +</details> -You can experience the product by signing up for our [hosted sandbox](https://app.hyperswitch.io/). The signup process accepts any email ID and provides access to the entire Control Center. You can set up connectors, define workflows for routing and retries, and even try payments from the dashboard. <a href="#architectural-overview"> <h2 id="architectural-overview">Architectural Overview</h2> </a> <img src="./docs/imgs/features.png" /> <img src="./docs/imgs/non-functional-features.png" /> - <img src="./docs/imgs/hyperswitch-architecture-v1.png" /> -[docs-link-for-enterprise]: https://docs.hyperswitch.io/hyperswitch-cloud/quickstart -[docs-link-for-developers]: https://docs.hyperswitch.io/hyperswitch-open-source/overview -[contributing-guidelines]: docs/CONTRIBUTING.md -[dashboard-link]: https://app.hyperswitch.io/ -[website-link]: https://hyperswitch.io/ -[learning-resources]: https://docs.hyperswitch.io/learn-more/payment-flows -[local-setup-guide]: /docs/try_local_system.md -[docker-compose-scheduler-monitoring]: /docs/try_local_system.md#running-additional-services -[configure-a-connector]: https://docs.hyperswitch.io/hyperswitch-open-source/account-setup/using-hyperswitch-control-center#add-a-payment-processor -[try-a-payment]: https://docs.hyperswitch.io/hyperswitch-open-source/account-setup/test-a-payment - -<a href="community-and-contributions"> - <h2 id="community-and-contributions">Community & Contributions</h2> -</a> +## Why Hyperswitch? -If you have any questions, feel free to drop them in our [Slack community](https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2jqxmpsbm-WXUENx022HjNEy~Ark7Orw). +Hyperswitch is a commercial open-source payments stack purpose-built for scale, flexibility, and developer experience. Designed with a modular architecture, Hyperswitch lets you pick only the components you need—whether it’s routing, retries, vaulting, or observability—without vendor lock-in or bloated integrations. -We welcome contributors from around the world to help build Hyperswitch. To get started, please read our [contribution guidelines](contributing-guidelines). +Built in Rust for performance and reliability, Hyperswitch supports global payment methods (cards, wallets, BNPL, UPI, Pay by Bank), exposes smart routing and retry logic, and provides a visual workflow builder in the Control Center. Whether you're integrating a full payment suite or augmenting an existing stack with a single module, Hyperswitch meets you where you are. -<a href="feature-requests"> - <h2 id="feature-requests">Feature requests & Bugs</h2> -</a> +<strong>“Linux for Payments”</strong> — Hyperswitch is a well-architected reference for teams who want to own their payments stack. -For new product features, enhancements, roadmap discussions, or to share queries and ideas, visit our [GitHub Discussions](https://github.com/juspay/hyperswitch/discussions) +We believe in: -For reporting a bug, please read the issue guidelines and search for [existing and closed issues]. If your problem or idea is not addressed yet, please [open a new issue]. +- <strong> Embracing Payment Diversity:</strong> Innovation comes from enabling choice—across payment methods, processors, and flows. -[existing and closed issues]: https://github.com/juspay/hyperswitch/issues -[open a new issue]: https://github.com/juspay/hyperswitch/issues/new/choose +- <strong> Open Source by Default:</strong> Transparency drives trust and builds better, reusable software. -<a href="our-vision"> - <h2 id="our-vision">Our Vision</h2> -</a> +- <strong> Community-Driven Development:</strong> Our roadmap is shaped by real-world use cases and contributors. -> Linux for Payments +- <strong> Systems-Level Engineering:</strong> We hold ourselves to a high bar for reliability, security, and performance. -Payments are evolving rapidly worldwide, with hundreds of processors, fraud detection systems, authentication modules, and new payment methods and flows emerging. Businesses building or managing their own payment stacks often face similar challenges, struggle with comparable issues, and find it hard to innovate at the desired pace. +- <strong> Maximizing Value Creation:</strong> For developers, customers, and partners alike. -Hyperswitch serves as a well-architected designed reference platform, built on best-in-class design principles, empowering businesses to own and customize their payment stack. It provides a reusable core payments stack that can be tailored to specific requirements while relying on the Hyperswitch team for enhancements, support, and continuous innovation. +- <strong> Community-Driven, Enterprise-Tested:</strong> Hyperswitch is built in the open with real-world feedback from developers and contributors, and maintained by Juspay, the team powering payment infrastructure for 400+ leading enterprises worldwide. -### Our Values +## Contributing -1. Embrace Payments Diversity: It will drive innovation in the ecosystem in - multiple ways. -2. Make it Open Source: Increases trust; Improves the quality and reusability of - software. -3. Be community driven: It enables participatory design and development. -4. Build it like Systems Software: This sets a high bar for Reliability, - Security and Performance SLAs. -5. Maximise Value Creation: For developers, customers & partners. +We welcome contributors from around the world to help build Hyperswitch. Whether you're fixing bugs, improving documentation, or adding new features, your help is appreciated. -This project is being created and maintained by [Juspay](https://juspay.io) +Please read our [contributing guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) to get started. + +Join the conversation on [Slack](https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2jqxmpsbm-WXUENx022HjNEy~Ark7Orw) or explore open issues on [GitHub](https://github.com/juspay/hyperswitch/issues). + +<a href="#feature-requests"> + <h2 id="feature-requests">Feature requests & Bugs</h2> +</a> + +For new product features, enhancements, roadmap discussions, or to share queries and ideas, visit our [GitHub Discussions](https://github.com/juspay/hyperswitch/discussions) + +For reporting a bug, please read the issue guidelines and search for [existing and closed issues](https://github.com/juspay/hyperswitch/issues). If your problem or idea is not addressed yet, please [open a new issue](https://github.com/juspay/hyperswitch/issues/new/choose). <a href="#versioning"> <h2 id="versioning">Versioning</h2> @@ -199,8 +218,7 @@ Check the [CHANGELOG.md](./CHANGELOG.md) file for details. This product is licensed under the [Apache 2.0 License](LICENSE). - -<a href="team-behind-hyperswitch"> +<a href="#team-behind-hyperswitch"> <h2 id="team-behind-hyperswitch">Team behind Hyperswitch</h2> </a> diff --git a/docs/gifs/quickstart.gif b/docs/gifs/quickstart.gif new file mode 100644 index 00000000000..d749ce798ff Binary files /dev/null and b/docs/gifs/quickstart.gif differ diff --git a/docs/imgs/try-the-sandbox.png b/docs/imgs/try-the-sandbox.png new file mode 100644 index 00000000000..a1b2edf5d04 Binary files /dev/null and b/docs/imgs/try-the-sandbox.png differ
2025-06-04T21:52:44Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> I updated the readme for better navigation ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? updated the readme for improved developer experience If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
4a7c08fbc57f9712f1ff478d01d4929b9576b448
4a7c08fbc57f9712f1ff478d01d4929b9576b448
juspay/hyperswitch
juspay__hyperswitch-8268
Bug: docs: API reference improvements API Reference needed some context on the payments flows, and improvements in some descriptions.
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index d88111cc43e..09346e388fd 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -3990,7 +3990,7 @@ "properties": { "city": { "type": "string", - "description": "The address city", + "description": "The city, district, suburb, town, or village of the address.", "example": "New York", "nullable": true, "maxLength": 50 @@ -4005,21 +4005,21 @@ }, "line1": { "type": "string", - "description": "The first line of the address", + "description": "The first line of the street address or P.O. Box.", "example": "123, King Street", "nullable": true, "maxLength": 200 }, "line2": { "type": "string", - "description": "The second line of the address", + "description": "The second line of the street address or P.O. Box (e.g., apartment, suite, unit, or building).", "example": "Powelson Avenue", "nullable": true, "maxLength": 50 }, "line3": { "type": "string", - "description": "The third line of the address", + "description": "The third line of the street address, if applicable.", "example": "Bridgewater", "nullable": true, "maxLength": 50 @@ -4899,7 +4899,7 @@ }, "AuthenticationType": { "type": "string", - "description": "Pass this parameter to force 3DS or non 3DS auth for this payment. Some connectors will still force 3DS auth even in case of passing 'no_three_ds' here and vice versa. Default value is 'no_three_ds' if not set", + "description": "Specifies the type of cardholder authentication to be applied for a payment.\n\n- `ThreeDs`: Requests 3D Secure (3DS) authentication. If the card is enrolled, 3DS authentication will be activated, potentially shifting chargeback liability to the issuer.\n- `NoThreeDs`: Indicates that 3D Secure authentication should not be performed. The liability for chargebacks typically remains with the merchant. This is often the default if not specified.\n\nNote: The actual authentication behavior can also be influenced by merchant configuration and specific connector defaults. Some connectors might still enforce 3DS or bypass it regardless of this parameter.", "enum": [ "three_ds", "no_three_ds" @@ -7081,7 +7081,7 @@ }, "CaptureMethod": { "type": "string", - "description": "Default value if not passed is set to 'automatic' which results in Auth and Capture in one single API request. Pass 'manual' or 'manual_multiple' in case you want do a separate Auth and Capture by first authorizing and placing a hold on your customer's funds so that you can use the Payments/Capture endpoint later to capture the authorized amount. Pass 'manual' if you want to only capture the amount later once or 'manual_multiple' if you want to capture the funds multiple times later. Both 'manual' and 'manual_multiple' are only supported by a specific list of processors", + "description": "Specifies how the payment is captured.\n- `automatic`: Funds are captured immediately after successful authorization. This is the default behavior if the field is omitted.\n- `manual`: Funds are authorized but not captured. A separate request to the `/payments/{payment_id}/capture` endpoint is required to capture the funds.", "enum": [ "automatic", "manual", @@ -7103,7 +7103,7 @@ "properties": { "capture_id": { "type": "string", - "description": "Unique identifier for the capture" + "description": "A unique identifier for this specific capture operation." }, "status": { "$ref": "#/components/schemas/CaptureStatus" @@ -7124,11 +7124,11 @@ }, "connector": { "type": "string", - "description": "The connector used for the payment" + "description": "The name of the payment connector that processed this capture." }, "authorized_attempt_id": { "type": "string", - "description": "Unique identifier for the parent attempt on which this capture is made" + "description": "The ID of the payment attempt that was successfully authorized and subsequently captured by this operation." }, "connector_capture_id": { "type": "string", @@ -7142,22 +7142,22 @@ }, "error_message": { "type": "string", - "description": "If there was an error while calling the connector the error message is received here", + "description": "A human-readable message from the connector explaining why this capture operation failed, if applicable.", "nullable": true }, "error_code": { "type": "string", - "description": "If there was an error while calling the connectors the code is received here", + "description": "The error code returned by the connector if this capture operation failed. This code is connector-specific.", "nullable": true }, "error_reason": { "type": "string", - "description": "If there was an error while calling the connectors the reason is received here", + "description": "A more detailed reason from the connector explaining the capture failure, if available.", "nullable": true }, "reference_id": { "type": "string", - "description": "Reference to the capture at connector side", + "description": "The connector's own reference or transaction ID for this specific capture operation. Useful for reconciliation.", "nullable": true } } @@ -9148,7 +9148,7 @@ }, "Currency": { "type": "string", - "description": "The three letter ISO currency code in uppercase. Eg: 'USD' for the United States Dollar.", + "description": "The three-letter ISO 4217 currency code (e.g., \"USD\", \"EUR\") for the payment amount. This field is mandatory for creating a payment.", "enum": [ "AED", "AFN", @@ -11308,7 +11308,7 @@ }, "FutureUsage": { "type": "string", - "description": "Indicates that you intend to make future payments with the payment methods used for this Payment. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\n- On_session - Payment method saved only at hyperswitch when consent is provided by the user. CVV will asked during the returning user payment\n- Off_session - Payment method saved at both hyperswitch and Processor when consent is provided by the user. No input is required during the returning user payment.", + "description": "Specifies how the payment method can be used for future payments.\n- `off_session`: The payment method can be used for future payments when the customer is not present.\n- `on_session`: The payment method is intended for use only when the customer is present during checkout.\nIf omitted, defaults to `on_session`.", "enum": [ "off_session", "on_session" @@ -12364,7 +12364,7 @@ }, "IntentStatus": { "type": "string", - "description": "The status of the current payment that was made", + "description": "Represents the overall status of a payment intent.\nThe status transitions through various states depending on the payment method, confirmation, capture method, and any subsequent actions (like customer authentication or manual capture).", "enum": [ "succeeded", "failed", @@ -17959,7 +17959,6 @@ }, "payment_token": { "type": "string", - "description": "Provide a reference to a stored payment method", "example": "187282ab-40ef-47a9-9206-5099ba31e432", "nullable": true } @@ -24028,6 +24027,7 @@ }, "ThreeDsCompletionIndicator": { "type": "string", + "description": "Indicates if 3DS method data was successfully completed or not", "enum": [ "Y", "N", diff --git a/api-reference/api-reference/payments/payment--flows.mdx b/api-reference/api-reference/payments/payment--flows.mdx new file mode 100644 index 00000000000..eff90a0dcb8 --- /dev/null +++ b/api-reference/api-reference/payments/payment--flows.mdx @@ -0,0 +1,256 @@ +--- +tags: [Payments] +sidebarTitle: "Payment Flows" +icon: "arrows-retweet" +iconType: "solid" +--- +Hyperswitch provides flexible payment processing with multiple flow patterns to accommodate different business needs. The system supports one-time payments, saved payment methods, and recurring billing through a comprehensive API design. + +```mermaid +graph TD + A["Payment Request"] --> B{"Payment Type"} + B -->|One-time| C["One-time Payment Flows"] + B -->|Save for Future| D["Payment Method Storage"] + B -->|Recurring| E["Recurring Payment Flows"] + + C --> C1["Instant Payment"] + C --> C2["Manual Capture"] + C --> C3["Decoupled Flow"] + C --> C4["3DS Authentication"] + + D --> D1["Save During Payment"] + D --> D2["List Saved Methods"] + + E --> E1["Setup (CIT)"] + E --> E2["Execute (MIT)"] +``` + +## One-Time Payment Patterns + +### 1. Instant Payment (Automatic Capture) +**Use Case:** Simple, immediate payment processing + +**Endpoint:** +`POST /payments` + +```mermaid +sequenceDiagram + participant Client + participant Hyperswitch + participant Processor + + Client->>Hyperswitch: POST /payments<br/>{confirm: true, capture_method: "automatic"} + Hyperswitch->>Processor: Authorize + Capture + Processor-->>Hyperswitch: Payment Complete + Hyperswitch-->>Client: Status: succeeded +``` + +**Required Fields:** +- `confirm: true` +- `capture_method: "automatic"` +- `payment_method` + +**Final Status:** `succeeded` + +### 2. Two-Step Manual Capture +**Use Case:** Deferred settlement (e.g., ship before charging) + +```mermaid +sequenceDiagram + participant Client + participant Hyperswitch + participant Processor + + Client->>Hyperswitch: POST /payments<br/>{confirm: true, capture_method: "manual"} + Hyperswitch->>Processor: Authorize Only + Processor-->>Hyperswitch: Authorization Hold + Hyperswitch-->>Client: Status: requires_capture + + Note over Client: Ship goods, then capture + + Client->>Hyperswitch: POST /payments/{id}/capture + Hyperswitch->>Processor: Capture Funds + Processor-->>Hyperswitch: Capture Complete + Hyperswitch-->>Client: Status: succeeded +``` + +**Flow:** +1. **Authorize:** `POST /payments` with `capture_method: "manual"` +2. **Status:** `requires_capture` +3. **Capture:** `POST /payments/{payment_id}/capture` +4. **Final Status:** `succeeded` + +### 3. Fully Decoupled Flow +**Use Case:** Complex checkout journeys with multiple modification steps. Useful in headless checkout or B2B portals where data is filled progressively. + +```mermaid +sequenceDiagram + participant Client + participant Hyperswitch + + Client->>Hyperswitch: POST /payments<br/>(Create Intent) + Hyperswitch-->>Client: payment_id + client_secret + + Client->>Hyperswitch: POST /payments/{id}<br/>(Update: customer, amount, etc.) + Hyperswitch-->>Client: Updated Intent + + Client->>Hyperswitch: POST /payments/{id}/confirm<br/>(Final Confirmation) + Hyperswitch-->>Client: Status: succeeded/requires_capture + + opt Manual Capture + Client->>Hyperswitch: POST /payments/{id}/capture + Hyperswitch-->>Client: Status: succeeded + end +``` + +**Endpoints:** +- **Create:** + `POST /payments` +- **Update:** + `POST /payments/{payment_id}` +- **Confirm:** + `POST /payments/{payment_id}/confirm` +- **Capture:** + `POST /payments/{payment_id}/capture` (if manual) + +### 4. 3D Secure Authentication Flow +**Use Case:** Enhanced security with customer authentication + +```mermaid +sequenceDiagram + participant Client + participant Hyperswitch + participant Customer + participant Bank + + Client->>Hyperswitch: POST /payments<br/>{authentication_type: "three_ds"} + Hyperswitch-->>Client: Status: requires_customer_action<br/>+ redirect_url + + Client->>Customer: Redirect to 3DS page + Customer->>Bank: Complete 3DS Challenge + Bank-->>Hyperswitch: Authentication Result + Hyperswitch->>Hyperswitch: Resume Payment Processing + Hyperswitch-->>Client: Status: succeeded +``` + +**Additional Fields:** +- `authentication_type: "three_ds"` + +**Status Progression:** `processing` → `requires_customer_action` → `succeeded` + +## Payment Method Management + +### 1. Saving Payment Methods + +```mermaid +graph LR + A["Payment Request"] --> B["Add setup_future_usage"] + B --> C{"Usage Type"} + C -->|"off_session"| D["For Recurring/MIT"] + C -->|"on_session"| E["For Customer-Present"] + D --> F["payment_method_id Returned"] + E --> F +``` + +**During Payment Creation:** +- Add `setup_future_usage: "off_session"` or `"on_session"` +- Include `customer_id` +- **Result:** `payment_method_id` returned on success + +**Understanding `setup_future_usage`:** +- **`on_session`**: Use when the customer is actively present during the transaction. This is typical for scenarios like saving card details for faster checkouts in subsequent sessions where the customer will still be present to initiate the payment (e.g., card vaulting for e-commerce sites). +- **`off_session`**: Use when you intend to charge the customer later without their active involvement at the time of charge. This is suitable for subscriptions, recurring billing, or merchant-initiated transactions (MITs) where the customer has pre-authorized future charges. + +### 2. Using Saved Payment Methods + +```mermaid +sequenceDiagram + participant Client + participant Hyperswitch + + Client->>Hyperswitch: POST /payments/create<br/>{customer_id} + Hyperswitch-->>Client: client_secret + + Client->>Hyperswitch: GET /customers/payment_methods<br/>{client_secret, publishable_key} + Hyperswitch-->>Client: List of payment_tokens + + Client->>Hyperswitch: POST /payments/{id}/confirm<br/>{payment_token} + Hyperswitch-->>Client: Payment Result +``` + +**Steps:** +1. **Initiate:** Create payment with `customer_id` +2. **List:** Get saved cards via `GET /customers/payment_methods` +3. **Confirm:** Use selected `payment_token` in confirm call + +### PCI Compliance and `payment_method_id` +Storing `payment_method_id` (which is a token representing the actual payment instrument, which could be a payment token, network token, or payment processor token) significantly reduces your PCI DSS scope. Hyperswitch securely stores the sensitive card details and provides you with this token. While you still need to ensure your systems handle `payment_method_id` and related customer data securely, you avoid the complexities of storing raw card numbers. Always consult with a PCI QSA to understand your specific compliance obligations. + +## Recurring Payment Flows + +### 3. Customer-Initiated Transaction (CIT) Setup + +```mermaid +graph TD + A["CIT Setup"] --> B{"Setup Type"} + B -->|"With Charge"| C["Amount > 0<br/>setup_future_usage: off_session"] + B -->|"Zero Dollar Auth"| D["Amount: 0<br/>payment_type: setup_mandate"] + C --> E["payment_method_id"] + D --> E +``` + +**Option 1 - Setup with Charge:** +- `setup_future_usage: "off_session"` +- `amount > 0` + +**Option 2 - Zero Dollar Authorization:** +- `setup_future_usage: "off_session"` +- `amount: 0` +- `payment_type: "setup_mandate"` + +### 4. Merchant-Initiated Transaction (MIT) Execution + +```mermaid +sequenceDiagram + participant Merchant + participant Hyperswitch + participant Processor + + Note over Merchant: Subscription billing trigger + + Merchant->>Hyperswitch: POST /payments<br/>{off_session: true, recurring_details} + Hyperswitch->>Processor: Process with saved payment_method_id + Processor-->>Hyperswitch: Payment Result + Hyperswitch-->>Merchant: Status: succeeded +``` + +**Required Fields:** +- `off_session: true` +- `recurring_details: { payment_method_id: "<from_setup>" }` + +**Use Case:** Subscription charges, scheduled billing without customer interaction + +## Status Flow Summary + +```mermaid +stateDiagram-v2 + [*] --> RequiresConfirmation + RequiresConfirmation --> Processing: confirm=true + Processing --> RequiresCustomerAction: 3DS needed + RequiresCustomerAction --> Processing: 3DS complete + Processing --> RequiresCapture: manual capture + Processing --> Succeeded: automatic capture + RequiresCapture --> Succeeded: capture API call + RequiresCapture --> PartiallyCaptured: partial capture + PartiallyCaptured --> [*] + Succeeded --> [*] + Processing --> Failed: payment failed + Failed --> [*] +``` + +## Notes + +- **Terminal States:** `succeeded`, `failed`, `cancelled`, `partially_captured` are terminal states requiring no further action +- **Capture Methods:** System supports `automatic` (funds captured immediately), `manual` (funds captured in a separate step), `manual_multiple` (funds captured in multiple partial amounts via separate steps), and `scheduled` (funds captured automatically at a future predefined time) capture methods. +- **Authentication:** 3DS authentication automatically resumes payment processing after customer completion +- **MIT Compliance:** Off-session recurring payments follow industry standards for merchant-initiated transactions diff --git a/api-reference/api-reference/payments/Introduction--to--payments.mdx b/api-reference/api-reference/payments/setup--instructions.mdx similarity index 97% rename from api-reference/api-reference/payments/Introduction--to--payments.mdx rename to api-reference/api-reference/payments/setup--instructions.mdx index 2893aec261b..62de90d58c1 100644 --- a/api-reference/api-reference/payments/Introduction--to--payments.mdx +++ b/api-reference/api-reference/payments/setup--instructions.mdx @@ -1,11 +1,9 @@ --- tags: [Payments] -sidebarTitle: "Getting Started with Payments" -icon: "circle-play" +sidebarTitle: "Setup Instructions" +icon: "flag" iconType: "solid" -color: "Green" --- - The **Hyperswitch Payments API** enables businesses to **accept, process, and manage payments seamlessly**. It supports the entire **payment lifecycle**—from creation to capture, refunds, and disputes—allowing smooth integration of **various payment methods** into any application with minimal complexity. ### How to try your first payment through hyperswitch? @@ -57,4 +55,3 @@ Each option has specific nuances, we have mentioned the differences in the below Test the use cases you are interested in and in case of difficulty, feel free to contact us on our [slack channel](https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2jqxmpsbm-WXUENx022HjNEy~Ark7Orw) </Step> </Steps> ---- diff --git a/api-reference/docs.json b/api-reference/docs.json new file mode 100644 index 00000000000..7727f1e8650 --- /dev/null +++ b/api-reference/docs.json @@ -0,0 +1,377 @@ +{ + "$schema": "https://mintlify.com/docs.json", + "theme": "mint", + "name": "Hyperswitch", + "colors": { + "primary": "#4F8EFF", + "light": "#6BA3FF", + "dark": "#2563EB" + }, + "favicon": "/favicon.png", + "navigation": { + "tabs": [ + { + "tab": "Documentation", + "groups": [ + { + "group": "Get Started", + "pages": [ + "introduction" + ] + }, + { + "group": "Essentials", + "pages": [ + "essentials/error_codes", + "essentials/rate_limit", + "essentials/go-live" + ] + }, + { + "group": "Payments Core APIs", + "pages": [ + "api-reference/payments/setup--instructions", + "api-reference/payments/payment--flows", + { + "group": "Payments", + "pages": [ + "api-reference/payments/payments--create", + "api-reference/payments/payments--update", + "api-reference/payments/payments--confirm", + "api-reference/payments/payments--retrieve", + "api-reference/payments/payments--cancel", + "api-reference/payments/payments--capture", + "api-reference/payments/payments--incremental-authorization", + "api-reference/payments/payments--session-token", + "api-reference/payments/payments-link--retrieve", + "api-reference/payments/payments--list", + "api-reference/payments/payments--external-3ds-authentication", + "api-reference/payments/payments--complete-authorize", + "api-reference/payments/payments--update-metadata" + ] + }, + { + "group": "Payment Methods", + "pages": [ + "api-reference/payment-methods/paymentmethods--create", + "api-reference/payment-methods/payment-method--retrieve", + "api-reference/payment-methods/payment-method--update", + "api-reference/payment-methods/payment-method--delete", + "api-reference/payment-methods/payment-method--set-default-payment-method-for-customer", + "api-reference/payment-methods/list-payment-methods-for-a-merchant", + "api-reference/payment-methods/list-customer-saved-payment-methods-for-a-payment", + "api-reference/payment-methods/list-payment-methods-for-a-customer", + "api-reference/customer-set-default-payment-method/customers--set-default-payment-method" + ] + }, + { + "group": "Customers", + "pages": [ + "api-reference/customers/customers--create", + "api-reference/customers/customers--retrieve", + "api-reference/customers/customers--update", + "api-reference/customers/customers--delete", + "api-reference/customers/customers--list" + ] + }, + { + "group": "Mandates", + "pages": [ + "api-reference/mandates/mandates--revoke-mandate", + "api-reference/mandates/mandates--retrieve-mandate", + "api-reference/mandates/mandates--customer-mandates-list" + ] + }, + { + "group": "Refunds", + "pages": [ + "api-reference/refunds/refunds--create", + "api-reference/refunds/refunds--update", + "api-reference/refunds/refunds--retrieve", + "api-reference/refunds/refunds--list" + ] + }, + { + "group": "Disputes", + "pages": [ + "api-reference/disputes/disputes--retrieve", + "api-reference/disputes/disputes--list" + ] + }, + { + "group": "Payouts", + "pages": [ + "api-reference/payouts/payouts--create", + "api-reference/payouts/payouts--update", + "api-reference/payouts/payouts--cancel", + "api-reference/payouts/payouts--fulfill", + "api-reference/payouts/payouts--confirm", + "api-reference/payouts/payouts--retrieve", + "api-reference/payouts/payouts--list", + "api-reference/payouts/payouts--list-filters", + "api-reference/payouts/payouts--filter" + ] + } + ] + }, + { + "group": "Account management APIs", + "pages": [ + { + "group": "Organization", + "pages": [ + "api-reference/organization/organization--create", + "api-reference/organization/organization--retrieve", + "api-reference/organization/organization--update" + ] + }, + { + "group": "Merchant Account", + "pages": [ + "api-reference/merchant-account/merchant-account--create", + "api-reference/merchant-account/merchant-account--retrieve", + "api-reference/merchant-account/merchant-account--update", + "api-reference/merchant-account/merchant-account--delete", + "api-reference/merchant-account/merchant-account--kv-status" + ] + }, + { + "group": "Business Profile", + "pages": [ + "api-reference/business-profile/business-profile--create", + "api-reference/business-profile/business-profile--update", + "api-reference/business-profile/business-profile--retrieve", + "api-reference/business-profile/business-profile--delete", + "api-reference/business-profile/business-profile--list" + ] + }, + { + "group": "API Key", + "pages": [ + "api-reference/api-key/api-key--create", + "api-reference/api-key/api-key--retrieve", + "api-reference/api-key/api-key--update", + "api-reference/api-key/api-key--revoke", + "api-reference/api-key/api-key--list" + ] + }, + { + "group": "Merchant Connector Account", + "pages": [ + "api-reference/merchant-connector-account/merchant-connector--create", + "api-reference/merchant-connector-account/merchant-connector--retrieve", + "api-reference/merchant-connector-account/merchant-connector--update", + "api-reference/merchant-connector-account/merchant-connector--delete", + "api-reference/merchant-connector-account/merchant-connector--list" + ] + }, + { + "group": "GSM (Global Status Mapping)", + "pages": [ + "api-reference/gsm/gsm--create", + "api-reference/gsm/gsm--get", + "api-reference/gsm/gsm--update", + "api-reference/gsm/gsm--delete" + ] + } + ] + }, + { + "group": "Other APIs", + "pages": [ + { + "group": "Event", + "pages": [ + "api-reference/event/events--list", + "api-reference/event/events--delivery-attempt-list", + "api-reference/event/events--manual-retry" + ] + }, + { + "group": "Poll", + "pages": [ + "api-reference/poll/poll--retrieve-poll-status" + ] + }, + { + "group": "Blocklist", + "pages": [ + "api-reference/blocklist/get-blocklist", + "api-reference/blocklist/post-blocklist", + "api-reference/blocklist/delete-blocklist", + "api-reference/blocklist/post-blocklisttoggle" + ] + }, + { + "group": "Routing", + "pages": [ + "api-reference/routing/routing--list", + "api-reference/routing/routing--create", + "api-reference/routing/routing--retrieve-config", + "api-reference/routing/routing--deactivate", + "api-reference/routing/routing--retrieve-default-config", + "api-reference/routing/routing--update-default-config", + "api-reference/routing/routing--retrieve-default-for-profile", + "api-reference/routing/routing--update-default-for-profile", + "api-reference/routing/routing--retrieve", + "api-reference/routing/routing--activate-config" + ] + }, + { + "group": "Relay", + "pages": [ + "api-reference/relay/relay", + "api-reference/relay/relay--retrieve" + ] + }, + { + "group": "Schemas", + "pages": [ + "api-reference/schemas/outgoing--webhook" + ] + } + ] + } + ] + }, + { + "tab": "Locker API Reference", + "groups": [ + { + "group": "Hyperswitch Card Vault", + "pages": [ + "locker-api-reference/overview" + ] + }, + { + "group": "API Reference", + "pages": [ + { + "group": "Locker - Health", + "pages": [ + "locker-api-reference/locker-health/get-health" + ] + }, + { + "group": "Locker - Key Custodian", + "pages": [ + "locker-api-reference/key-custodian/provide-key-1", + "locker-api-reference/key-custodian/provide-key-2", + "locker-api-reference/key-custodian/unlock-the-locker" + ] + }, + { + "group": "Locker - Cards", + "pages": [ + "locker-api-reference/cards/add-data-in-locker", + "locker-api-reference/cards/delete-data-from-locker", + "locker-api-reference/cards/retrieve-data-from-locker", + "locker-api-reference/cards/get-or-insert-the-card-fingerprint" + ] + } + ] + } + ] + }, + { + "tab": "Intelligent Router API Reference", + "groups": [ + { + "group": "Hyperswitch Intelligent Router", + "pages": [ + "intelligent-router-api-reference/overview" + ] + }, + { + "group": "API Reference", + "pages": [ + { + "group": "Success Rate", + "pages": [ + "intelligent-router-api-reference/success-rate/fetch-success-rate-for-an-entity", + "intelligent-router-api-reference/success-rate/update-success-rate-window", + "intelligent-router-api-reference/success-rate/invalidate-windows", + "intelligent-router-api-reference/success-rate/fetch-entity-and-global-success-rates" + ] + }, + { + "group": "Elimination", + "pages": [ + "intelligent-router-api-reference/elimination/fetch-eliminated-processor-list", + "intelligent-router-api-reference/elimination/update-elimination-bucket", + "intelligent-router-api-reference/elimination/invalidate-elimination-bucket" + ] + }, + { + "group": "Contract Routing", + "pages": [ + "intelligent-router-api-reference/contract-routing/fetch-contract-scores-for-an-entity", + "intelligent-router-api-reference/contract-routing/update-contract-information-for-an-entity", + "intelligent-router-api-reference/contract-routing/invalidate-contract-information-for-an-entity" + ] + }, + { + "group": "Static Routing", + "pages": [ + "intelligent-router-api-reference/static-routing/create-a-routing-rule", + "intelligent-router-api-reference/static-routing/evaluate-routing-rule" + ] + } + ] + } + ] + } + ] + }, + "logo": { + "light": "/logo/light.svg", + "dark": "/logo/dark.svg" + }, + "api": { + "openapi": [ + "openapi_spec.json", + "rust_locker_open_api_spec.yml" + ] + }, + "background": { + "color": { + "light": "#FAFBFC", + "dark": "#1d1d1d" + } + }, + "navbar": { + "links": [ + { + "label": "Contact Us", + "href": "https://inviter.co/hyperswitch-slack" + } + ], + "primary": { + "type": "button", + "label": "Self-Deploy", + "href": "https://docs.hyperswitch.io/hyperswitch-open-source/overview" + } + }, + "footer": { + "socials": { + "github": "https://github.com/juspay/hyperswitch", + "linkedin": "https://www.linkedin.com/company/hyperswitch" + } + }, + "integrations": { + "gtm": { + "tagId": "GTM-PLBNKQFQ" + }, + "mixpanel": { + "projectToken": "b00355f29d9548d1333608df71d5d53d" + } + }, + "contextual": { + "options": [ + "copy", + "claude", + "chatgpt", + "view" + ] + } +} \ No newline at end of file diff --git a/api-reference/mint.json b/api-reference/mint.json deleted file mode 100644 index 4eea12777b0..00000000000 --- a/api-reference/mint.json +++ /dev/null @@ -1,366 +0,0 @@ -{ - "$schema": "https://mintlify.com/schema.json", - "name": "Hyperswitch", - "logo": { - "dark": "/logo/dark.svg", - "light": "/logo/light.svg" - }, - "topbarLinks": [ - { - "name": "Contact Us", - "url": "https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2jqxmpsbm-WXUENx022HjNEy~Ark7Orw" - } - ], - "topbarCtaButton": { - "type": "link", - "url": "https://docs.hyperswitch.io/hyperswitch-open-source/overview", - "name": "Self-Deploy" - }, - "favicon": "/favicon.png", - "colors": { - "primary": "#006DF9", - "light": "#006DF9", - "dark": "#006DF9", - "background": { - "dark": "#242F48" - } - }, - "sidebar": { - "items": "card" - }, - "tabs": [ - { - "name": "Locker API Reference", - "url": "locker-api-reference" - }, - { - "name": "Intelligent Router API Reference", - "url": "intelligent-router-api-reference" - } - ], - "navigation": [ - { - "group": "Get Started", - "pages": [ - "introduction" - ] - }, - { - "group": "Essentials", - "pages": [ - "essentials/error_codes", - "essentials/rate_limit", - "essentials/go-live" - ] - }, - { - "group": "API Reference", - "pages": [ - { - "group": "Payments", - "pages": [ - "api-reference/payments/Introduction--to--payments", - "api-reference/payments/payments--create", - "api-reference/payments/payments--update", - "api-reference/payments/payments--confirm", - "api-reference/payments/payments--retrieve", - "api-reference/payments/payments--cancel", - "api-reference/payments/payments--capture", - "api-reference/payments/payments--incremental-authorization", - "api-reference/payments/payments--session-token", - "api-reference/payments/payments-link--retrieve", - "api-reference/payments/payments--list", - "api-reference/payments/payments--external-3ds-authentication", - "api-reference/payments/payments--complete-authorize", - "api-reference/payments/payments--update-metadata" - ] - }, - { - "group": "Payment Methods", - "pages": [ - "api-reference/payment-methods/paymentmethods--create", - "api-reference/payment-methods/payment-method--retrieve", - "api-reference/payment-methods/payment-method--update", - "api-reference/payment-methods/payment-method--delete", - "api-reference/payment-methods/payment-method--set-default-payment-method-for-customer", - "api-reference/payment-methods/list-payment-methods-for-a-merchant", - "api-reference/payment-methods/list-customer-saved-payment-methods-for-a-payment", - "api-reference/payment-methods/list-payment-methods-for-a-customer", - "api-reference/customer-set-default-payment-method/customers--set-default-payment-method" - ] - }, - { - "group": "Customers", - "pages": [ - "api-reference/customers/customers--create", - "api-reference/customers/customers--retrieve", - "api-reference/customers/customers--update", - "api-reference/customers/customers--delete", - "api-reference/customers/customers--list" - ] - }, - { - "group": "Mandates", - "pages": [ - "api-reference/mandates/mandates--revoke-mandate", - "api-reference/mandates/mandates--retrieve-mandate", - "api-reference/mandates/mandates--customer-mandates-list" - ] - }, - { - "group": "Refunds", - "pages": [ - "api-reference/refunds/refunds--create", - "api-reference/refunds/refunds--update", - "api-reference/refunds/refunds--retrieve", - "api-reference/refunds/refunds--list" - ] - }, - { - "group": "Disputes", - "pages": [ - "api-reference/disputes/disputes--retrieve", - "api-reference/disputes/disputes--list" - ] - }, - { - "group": "Payouts", - "pages": [ - "api-reference/payouts/payouts--create", - "api-reference/payouts/payouts--update", - "api-reference/payouts/payouts--cancel", - "api-reference/payouts/payouts--fulfill", - "api-reference/payouts/payouts--confirm", - "api-reference/payouts/payouts--retrieve", - "api-reference/payouts/payouts--list", - "api-reference/payouts/payouts--list-filters", - "api-reference/payouts/payouts--filter" - ] - }, - { - "group": "Event", - "pages": [ - "api-reference/event/events--list", - "api-reference/event/events--delivery-attempt-list", - "api-reference/event/events--manual-retry" - ] - }, - { - "group": "Poll", - "pages": [ - "api-reference/poll/poll--retrieve-poll-status" - ] - }, - { - "group": "Blocklist", - "pages": [ - "api-reference/blocklist/get-blocklist", - "api-reference/blocklist/post-blocklist", - "api-reference/blocklist/delete-blocklist", - "api-reference/blocklist/post-blocklisttoggle" - ] - }, - { - "group": "Routing", - "pages": [ - "api-reference/routing/routing--list", - "api-reference/routing/routing--create", - "api-reference/routing/routing--retrieve-config", - "api-reference/routing/routing--deactivate", - "api-reference/routing/routing--retrieve-default-config", - "api-reference/routing/routing--update-default-config", - "api-reference/routing/routing--retrieve-default-for-profile", - "api-reference/routing/routing--update-default-for-profile", - "api-reference/routing/routing--retrieve", - "api-reference/routing/routing--activate-config" - ] - }, - { - "group": "Relay", - "pages": [ - "api-reference/relay/relay", - "api-reference/relay/relay--retrieve" - ] - }, - { - "group": "3DS Decision", - "pages": [ - "api-reference/3ds-decision-rule/execute-a-3ds-decision-rule-based-on-the-provided-input" - ] - }, - { - "group": "Schemas", - "pages": [ - "api-reference/schemas/outgoing--webhook" - ] - } - ] - }, - { - "group": "Admin API based", - "pages": [ - { - "group": "Organization", - "pages": [ - "api-reference/organization/organization--create", - "api-reference/organization/organization--retrieve", - "api-reference/organization/organization--update" - ] - }, - { - "group": "Merchant Account", - "pages": [ - "api-reference/merchant-account/merchant-account--create", - "api-reference/merchant-account/merchant-account--retrieve", - "api-reference/merchant-account/merchant-account--update", - "api-reference/merchant-account/merchant-account--delete", - "api-reference/merchant-account/merchant-account--kv-status" - ] - }, - { - "group": "Business Profile", - "pages": [ - "api-reference/business-profile/business-profile--create", - "api-reference/business-profile/business-profile--update", - "api-reference/business-profile/business-profile--retrieve", - "api-reference/business-profile/business-profile--delete", - "api-reference/business-profile/business-profile--list" - ] - }, - { - "group": "API Key", - "pages": [ - "api-reference/api-key/api-key--create", - "api-reference/api-key/api-key--retrieve", - "api-reference/api-key/api-key--update", - "api-reference/api-key/api-key--revoke", - "api-reference/api-key/api-key--list" - ] - }, - { - "group": "Merchant Connector Account", - "pages": [ - "api-reference/merchant-connector-account/merchant-connector--create", - "api-reference/merchant-connector-account/merchant-connector--retrieve", - "api-reference/merchant-connector-account/merchant-connector--update", - "api-reference/merchant-connector-account/merchant-connector--delete", - "api-reference/merchant-connector-account/merchant-connector--list" - ] - }, - { - "group": "GSM (Global Status Mapping)", - "pages": [ - "api-reference/gsm/gsm--create", - "api-reference/gsm/gsm--get", - "api-reference/gsm/gsm--update", - "api-reference/gsm/gsm--delete" - ] - }, - { - "group": "Event", - "pages": [ - "api-reference/event/events--list", - "api-reference/event/events--delivery-attempt-list", - "api-reference/event/events--manual-retry" - ] - } - ] - }, - { - "group": "Hyperswitch Card Vault", - "pages": [ - "locker-api-reference/overview" - ] - }, - { - "group": "API Reference", - "pages": [ - { - "group": "Locker - Health", - "pages": [ - "locker-api-reference/locker-health/get-health" - ] - }, - { - "group": "Locker - Key Custodian", - "pages": [ - "locker-api-reference/key-custodian/provide-key-1", - "locker-api-reference/key-custodian/provide-key-2", - "locker-api-reference/key-custodian/unlock-the-locker" - ] - }, - { - "group": "Locker - Cards", - "pages": [ - "locker-api-reference/cards/add-data-in-locker", - "locker-api-reference/cards/delete-data-from-locker", - "locker-api-reference/cards/retrieve-data-from-locker", - "locker-api-reference/cards/get-or-insert-the-card-fingerprint" - ] - } - ] - }, - { - "group": "Hyperswitch Intelligent Router", - "pages": [ - "intelligent-router-api-reference/overview" - ] - }, - { - "group": "API Reference", - "pages": [ - { - "group": "Success Rate", - "pages": [ - "intelligent-router-api-reference/success-rate/fetch-success-rate-for-an-entity", - "intelligent-router-api-reference/success-rate/update-success-rate-window", - "intelligent-router-api-reference/success-rate/invalidate-windows", - "intelligent-router-api-reference/success-rate/fetch-entity-and-global-success-rates" - ] - }, - { - "group": "Elimination", - "pages": [ - "intelligent-router-api-reference/elimination/fetch-eliminated-processor-list", - "intelligent-router-api-reference/elimination/update-elimination-bucket", - "intelligent-router-api-reference/elimination/invalidate-elimination-bucket" - ] - }, - { - "group": "Contract Routing", - "pages": [ - "intelligent-router-api-reference/contract-routing/fetch-contract-scores-for-an-entity", - "intelligent-router-api-reference/contract-routing/update-contract-information-for-an-entity", - "intelligent-router-api-reference/contract-routing/invalidate-contract-information-for-an-entity" - ] - }, - { - "group": "Static Routing", - "pages": [ - "intelligent-router-api-reference/static-routing/create-a-routing-rule", - "intelligent-router-api-reference/static-routing/evaluate-routing-rule" - ] - } - ] - } - ], - "footerSocials": { - "github": "https://github.com/juspay/hyperswitch", - "linkedin": "https://www.linkedin.com/company/hyperswitch" - }, - "openapi": [ - "openapi_spec.json", - "rust_locker_open_api_spec.yml" - ], - "api": { - "maintainOrder": true - }, - "analytics": { - "gtm": { - "tagId": "GTM-PLBNKQFQ" - }, - "mixpanel": { - "projectToken": "b00355f29d9548d1333608df71d5d53d" - } - } -} \ No newline at end of file diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 7d9a7f0e4ba..525f65ea72c 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -26,7 +26,7 @@ "Payments" ], "summary": "Payments - Create", - "description": "**Creates a payment object when amount and currency are passed.**\n\nThis API is also used to create a mandate by passing the `mandate_object`.\n\nDepending on the user journey you wish to achieve, you may opt to complete all the steps in a single request **by attaching a payment method, setting `confirm=true` and `capture_method = automatic`** in the *Payments/Create API* request.\n\nOtherwise, To completely process a payment you will have to **create a payment, attach a payment method, confirm and capture funds**. For that you could use the following sequence of API requests -\n\n1. Payments - Create\n\n2. Payments - Update\n\n3. Payments - Confirm\n\n4. Payments - Capture.\n\nYou will require the 'API - Key' from the Hyperswitch dashboard to make the first call, and use the 'client secret' returned in this API along with your 'publishable key' to make subsequent API calls from your client.\n\nThis page lists the various combinations in which the Payments - Create API can be used and the details about the various fields in the requests and responses.", + "description": "Creates a payment resource, which represents a customer's intent to pay.\nThis endpoint is the starting point for various payment flows:\n", "operationId": "Create a Payment", "requestBody": { "content": { @@ -35,79 +35,13 @@ "$ref": "#/components/schemas/PaymentsCreateRequest" }, "examples": { - "Create a 3DS payment": { + "1. Create a payment with minimal fields": { "value": { "amount": 6540, - "authentication_type": "three_ds", "currency": "USD" } }, - "Create a manual capture payment": { - "value": { - "amount": 6540, - "billing": { - "address": { - "city": "San Fransico", - "country": "US", - "first_name": "joseph", - "last_name": "Doe", - "line1": "1467", - "line2": "Harrison Street", - "line3": "Harrison Street", - "state": "California", - "zip": "94122" - }, - "phone": { - "country_code": "+91", - "number": "9123456789" - } - }, - "currency": "USD", - "customer": { - "id": "cus_abcdefgh" - } - } - }, - "Create a payment and save the card": { - "value": { - "amount": 6540, - "authentication_type": "no_three_ds", - "confirm": true, - "currency": "USD", - "customer_acceptance": { - "acceptance_type": "online", - "accepted_at": "1963-05-03T04:07:52.723Z", - "online": { - "ip_address": "127.0.0.1", - "user_agent": "amet irure esse" - } - }, - "customer_id": "StripeCustomer123", - "payment_method": "card", - "payment_method_data": { - "card": { - "card_cvc": "123", - "card_exp_month": "10", - "card_exp_year": "25", - "card_holder_name": "joseph Doe", - "card_number": "4242424242424242" - } - }, - "setup_future_usage": "off_session" - } - }, - "Create a payment using an already saved card's token": { - "value": { - "amount": 6540, - "card_cvc": "123", - "client_secret": "{{client_secret}}", - "confirm": true, - "currency": "USD", - "payment_method": "card", - "payment_token": "{{payment_token}}" - } - }, - "Create a payment with customer details and metadata": { + "2. Create a payment with customer details and metadata": { "value": { "amount": 6540, "currency": "USD", @@ -127,24 +61,21 @@ "statement_descriptor_suffix": "JS" } }, - "Create a payment with minimal fields": { + "3. Create a 3DS payment": { "value": { "amount": 6540, + "authentication_type": "three_ds", "currency": "USD" } }, - "Create a recurring payment with mandate_id": { + "4. Create a manual capture payment (basic)": { "value": { "amount": 6540, - "authentication_type": "no_three_ds", - "confirm": true, - "currency": "USD", - "customer_id": "StripeCustomer", - "mandate_id": "{{mandate_id}}", - "off_session": true + "capture_method": "manual", + "currency": "USD" } }, - "Create a setup mandate payment": { + "5. Create a setup mandate payment": { "value": { "amount": 6540, "authentication_type": "no_three_ds", @@ -187,6 +118,82 @@ }, "setup_future_usage": "off_session" } + }, + "6. Create a recurring payment with mandate_id": { + "value": { + "amount": 6540, + "authentication_type": "no_three_ds", + "confirm": true, + "currency": "USD", + "customer_id": "StripeCustomer", + "mandate_id": "{{mandate_id}}", + "off_session": true + } + }, + "7. Create a payment and save the card": { + "value": { + "amount": 6540, + "authentication_type": "no_three_ds", + "confirm": true, + "currency": "USD", + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, + "customer_id": "StripeCustomer123", + "payment_method": "card", + "payment_method_data": { + "card": { + "card_cvc": "123", + "card_exp_month": "10", + "card_exp_year": "25", + "card_holder_name": "joseph Doe", + "card_number": "4242424242424242" + } + }, + "setup_future_usage": "off_session" + } + }, + "8. Create a payment using an already saved card's token": { + "value": { + "amount": 6540, + "card_cvc": "123", + "client_secret": "{{client_secret}}", + "confirm": true, + "currency": "USD", + "payment_method": "card", + "payment_token": "{{payment_token}}" + } + }, + "9. Create a payment with billing details": { + "value": { + "amount": 6540, + "billing": { + "address": { + "city": "San Fransico", + "country": "US", + "first_name": "joseph", + "last_name": "Doe", + "line1": "1467", + "line2": "Harrison Street", + "line3": "Harrison Street", + "state": "California", + "zip": "94122" + }, + "phone": { + "country_code": "+91", + "number": "9123456789" + } + }, + "currency": "USD", + "customer": { + "id": "cus_abcdefgh" + } + } } } } @@ -200,6 +207,255 @@ "application/json": { "schema": { "$ref": "#/components/schemas/PaymentsCreateResponseOpenApi" + }, + "examples": { + "1. Response for minimal payment creation (requires payment method)": { + "value": { + "amount": 6540, + "amount_capturable": 6540, + "attempt_count": 1, + "client_secret": "pay_syxxxxxxxxxxxx_secret_szzzzzzzzzzz", + "created": "2023-10-26T10:00:00Z", + "currency": "USD", + "expires_on": "2023-10-26T10:15:00Z", + "merchant_id": "merchant_myyyyyyyyyyyy", + "payment_id": "pay_syxxxxxxxxxxxx", + "profile_id": "pro_pzzzzzzzzzzz", + "status": "requires_payment_method" + } + }, + "2. Response for payment with customer details (requires payment method)": { + "value": { + "amount": 6540, + "attempt_count": 1, + "client_secret": "pay_custmeta_xxxxxxxxxxxx_secret_szzzzzzzzzzz", + "created": "2023-10-26T10:05:00Z", + "currency": "USD", + "customer": { + "email": "[email protected]", + "id": "cus_abcdefgh", + "name": "John Dough", + "phone": "9123456789" + }, + "customer_id": "cus_abcdefgh", + "description": "Its my first payment request", + "ephemeral_key": { + "customer_id": "cus_abcdefgh", + "secret": "epk_ephemeralxxxxxxxxxxxx" + }, + "expires_on": "2023-10-26T10:20:00Z", + "merchant_id": "merchant_myyyyyyyyyyyy", + "metadata": { + "udf1": "some-value", + "udf2": "some-value" + }, + "payment_id": "pay_custmeta_xxxxxxxxxxxx", + "profile_id": "pro_pzzzzzzzzzzz", + "statement_descriptor_name": "joseph", + "statement_descriptor_suffix": "JS", + "status": "requires_payment_method" + } + }, + "3. Response for 3DS payment creation (requires payment method)": { + "value": { + "amount": 6540, + "attempt_count": 1, + "authentication_type": "three_ds", + "client_secret": "pay_3ds_xxxxxxxxxxxx_secret_szzzzzzzzzzz", + "created": "2023-10-26T10:10:00Z", + "currency": "USD", + "expires_on": "2023-10-26T10:25:00Z", + "merchant_id": "merchant_myyyyyyyyyyyy", + "payment_id": "pay_3ds_xxxxxxxxxxxx", + "profile_id": "pro_pzzzzzzzzzzz", + "status": "requires_payment_method" + } + }, + "4. Response for basic manual capture payment (requires payment method)": { + "value": { + "amount": 6540, + "attempt_count": 1, + "capture_method": "manual", + "client_secret": "pay_manualcap_xxxxxxxxxxxx_secret_szzzzzzzzzzz", + "created": "2023-10-26T10:15:00Z", + "currency": "USD", + "expires_on": "2023-10-26T10:30:00Z", + "merchant_id": "merchant_myyyyyyyyyyyy", + "payment_id": "pay_manualcap_xxxxxxxxxxxx", + "profile_id": "pro_pzzzzzzzzzzz", + "status": "requires_payment_method" + } + }, + "5. Response for successful setup mandate payment": { + "value": { + "amount": 6540, + "amount_capturable": 0, + "amount_received": 6540, + "attempt_count": 1, + "authentication_type": "no_three_ds", + "client_secret": "pay_mandatesetup_xxxxxxxxxxxx_secret_szzzzzzzzzzz", + "connector": "fauxpay", + "connector_transaction_id": "txn_connectortransidxxxx", + "created": "2023-10-26T10:20:00Z", + "currency": "USD", + "customer_id": "StripeCustomer123", + "ephemeral_key": { + "customer_id": "StripeCustomer123", + "secret": "epk_ephemeralxxxxxxxxxxxx" + }, + "mandate_data": { + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { + "ip_address": "127.0.0.1", + "user_agent": "amet irure esse" + } + }, + "mandate_type": { + "single_use": { + "amount": 6540, + "currency": "USD" + } + } + }, + "mandate_id": "man_xxxxxxxxxxxx", + "merchant_connector_id": "mca_mcaconnectorxxxx", + "merchant_id": "merchant_myyyyyyyyyyyy", + "payment_id": "pay_mandatesetup_xxxxxxxxxxxx", + "payment_method": "card", + "payment_method_data": { + "card": { + "card_exp_month": "10", + "card_exp_year": "25", + "card_holder_name": "joseph Doe", + "last4": "4242" + } + }, + "profile_id": "pro_pzzzzzzzzzzz", + "setup_future_usage": "on_session", + "status": "succeeded" + } + }, + "6. Response for successful recurring payment with mandate_id": { + "value": { + "amount": 6540, + "amount_capturable": 0, + "amount_received": 6540, + "attempt_count": 1, + "authentication_type": "no_three_ds", + "client_secret": "pay_recurring_xxxxxxxxxxxx_secret_szzzzzzzzzzz", + "connector": "fauxpay", + "connector_transaction_id": "txn_connectortransidxxxx", + "created": "2023-10-26T10:22:00Z", + "currency": "USD", + "customer_id": "StripeCustomer", + "mandate_id": "{{mandate_id}}", + "merchant_connector_id": "mca_mcaconnectorxxxx", + "merchant_id": "merchant_myyyyyyyyyyyy", + "off_session": true, + "payment_id": "pay_recurring_xxxxxxxxxxxx", + "payment_method": "card", + "profile_id": "pro_pzzzzzzzzzzz", + "status": "succeeded" + } + }, + "7. Response for successful payment with card saved": { + "value": { + "amount": 6540, + "amount_capturable": 0, + "amount_received": 6540, + "attempt_count": 1, + "authentication_type": "no_three_ds", + "client_secret": "pay_savecard_xxxxxxxxxxxx_secret_szzzzzzzzzzz", + "connector": "fauxpay", + "connector_transaction_id": "txn_connectortransidxxxx", + "created": "2023-10-26T10:25:00Z", + "currency": "USD", + "customer_id": "StripeCustomer123", + "ephemeral_key": { + "customer_id": "StripeCustomer123", + "secret": "epk_ephemeralxxxxxxxxxxxx" + }, + "merchant_connector_id": "mca_mcaconnectorxxxx", + "merchant_id": "merchant_myyyyyyyyyyyy", + "payment_id": "pay_savecard_xxxxxxxxxxxx", + "payment_method": "card", + "payment_method_data": { + "card": { + "card_exp_month": "10", + "card_exp_year": "25", + "card_holder_name": "joseph Doe", + "last4": "4242" + } + }, + "payment_token": null, + "profile_id": "pro_pzzzzzzzzzzz", + "setup_future_usage": "on_session", + "status": "succeeded" + } + }, + "8. Response for successful payment using saved card token": { + "value": { + "amount": 6540, + "amount_capturable": 0, + "amount_received": 6540, + "attempt_count": 1, + "client_secret": "pay_token_xxxxxxxxxxxx_secret_szzzzzzzzzzz", + "connector": "fauxpay", + "connector_transaction_id": "txn_connectortransidxxxx", + "created": "2023-10-26T10:27:00Z", + "currency": "USD", + "merchant_connector_id": "mca_mcaconnectorxxxx", + "merchant_id": "merchant_myyyyyyyyyyyy", + "payment_id": "pay_token_xxxxxxxxxxxx", + "payment_method": "card", + "payment_token": "{{payment_token}}", + "profile_id": "pro_pzzzzzzzzzzz", + "status": "succeeded" + } + }, + "9. Response for payment with billing details (requires payment method)": { + "value": { + "amount": 6540, + "attempt_count": 1, + "billing": { + "address": { + "city": "San Fransico", + "country": "US", + "first_name": "joseph", + "last_name": "Doe", + "line1": "1467", + "line2": "Harrison Street", + "state": "California", + "zip": "94122" + }, + "phone": { + "country_code": "+91", + "number": "9123456789" + } + }, + "client_secret": "pay_manualbill_xxxxxxxxxxxx_secret_szzzzzzzzzzz", + "created": "2023-10-26T10:30:00Z", + "currency": "USD", + "customer": { + "email": "[email protected]", + "id": "cus_abcdefgh", + "name": "John Dough", + "phone": "9123456789" + }, + "customer_id": "cus_abcdefgh", + "ephemeral_key": { + "customer_id": "cus_abcdefgh", + "secret": "epk_ephemeralxxxxxxxxxxxx" + }, + "expires_on": "2023-10-26T10:45:00Z", + "merchant_id": "merchant_myyyyyyyyyyyy", + "payment_id": "pay_manualbill_xxxxxxxxxxxx", + "profile_id": "pro_pzzzzzzzzzzz", + "status": "requires_payment_method" + } + } } } } @@ -385,7 +641,7 @@ "Payments" ], "summary": "Payments - Confirm", - "description": "**Use this API to confirm the payment and forward the payment to the payment processor.**\n\nAlternatively you can confirm the payment within the *Payments/Create* API by setting `confirm=true`. After confirmation, the payment could either:\n\n1. fail with `failed` status or\n\n2. transition to a `requires_customer_action` status with a `next_action` block or\n\n3. succeed with either `succeeded` in case of automatic capture or `requires_capture` in case of manual capture", + "description": "Confirms a payment intent that was previously created with `confirm: false`. This action attempts to authorize the payment with the payment processor.\n\nExpected status transitions after confirmation:\n- `succeeded`: If authorization is successful and `capture_method` is `automatic`.\n- `requires_capture`: If authorization is successful and `capture_method` is `manual`.\n- `failed`: If authorization fails.", "operationId": "Confirm a Payment", "parameters": [ { @@ -464,7 +720,7 @@ "Payments" ], "summary": "Payments - Capture", - "description": "To capture the funds for an uncaptured payment", + "description": "Captures the funds for a previously authorized payment intent where `capture_method` was set to `manual` and the payment is in a `requires_capture` state.\n\nUpon successful capture, the payment status usually transitions to `succeeded`.\nThe `amount_to_capture` can be specified in the request body; it must be less than or equal to the payment's `amount_capturable`. If omitted, the full capturable amount is captured.\n\nA payment must be in a capturable state (e.g., `requires_capture`). Attempting to capture an already `succeeded` (and fully captured) payment or one in an invalid state will lead to an error.\n", "operationId": "Capture a Payment", "parameters": [ { @@ -6154,7 +6410,7 @@ "properties": { "city": { "type": "string", - "description": "The address city", + "description": "The city, district, suburb, town, or village of the address.", "example": "New York", "nullable": true, "maxLength": 50 @@ -6169,21 +6425,21 @@ }, "line1": { "type": "string", - "description": "The first line of the address", + "description": "The first line of the street address or P.O. Box.", "example": "123, King Street", "nullable": true, "maxLength": 200 }, "line2": { "type": "string", - "description": "The second line of the address", + "description": "The second line of the street address or P.O. Box (e.g., apartment, suite, unit, or building).", "example": "Powelson Avenue", "nullable": true, "maxLength": 50 }, "line3": { "type": "string", - "description": "The third line of the address", + "description": "The third line of the street address, if applicable.", "example": "Bridgewater", "nullable": true, "maxLength": 50 @@ -6860,7 +7116,7 @@ }, "AuthenticationType": { "type": "string", - "description": "Pass this parameter to force 3DS or non 3DS auth for this payment. Some connectors will still force 3DS auth even in case of passing 'no_three_ds' here and vice versa. Default value is 'no_three_ds' if not set", + "description": "Specifies the type of cardholder authentication to be applied for a payment.\n\n- `ThreeDs`: Requests 3D Secure (3DS) authentication. If the card is enrolled, 3DS authentication will be activated, potentially shifting chargeback liability to the issuer.\n- `NoThreeDs`: Indicates that 3D Secure authentication should not be performed. The liability for chargebacks typically remains with the merchant. This is often the default if not specified.\n\nNote: The actual authentication behavior can also be influenced by merchant configuration and specific connector defaults. Some connectors might still enforce 3DS or bypass it regardless of this parameter.", "enum": [ "three_ds", "no_three_ds" @@ -9020,7 +9276,7 @@ }, "CaptureMethod": { "type": "string", - "description": "Default value if not passed is set to 'automatic' which results in Auth and Capture in one single API request. Pass 'manual' or 'manual_multiple' in case you want do a separate Auth and Capture by first authorizing and placing a hold on your customer's funds so that you can use the Payments/Capture endpoint later to capture the authorized amount. Pass 'manual' if you want to only capture the amount later once or 'manual_multiple' if you want to capture the funds multiple times later. Both 'manual' and 'manual_multiple' are only supported by a specific list of processors", + "description": "Specifies how the payment is captured.\n- `automatic`: Funds are captured immediately after successful authorization. This is the default behavior if the field is omitted.\n- `manual`: Funds are authorized but not captured. A separate request to the `/payments/{payment_id}/capture` endpoint is required to capture the funds.", "enum": [ "automatic", "manual", @@ -9042,7 +9298,7 @@ "properties": { "capture_id": { "type": "string", - "description": "Unique identifier for the capture" + "description": "A unique identifier for this specific capture operation." }, "status": { "$ref": "#/components/schemas/CaptureStatus" @@ -9063,11 +9319,11 @@ }, "connector": { "type": "string", - "description": "The connector used for the payment" + "description": "The name of the payment connector that processed this capture." }, "authorized_attempt_id": { "type": "string", - "description": "Unique identifier for the parent attempt on which this capture is made" + "description": "The ID of the payment attempt that was successfully authorized and subsequently captured by this operation." }, "connector_capture_id": { "type": "string", @@ -9081,22 +9337,22 @@ }, "error_message": { "type": "string", - "description": "If there was an error while calling the connector the error message is received here", + "description": "A human-readable message from the connector explaining why this capture operation failed, if applicable.", "nullable": true }, "error_code": { "type": "string", - "description": "If there was an error while calling the connectors the code is received here", + "description": "The error code returned by the connector if this capture operation failed. This code is connector-specific.", "nullable": true }, "error_reason": { "type": "string", - "description": "If there was an error while calling the connectors the reason is received here", + "description": "A more detailed reason from the connector explaining the capture failure, if available.", "nullable": true }, "reference_id": { "type": "string", - "description": "Reference to the capture at connector side", + "description": "The connector's own reference or transaction ID for this specific capture operation. Useful for reconciliation.", "nullable": true } } @@ -11303,7 +11559,7 @@ }, "Currency": { "type": "string", - "description": "The three letter ISO currency code in uppercase. Eg: 'USD' for the United States Dollar.", + "description": "The three-letter ISO 4217 currency code (e.g., \"USD\", \"EUR\") for the payment amount. This field is mandatory for creating a payment.", "enum": [ "AED", "AFN", @@ -13613,7 +13869,7 @@ }, "FutureUsage": { "type": "string", - "description": "Indicates that you intend to make future payments with the payment methods used for this Payment. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\n- On_session - Payment method saved only at hyperswitch when consent is provided by the user. CVV will asked during the returning user payment\n- Off_session - Payment method saved at both hyperswitch and Processor when consent is provided by the user. No input is required during the returning user payment.", + "description": "Specifies how the payment method can be used for future payments.\n- `off_session`: The payment method can be used for future payments when the customer is not present.\n- `on_session`: The payment method is intended for use only when the customer is present during checkout.\nIf omitted, defaults to `on_session`.", "enum": [ "off_session", "on_session" @@ -14598,7 +14854,7 @@ }, "IntentStatus": { "type": "string", - "description": "The status of the current payment that was made", + "description": "Represents the overall status of a payment intent.\nThe status transitions through various states depending on the payment method, confirmation, capture method, and any subsequent actions (like customer authentication or manual capture).", "enum": [ "succeeded", "failed", @@ -17868,7 +18124,7 @@ "properties": { "attempt_id": { "type": "string", - "description": "Unique identifier for the attempt" + "description": "A unique identifier for this specific payment attempt." }, "status": { "$ref": "#/components/schemas/AttemptStatus" @@ -17896,12 +18152,12 @@ }, "connector": { "type": "string", - "description": "The connector used for the payment", + "description": "The name of the payment connector (e.g., 'stripe', 'adyen') used for this attempt.", "nullable": true }, "error_message": { "type": "string", - "description": "If there was an error while calling the connector, the error message is received here", + "description": "A human-readable message from the connector explaining the error, if one occurred during this payment attempt.", "nullable": true }, "payment_method": { @@ -17953,17 +18209,17 @@ }, "mandate_id": { "type": "string", - "description": "A unique identifier to link the payment to a mandate, can be use instead of payment_method_data", + "description": "If this payment attempt is associated with a mandate (e.g., for a recurring or subsequent payment), this field will contain the ID of that mandate.", "nullable": true }, "error_code": { "type": "string", - "description": "If there was an error while calling the connectors the error code is received here", + "description": "The error code returned by the connector if this payment attempt failed. This code is specific to the connector.", "nullable": true }, "payment_token": { "type": "string", - "description": "Provide a reference to a stored payment method", + "description": "If a tokenized (saved) payment method was used for this attempt, this field contains the payment token representing that payment method.", "nullable": true }, "connector_metadata": { @@ -17988,7 +18244,7 @@ }, "reference_id": { "type": "string", - "description": "Reference to the payment at connector side", + "description": "The connector's own reference or transaction ID for this specific payment attempt. Useful for reconciliation with the connector.", "example": "993672945374576J", "nullable": true }, @@ -19861,34 +20117,32 @@ }, "PaymentsCaptureRequest": { "type": "object", - "required": [ - "amount_to_capture" - ], "properties": { "merchant_id": { "type": "string", - "description": "The unique identifier for the merchant", + "description": "The unique identifier for the merchant. This is usually inferred from the API key.", "nullable": true }, "amount_to_capture": { "type": "integer", "format": "int64", - "description": "The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured.", - "example": 6540 + "description": "The amount to capture, in the lowest denomination of the currency. If omitted, the entire `amount_capturable` of the payment will be captured. Must be less than or equal to the current `amount_capturable`.", + "example": 6540, + "nullable": true }, "refund_uncaptured_amount": { "type": "boolean", - "description": "Decider to refund the uncaptured amount", + "description": "Decider to refund the uncaptured amount. (Currently not fully supported or behavior may vary by connector).", "nullable": true }, "statement_descriptor_suffix": { "type": "string", - "description": "Provides information about a card payment that customers see on their statements.", + "description": "A dynamic suffix that appears on your customer's credit card statement. This is concatenated with the (shortened) descriptor prefix set on your account to form the complete statement descriptor. The combined length should not exceed connector-specific limits (typically 22 characters).", "nullable": true }, "statement_descriptor_prefix": { "type": "string", - "description": "Concatenated with the statement descriptor suffix that’s set on the account to form the complete statement descriptor.", + "description": "An optional prefix for the statement descriptor that appears on your customer's credit card statement. This can override the default prefix set on your merchant account. The combined length of prefix and suffix should not exceed connector-specific limits (typically 22 characters).", "nullable": true }, "merchant_connector_details": { @@ -19935,7 +20189,7 @@ "amount": { "type": "integer", "format": "int64", - "description": "The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies)", + "description": "The primary amount for the payment, provided in the lowest denomination of the specified currency (e.g., 6540 for $65.40 USD). This field is mandatory for creating a payment.", "example": 6540, "nullable": true, "minimum": 0 @@ -19943,7 +20197,7 @@ "order_tax_amount": { "type": "integer", "format": "int64", - "description": "Total tax amount applicable to the order", + "description": "Total tax amount applicable to the order, in the lowest denomination of the currency.", "example": 6540, "nullable": true }, @@ -19958,7 +20212,7 @@ "amount_to_capture": { "type": "integer", "format": "int64", - "description": "The Amount to be captured / debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, the default amount_to_capture will be the payment amount. Also, it must be less than or equal to the original payment account.", + "description": "The amount to be captured from the user's payment method, in the lowest denomination. If not provided, and `capture_method` is `automatic`, the full payment `amount` will be captured. If `capture_method` is `manual`, this can be specified in the `/capture` call. Must be less than or equal to the authorized amount.", "example": 6540, "nullable": true }, @@ -19971,7 +20225,7 @@ }, "payment_id": { "type": "string", - "description": "Unique identifier for the payment. This ensures idempotency for multiple payments\nthat have been done by a single merchant. The value for this field can be specified in the request, it will be auto generated otherwise and returned in the API response.", + "description": "Optional. A merchant-provided unique identifier for the payment, contains 30 characters long (e.g., \"pay_mbabizu24mvu3mela5njyhpit4\"). If provided, it ensures idempotency for the payment creation request. If omitted, Hyperswitch generates a unique ID for the payment.", "example": "pay_mbabizu24mvu3mela5njyhpit4", "nullable": true, "maxLength": 30, @@ -20024,7 +20278,7 @@ }, "confirm": { "type": "boolean", - "description": "Whether to confirm the payment (if applicable). It can be used to completely process a payment by attaching a payment method, setting `confirm=true` and `capture_method = automatic` in the *Payments/Create API* request itself.", + "description": "If set to `true`, Hyperswitch attempts to confirm and authorize the payment immediately after creation, provided sufficient payment method details are included. If `false` or omitted (default is `false`), the payment is created with a status such as `requires_payment_method` or `requires_confirmation`, and a separate `POST /payments/{payment_id}/confirm` call is necessary to proceed with authorization.", "default": false, "example": true, "nullable": true @@ -20053,13 +20307,13 @@ }, "description": { "type": "string", - "description": "A description for the payment", + "description": "An arbitrary string attached to the payment. Often useful for displaying to users or for your own internal record-keeping.", "example": "It's my first payment request", "nullable": true }, "return_url": { "type": "string", - "description": "The URL to which you want the user to be redirected after the completion of the payment operation", + "description": "The URL to redirect the customer to after they complete the payment process or authentication. This is crucial for flows that involve off-site redirection (e.g., 3DS, some bank redirects, wallet payments).", "example": "https://hyperswitch.io", "nullable": true, "maxLength": 2048 @@ -20291,7 +20545,7 @@ }, "merchant_order_reference_id": { "type": "string", - "description": "Merchant's identifier for the payment/invoice. This will be sent to the connector\nif the connector provides support to accept multiple reference ids.\nIn case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference.", + "description": "Your unique identifier for this payment or order. This ID helps you reconcile payments on your system. If provided, it is passed to the connector if supported.", "example": "Custom_Order_id_123", "nullable": true, "maxLength": 255 @@ -20352,13 +20606,13 @@ "amount": { "type": "integer", "format": "int64", - "description": "The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies)", + "description": "The primary amount for the payment, provided in the lowest denomination of the specified currency (e.g., 6540 for $65.40 USD). This field is mandatory for creating a payment.", "minimum": 0 }, "order_tax_amount": { "type": "integer", "format": "int64", - "description": "Total tax amount applicable to the order", + "description": "Total tax amount applicable to the order, in the lowest denomination of the currency.", "example": 6540, "nullable": true }, @@ -20368,7 +20622,7 @@ "amount_to_capture": { "type": "integer", "format": "int64", - "description": "The Amount to be captured / debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, the default amount_to_capture will be the payment amount. Also, it must be less than or equal to the original payment account.", + "description": "The amount to be captured from the user's payment method, in the lowest denomination. If not provided, and `capture_method` is `automatic`, the full payment `amount` will be captured. If `capture_method` is `manual`, this can be specified in the `/capture` call. Must be less than or equal to the authorized amount.", "example": 6540, "nullable": true }, @@ -20381,7 +20635,7 @@ }, "payment_id": { "type": "string", - "description": "Unique identifier for the payment. This ensures idempotency for multiple payments\nthat have been done by a single merchant. The value for this field can be specified in the request, it will be auto generated otherwise and returned in the API response.", + "description": "Optional. A merchant-provided unique identifier for the payment, contains 30 characters long (e.g., \"pay_mbabizu24mvu3mela5njyhpit4\"). If provided, it ensures idempotency for the payment creation request. If omitted, Hyperswitch generates a unique ID for the payment.", "example": "pay_mbabizu24mvu3mela5njyhpit4", "nullable": true, "maxLength": 30, @@ -20434,7 +20688,7 @@ }, "confirm": { "type": "boolean", - "description": "Whether to confirm the payment (if applicable). It can be used to completely process a payment by attaching a payment method, setting `confirm=true` and `capture_method = automatic` in the *Payments/Create API* request itself.", + "description": "If set to `true`, Hyperswitch attempts to confirm and authorize the payment immediately after creation, provided sufficient payment method details are included. If `false` or omitted (default is `false`), the payment is created with a status such as `requires_payment_method` or `requires_confirmation`, and a separate `POST /payments/{payment_id}/confirm` call is necessary to proceed with authorization.", "default": false, "example": true, "nullable": true @@ -20463,13 +20717,13 @@ }, "description": { "type": "string", - "description": "A description for the payment", + "description": "An arbitrary string attached to the payment. Often useful for displaying to users or for your own internal record-keeping.", "example": "It's my first payment request", "nullable": true }, "return_url": { "type": "string", - "description": "The URL to which you want the user to be redirected after the completion of the payment operation", + "description": "The URL to redirect the customer to after they complete the payment process or authentication. This is crucial for flows that involve off-site redirection (e.g., 3DS, some bank redirects, wallet payments).", "example": "https://hyperswitch.io", "nullable": true, "maxLength": 2048 @@ -20714,7 +20968,7 @@ }, "merchant_order_reference_id": { "type": "string", - "description": "Merchant's identifier for the payment/invoice. This will be sent to the connector\nif the connector provides support to accept multiple reference ids.\nIn case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference.", + "description": "Your unique identifier for this payment or order. This ID helps you reconcile payments on your system. If provided, it is passed to the connector if supported.", "example": "Custom_Order_id_123", "nullable": true, "maxLength": 255 @@ -20822,33 +21076,33 @@ "amount_capturable": { "type": "integer", "format": "int64", - "description": "The maximum amount that could be captured from the payment", + "description": "The amount (in minor units) that can still be captured for this payment. This is relevant when `capture_method` is `manual`. Once fully captured, or if `capture_method` is `automatic` and payment succeeded, this will be 0.", "example": 6540, "minimum": 100 }, "amount_received": { "type": "integer", "format": "int64", - "description": "The amount which is already captured from the payment, this helps in the cases where merchants can't capture all capturable amount at once.", + "description": "The total amount (in minor units) that has been captured for this payment. For `fauxpay` sandbox connector, this might reflect the authorized amount if `status` is `succeeded` even if `capture_method` was `manual`.", "example": 6540, "nullable": true }, "connector": { "type": "string", - "description": "The connector used for the payment", + "description": "The name of the payment connector (e.g., 'stripe', 'adyen') that processed or is processing this payment.", "example": "stripe", "nullable": true }, "client_secret": { "type": "string", - "description": "It's a token used for client side verification.", + "description": "A secret token unique to this payment intent. It is primarily used by client-side applications (e.g., Hyperswitch SDKs) to authenticate actions like confirming the payment or handling next actions. This secret should be handled carefully and not exposed publicly beyond its intended client-side use.", "example": "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo", "nullable": true }, "created": { "type": "string", "format": "date-time", - "description": "Time when the payment was created", + "description": "Timestamp indicating when this payment intent was created, in ISO 8601 format.", "example": "2022-09-10T10:11:12Z", "nullable": true }, @@ -20866,7 +21120,7 @@ }, "description": { "type": "string", - "description": "A description of the payment", + "description": "An arbitrary string providing a description for the payment, often useful for display or internal record-keeping.", "example": "It's my first payment request", "nullable": true }, @@ -20875,7 +21129,7 @@ "items": { "$ref": "#/components/schemas/RefundResponse" }, - "description": "List of refunds that happened on this intent, as same payment intent can have multiple refund requests depending on the nature of order", + "description": "An array of refund objects associated with this payment. Empty or null if no refunds have been processed.", "nullable": true }, "disputes": { @@ -21044,18 +21298,18 @@ }, "cancellation_reason": { "type": "string", - "description": "If the payment was cancelled the reason will be provided here", + "description": "If the payment intent was cancelled, this field provides a textual reason for the cancellation (e.g., \"requested_by_customer\", \"abandoned\").", "nullable": true }, "error_code": { "type": "string", - "description": "If there was an error while calling the connectors the code is received here", + "description": "The connector-specific error code from the last failed payment attempt associated with this payment intent.", "example": "E0001", "nullable": true }, "error_message": { "type": "string", - "description": "If there was an error while calling the connector the error message is received here", + "description": "A human-readable error message from the last failed payment attempt associated with this payment intent.", "example": "Failed while verifying the card", "nullable": true }, @@ -21077,7 +21331,7 @@ }, "connector_label": { "type": "string", - "description": "The connector used for this payment along with the country and business details", + "description": "A label identifying the specific merchant connector account (MCA) used for this payment. This often combines the connector name, business country, and a custom label (e.g., \"stripe_US_primary\").", "example": "stripe_US_food", "nullable": true }, @@ -21091,12 +21345,12 @@ }, "business_label": { "type": "string", - "description": "The business label of merchant for this payment", + "description": "The label identifying the specific business unit or profile under which this payment was processed by the merchant.", "nullable": true }, "business_sub_label": { "type": "string", - "description": "The business_sub_label for this payment", + "description": "An optional sub-label for further categorization of the business unit or profile used for this payment.", "nullable": true }, "allowed_payment_method_types": { @@ -21251,7 +21505,7 @@ }, "payment_method_id": { "type": "string", - "description": "Identifier for Payment Method used for the payment", + "description": "A unique identifier for the payment method used in this payment. If the payment method was saved or tokenized, this ID can be used to reference it for future transactions or recurring payments.", "nullable": true }, "payment_method_status": { @@ -21567,7 +21821,7 @@ "amount": { "type": "integer", "format": "int64", - "description": "The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies)", + "description": "The primary amount for the payment, provided in the lowest denomination of the specified currency (e.g., 6540 for $65.40 USD). This field is mandatory for creating a payment.", "example": 6540, "nullable": true, "minimum": 0 @@ -21575,7 +21829,7 @@ "order_tax_amount": { "type": "integer", "format": "int64", - "description": "Total tax amount applicable to the order", + "description": "Total tax amount applicable to the order, in the lowest denomination of the currency.", "example": 6540, "nullable": true }, @@ -21590,7 +21844,7 @@ "amount_to_capture": { "type": "integer", "format": "int64", - "description": "The Amount to be captured / debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, the default amount_to_capture will be the payment amount. Also, it must be less than or equal to the original payment account.", + "description": "The amount to be captured from the user's payment method, in the lowest denomination. If not provided, and `capture_method` is `automatic`, the full payment `amount` will be captured. If `capture_method` is `manual`, this can be specified in the `/capture` call. Must be less than or equal to the authorized amount.", "example": 6540, "nullable": true }, @@ -21603,7 +21857,7 @@ }, "payment_id": { "type": "string", - "description": "Unique identifier for the payment. This ensures idempotency for multiple payments\nthat have been done by a single merchant. The value for this field can be specified in the request, it will be auto generated otherwise and returned in the API response.", + "description": "Optional. A merchant-provided unique identifier for the payment, contains 30 characters long (e.g., \"pay_mbabizu24mvu3mela5njyhpit4\"). If provided, it ensures idempotency for the payment creation request. If omitted, Hyperswitch generates a unique ID for the payment.", "example": "pay_mbabizu24mvu3mela5njyhpit4", "nullable": true, "maxLength": 30, @@ -21670,7 +21924,7 @@ }, "confirm": { "type": "boolean", - "description": "Whether to confirm the payment (if applicable). It can be used to completely process a payment by attaching a payment method, setting `confirm=true` and `capture_method = automatic` in the *Payments/Create API* request itself.", + "description": "If set to `true`, Hyperswitch attempts to confirm and authorize the payment immediately after creation, provided sufficient payment method details are included. If `false` or omitted (default is `false`), the payment is created with a status such as `requires_payment_method` or `requires_confirmation`, and a separate `POST /payments/{payment_id}/confirm` call is necessary to proceed with authorization.", "default": false, "example": true, "nullable": true @@ -21731,13 +21985,13 @@ }, "description": { "type": "string", - "description": "A description for the payment", + "description": "An arbitrary string attached to the payment. Often useful for displaying to users or for your own internal record-keeping.", "example": "It's my first payment request", "nullable": true }, "return_url": { "type": "string", - "description": "The URL to which you want the user to be redirected after the completion of the payment operation", + "description": "The URL to redirect the customer to after they complete the payment process or authentication. This is crucial for flows that involve off-site redirection (e.g., 3DS, some bank redirects, wallet payments).", "example": "https://hyperswitch.io", "nullable": true, "maxLength": 2048 @@ -22015,7 +22269,7 @@ }, "merchant_order_reference_id": { "type": "string", - "description": "Merchant's identifier for the payment/invoice. This will be sent to the connector\nif the connector provides support to accept multiple reference ids.\nIn case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference.", + "description": "Your unique identifier for this payment or order. This ID helps you reconcile payments on your system. If provided, it is passed to the connector if supported.", "example": "Custom_Order_id_123", "nullable": true, "maxLength": 255 @@ -22124,33 +22378,33 @@ "amount_capturable": { "type": "integer", "format": "int64", - "description": "The maximum amount that could be captured from the payment", + "description": "The amount (in minor units) that can still be captured for this payment. This is relevant when `capture_method` is `manual`. Once fully captured, or if `capture_method` is `automatic` and payment succeeded, this will be 0.", "example": 6540, "minimum": 100 }, "amount_received": { "type": "integer", "format": "int64", - "description": "The amount which is already captured from the payment, this helps in the cases where merchants can't capture all capturable amount at once.", + "description": "The total amount (in minor units) that has been captured for this payment. For `fauxpay` sandbox connector, this might reflect the authorized amount if `status` is `succeeded` even if `capture_method` was `manual`.", "example": 6540, "nullable": true }, "connector": { "type": "string", - "description": "The connector used for the payment", + "description": "The name of the payment connector (e.g., 'stripe', 'adyen') that processed or is processing this payment.", "example": "stripe", "nullable": true }, "client_secret": { "type": "string", - "description": "It's a token used for client side verification.", + "description": "A secret token unique to this payment intent. It is primarily used by client-side applications (e.g., Hyperswitch SDKs) to authenticate actions like confirming the payment or handling next actions. This secret should be handled carefully and not exposed publicly beyond its intended client-side use.", "example": "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo", "nullable": true }, "created": { "type": "string", "format": "date-time", - "description": "Time when the payment was created", + "description": "Timestamp indicating when this payment intent was created, in ISO 8601 format.", "example": "2022-09-10T10:11:12Z", "nullable": true }, @@ -22176,7 +22430,7 @@ }, "description": { "type": "string", - "description": "A description of the payment", + "description": "An arbitrary string providing a description for the payment, often useful for display or internal record-keeping.", "example": "It's my first payment request", "nullable": true }, @@ -22185,7 +22439,7 @@ "items": { "$ref": "#/components/schemas/RefundResponse" }, - "description": "List of refunds that happened on this intent, as same payment intent can have multiple refund requests depending on the nature of order", + "description": "An array of refund objects associated with this payment. Empty or null if no refunds have been processed.", "nullable": true }, "disputes": { @@ -22361,18 +22615,18 @@ }, "cancellation_reason": { "type": "string", - "description": "If the payment was cancelled the reason will be provided here", + "description": "If the payment intent was cancelled, this field provides a textual reason for the cancellation (e.g., \"requested_by_customer\", \"abandoned\").", "nullable": true }, "error_code": { "type": "string", - "description": "If there was an error while calling the connectors the code is received here", + "description": "The connector-specific error code from the last failed payment attempt associated with this payment intent.", "example": "E0001", "nullable": true }, "error_message": { "type": "string", - "description": "If there was an error while calling the connector the error message is received here", + "description": "A human-readable error message from the last failed payment attempt associated with this payment intent.", "example": "Failed while verifying the card", "nullable": true }, @@ -22404,7 +22658,7 @@ }, "connector_label": { "type": "string", - "description": "The connector used for this payment along with the country and business details", + "description": "A label identifying the specific merchant connector account (MCA) used for this payment. This often combines the connector name, business country, and a custom label (e.g., \"stripe_US_primary\").", "example": "stripe_US_food", "nullable": true }, @@ -22418,12 +22672,12 @@ }, "business_label": { "type": "string", - "description": "The business label of merchant for this payment", + "description": "The label identifying the specific business unit or profile under which this payment was processed by the merchant.", "nullable": true }, "business_sub_label": { "type": "string", - "description": "The business_sub_label for this payment", + "description": "An optional sub-label for further categorization of the business unit or profile used for this payment.", "nullable": true }, "allowed_payment_method_types": { @@ -22578,7 +22832,7 @@ }, "payment_method_id": { "type": "string", - "description": "Identifier for Payment Method used for the payment", + "description": "A unique identifier for the payment method used in this payment. If the payment method was saved or tokenized, this ID can be used to reference it for future transactions or recurring payments.", "nullable": true }, "payment_method_status": { @@ -22702,12 +22956,12 @@ }, "param": { "type": "string", - "description": "The parameters passed to a retrieve request", + "description": "Optional query parameters that might be specific to a connector or flow, passed through during the retrieve operation. Use with caution and refer to specific connector documentation if applicable.", "nullable": true }, "connector": { "type": "string", - "description": "The name of the connector", + "description": "Optionally specifies the connector to be used for a 'force_sync' retrieve operation. If provided, Hyperswitch will attempt to sync the payment status from this specific connector.", "nullable": true }, "merchant_connector_details": { @@ -22834,7 +23088,7 @@ "amount": { "type": "integer", "format": "int64", - "description": "The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies)", + "description": "The primary amount for the payment, provided in the lowest denomination of the specified currency (e.g., 6540 for $65.40 USD). This field is mandatory for creating a payment.", "example": 6540, "nullable": true, "minimum": 0 @@ -22842,7 +23096,7 @@ "order_tax_amount": { "type": "integer", "format": "int64", - "description": "Total tax amount applicable to the order", + "description": "Total tax amount applicable to the order, in the lowest denomination of the currency.", "example": 6540, "nullable": true }, @@ -22857,7 +23111,7 @@ "amount_to_capture": { "type": "integer", "format": "int64", - "description": "The Amount to be captured / debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, the default amount_to_capture will be the payment amount. Also, it must be less than or equal to the original payment account.", + "description": "The amount to be captured from the user's payment method, in the lowest denomination. If not provided, and `capture_method` is `automatic`, the full payment `amount` will be captured. If `capture_method` is `manual`, this can be specified in the `/capture` call. Must be less than or equal to the authorized amount.", "example": 6540, "nullable": true }, @@ -22870,7 +23124,7 @@ }, "payment_id": { "type": "string", - "description": "Unique identifier for the payment. This ensures idempotency for multiple payments\nthat have been done by a single merchant. The value for this field can be specified in the request, it will be auto generated otherwise and returned in the API response.", + "description": "Optional. A merchant-provided unique identifier for the payment, contains 30 characters long (e.g., \"pay_mbabizu24mvu3mela5njyhpit4\"). If provided, it ensures idempotency for the payment creation request. If omitted, Hyperswitch generates a unique ID for the payment.", "example": "pay_mbabizu24mvu3mela5njyhpit4", "nullable": true, "maxLength": 30, @@ -22923,7 +23177,7 @@ }, "confirm": { "type": "boolean", - "description": "Whether to confirm the payment (if applicable). It can be used to completely process a payment by attaching a payment method, setting `confirm=true` and `capture_method = automatic` in the *Payments/Create API* request itself.", + "description": "If set to `true`, Hyperswitch attempts to confirm and authorize the payment immediately after creation, provided sufficient payment method details are included. If `false` or omitted (default is `false`), the payment is created with a status such as `requires_payment_method` or `requires_confirmation`, and a separate `POST /payments/{payment_id}/confirm` call is necessary to proceed with authorization.", "default": false, "example": true, "nullable": true @@ -22952,13 +23206,13 @@ }, "description": { "type": "string", - "description": "A description for the payment", + "description": "An arbitrary string attached to the payment. Often useful for displaying to users or for your own internal record-keeping.", "example": "It's my first payment request", "nullable": true }, "return_url": { "type": "string", - "description": "The URL to which you want the user to be redirected after the completion of the payment operation", + "description": "The URL to redirect the customer to after they complete the payment process or authentication. This is crucial for flows that involve off-site redirection (e.g., 3DS, some bank redirects, wallet payments).", "example": "https://hyperswitch.io", "nullable": true, "maxLength": 2048 @@ -23185,7 +23439,7 @@ }, "merchant_order_reference_id": { "type": "string", - "description": "Merchant's identifier for the payment/invoice. This will be sent to the connector\nif the connector provides support to accept multiple reference ids.\nIn case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference.", + "description": "Your unique identifier for this payment or order. This ID helps you reconcile payments on your system. If provided, it is passed to the connector if supported.", "example": "Custom_Order_id_123", "nullable": true, "maxLength": 255 @@ -28374,6 +28628,7 @@ }, "ThreeDsCompletionIndicator": { "type": "string", + "description": "Indicates if 3DS method data was successfully completed or not", "enum": [ "Y", "N", diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 4a0069baa6e..eb153ff9cd1 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -73,7 +73,6 @@ pub struct ConnectorCode { pub connector: api_enums::Connector, pub code: String, } - #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct BankCodeResponse { #[schema(value_type = Vec<BankNames>)] @@ -852,23 +851,23 @@ impl AmountDetailsUpdate { #[generate_schemas(PaymentsCreateRequest, PaymentsUpdateRequest, PaymentsConfirmRequest)] #[serde(deny_unknown_fields)] pub struct PaymentsRequest { - /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) + /// The primary amount for the payment, provided in the lowest denomination of the specified currency (e.g., 6540 for $65.40 USD). This field is mandatory for creating a payment. #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] #[mandatory_in(PaymentsCreateRequest = u64)] // Makes the field mandatory in PaymentsCreateRequest pub amount: Option<Amount>, - /// Total tax amount applicable to the order + /// Total tax amount applicable to the order, in the lowest denomination of the currency. #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, - /// The three letter ISO currency code in uppercase. Eg: 'USD' to charge US Dollars + /// The three-letter ISO 4217 currency code (e.g., "USD", "EUR") for the payment amount. This field is mandatory for creating a payment. #[schema(example = "USD", value_type = Option<Currency>)] #[mandatory_in(PaymentsCreateRequest = Currency)] pub currency: Option<api_enums::Currency>, - /// The Amount to be captured / debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, the default amount_to_capture will be the payment amount. Also, it must be less than or equal to the original payment account. + /// The amount to be captured from the user's payment method, in the lowest denomination. If not provided, and `capture_method` is `automatic`, the full payment `amount` will be captured. If `capture_method` is `manual`, this can be specified in the `/capture` call. Must be less than or equal to the authorized amount. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, @@ -876,8 +875,7 @@ pub struct PaymentsRequest { #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, - /// Unique identifier for the payment. This ensures idempotency for multiple payments - /// that have been done by a single merchant. The value for this field can be specified in the request, it will be auto generated otherwise and returned in the API response. + /// Optional. A merchant-provided unique identifier for the payment, contains 30 characters long (e.g., "pay_mbabizu24mvu3mela5njyhpit4"). If provided, it ensures idempotency for the payment creation request. If omitted, Hyperswitch generates a unique ID for the payment. #[schema( value_type = Option<String>, min_length = 30, @@ -920,7 +918,7 @@ pub struct PaymentsRequest { #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub capture_on: Option<PrimitiveDateTime>, - /// Whether to confirm the payment (if applicable). It can be used to completely process a payment by attaching a payment method, setting `confirm=true` and `capture_method = automatic` in the *Payments/Create API* request itself. + /// If set to `true`, Hyperswitch attempts to confirm and authorize the payment immediately after creation, provided sufficient payment method details are included. If `false` or omitted (default is `false`), the payment is created with a status such as `requires_payment_method` or `requires_confirmation`, and a separate `POST /payments/{payment_id}/confirm` call is necessary to proceed with authorization. #[schema(default = false, example = true)] pub confirm: Option<bool>, @@ -959,11 +957,11 @@ pub struct PaymentsRequest { #[schema(example = true)] pub off_session: Option<bool>, - /// A description for the payment + /// An arbitrary string attached to the payment. Often useful for displaying to users or for your own internal record-keeping. #[schema(example = "It's my first payment request")] pub description: Option<String>, - /// The URL to which you want the user to be redirected after the completion of the payment operation + /// The URL to redirect the customer to after they complete the payment process or authentication. This is crucial for flows that involve off-site redirection (e.g., 3DS, some bank redirects, wallet payments). #[schema(value_type = Option<String>, example = "https://hyperswitch.io", max_length = 2048)] pub return_url: Option<Url>, @@ -1136,9 +1134,7 @@ pub struct PaymentsRequest { #[schema(value_type = Option<bool>, default = false)] pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, - /// Merchant's identifier for the payment/invoice. This will be sent to the connector - /// if the connector provides support to accept multiple reference ids. - /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. + /// Your unique identifier for this payment or order. This ID helps you reconcile payments on your system. If provided, it is passed to the connector if supported. #[schema( value_type = Option<String>, max_length = 255, @@ -1472,7 +1468,7 @@ impl RequestSurchargeDetails { #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { - /// Unique identifier for the attempt + /// A unique identifier for this specific payment attempt. pub attempt_id: String, /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] @@ -1486,9 +1482,9 @@ pub struct PaymentAttemptResponse { /// The currency of the amount of the payment attempt #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, - /// The connector used for the payment + /// The name of the payment connector (e.g., 'stripe', 'adyen') used for this attempt. pub connector: Option<String>, - /// If there was an error while calling the connector, the error message is received here + /// A human-readable message from the connector explaining the error, if one occurred during this payment attempt. pub error_message: Option<String>, /// The payment method that is to be used #[schema(value_type = Option<PaymentMethod>, example = "bank_transfer")] @@ -1511,11 +1507,11 @@ pub struct PaymentAttemptResponse { pub modified_at: PrimitiveDateTime, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, - /// A unique identifier to link the payment to a mandate, can be use instead of payment_method_data + /// If this payment attempt is associated with a mandate (e.g., for a recurring or subsequent payment), this field will contain the ID of that mandate. pub mandate_id: Option<String>, - /// If there was an error while calling the connectors the error code is received here + /// The error code returned by the connector if this payment attempt failed. This code is specific to the connector. pub error_code: Option<String>, - /// Provide a reference to a stored payment method + /// If a tokenized (saved) payment method was used for this attempt, this field contains the payment token representing that payment method. pub payment_token: Option<String>, /// Additional data related to some connectors pub connector_metadata: Option<serde_json::Value>, @@ -1525,7 +1521,7 @@ pub struct PaymentAttemptResponse { /// Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<enums::PaymentMethodType>, - /// Reference to the payment at connector side + /// The connector's own reference or transaction ID for this specific payment attempt. Useful for reconciliation with the connector. #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// (This field is not live yet)Error code unified across the connectors is received here if there was an error while calling connector @@ -1647,7 +1643,7 @@ pub struct PaymentAttemptRevenueRecoveryData { Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema, )] pub struct CaptureResponse { - /// Unique identifier for the capture + /// A unique identifier for this specific capture operation. pub capture_id: String, /// The status of the capture #[schema(value_type = CaptureStatus, example = "charged")] @@ -1658,21 +1654,21 @@ pub struct CaptureResponse { /// The currency of the amount of the capture #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, - /// The connector used for the payment + /// The name of the payment connector that processed this capture. pub connector: String, - /// Unique identifier for the parent attempt on which this capture is made + /// The ID of the payment attempt that was successfully authorized and subsequently captured by this operation. pub authorized_attempt_id: String, /// A unique identifier for this capture provided by the connector pub connector_capture_id: Option<String>, /// Sequence number of this capture, in the series of captures made for the parent attempt pub capture_sequence: i16, - /// If there was an error while calling the connector the error message is received here + /// A human-readable message from the connector explaining why this capture operation failed, if applicable. pub error_message: Option<String>, - /// If there was an error while calling the connectors the code is received here + /// The error code returned by the connector if this capture operation failed. This code is connector-specific. pub error_code: Option<String>, - /// If there was an error while calling the connectors the reason is received here + /// A more detailed reason from the connector explaining the capture failure, if available. pub error_reason: Option<String>, - /// Reference to the capture at connector side + /// The connector's own reference or transaction ID for this specific capture operation. Useful for reconciliation. pub reference_id: Option<String>, } @@ -4314,23 +4310,23 @@ impl Address { #[derive(Clone, Default, Debug, Eq, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] #[serde(deny_unknown_fields)] pub struct AddressDetails { - /// The address city + /// The city, district, suburb, town, or village of the address. #[schema(max_length = 50, example = "New York")] pub city: Option<String>, - /// The two-letter ISO country code for the address + /// The two-letter ISO 3166-1 alpha-2 country code (e.g., US, GB). #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub country: Option<api_enums::CountryAlpha2>, - /// The first line of the address + /// The first line of the street address or P.O. Box. #[schema(value_type = Option<String>, max_length = 200, example = "123, King Street")] pub line1: Option<Secret<String>>, - /// The second line of the address + /// The second line of the street address or P.O. Box (e.g., apartment, suite, unit, or building). #[schema(value_type = Option<String>, max_length = 50, example = "Powelson Avenue")] pub line2: Option<Secret<String>>, - /// The third line of the address + /// The third line of the street address, if applicable. #[schema(value_type = Option<String>, max_length = 50, example = "Bridgewater")] pub line3: Option<Secret<String>>, @@ -4424,22 +4420,22 @@ pub struct PhoneDetails { #[cfg(feature = "v1")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { - /// The unique identifier for the payment + /// The unique identifier for the payment being captured. This is taken from the path parameter. #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, - /// The unique identifier for the merchant + /// The unique identifier for the merchant. This is usually inferred from the API key. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, - /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. - #[schema(value_type = i64, example = 6540)] + /// The amount to capture, in the lowest denomination of the currency. If omitted, the entire `amount_capturable` of the payment will be captured. Must be less than or equal to the current `amount_capturable`. + #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, - /// Decider to refund the uncaptured amount + /// Decider to refund the uncaptured amount. (Currently not fully supported or behavior may vary by connector). pub refund_uncaptured_amount: Option<bool>, - /// Provides information about a card payment that customers see on their statements. + /// A dynamic suffix that appears on your customer's credit card statement. This is concatenated with the (shortened) descriptor prefix set on your account to form the complete statement descriptor. The combined length should not exceed connector-specific limits (typically 22 characters). pub statement_descriptor_suffix: Option<String>, - /// Concatenated with the statement descriptor suffix that’s set on the account to form the complete statement descriptor. + /// An optional prefix for the statement descriptor that appears on your customer's credit card statement. This can override the default prefix set on your merchant account. The combined length of prefix and suffix should not exceed connector-specific limits (typically 22 characters). pub statement_descriptor_prefix: Option<String>, - /// Merchant connector details used to make payments. + /// Merchant connector details used to make payments. (Deprecated) #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } @@ -4824,28 +4820,28 @@ pub struct PaymentsResponse { #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, - /// The maximum amount that could be captured from the payment + /// The amount (in minor units) that can still be captured for this payment. This is relevant when `capture_method` is `manual`. Once fully captured, or if `capture_method` is `automatic` and payment succeeded, this will be 0. #[schema(value_type = i64, minimum = 100, example = 6540)] pub amount_capturable: MinorUnit, - /// The amount which is already captured from the payment, this helps in the cases where merchants can't capture all capturable amount at once. + /// The total amount (in minor units) that has been captured for this payment. For `fauxpay` sandbox connector, this might reflect the authorized amount if `status` is `succeeded` even if `capture_method` was `manual`. #[schema(value_type = Option<i64>, example = 6540)] pub amount_received: Option<MinorUnit>, - /// The connector used for the payment + /// The name of the payment connector (e.g., 'stripe', 'adyen') that processed or is processing this payment. #[schema(example = "stripe")] pub connector: Option<String>, - /// It's a token used for client side verification. + /// A secret token unique to this payment intent. It is primarily used by client-side applications (e.g., Hyperswitch SDKs) to authenticate actions like confirming the payment or handling next actions. This secret should be handled carefully and not exposed publicly beyond its intended client-side use. #[schema(value_type = Option<String>, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: Option<Secret<String>>, - /// Time when the payment was created + /// Timestamp indicating when this payment intent was created, in ISO 8601 format. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, - /// The currency of the amount of the payment + /// Three-letter ISO currency code (e.g., USD, EUR) for the payment amount. #[schema(value_type = Currency, example = "USD")] pub currency: String, @@ -4862,11 +4858,11 @@ pub struct PaymentsResponse { pub customer: Option<CustomerDetailsResponse>, - /// A description of the payment + /// An arbitrary string providing a description for the payment, often useful for display or internal record-keeping. #[schema(example = "It's my first payment request")] pub description: Option<String>, - /// List of refunds that happened on this intent, as same payment intent can have multiple refund requests depending on the nature of order + /// An array of refund objects associated with this payment. Empty or null if no refunds have been processed. #[schema(value_type = Option<Vec<RefundResponse>>)] pub refunds: Option<Vec<refunds::RefundResponse>>, @@ -4968,17 +4964,17 @@ pub struct PaymentsResponse { #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, - /// Additional information required for redirection + /// If the payment requires further action from the customer (e.g., 3DS authentication, redirect to a bank page), this object will contain the necessary information for the client to proceed. Null if no further action is needed from the customer at this stage. pub next_action: Option<NextActionData>, - /// If the payment was cancelled the reason will be provided here + /// If the payment intent was cancelled, this field provides a textual reason for the cancellation (e.g., "requested_by_customer", "abandoned"). pub cancellation_reason: Option<String>, - /// If there was an error while calling the connectors the code is received here + /// The connector-specific error code from the last failed payment attempt associated with this payment intent. #[schema(example = "E0001")] pub error_code: Option<String>, - /// If there was an error while calling the connector the error message is received here + /// A human-readable error message from the last failed payment attempt associated with this payment intent. #[schema(example = "Failed while verifying the card")] pub error_message: Option<String>, @@ -4990,26 +4986,26 @@ pub struct PaymentsResponse { #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_message: Option<String>, - /// Payment Experience for the current payment + /// Describes the type of payment flow experienced by the customer (e.g., 'redirect_to_url', 'invoke_sdk', 'display_qr_code'). #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, - /// Can be used to specify the Payment Method Type + /// The specific payment method subtype used for this payment (e.g., 'credit_card', 'klarna', 'gpay'). This provides more granularity than the 'payment_method' field. #[schema(value_type = Option<PaymentMethodType>, example = "gpay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, - /// The connector used for this payment along with the country and business details + /// A label identifying the specific merchant connector account (MCA) used for this payment. This often combines the connector name, business country, and a custom label (e.g., "stripe_US_primary"). #[schema(example = "stripe_US_food")] pub connector_label: Option<String>, - /// The business country of merchant for this payment + /// The two-letter ISO country code (e.g., US, GB) of the business unit or profile under which this payment was processed. #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub business_country: Option<api_enums::CountryAlpha2>, - /// The business label of merchant for this payment + /// The label identifying the specific business unit or profile under which this payment was processed by the merchant. pub business_label: Option<String>, - /// The business_sub_label for this payment + /// An optional sub-label for further categorization of the business unit or profile used for this payment. pub business_sub_label: Option<String>, /// Allowed Payment Method Types for a given PaymentIntent @@ -5092,7 +5088,7 @@ pub struct PaymentsResponse { /// The browser information used for this payment pub browser_info: Option<serde_json::Value>, - /// Identifier for Payment Method used for the payment + /// A unique identifier for the payment method used in this payment. If the payment method was saved or tokenized, this ID can be used to reference it for future transactions or recurring payments. pub payment_method_id: Option<String>, /// Payment Method Status, refers to the status of the payment method used for this payment. @@ -5330,7 +5326,6 @@ pub struct PaymentsConfirmIntentRequest { #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, - /// Provide a reference to a stored payment method #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, } @@ -6414,9 +6409,9 @@ pub struct PaymentsRetrieveRequest { pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: bool, - /// The parameters passed to a retrieve request + /// Optional query parameters that might be specific to a connector or flow, passed through during the retrieve operation. Use with caution and refer to specific connector documentation if applicable. pub param: Option<String>, - /// The name of the connector + /// Optionally specifies the connector to be used for a 'force_sync' retrieve operation. If provided, Hyperswitch will attempt to sync the payment status from this specific connector. pub connector: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] @@ -7563,6 +7558,7 @@ pub struct PaymentsManualUpdateResponse { } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] +/// Indicates if 3DS method data was successfully completed or not pub enum ThreeDsCompletionIndicator { /// 3DS method successfully completed #[serde(rename = "Y")] diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 57b119b8d11..893a3b7dafa 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -241,7 +241,12 @@ pub enum RevenueRecoveryAlgorithmType { Cascading, } -/// Pass this parameter to force 3DS or non 3DS auth for this payment. Some connectors will still force 3DS auth even in case of passing 'no_three_ds' here and vice versa. Default value is 'no_three_ds' if not set +/// Specifies the type of cardholder authentication to be applied for a payment. +/// +/// - `ThreeDs`: Requests 3D Secure (3DS) authentication. If the card is enrolled, 3DS authentication will be activated, potentially shifting chargeback liability to the issuer. +/// - `NoThreeDs`: Indicates that 3D Secure authentication should not be performed. The liability for chargebacks typically remains with the merchant. This is often the default if not specified. +/// +/// Note: The actual authentication behavior can also be influenced by merchant configuration and specific connector defaults. Some connectors might still enforce 3DS or bypass it regardless of this parameter. #[derive( Clone, Copy, @@ -395,7 +400,9 @@ pub enum BlocklistDataKind { ExtendedCardBin, } -/// Default value if not passed is set to 'automatic' which results in Auth and Capture in one single API request. Pass 'manual' or 'manual_multiple' in case you want do a separate Auth and Capture by first authorizing and placing a hold on your customer's funds so that you can use the Payments/Capture endpoint later to capture the authorized amount. Pass 'manual' if you want to only capture the amount later once or 'manual_multiple' if you want to capture the funds multiple times later. Both 'manual' and 'manual_multiple' are only supported by a specific list of processors +/// Specifies how the payment is captured. +/// - `automatic`: Funds are captured immediately after successful authorization. This is the default behavior if the field is omitted. +/// - `manual`: Funds are authorized but not captured. A separate request to the `/payments/{payment_id}/capture` endpoint is required to capture the funds. #[derive( Clone, Copy, @@ -416,16 +423,16 @@ pub enum BlocklistDataKind { #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CaptureMethod { - /// Post the payment authorization, the capture will be executed on the full amount immediately + /// Post the payment authorization, the capture will be executed on the full amount immediately. #[default] Automatic, - /// The capture will happen only if the merchant triggers a Capture API request + /// The capture will happen only if the merchant triggers a Capture API request. Allows for a single capture of the authorized amount. Manual, - /// The capture will happen only if the merchant triggers a Capture API request + /// The capture will happen only if the merchant triggers a Capture API request. Allows for multiple partial captures up to the authorized amount. ManualMultiple, - /// The capture can be scheduled to automatically get triggered at a specific date & time + /// The capture can be scheduled to automatically get triggered at a specific date & time. Scheduled, - /// Handles separate auth and capture sequentially; same as `Automatic` for most connectors. + /// Handles separate auth and capture sequentially; effectively the same as `Automatic` for most connectors. SequentialAutomatic, } @@ -494,7 +501,7 @@ pub enum CallConnectorAction { HandleResponse(Vec<u8>), } -/// The three letter ISO currency code in uppercase. Eg: 'USD' for the United States Dollar. +/// The three-letter ISO 4217 currency code (e.g., "USD", "EUR") for the payment amount. This field is mandatory for creating a payment. #[allow(clippy::upper_case_acronyms)] #[derive( Clone, @@ -1555,7 +1562,8 @@ pub enum MerchantStorageScheme { RedisKv, } -/// The status of the current payment that was made +/// Represents the overall status of a payment intent. +/// The status transitions through various states depending on the payment method, confirmation, capture method, and any subsequent actions (like customer authentication or manual capture). #[derive( Clone, Copy, @@ -1642,9 +1650,10 @@ impl IntentStatus { } } -/// Indicates that you intend to make future payments with the payment methods used for this Payment. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. -/// - On_session - Payment method saved only at hyperswitch when consent is provided by the user. CVV will asked during the returning user payment -/// - Off_session - Payment method saved at both hyperswitch and Processor when consent is provided by the user. No input is required during the returning user payment. +/// Specifies how the payment method can be used for future payments. +/// - `off_session`: The payment method can be used for future payments when the customer is not present. +/// - `on_session`: The payment method is intended for use only when the customer is present during checkout. +/// If omitted, defaults to `on_session`. #[derive( Clone, Copy, diff --git a/crates/openapi/src/routes/payments.rs b/crates/openapi/src/routes/payments.rs index ee659e1f707..6160b68b44b 100644 --- a/crates/openapi/src/routes/payments.rs +++ b/crates/openapi/src/routes/payments.rs @@ -1,24 +1,8 @@ /// Payments - Create /// -/// **Creates a payment object when amount and currency are passed.** +/// Creates a payment resource, which represents a customer's intent to pay. +/// This endpoint is the starting point for various payment flows: /// -/// This API is also used to create a mandate by passing the `mandate_object`. -/// -/// Depending on the user journey you wish to achieve, you may opt to complete all the steps in a single request **by attaching a payment method, setting `confirm=true` and `capture_method = automatic`** in the *Payments/Create API* request. -/// -/// Otherwise, To completely process a payment you will have to **create a payment, attach a payment method, confirm and capture funds**. For that you could use the following sequence of API requests - -/// -/// 1. Payments - Create -/// -/// 2. Payments - Update -/// -/// 3. Payments - Confirm -/// -/// 4. Payments - Capture. -/// -/// You will require the 'API - Key' from the Hyperswitch dashboard to make the first call, and use the 'client secret' returned in this API along with your 'publishable key' to make subsequent API calls from your client. -/// -/// This page lists the various combinations in which the Payments - Create API can be used and the details about the various fields in the requests and responses. #[utoipa::path( post, path = "/payments", @@ -26,12 +10,12 @@ content = PaymentsCreateRequest, examples( ( - "Create a payment with minimal fields" = ( + "1. Create a payment with minimal fields" = ( value = json!({"amount": 6540,"currency": "USD"}) ) ), ( - "Create a payment with customer details and metadata" = ( + "2. Create a payment with customer details and metadata" = ( value = json!({ "amount": 6540, "currency": "USD", @@ -53,7 +37,7 @@ ) ), ( - "Create a 3DS payment" = ( + "3. Create a 3DS payment" = ( value = json!({ "amount": 6540, "currency": "USD", @@ -62,7 +46,7 @@ ) ), ( - "Create a manual capture payment" = ( + "4. Create a manual capture payment (basic)" = ( value = json!({ "amount": 6540, "currency": "USD", @@ -71,7 +55,7 @@ ) ), ( - "Create a setup mandate payment" = ( + "5. Create a setup mandate payment" = ( value = json!({ "amount": 6540, "currency": "USD", @@ -117,7 +101,7 @@ ) ), ( - "Create a recurring payment with mandate_id" = ( + "6. Create a recurring payment with mandate_id" = ( value = json!({ "amount": 6540, "currency": "USD", @@ -130,7 +114,7 @@ ) ), ( - "Create a payment and save the card" = ( + "7. Create a payment and save the card" = ( value = json!({ "amount": 6540, "currency": "USD", @@ -160,7 +144,7 @@ ) ), ( - "Create a payment using an already saved card's token" = ( + "8. Create a payment using an already saved card's token" = ( value = json!({ "amount": 6540, "currency": "USD", @@ -173,7 +157,7 @@ ) ), ( - "Create a manual capture payment" = ( + "9. Create a payment with billing details" = ( value = json!({ "amount": 6540, "currency": "USD", @@ -203,7 +187,222 @@ ), ), responses( - (status = 200, description = "Payment created", body = PaymentsCreateResponseOpenApi), + (status = 200, description = "Payment created", body = PaymentsCreateResponseOpenApi, + examples( + ("1. Response for minimal payment creation (requires payment method)" = ( + value = json!({ + "payment_id": "pay_syxxxxxxxxxxxx", + "merchant_id": "merchant_myyyyyyyyyyyy", + "status": "requires_payment_method", + "amount": 6540, + "currency": "USD", + "client_secret": "pay_syxxxxxxxxxxxx_secret_szzzzzzzzzzz", + "created": "2023-10-26T10:00:00Z", + "amount_capturable": 6540, + "profile_id": "pro_pzzzzzzzzzzz", + "attempt_count": 1, + "expires_on": "2023-10-26T10:15:00Z" + }) + )), + ("2. Response for payment with customer details (requires payment method)" = ( + value = json!({ + "payment_id": "pay_custmeta_xxxxxxxxxxxx", + "merchant_id": "merchant_myyyyyyyyyyyy", + "status": "requires_payment_method", + "amount": 6540, + "currency": "USD", + "customer_id": "cus_abcdefgh", + "customer": { + "id": "cus_abcdefgh", + "name": "John Dough", + "email": "[email protected]", + "phone": "9123456789" + }, + "description": "Its my first payment request", + "statement_descriptor_name": "joseph", + "statement_descriptor_suffix": "JS", + "metadata": { + "udf1": "some-value", + "udf2": "some-value" + }, + "client_secret": "pay_custmeta_xxxxxxxxxxxx_secret_szzzzzzzzzzz", + "created": "2023-10-26T10:05:00Z", + "ephemeral_key": { + "customer_id": "cus_abcdefgh", + "secret": "epk_ephemeralxxxxxxxxxxxx" + }, + "profile_id": "pro_pzzzzzzzzzzz", + "attempt_count": 1, + "expires_on": "2023-10-26T10:20:00Z" + }) + )), + ("3. Response for 3DS payment creation (requires payment method)" = ( + value = json!({ + "payment_id": "pay_3ds_xxxxxxxxxxxx", + "merchant_id": "merchant_myyyyyyyyyyyy", + "status": "requires_payment_method", + "amount": 6540, + "currency": "USD", + "authentication_type": "three_ds", + "client_secret": "pay_3ds_xxxxxxxxxxxx_secret_szzzzzzzzzzz", + "created": "2023-10-26T10:10:00Z", + "profile_id": "pro_pzzzzzzzzzzz", + "attempt_count": 1, + "expires_on": "2023-10-26T10:25:00Z" + }) + )), + ("4. Response for basic manual capture payment (requires payment method)" = ( + value = json!({ + "payment_id": "pay_manualcap_xxxxxxxxxxxx", + "merchant_id": "merchant_myyyyyyyyyyyy", + "status": "requires_payment_method", + "amount": 6540, + "currency": "USD", + "capture_method": "manual", + "client_secret": "pay_manualcap_xxxxxxxxxxxx_secret_szzzzzzzzzzz", + "created": "2023-10-26T10:15:00Z", + "profile_id": "pro_pzzzzzzzzzzz", + "attempt_count": 1, + "expires_on": "2023-10-26T10:30:00Z" + }) + )), + ("5. Response for successful setup mandate payment" = ( + value = json!({ + "payment_id": "pay_mandatesetup_xxxxxxxxxxxx", + "merchant_id": "merchant_myyyyyyyyyyyy", + "status": "succeeded", + "amount": 6540, + "currency": "USD", + "amount_capturable": 0, + "amount_received": 6540, + "connector": "fauxpay", + "customer_id": "StripeCustomer123", + "mandate_id": "man_xxxxxxxxxxxx", + "mandate_data": { + "customer_acceptance": { + "acceptance_type": "online", + "accepted_at": "1963-05-03T04:07:52.723Z", + "online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" } + }, + "mandate_type": { "single_use": { "amount": 6540, "currency": "USD" } } + }, + "setup_future_usage": "on_session", + "payment_method": "card", + "payment_method_data": { + "card": { "last4": "4242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" } + }, + "authentication_type": "no_three_ds", + "client_secret": "pay_mandatesetup_xxxxxxxxxxxx_secret_szzzzzzzzzzz", + "created": "2023-10-26T10:20:00Z", + "ephemeral_key": { "customer_id": "StripeCustomer123", "secret": "epk_ephemeralxxxxxxxxxxxx" }, + "profile_id": "pro_pzzzzzzzzzzz", + "attempt_count": 1, + "merchant_connector_id": "mca_mcaconnectorxxxx", + "connector_transaction_id": "txn_connectortransidxxxx" + }) + )), + ("6. Response for successful recurring payment with mandate_id" = ( + value = json!({ + "payment_id": "pay_recurring_xxxxxxxxxxxx", + "merchant_id": "merchant_myyyyyyyyyyyy", + "status": "succeeded", + "amount": 6540, + "currency": "USD", + "amount_capturable": 0, + "amount_received": 6540, + "connector": "fauxpay", + "customer_id": "StripeCustomer", + "mandate_id": "{{mandate_id}}", + "off_session": true, + "payment_method": "card", + "authentication_type": "no_three_ds", + "client_secret": "pay_recurring_xxxxxxxxxxxx_secret_szzzzzzzzzzz", + "created": "2023-10-26T10:22:00Z", + "profile_id": "pro_pzzzzzzzzzzz", + "attempt_count": 1, + "merchant_connector_id": "mca_mcaconnectorxxxx", + "connector_transaction_id": "txn_connectortransidxxxx" + }) + )), + ("7. Response for successful payment with card saved" = ( + value = json!({ + "payment_id": "pay_savecard_xxxxxxxxxxxx", + "merchant_id": "merchant_myyyyyyyyyyyy", + "status": "succeeded", + "amount": 6540, + "currency": "USD", + "amount_capturable": 0, + "amount_received": 6540, + "connector": "fauxpay", + "customer_id": "StripeCustomer123", + "setup_future_usage": "on_session", + "payment_method": "card", + "payment_method_data": { + "card": { "last4": "4242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" } + }, + "authentication_type": "no_three_ds", + "client_secret": "pay_savecard_xxxxxxxxxxxx_secret_szzzzzzzzzzz", + "created": "2023-10-26T10:25:00Z", + "ephemeral_key": { "customer_id": "StripeCustomer123", "secret": "epk_ephemeralxxxxxxxxxxxx" }, + "profile_id": "pro_pzzzzzzzzzzz", + "attempt_count": 1, + "merchant_connector_id": "mca_mcaconnectorxxxx", + "connector_transaction_id": "txn_connectortransidxxxx", + "payment_token": null // Assuming payment_token is for subsequent use, not in this response. + }) + )), + ("8. Response for successful payment using saved card token" = ( + value = json!({ + "payment_id": "pay_token_xxxxxxxxxxxx", + "merchant_id": "merchant_myyyyyyyyyyyy", + "status": "succeeded", + "amount": 6540, + "currency": "USD", + "amount_capturable": 0, + "amount_received": 6540, + "connector": "fauxpay", + "payment_method": "card", + "payment_token": "{{payment_token}}", + "client_secret": "pay_token_xxxxxxxxxxxx_secret_szzzzzzzzzzz", + "created": "2023-10-26T10:27:00Z", + "profile_id": "pro_pzzzzzzzzzzz", + "attempt_count": 1, + "merchant_connector_id": "mca_mcaconnectorxxxx", + "connector_transaction_id": "txn_connectortransidxxxx" + }) + )), + ("9. Response for payment with billing details (requires payment method)" = ( + value = json!({ + "payment_id": "pay_manualbill_xxxxxxxxxxxx", + "merchant_id": "merchant_myyyyyyyyyyyy", + "status": "requires_payment_method", + "amount": 6540, + "currency": "USD", + "customer_id": "cus_abcdefgh", + "customer": { + "id": "cus_abcdefgh", + "name": "John Dough", + "email": "[email protected]", + "phone": "9123456789" + }, + "billing": { + "address": { + "line1": "1467", "line2": "Harrison Street", "city": "San Fransico", + "state": "California", "zip": "94122", "country": "US", + "first_name": "joseph", "last_name": "Doe" + }, + "phone": { "number": "9123456789", "country_code": "+91" } + }, + "client_secret": "pay_manualbill_xxxxxxxxxxxx_secret_szzzzzzzzzzz", + "created": "2023-10-26T10:30:00Z", + "ephemeral_key": { "customer_id": "cus_abcdefgh", "secret": "epk_ephemeralxxxxxxxxxxxx" }, + "profile_id": "pro_pzzzzzzzzzzz", + "attempt_count": 1, + "expires_on": "2023-10-26T10:45:00Z" + }) + )) + ) + ), (status = 400, description = "Missing Mandatory fields") ), tag = "Payments", @@ -294,15 +493,12 @@ pub fn payments_update() {} /// Payments - Confirm /// -/// **Use this API to confirm the payment and forward the payment to the payment processor.** +/// Confirms a payment intent that was previously created with `confirm: false`. This action attempts to authorize the payment with the payment processor. /// -/// Alternatively you can confirm the payment within the *Payments/Create* API by setting `confirm=true`. After confirmation, the payment could either: -/// -/// 1. fail with `failed` status or -/// -/// 2. transition to a `requires_customer_action` status with a `next_action` block or -/// -/// 3. succeed with either `succeeded` in case of automatic capture or `requires_capture` in case of manual capture +/// Expected status transitions after confirmation: +/// - `succeeded`: If authorization is successful and `capture_method` is `automatic`. +/// - `requires_capture`: If authorization is successful and `capture_method` is `manual`. +/// - `failed`: If authorization fails. #[utoipa::path( post, path = "/payments/{payment_id}/confirm", @@ -352,7 +548,13 @@ pub fn payments_confirm() {} /// Payments - Capture /// -/// To capture the funds for an uncaptured payment +/// Captures the funds for a previously authorized payment intent where `capture_method` was set to `manual` and the payment is in a `requires_capture` state. +/// +/// Upon successful capture, the payment status usually transitions to `succeeded`. +/// The `amount_to_capture` can be specified in the request body; it must be less than or equal to the payment's `amount_capturable`. If omitted, the full capturable amount is captured. +/// +/// A payment must be in a capturable state (e.g., `requires_capture`). Attempting to capture an already `succeeded` (and fully captured) payment or one in an invalid state will lead to an error. +/// #[utoipa::path( post, path = "/payments/{payment_id}/capture",
2025-05-31T21:42:29Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [X] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Improving API-Reference to include payment flows, and include better and correct description of some fields. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **Documentation** - Introduced a comprehensive "Payment Flows" API reference covering payment processing patterns, one-time and recurring payments, and flow diagrams. - Enhanced OpenAPI specifications with clearer endpoint and schema descriptions, improved field explanations, and expanded example requests and responses. - Updated sidebar metadata and icons for setup instructions. - Added a new documentation site configuration file with structured navigation, theming, and integrations. - Removed legacy API documentation configuration file. - Improved in-code documentation for payment models and endpoints to clarify field usage and API behaviors. - Refined descriptive text in API schemas for addresses, captures, payment attempts, and payment methods to improve clarity and precision. - Expanded and clarified enum documentation for payment authentication, capture methods, currency codes, intent statuses, and future usage. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
v1.114.0
b159a1d23dd37a038debaa0538355e14a3847249
b159a1d23dd37a038debaa0538355e14a3847249
juspay/hyperswitch
juspay__hyperswitch-8240
Bug: refactor(dynamic_routing): add support for shuffle on tie flag to success_based routing
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index bb4db422556..9724050266d 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -9482,6 +9482,7 @@ "customer_id", "payment_method_type", "payment_method_subtype", + "recurring_enabled", "created", "requires_cvv", "last_used_at", @@ -9513,9 +9514,8 @@ }, "recurring_enabled": { "type": "boolean", - "description": "Indicates whether the payment method supports recurring payments. Optional.", - "example": true, - "nullable": true + "description": "Indicates whether the payment method is eligible for recurring payments", + "example": true }, "payment_method_data": { "allOf": [ @@ -17142,7 +17142,6 @@ "customer_id", "payment_method_type", "payment_method_subtype", - "recurring_enabled", "created", "requires_cvv", "is_default", @@ -17169,8 +17168,9 @@ }, "recurring_enabled": { "type": "boolean", - "description": "Indicates whether the payment method is eligible for recurring payments", - "example": true + "description": "Indicates whether the payment method supports recurring payments. Optional.", + "example": true, + "nullable": true }, "payment_method_data": { "allOf": [ @@ -23804,6 +23804,10 @@ "type": "number", "format": "double", "nullable": true + }, + "shuffle_on_tie_during_exploitation": { + "type": "boolean", + "nullable": true } } }, diff --git a/api-reference/hyperswitch_intelligent_router_open_api_spec.yml b/api-reference/hyperswitch_intelligent_router_open_api_spec.yml index 7372a083b88..c3c1d3458ca 100644 --- a/api-reference/hyperswitch_intelligent_router_open_api_spec.yml +++ b/api-reference/hyperswitch_intelligent_router_open_api_spec.yml @@ -45,6 +45,7 @@ paths: default_success_rate: 0.95 specificity_level: ENTITY exploration_percent: 20.0 + shuffle_on_tie_during_exploitation: true responses: "200": description: Success rate calculated successfully diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 636f73ae217..9d85cebb9a6 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -28160,6 +28160,10 @@ "type": "number", "format": "double", "nullable": true + }, + "shuffle_on_tie_during_exploitation": { + "type": "boolean", + "nullable": true } } }, diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index ed1915764cb..aea14c23fe8 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -1016,6 +1016,7 @@ impl Default for SuccessBasedRoutingConfig { }), specificity_level: SuccessRateSpecificityLevel::default(), exploration_percent: Some(20.0), + shuffle_on_tie_during_exploitation: Some(false), }), decision_engine_configs: None, } @@ -1044,6 +1045,7 @@ pub struct SuccessBasedRoutingConfigBody { #[serde(default)] pub specificity_level: SuccessRateSpecificityLevel, pub exploration_percent: Option<f64>, + pub shuffle_on_tie_during_exploitation: Option<bool>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] @@ -1173,6 +1175,9 @@ impl SuccessBasedRoutingConfigBody { if let Some(exploration_percent) = new.exploration_percent { self.exploration_percent = Some(exploration_percent); } + if let Some(shuffle_on_tie_during_exploitation) = new.shuffle_on_tie_during_exploitation { + self.shuffle_on_tie_during_exploitation = Some(shuffle_on_tie_during_exploitation); + } } } diff --git a/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs b/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs index b63f435327e..00f3e1f159a 100644 --- a/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs +++ b/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs @@ -291,6 +291,7 @@ impl ForeignTryFrom<SuccessBasedRoutingConfigBody> for CalSuccessRateConfig { SuccessRateSpecificityLevel::Global => Some(ProtoSpecificityLevel::Global.into()), }, exploration_percent: config.exploration_percent, + shuffle_on_tie_during_exploitation: config.shuffle_on_tie_during_exploitation, }) } } diff --git a/proto/success_rate.proto b/proto/success_rate.proto index efdd439cac9..cdcde99fa87 100644 --- a/proto/success_rate.proto +++ b/proto/success_rate.proto @@ -24,6 +24,7 @@ message CalSuccessRateConfig { double default_success_rate = 2; optional SuccessRateSpecificityLevel specificity_level = 3; optional double exploration_percent = 4; + optional bool shuffle_on_tie_during_exploitation = 5; } enum SuccessRateSpecificityLevel { @@ -78,13 +79,13 @@ message UpdateSuccessRateWindowResponse { UpdationStatus status = 1; } - // API-3 types +// API-3 types message InvalidateWindowsRequest { string id = 1; } message InvalidateWindowsResponse { - enum InvalidationStatus { + enum InvalidationStatus { WINDOW_INVALIDATION_SUCCEEDED = 0; WINDOW_INVALIDATION_FAILED = 1; }
2025-06-04T12:48:08Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This pull request introduces a new feature to the routing configuration: the ability to shuffle results on a tie during exploitation. This feature is implemented across multiple files, including API specifications, Rust models, and protocol buffer definitions. Below is a summary of the most important changes grouped by theme. ### Feature Addition: Shuffle on Tie During Exploitation * **API Specification Update**: Added `shuffle_on_tie_during_exploitation` to the routing configuration in `api-reference/hyperswitch_intelligent_router_open_api_spec.yml`. This parameter enhances routing behavior during exploitation when multiple options have equal success rates. * **Rust Model Updates**: - Updated the `SuccessBasedRoutingConfig` default implementation in `crates/api_models/src/routing.rs` to include `shuffle_on_tie_during_exploitation` with a default value of `false`. - Added `shuffle_on_tie_during_exploitation` as an optional field in the `SuccessBasedRoutingConfigBody` struct to allow API clients to configure this behavior. - Modified the `update_from` method in `SuccessBasedRoutingConfigBody` to handle updates to the `shuffle_on_tie_during_exploitation` field. * **Protocol Buffer Update**: Added `shuffle_on_tie_during_exploitation` as an optional field in the `CalSuccessRateConfig` message definition in `proto/success_rate.proto`. This ensures compatibility with external services using gRPC. * **gRPC Client Update**: Incorporated the new `shuffle_on_tie_during_exploitation` field into the `ForeignTryFrom` implementation for `CalSuccessRateConfig` in `crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs`. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create merchant_account, api_key. 2. Toggle SR for the default profile_created above ``` curl --location --request POST 'http://localhost:8080/account/merchant_1748681084/business_profile/pro_3gHXWoq1Xh3AKi6tNZV1/dynamic_routing/success_based/toggle?enable=dynamic_connector_selection' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: xyz' ``` Check the `routing_algorithm` table for `shuffle_on_tie_during_exploitation` field in `algorithm_data` column. By default it will be set to `false` 3. If you want to update it, hit below curl and activate that algorithm_id for profile. ``` curl --location --request PATCH 'http://localhost:8080/account/merchant_1749040696/business_profile/pro_IFPbNQgBfzPAsqXUSAll/dynamic_routing/success_based/config/routing_Vl1hWGUqg203J5WqeCtK' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: xyz' \ --data '{ "config": { "shuffle_on_tie_during_exploitation": true } } ' ``` Check the `routing_algorithm` table for `shuffle_on_tie_during_exploitation` field in `algorithm_data` column for the newly created algorithm above after updating. It should be set to `true` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Introduced a new optional configuration parameter to control shuffle behavior during exploitation ties in success-based routing. - Enhanced payment method information by indicating eligibility for recurring payments and added filtering options for payment methods. - **Documentation** - Updated API documentation and example requests to reflect the new configuration option and payment method changes. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
v1.114.0
67a42f0c27157f876698982a6b5f0a1cd3e15ffb
67a42f0c27157f876698982a6b5f0a1cd3e15ffb
juspay/hyperswitch
juspay__hyperswitch-8228
Bug: [FEATURE] Fix spell check ### Feature Description Need to fix spell check in router ### Possible Implementation Need to fix spell check in router ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/analytics/src/routing_events/events.rs b/crates/analytics/src/routing_events/events.rs index 27b2f251627..b6090a588d2 100644 --- a/crates/analytics/src/routing_events/events.rs +++ b/crates/analytics/src/routing_events/events.rs @@ -70,4 +70,5 @@ pub struct RoutingEventsResult { pub created_at: PrimitiveDateTime, pub method: String, pub routing_engine: String, + pub routing_approach: Option<String>, } diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index 46cd37bc68a..e416bf4bae9 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -1339,7 +1339,7 @@ pub struct LabelWithScoreEventResponse { #[serde(rename_all = "snake_case")] pub struct CalSuccessRateEventResponse { pub labels_with_score: Vec<LabelWithScoreEventResponse>, - pub routing_apporach: RoutingApproach, + pub routing_approach: RoutingApproach, } #[derive(Clone, Debug, Serialize, Deserialize)] diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index fa161efb212..219eef52073 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -2087,7 +2087,7 @@ pub async fn perform_success_based_routing( "unable to calculate/fetch success rate from dynamic routing service", )?; - let event_resposne = api_routing::CalSuccessRateEventResponse { + let event_response = api_routing::CalSuccessRateEventResponse { labels_with_score: success_based_connectors .labels_with_score .iter() @@ -2098,7 +2098,7 @@ pub async fn perform_success_based_routing( }, ) .collect(), - routing_apporach: match success_based_connectors.routing_approach { + routing_approach: match success_based_connectors.routing_approach { 0 => api_routing::RoutingApproach::Exploration, 1 => api_routing::RoutingApproach::Exploitation, _ => { @@ -2113,8 +2113,8 @@ pub async fn perform_success_based_routing( }, }; - routing_event.set_response_body(&event_resposne); - routing_event.set_routing_approach(event_resposne.routing_apporach.to_string()); + routing_event.set_response_body(&event_response); + routing_event.set_routing_approach(event_response.routing_approach.to_string()); let mut connectors = Vec::with_capacity(success_based_connectors.labels_with_score.len()); for label_with_score in success_based_connectors.labels_with_score { diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 4798cce9b02..f568aff55b1 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -1452,7 +1452,7 @@ pub async fn push_metrics_with_update_window_for_contract_based_routing( routing_events::RoutingEngine::IntelligentRouter, ); - let update_respose = client + let update_response = client .update_contracts( profile_id.get_string_repr().into(), vec![request_label_info], @@ -1474,7 +1474,7 @@ pub async fn push_metrics_with_update_window_for_contract_based_routing( )?; let event_response = routing_types::UpdateContractEventResponse { - status: match update_respose.status { + status: match update_response.status { 0 => routing_types::ContractUpdationStatusEventResponse::ContractUpdationSucceeded, 1 => routing_types::ContractUpdationStatusEventResponse::ContractUpdationFailed, _ => {
2025-06-03T12:43:34Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - Fixed spell checks - Added `routing_approach` field in routing events API response ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. hit the routing analytics API ``` curl -H "api-key: dev_R5xpWKgvxcaxLcQateRbZKt8B9XkvqaPziIdwPHaPQrGTDTq5JRyncxPtOq9JNsj" "http://localhost:8080/analytics/v1/profile/routing_event_logs?type=Payment&payment_id=pay_evlgasQRCFOJplN3yWge" ``` Response - ``` [ { "merchant_id": "merchant_1748952604", "profile_id": "pro_SoNvSCTpaIDKRzkJqf59", "payment_id": "pay_evlgasQRCFOJplN3yWge", "routable_connectors": "Stripe:\"mca_rozlszQ8vn82sR6d42xe\"", "payment_connector": null, "request_id": "019735b4-19a5-7ed1-8efb-412f3d26f6e0", "flow": "Intelligent-router FetchSuccessRate", "url": "SuccessRateCalculator.FetchSuccessRate", "request": "{\"id\":\"pro_SoNvSCTpaIDKRzkJqf59\",\"params\":\"card\",\"labels\":[\"stripe:mca_rozlszQ8vn82sR6d42xe\"],\"config\":{\"min_aggregates_size\":5,\"default_success_rate\":100.0,\"specificity_level\":\"merchant\",\"exploration_percent\":20.0}}", "response": "{\"labels_with_score\":[{\"score\":100.0,\"label\":\"stripe:mca_rozlszQ8vn82sR6d42xe\"}],\"routing_approach\":\"exploitation\"}", "error": null, "status_code": 200, "created_at": "2025-06-03T12:11:25.008Z", "method": "Grpc", "routing_engine": "intelligent_router", "routing_approach": "Exploitation" }, { "merchant_id": "merchant_1748952604", "profile_id": "pro_SoNvSCTpaIDKRzkJqf59", "payment_id": "pay_evlgasQRCFOJplN3yWge", "routable_connectors": "", "payment_connector": "Stripe:\"mca_rozlszQ8vn82sR6d42xe\"", "request_id": "019735b4-19a5-7ed1-8efb-412f3d26f6e0", "flow": "Intelligent-router UpdateSuccessRateWindow", "url": "SuccessRateCalculator.UpdateSuccessRateWindow", "request": "{\"id\":\"pro_SoNvSCTpaIDKRzkJqf59\",\"params\":\"card\",\"labels_with_status\":[{\"label\":\"stripe:mca_rozlszQ8vn82sR6d42xe\",\"status\":true}],\"config\":{\"max_aggregates_size\":8,\"current_block_threshold\":{\"duration_in_mins\":null,\"max_total_count\":5}},\"global_labels_with_status\":[{\"label\":\"stripe:mca_rozlszQ8vn82sR6d42xe\",\"status\":true}]}", "response": "{\"status\":\"window_updation_succeeded\"}", "error": null, "status_code": 200, "created_at": "2025-06-03T12:11:26.323Z", "method": "Grpc", "routing_engine": "intelligent_router", "routing_approach": null } ] ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
ec908d38acb6e6e6a5bc204dc4b47ec46248d00e
ec908d38acb6e6e6a5bc204dc4b47ec46248d00e
juspay/hyperswitch
juspay__hyperswitch-8216
Bug: chore: Update apple pay currency filter configs Update apple pay currency filter configs as a temporary fix for failing PR #7921
diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 16b0a3ad1d1..65399b000c7 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -246,7 +246,7 @@ ach = { country = "US", currency = "USD" } affirm = { country = "US", currency = "USD" } afterpay_clearpay = { country = "AU,NZ,ES,GB,FR,IT,CA,US", currency = "GBP" } ali_pay = { country = "AU,JP,HK,SG,MY,TH,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,FI,RO,MT,SI,GR,PT,IE,IT,CA,US", currency = "USD,EUR,GBP,JPY,AUD,SGD,CHF,SEK,NOK,NZD,THB,HKD,CAD,CNY" } -apple_pay = { country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HU,IS,IE,IM,IT,KZ,JE,LV,LI,LT,LU,MT,MD,MC,ME,NL,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,UA,GB,AR,CO,CR,BR,MX,PE,BH,IL,JO,KW,PS,QA,SA,AE,CA,UM,US,KR,VN,MA,ZA,VA,CL,SV,GT,HN,PA", currency = "AUD,CHF,CAD,EUR,GBP,HKD,SGD,USD" } +apple_pay = { country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HU,IS,IE,IM,IT,KZ,JE,LV,LI,LT,LU,MT,MD,MC,ME,NL,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,UA,GB,AR,CO,CR,BR,MX,PE,BH,IL,JO,KW,PS,QA,SA,AE,CA,UM,US,KR,VN,MA,ZA,VA,CL,SV,GT,HN,PA", currency = "AED,AUD,CHF,CAD,EUR,GBP,HKD,SGD,USD" } bacs = { country = "GB", currency = "GBP" } bancontact_card = { country = "BE", currency = "EUR" } blik = { country = "PL", currency = "PLN" }
2025-06-03T07:32:25Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Apple pay payments for noon were failing due to PR#7921. Adding AED to the currency list for apple pay is a temporary fix for this failure. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #8216 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
06c5215c0edf0ed47cc55fd5216c4642cc515f37
06c5215c0edf0ed47cc55fd5216c4642cc515f37
juspay/hyperswitch
juspay__hyperswitch-8230
Bug: [CYPRESS] Fix Cypress connector failures Wise Elavon Paybox Datatrans Facilitapay Itaubank
2025-06-03T12:45:52Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> This PR fixes Cypress tests for Itaubank, Paybox and Datatrans. Datatrans still fail. Datatrans fails because `ResponseCustom` needs a refactor while Paybox requires us to pass `FR` as country and upon fixing it, it started to say wrong creds. Facilitapay has no issues. Wise and Elavon creds issue. JP Morgan addressed in https://github.com/juspay/hyperswitch/pull/8282 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Fix stuff. Closes #8230 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> |command|screenshot| |-|-| |`CYPRESS_CONNECTOR=itaubank npm run cypress:payments`|<img width="420" alt="image" src="https://github.com/user-attachments/assets/988695cf-97af-4c6d-88bc-8fdc04ae4caf" />| |`CYPRESS_CONNECTOR=datatrans npm run cypress:payments`|<img width="424" alt="image" src="https://github.com/user-attachments/assets/398e7468-fec9-43f9-a8e4-9bc24c41eeb2" />| |`CYPRESS_CONNECTOR=facilitapay npm run cypress:payments`|![image](https://github.com/user-attachments/assets/fe19b957-7f86-4936-a75e-514d589cdb6c)| ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
45d4ebfde33c778d3d6063c1c8d45ef6373a5afd
45d4ebfde33c778d3d6063c1c8d45ef6373a5afd
juspay/hyperswitch
juspay__hyperswitch-8223
Bug: add retry support for debit routing In the case of debit routing flow, the routing output (`CallConnectorType`) will include both the connector and its associated card network. In our current implementation, we simply iterate over the connector list and pass the connector. With the updated requirement, we will also need to pass the corresponding card network for each connector in the case of debit routing.
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 2cd9f507893..0994dadb5c5 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -1516,7 +1516,7 @@ fn get_connector_data_with_routing_decision( let routing_decision = routing_helpers::RoutingDecisionData::get_debit_routing_decision_data( card_network, - debit_routing_output, + Some(debit_routing_output), ); return Ok((data, Some(routing_decision))); } diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index df36f9f5117..b8127940ff1 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -16,6 +16,7 @@ use crate::{ flows::{ConstructFlowSpecificData, Feature}, operations, }, + routing::helpers as routing_helpers, }, db::StorageInterface, routes::{ @@ -109,6 +110,7 @@ where frm_suggestion, business_profile, false, //should_retry_with_pan is not applicable for step-up + None, ) .await?; } @@ -155,11 +157,20 @@ where .unwrap_or(false) && business_profile.is_clear_pan_retries_enabled; - let connector = if should_retry_with_pan { + let (connector, routing_decision) = if should_retry_with_pan { // If should_retry_with_pan is true, it indicates that we are retrying with PAN using the same connector. - original_connector_data.clone() + (original_connector_data.clone(), None) } else { - super::get_connector_data(&mut connector_routing_data)?.connector_data + let connector_routing_data = + super::get_connector_data(&mut connector_routing_data)?; + let routing_decision = connector_routing_data.network.map(|card_network| { + routing_helpers::RoutingDecisionData::get_debit_routing_decision_data( + card_network, + None, + ) + }); + + (connector_routing_data.connector_data, routing_decision) }; router_data = do_retry( @@ -178,6 +189,7 @@ where frm_suggestion, business_profile, should_retry_with_pan, + routing_decision, ) .await?; @@ -329,6 +341,7 @@ pub async fn do_retry<F, ApiRequest, FData, D>( frm_suggestion: Option<storage_enums::FrmSuggestion>, business_profile: &domain::Profile, should_retry_with_pan: bool, + routing_decision: Option<routing_helpers::RoutingDecisionData>, ) -> RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>> where F: Clone + Send + Sync, @@ -372,7 +385,7 @@ where business_profile, true, should_retry_with_pan, - None, + routing_decision, None, ) .await?; diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 4798cce9b02..ca23d8c2d74 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -330,7 +330,7 @@ pub enum RoutingDecisionData { #[cfg(feature = "v1")] pub struct DebitRoutingDecisionData { pub card_network: common_enums::enums::CardNetwork, - pub debit_routing_result: open_router::DebitRoutingOutput, + pub debit_routing_result: Option<open_router::DebitRoutingOutput>, } #[cfg(feature = "v1")] impl RoutingDecisionData { @@ -350,7 +350,7 @@ impl RoutingDecisionData { pub fn get_debit_routing_decision_data( network: common_enums::enums::CardNetwork, - debit_routing_result: open_router::DebitRoutingOutput, + debit_routing_result: Option<open_router::DebitRoutingOutput>, ) -> Self { Self::DebitRouting(DebitRoutingDecisionData { card_network: network, @@ -370,7 +370,9 @@ impl DebitRoutingDecisionData { + Clone, { payment_data.set_card_network(self.card_network.clone()); - payment_data.set_co_badged_card_data(&self.debit_routing_result); + self.debit_routing_result + .as_ref() + .map(|data| payment_data.set_co_badged_card_data(data)); } } #[derive(Clone, Debug)]
2025-06-03T09:48:41Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> In the case of debit routing flow, the routing output (`CallConnectorType`) will include both the connector and its associated card network. In our current implementation, we simply iterate over the connector list and pass the connector. With the updated requirement, we will also need to pass the corresponding card network for each connector in the case of debit routing. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Create a business profile and enable debit routing for it ``` curl --location 'http://localhost:8080/account/merchant_1748851578/business_profile/pro_gEwS6ve9KVqywWL0hmAq' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: ' \ --data '{ "is_debit_routing_enabled": true }' ``` -> Create a adyen connector -> I have created a db entry that contains the wrong card network so that the payment can be retried ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-feature: router-custom' \ --header 'x-tenant-id: hyperswitch' \ --header 'api-key: ' \ --data-raw '{ "amount": 10000, "amount_to_capture": 10000, "currency": "USD", "confirm": true, "capture_method": "automatic", "setup_future_usage": "on_session", "capture_on": "2022-09-10T10:11:12Z", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "customer_id": "cu_1748948839", "return_url": "http://127.0.0.1:4040", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4000033003300335", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "737" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX", "last_name": "ss" }, "email": "[email protected]" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ``` { "payment_id": "pay_JMfKcXwsfYNl06UWsCc0", "merchant_id": "merchant_1748851578", "status": "succeeded", "amount": 10000, "net_amount": 10000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 10000, "connector": "adyen", "client_secret": "pay_JMfKcXwsfYNl06UWsCc0_secret_IHW3HhesmOpMBaUyGd8l", "created": "2025-06-03T11:07:12.121Z", "currency": "USD", "customer_id": "cu_1748948832", "customer": { "id": "cu_1748948832", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0335", "card_type": "DEBIT", "card_network": "Visa", "card_issuer": "VISA U.S.A. INC.", "card_issuing_country": "UNITEDSTATES", "card_isin": "400003", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": "ss" }, "phone": null, "email": "[email protected]" }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "http://127.0.0.1:4040/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1748948832", "created_at": 1748948832, "expires": 1748952432, "secret": "epk_caf2195bee8848358df1077b25cf2a73" }, "manual_retry_allowed": false, "connector_transaction_id": "DF4NDC3W8WH68775", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_JMfKcXwsfYNl06UWsCc0_2", "payment_link": null, "profile_id": "pro_gEwS6ve9KVqywWL0hmAq", "surcharge_details": null, "attempt_count": 2, "merchant_decision": null, "merchant_connector_id": "mca_zMyPaKk9qUVauLL7wFrV", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-06-03T11:22:12.120Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "125.0.0.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-06-03T11:07:15.083Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` -> the payment response contains two attempts -> List all the attempts for a payments ``` curl --location 'http://localhost:8080/payments/pay_JMfKcXwsfYNl06UWsCc0?force_sync=true&expand_attempts=true' \ --header 'Accept: application/json' \ --header 'api-key: ' ``` ``` { "payment_id": "pay_JMfKcXwsfYNl06UWsCc0", "merchant_id": "merchant_1748851578", "status": "succeeded", "amount": 10000, "net_amount": 10000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 10000, "connector": "adyen", "client_secret": "pay_JMfKcXwsfYNl06UWsCc0_secret_IHW3HhesmOpMBaUyGd8l", "created": "2025-06-03T11:07:12.121Z", "currency": "USD", "customer_id": "cu_1748948832", "customer": { "id": "cu_1748948832", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "attempts": [ { "attempt_id": "pay_JMfKcXwsfYNl06UWsCc0_2", "status": "charged", "amount": 10000, "order_tax_amount": null, "currency": "USD", "connector": "adyen", "error_message": null, "payment_method": "card", "connector_transaction_id": "DF4NDC3W8WH68775", "capture_method": "automatic", "authentication_type": "no_three_ds", "created_at": "2025-06-03T11:07:14.071Z", "modified_at": "2025-06-03T11:07:15.143Z", "cancellation_reason": null, "mandate_id": null, "error_code": null, "payment_token": null, "connector_metadata": null, "payment_experience": null, "payment_method_type": "debit", "reference_id": "pay_JMfKcXwsfYNl06UWsCc0_2", "unified_code": null, "unified_message": null, "client_source": null, "client_version": null }, { "attempt_id": "pay_JMfKcXwsfYNl06UWsCc0_1", "status": "failure", "amount": 10000, "order_tax_amount": null, "currency": "USD", "connector": "adyen", "error_message": "Invalid variant", "payment_method": "card", "connector_transaction_id": "ZBRJ4V4RGLQD2HV5", "capture_method": "automatic", "authentication_type": "no_three_ds", "created_at": "2025-06-03T11:07:12.121Z", "modified_at": "2025-06-03T11:07:14.075Z", "cancellation_reason": null, "mandate_id": null, "error_code": "109", "payment_token": null, "connector_metadata": null, "payment_experience": null, "payment_method_type": "debit", "reference_id": null, "unified_code": null, "unified_message": null, "client_source": null, "client_version": null } ], "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0335", "card_type": "DEBIT", "card_network": "Visa", "card_issuer": "VISA U.S.A. INC.", "card_issuing_country": "UNITEDSTATES", "card_isin": "400003", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": "ss" }, "phone": null, "email": "[email protected]" }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "http://127.0.0.1:4040/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "DF4NDC3W8WH68775", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_JMfKcXwsfYNl06UWsCc0_2", "payment_link": null, "profile_id": "pro_gEwS6ve9KVqywWL0hmAq", "surcharge_details": null, "attempt_count": 2, "merchant_decision": null, "merchant_connector_id": "mca_zMyPaKk9qUVauLL7wFrV", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-06-03T11:22:12.120Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "125.0.0.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": "pm_d6OTFivsWBpZpC9u53Hh", "payment_method_status": "active", "updated": "2025-06-03T11:07:15.083Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` -> The payment was first tried with `star` card network and then with the `visa` ![image](https://github.com/user-attachments/assets/9167038f-b03b-411a-8d13-a52b14c9685e) ![image](https://github.com/user-attachments/assets/7f1f1120-b3ff-4556-9140-248f922b279b) ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
e6482fbe84e2e7bcbcafa7ab95c8ab573bc4bed7
e6482fbe84e2e7bcbcafa7ab95c8ab573bc4bed7
juspay/hyperswitch
juspay__hyperswitch-8200
Bug: [FEATURE] Introduce routing in V2 - Implement rule based profile level activation , straight through routing and default fallback in V2 apis.
diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index d200d352fa4..ae2710c50e9 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -346,6 +346,7 @@ pub struct PaymentIntentNew { pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, pub processor_merchant_id: Option<common_utils::id_type::MerchantId>, + pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub created_by: Option<String>, pub is_iframe_redirection_enabled: Option<bool>, } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 44b75e6e647..5b1201027b7 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -1344,6 +1344,8 @@ diesel::table! { created_at -> Timestamp, modified_at -> Timestamp, algorithm_for -> TransactionType, + #[max_length = 64] + decision_engine_routing_id -> Nullable<Varchar>, } } diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs index 8e5de204fba..992bd58784f 100644 --- a/crates/hyperswitch_domain_models/src/business_profile.rs +++ b/crates/hyperswitch_domain_models/src/business_profile.rs @@ -1892,20 +1892,19 @@ impl super::behaviour::Conversion for Profile { authentication_product_ids: item.authentication_product_ids, three_ds_decision_manager_config: item.three_ds_decision_manager_config, card_testing_guard_config: item.card_testing_guard_config, - card_testing_secret_key: item - .card_testing_secret_key - .async_lift(|inner| async { - crypto_operation( - state, - type_name!(Self::DstType), - CryptoOperation::DecryptOptional(inner), - key_manager_identifier.clone(), - key.peek(), - ) - .await - .and_then(|val| val.try_into_optionaloperation()) - }) - .await?, + card_testing_secret_key: match item.card_testing_secret_key { + Some(encrypted_value) => crypto_operation( + state, + type_name!(Self::DstType), + CryptoOperation::DecryptOptional(Some(encrypted_value)), + key_manager_identifier.clone(), + key.peek(), + ) + .await + .and_then(|val| val.try_into_optionaloperation()) + .unwrap_or_default(), + None => None, + }, is_clear_pan_retries_enabled: item.is_clear_pan_retries_enabled, is_debit_routing_enabled: item.is_debit_routing_enabled, merchant_business_country: item.merchant_business_country, diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 0abc626bd19..2240df7241f 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -1,3 +1,6 @@ +#[cfg(feature = "v2")] +use std::str::FromStr; + use api_models::{ mandates, payment_methods::{self}, @@ -1904,6 +1907,7 @@ pub enum PaymentMethodsData { } impl PaymentMethodsData { + #[cfg(feature = "v1")] pub fn get_co_badged_card_data(&self) -> Option<payment_methods::CoBadgedCardData> { if let Self::Card(card) = self { card.co_badged_card_data.clone() @@ -1911,6 +1915,10 @@ impl PaymentMethodsData { None } } + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] + pub fn get_co_badged_card_data(&self) -> Option<payment_methods::CoBadgedCardData> { + todo!() + } } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] @@ -1933,6 +1941,10 @@ fn saved_in_locker_default() -> bool { true } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "payment_methods_v2") +))] #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct CardDetailsPaymentMethod { pub last4_digits: Option<String>, @@ -1950,6 +1962,54 @@ pub struct CardDetailsPaymentMethod { pub co_badged_card_data: Option<payment_methods::CoBadgedCardData>, } +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +pub struct CardDetailsPaymentMethod { + pub last4_digits: Option<String>, + pub issuer_country: Option<String>, + pub expiry_month: Option<Secret<String>>, + pub expiry_year: Option<Secret<String>>, + pub nick_name: Option<Secret<String>>, + pub card_holder_name: Option<Secret<String>>, + pub card_isin: Option<String>, + pub card_issuer: Option<String>, + pub card_network: Option<api_enums::CardNetwork>, + pub card_type: Option<String>, + #[serde(default = "saved_in_locker_default")] + pub saved_to_locker: bool, +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +impl CardDetailsPaymentMethod { + pub fn to_card_details_from_locker(self) -> payment_methods::CardDetailFromLocker { + payment_methods::CardDetailFromLocker { + card_number: None, + card_holder_name: self.card_holder_name.clone(), + card_issuer: self.card_issuer.clone(), + card_network: self.card_network.clone(), + card_type: self.card_type.clone(), + issuer_country: self.clone().get_issuer_country_alpha2(), + last4_digits: self.last4_digits, + expiry_month: self.expiry_month, + expiry_year: self.expiry_year, + card_fingerprint: None, + nick_name: self.nick_name, + card_isin: self.card_isin, + saved_to_locker: self.saved_to_locker, + } + } + + pub fn get_issuer_country_alpha2(self) -> Option<common_enums::CountryAlpha2> { + self.issuer_country + .as_ref() + .map(|c| api_enums::CountryAlpha2::from_str(c)) + .transpose() + .ok() + .flatten() + } +} + +#[cfg(feature = "v1")] impl From<payment_methods::CardDetail> for CardDetailsPaymentMethod { fn from(item: payment_methods::CardDetail) -> Self { Self { @@ -1969,6 +2029,25 @@ impl From<payment_methods::CardDetail> for CardDetailsPaymentMethod { } } +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +impl From<payment_methods::CardDetail> for CardDetailsPaymentMethod { + fn from(item: payment_methods::CardDetail) -> Self { + Self { + issuer_country: item.card_issuing_country.map(|c| c.to_string()), + last4_digits: Some(item.card_number.get_last4()), + expiry_month: Some(item.card_exp_month), + expiry_year: Some(item.card_exp_year), + card_holder_name: item.card_holder_name, + nick_name: item.nick_name, + card_isin: None, + card_issuer: item.card_issuer, + card_network: item.card_network, + card_type: item.card_type.map(|card| card.to_string()), + saved_to_locker: true, + } + } +} + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl From<NetworkTokenDetails> for NetworkTokenDetailsPaymentMethod { fn from(item: NetworkTokenDetails) -> Self { diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index 8df0ff705e7..c08a8130266 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -1936,6 +1936,7 @@ impl behaviour::Conversion for PaymentIntent { processor_merchant_id: Some(self.processor_merchant_id), created_by: self.created_by.map(|cb| cb.to_string()), is_iframe_redirection_enabled: self.is_iframe_redirection_enabled, + routing_algorithm_id: self.routing_algorithm_id, }) } } diff --git a/crates/hyperswitch_domain_models/src/routing.rs b/crates/hyperswitch_domain_models/src/routing.rs index 4a802250630..baa2d45ab4e 100644 --- a/crates/hyperswitch_domain_models/src/routing.rs +++ b/crates/hyperswitch_domain_models/src/routing.rs @@ -1,18 +1,32 @@ use std::collections::HashMap; use api_models::{enums as api_enums, routing}; +use common_utils::id_type; use serde; +#[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct RoutingData { pub routed_through: Option<String>, - pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, + pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub routing_info: PaymentRoutingInfo, pub algorithm: Option<routing::StraightThroughAlgorithm>, } +#[cfg(feature = "v2")] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct RoutingData { + // TODO: change this to RoutableConnectors enum + pub routed_through: Option<String>, + pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, + + pub pre_routing_connector_choice: Option<PreRoutingConnectorChoice>, + + pub algorithm_requested: Option<id_type::RoutingId>, +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)] #[serde(from = "PaymentRoutingInfoSerde", into = "PaymentRoutingInfoSerde")] pub struct PaymentRoutingInfo { diff --git a/crates/payment_methods/Cargo.toml b/crates/payment_methods/Cargo.toml index 26572c9e32f..73f3fe8ef96 100644 --- a/crates/payment_methods/Cargo.toml +++ b/crates/payment_methods/Cargo.toml @@ -35,7 +35,7 @@ workspace = true [features] customer_v2 = ["api_models/customer_v2", "hyperswitch_domain_models/customer_v2", "storage_impl/customer_v2"] -default = ["dummy_connector", "payouts", "v1"] +default = ["dummy_connector", "payouts"] v1 = ["hyperswitch_domain_models/v1", "storage_impl/v1", "common_utils/v1", "scheduler/v1", "common_types/v1"] v2 = ["customer_v2", "payment_methods_v2", "common_utils/v2", "scheduler/v2", "common_types/v2"] payment_methods_v2 = [ "hyperswitch_domain_models/payment_methods_v2", "storage_impl/payment_methods_v2", "common_utils/payment_methods_v2"] diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 7e13dbbed16..96ac030f57f 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -1889,7 +1889,8 @@ pub async fn vault_payment_method_external( let connector_name = merchant_connector_account .get_connector_name() - .unwrap_or_default(); // always get the connector name from this call + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Connector name not present for external vault")?; // always get the connector name from this call let connector_data = api::ConnectorData::get_external_vault_connector_by_name( &state.conf.connectors, diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index c545bcac503..911b4ece00e 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -1409,7 +1409,8 @@ pub async fn retrieve_payment_method_from_vault_external( let connector_name = merchant_connector_account .get_connector_name() - .unwrap_or_default(); // always get the connector name from this call + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Connector name not present for external vault")?; // always get the connector name from this call let connector_data = api::ConnectorData::get_external_vault_connector_by_name( &state.conf.connectors, @@ -1569,7 +1570,8 @@ pub async fn delete_payment_method_data_from_vault_external( let connector_name = merchant_connector_account .get_connector_name() - .unwrap_or_default(); // always get the connector name from this call + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Connector name not present for external vault")?; // always get the connector name from this call let connector_data = api::ConnectorData::get_external_vault_connector_by_name( &state.conf.connectors, diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 0993a6eee3f..38a53d9b2d1 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -241,7 +241,55 @@ where ) .await? } - ConnectorCallType::Retryable(vec) => todo!(), + ConnectorCallType::Retryable(connectors) => { + let mut connectors = connectors.clone().into_iter(); + let connector_data = get_connector_data(&mut connectors)?; + let router_data = call_connector_service( + state, + req_state.clone(), + &merchant_context, + connector_data.connector_data.clone(), + &operation, + &mut payment_data, + &customer, + call_connector_action.clone(), + None, + header_payload.clone(), + #[cfg(feature = "frm")] + None, + #[cfg(not(feature = "frm"))] + None, + profile, + false, + false, //should_retry_with_pan is set to false in case of PreDetermined ConnectorCallType + req.get_all_keys_required(), + ) + .await?; + + let payments_response_operation = Box::new(PaymentResponse); + + payments_response_operation + .to_post_update_tracker()? + .save_pm_and_mandate( + state, + &router_data, + &merchant_context, + &mut payment_data, + profile, + ) + .await?; + + payments_response_operation + .to_post_update_tracker()? + .update_tracker( + state, + payment_data, + router_data, + merchant_context.get_merchant_key_store(), + merchant_context.get_merchant_account().storage_scheme, + ) + .await? + } ConnectorCallType::SessionMultiple(vec) => todo!(), ConnectorCallType::Skip => payment_data, }; @@ -6574,23 +6622,167 @@ where Ok(decided_connector) } -#[allow(clippy::too_many_arguments)] #[cfg(feature = "v2")] -pub async fn decide_connector<F, D>( - state: SessionState, +#[allow(clippy::too_many_arguments)] +pub async fn connector_selection<F, D>( + state: &SessionState, merchant_context: &domain::MerchantContext, business_profile: &domain::Profile, payment_data: &mut D, - request_straight_through: Option<api::routing::StraightThroughAlgorithm>, - routing_data: &mut storage::RoutingData, - eligible_connectors: Option<Vec<enums::RoutableConnectors>>, mandate_type: Option<api::MandateTransactionType>, ) -> RouterResult<ConnectorCallType> where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { - todo!() + let mut routing_data = storage::RoutingData { + routed_through: payment_data.get_payment_attempt().connector.clone(), + + merchant_connector_id: payment_data + .get_payment_attempt() + .merchant_connector_id + .clone(), + pre_routing_connector_choice: payment_data.get_pre_routing_result().and_then( + |pre_routing_results| { + pre_routing_results + .get(&payment_data.get_payment_attempt().payment_method_subtype) + .cloned() + }, + ), + + algorithm_requested: payment_data + .get_payment_intent() + .routing_algorithm_id + .clone(), + }; + + let payment_dsl_input = core_routing::PaymentsDslInput::new( + None, + payment_data.get_payment_attempt(), + payment_data.get_payment_intent(), + payment_data.get_payment_method_data(), + payment_data.get_address(), + None, + payment_data.get_currency(), + ); + + let decided_connector = decide_connector( + state.clone(), + merchant_context, + business_profile, + &mut routing_data, + payment_dsl_input, + mandate_type, + ) + .await?; + + payment_data.set_connector_in_payment_attempt(routing_data.routed_through); + + payment_data.set_merchant_connector_id_in_attempt(routing_data.merchant_connector_id); + + Ok(decided_connector) +} + +#[allow(clippy::too_many_arguments)] +#[cfg(feature = "v2")] +pub async fn decide_connector( + state: SessionState, + merchant_context: &domain::MerchantContext, + business_profile: &domain::Profile, + routing_data: &mut storage::RoutingData, + payment_dsl_input: core_routing::PaymentsDslInput<'_>, + mandate_type: Option<api::MandateTransactionType>, +) -> RouterResult<ConnectorCallType> { + // If the connector was already decided previously, use the same connector + // This is in case of flows like payments_sync, payments_cancel where the successive operations + // with the connector have to be made using the same connector account. + + let predetermined_info_cloned = routing_data + .routed_through + .as_ref() + .zip(routing_data.merchant_connector_id.as_ref()) + .map(|(cn_ref, mci_ref)| (cn_ref.clone(), mci_ref.clone())); + + match ( + predetermined_info_cloned, + routing_data.pre_routing_connector_choice.as_ref(), + ) { + // Condition 1: Connector was already decided previously + (Some((owned_connector_name, owned_merchant_connector_id)), _) => { + api::ConnectorData::get_connector_by_name( + &state.conf.connectors, + &owned_connector_name, + api::GetToken::Connector, + Some(owned_merchant_connector_id.clone()), + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Invalid connector name received in 'routed_through'") + .map(|connector_data| { + routing_data.routed_through = Some(owned_connector_name); + ConnectorCallType::PreDetermined(connector_data.into()) + }) + } + // Condition 2: Pre-routing connector choice + (None, Some(routable_connector_choice)) => { + let routable_connector_list = match routable_connector_choice { + storage::PreRoutingConnectorChoice::Single(routable_connector) => { + vec![routable_connector.clone()] + } + storage::PreRoutingConnectorChoice::Multiple(routable_connector_list) => { + routable_connector_list.clone() + } + }; + + routable_connector_list + .first() + .ok_or_else(|| { + report!(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) + .attach_printable("No first routable connector in pre_routing_connector_choice") + }) + .and_then(|first_routable_connector| { + routing_data.routed_through = Some(first_routable_connector.connector.to_string()); + routing_data + .merchant_connector_id + .clone_from(&first_routable_connector.merchant_connector_id); + + let pre_routing_connector_data_list_result: RouterResult<Vec<api::ConnectorData>> = routable_connector_list + .iter() + .map(|connector_choice| { + api::ConnectorData::get_connector_by_name( + &state.conf.connectors, + &connector_choice.connector.to_string(), + api::GetToken::Connector, + connector_choice.merchant_connector_id.clone(), + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Invalid connector name received while processing pre_routing_connector_choice") + }) + .collect::<Result<Vec<_>, _>>(); // Collects into RouterResult<Vec<ConnectorData>> + + pre_routing_connector_data_list_result + .and_then(|list| { + list.first() + .cloned() + .ok_or_else(|| { + report!(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) + .attach_printable("Empty pre_routing_connector_data_list after mapping") + }) + .map(|first_data| ConnectorCallType::PreDetermined(first_data.into())) + }) + }) + } + (None, None) => { + route_connector_v2_for_payments( + &state, + merchant_context, + business_profile, + payment_dsl_input, + routing_data, + mandate_type, + ) + .await + } + } } #[allow(clippy::too_many_arguments)] @@ -6837,21 +7029,6 @@ where .await } -#[cfg(feature = "v2")] -pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone, D>( - state: &SessionState, - payment_data: &mut D, - routing_data: &mut storage::RoutingData, - connectors: Vec<api::ConnectorData>, - mandate_type: Option<api::MandateTransactionType>, - is_connector_agnostic_mit_enabled: Option<bool>, -) -> RouterResult<ConnectorCallType> -where - D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, -{ - todo!() -} - #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone, D>( @@ -7005,7 +7182,6 @@ where Err(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration.into()) } } - _ => { helpers::override_setup_future_usage_to_on_session(&*state.store, payment_data).await?; @@ -7025,22 +7201,6 @@ where } } -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -#[allow(clippy::too_many_arguments)] -pub async fn decide_connector_for_normal_or_recurring_payment<F: Clone, D>( - state: &SessionState, - payment_data: &mut D, - routing_data: &mut storage::RoutingData, - connectors: Vec<api::ConnectorData>, - is_connector_agnostic_mit_enabled: Option<bool>, - payment_method_info: &domain::PaymentMethod, -) -> RouterResult<ConnectorCallType> -where - D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, -{ - todo!() -} - #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") @@ -7400,6 +7560,60 @@ where }) } +#[cfg(feature = "v2")] +#[allow(clippy::too_many_arguments)] +pub async fn route_connector_v2_for_payments( + state: &SessionState, + merchant_context: &domain::MerchantContext, + business_profile: &domain::Profile, + transaction_data: core_routing::PaymentsDslInput<'_>, + routing_data: &mut storage::RoutingData, + _mandate_type: Option<api::MandateTransactionType>, +) -> RouterResult<ConnectorCallType> { + let routing_algorithm_id = routing_data + .algorithm_requested + .as_ref() + .or(business_profile.routing_algorithm_id.as_ref()); + + let connectors = routing::perform_static_routing_v1( + state, + merchant_context.get_merchant_account().get_id(), + routing_algorithm_id, + business_profile, + &TransactionData::Payment(transaction_data.clone()), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?; + + let connectors = routing::perform_eligibility_analysis_with_fallback( + &state.clone(), + merchant_context.get_merchant_key_store(), + connectors, + &TransactionData::Payment(transaction_data), + None, + business_profile, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed eligibility analysis and fallback")?; + + connectors + .first() + .map(|conn| { + routing_data.routed_through = Some(conn.connector.to_string()); + routing_data.merchant_connector_id = conn.merchant_connector_id.clone(); + api::ConnectorData::get_connector_by_name( + &state.conf.connectors, + &conn.connector.to_string(), + api::GetToken::Connector, + conn.merchant_connector_id.clone(), + ) + }) + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Invalid connector name received")? + .map(|connector_data| ConnectorCallType::PreDetermined(connector_data.into())) +} + #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn route_connector_v1_for_payments<F, D>( @@ -8259,6 +8473,11 @@ pub trait OperationSessionGetters<F> { #[cfg(feature = "v2")] fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt>; + + #[cfg(feature = "v2")] + fn get_pre_routing_result( + &self, + ) -> Option<HashMap<enums::PaymentMethodType, domain::PreRoutingConnectorChoice>>; } pub trait OperationSessionSetters<F> { @@ -8307,6 +8526,13 @@ pub trait OperationSessionSetters<F> { &mut self, straight_through_algorithm: serde_json::Value, ); + + #[cfg(feature = "v2")] + fn set_prerouting_algorithm_in_payment_intent( + &mut self, + straight_through_algorithm: storage::PaymentRoutingInfo, + ); + fn set_connector_in_payment_attempt(&mut self, connector: Option<String>); #[cfg(feature = "v1")] @@ -8758,10 +8984,22 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentIntentData<F> { fn get_whole_connector_response(&self) -> Option<String> { todo!(); } + + fn get_pre_routing_result( + &self, + ) -> Option<HashMap<enums::PaymentMethodType, domain::PreRoutingConnectorChoice>> { + None + } } #[cfg(feature = "v2")] impl<F: Clone> OperationSessionSetters<F> for PaymentIntentData<F> { + fn set_prerouting_algorithm_in_payment_intent( + &mut self, + straight_through_algorithm: storage::PaymentRoutingInfo, + ) { + self.payment_intent.prerouting_algorithm = Some(straight_through_algorithm); + } // Setters Implementation fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { self.payment_intent = payment_intent; @@ -9001,10 +9239,26 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentConfirmData<F> { fn get_whole_connector_response(&self) -> Option<String> { todo!() } + + fn get_pre_routing_result( + &self, + ) -> Option<HashMap<enums::PaymentMethodType, domain::PreRoutingConnectorChoice>> { + self.get_payment_intent() + .prerouting_algorithm + .clone() + .and_then(|pre_routing_algorithm| pre_routing_algorithm.pre_routing_results) + } } #[cfg(feature = "v2")] impl<F: Clone> OperationSessionSetters<F> for PaymentConfirmData<F> { + #[cfg(feature = "v2")] + fn set_prerouting_algorithm_in_payment_intent( + &mut self, + straight_through_algorithm: storage::PaymentRoutingInfo, + ) { + self.payment_intent.prerouting_algorithm = Some(straight_through_algorithm); + } // Setters Implementation fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { self.payment_intent = payment_intent; @@ -9245,10 +9499,23 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentStatusData<F> { fn get_whole_connector_response(&self) -> Option<String> { todo!() } + + fn get_pre_routing_result( + &self, + ) -> Option<HashMap<enums::PaymentMethodType, domain::PreRoutingConnectorChoice>> { + None + } } #[cfg(feature = "v2")] impl<F: Clone> OperationSessionSetters<F> for PaymentStatusData<F> { + #[cfg(feature = "v2")] + fn set_prerouting_algorithm_in_payment_intent( + &mut self, + straight_through_algorithm: storage::PaymentRoutingInfo, + ) { + self.payment_intent.prerouting_algorithm = Some(straight_through_algorithm); + } fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { self.payment_intent = payment_intent; } @@ -9490,10 +9757,22 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentCaptureData<F> { fn get_whole_connector_response(&self) -> Option<String> { todo!(); } + fn get_pre_routing_result( + &self, + ) -> Option<HashMap<enums::PaymentMethodType, domain::PreRoutingConnectorChoice>> { + None + } } #[cfg(feature = "v2")] impl<F: Clone> OperationSessionSetters<F> for PaymentCaptureData<F> { + #[cfg(feature = "v2")] + fn set_prerouting_algorithm_in_payment_intent( + &mut self, + straight_through_algorithm: storage::PaymentRoutingInfo, + ) { + self.payment_intent.prerouting_algorithm = Some(straight_through_algorithm); + } fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) { self.payment_intent = payment_intent; } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 220a48cd1e1..a166c54139d 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -3949,6 +3949,7 @@ impl MerchantConnectorAccountType { } } + #[cfg(feature = "v1")] pub fn get_connector_name(&self) -> Option<String> { match self { Self::DbVal(db_val) => Some(db_val.connector_name.to_string()), @@ -3956,6 +3957,14 @@ impl MerchantConnectorAccountType { } } + #[cfg(feature = "v2")] + pub fn get_connector_name(&self) -> Option<api_enums::Connector> { + match self { + Self::DbVal(db_val) => Some(db_val.connector_name), + Self::CacheVal(_) => None, + } + } + pub fn get_additional_merchant_data( &self, ) -> Option<Encryptable<masking::Secret<serde_json::Value>>> { @@ -5289,12 +5298,6 @@ where .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get merchant default fallback connectors config")?; - #[cfg(feature = "v2")] - let fallback_connetors_list = core_admin::ProfileWrapper::new(business_profile) - .get_default_fallback_list_of_connector_under_profile() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to get merchant default fallback connectors config")?; - let mut routing_connector_data_list = Vec::new(); pre_routing_connector_data_list.iter().for_each(|pre_val| { @@ -6876,6 +6879,34 @@ where Ok(()) } +pub async fn validate_routing_id_with_profile_id( + db: &dyn StorageInterface, + routing_id: &id_type::RoutingId, + profile_id: &id_type::ProfileId, +) -> CustomResult<(), errors::ApiErrorResponse> { + let _routing_id = db + .find_routing_algorithm_metadata_by_algorithm_id_profile_id(routing_id, profile_id) + .await + .map_err(|err| { + if err.current_context().is_db_not_found() { + logger::warn!( + "Routing id not found for routing id - {:?} and profile id - {:?}", + routing_id, + profile_id + ); + err.change_context(errors::ApiErrorResponse::InvalidDataFormat { + field_name: "routing_algorithm_id".to_string(), + expected_format: "A valid routing_id that belongs to the business_profile" + .to_string(), + }) + } else { + err.change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to validate routing id") + } + })?; + Ok(()) +} + #[cfg(feature = "v1")] pub async fn validate_merchant_connector_ids_in_connector_mandate_details( state: &SessionState, diff --git a/crates/router/src/core/payments/operations/payment_confirm_intent.rs b/crates/router/src/core/payments/operations/payment_confirm_intent.rs index 2074b28fd00..7084fc14bb8 100644 --- a/crates/router/src/core/payments/operations/payment_confirm_intent.rs +++ b/crates/router/src/core/payments/operations/payment_confirm_intent.rs @@ -338,34 +338,14 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsConfirmIntentRequest, PaymentConf // TODO: do not take the whole payment data here payment_data: &mut PaymentConfirmData<F>, ) -> CustomResult<ConnectorCallType, errors::ApiErrorResponse> { - use crate::core::payments::OperationSessionSetters; - - let fallback_config = admin::ProfileWrapper::new(business_profile.clone()) - .get_default_fallback_list_of_connector_under_profile() - .change_context(errors::RoutingError::FallbackConfigFetchFailed) - .change_context(errors::ApiErrorResponse::InternalServerError)?; - - let first_chosen_connector = fallback_config - .first() - .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?; - - let connector_name = first_chosen_connector.connector.to_string(); - let merchant_connector_id = first_chosen_connector - .merchant_connector_id - .clone() - .get_required_value("merchant_connector_id")?; - - payment_data.set_connector_in_payment_attempt(Some(connector_name.to_string())); - payment_data.set_merchant_connector_id_in_attempt(Some(merchant_connector_id.clone())); - - let connector_data = api::ConnectorData::get_connector_by_name( - &state.conf.connectors, - &connector_name, - api::GetToken::Connector, - Some(merchant_connector_id), - )?; - - Ok(ConnectorCallType::PreDetermined(connector_data.into())) + payments::connector_selection( + state, + merchant_context, + business_profile, + payment_data, + None, + ) + .await } } diff --git a/crates/router/src/core/payments/operations/payment_create_intent.rs b/crates/router/src/core/payments/operations/payment_create_intent.rs index c5cb9cdba12..1cb95a2b92e 100644 --- a/crates/router/src/core/payments/operations/payment_create_intent.rs +++ b/crates/router/src/core/payments/operations/payment_create_intent.rs @@ -4,7 +4,7 @@ use api_models::{enums::FrmSuggestion, payments::PaymentsCreateIntentRequest}; use async_trait::async_trait; use common_utils::{ errors::CustomResult, - ext_traits::{AsyncExt, Encode, ValueExt}, + ext_traits::Encode, types::{authentication, keymanager::ToEncryptable}, }; use error_stack::ResultExt; @@ -15,10 +15,9 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, - payments::{self, cards::create_encrypted_data, helpers, operations}, + payments::{self, helpers, operations}, }, routes::{app::ReqState, SessionState}, - services, types::{ api, domain::{self, types as domain_types}, @@ -100,6 +99,14 @@ impl<F: Send + Clone + Sync> _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<operations::GetTrackerResponse<payments::PaymentIntentData<F>>> { let db = &*state.store; + if let Some(routing_algorithm_id) = request.routing_algorithm_id.as_ref() { + helpers::validate_routing_id_with_profile_id( + db, + routing_algorithm_id, + profile.get_id(), + ) + .await?; + } let key_manager_state = &state.into(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; diff --git a/crates/router/src/core/payments/operations/payment_update_intent.rs b/crates/router/src/core/payments/operations/payment_update_intent.rs index c605f9b3421..b791dab22c1 100644 --- a/crates/router/src/core/payments/operations/payment_update_intent.rs +++ b/crates/router/src/core/payments/operations/payment_update_intent.rs @@ -136,10 +136,18 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentIntentData<F>, PaymentsUpda payment_id: &common_utils::id_type::GlobalPaymentId, request: &PaymentsUpdateIntentRequest, merchant_context: &domain::MerchantContext, - _profile: &domain::Profile, + profile: &domain::Profile, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<operations::GetTrackerResponse<payments::PaymentIntentData<F>>> { let db = &*state.store; + if let Some(routing_algorithm_id) = request.routing_algorithm_id.as_ref() { + helpers::validate_routing_id_with_profile_id( + db, + routing_algorithm_id, + profile.get_id(), + ) + .await?; + } let key_manager_state = &state.into(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let payment_intent = db diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index a7d8fecfe87..df36f9f5117 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -703,7 +703,6 @@ pub fn make_new_payment_attempt( todo!() } -#[cfg(feature = "v1")] pub async fn get_merchant_config_for_gsm( db: &dyn StorageInterface, merchant_id: &common_utils::id_type::MerchantId, diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index c3c4050f1d5..712d092fc77 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -2044,7 +2044,8 @@ pub async fn construct_vault_router_data<F>( ) -> RouterResult<VaultRouterDataV2<F>> { let connector_name = merchant_connector_account .get_connector_name() - .unwrap_or_default(); // always get the connector name from the merchant_connector_account + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Connector name not present for external vault")?; // always get the connector name from the merchant_connector_account let connector_auth_type: types::ConnectorAuthType = merchant_connector_account .get_connector_account_details() .parse_value("ConnectorAuthType") diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 2df62a36e17..12930b680ee 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -2764,9 +2764,16 @@ pub async fn payment_confirm_intent( )) .await }, - &auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment( - global_payment_id, - )), + auth::api_or_client_auth( + &auth::V2ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: false, + }, + &auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment( + global_payment_id, + )), + req.headers(), + ), locking_action, )) .await diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index f41fa33bb2d..1e9a0d17320 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -301,20 +301,24 @@ impl ConnectorData { #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub fn get_external_vault_connector_by_name( _connectors: &Connectors, - name: &str, + connector: &api_enums::Connector, connector_type: GetToken, connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, ) -> CustomResult<Self, errors::ApiErrorResponse> { - let connector = Self::convert_connector(name)?; - let external_vault_connector_name = api_enums::VaultConnectors::from_str(name) - .change_context(errors::ConnectorError::InvalidConnectorName) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable_lazy(|| { - format!("unable to parse external vault connector name {name}") - })?; + let connector_enum = Self::convert_connector(&connector.to_string())?; + let external_vault_connector_name = + api_enums::VaultConnectors::from_str(&connector.to_string()) + .change_context(errors::ConnectorError::InvalidConnectorName) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable_lazy(|| { + format!( + "unable to parse external vault connector name {:?}", + connector + ) + })?; let connector_name = api_enums::Connector::from(external_vault_connector_name); Ok(Self { - connector, + connector: connector_enum, connector_name, get_token: connector_type, merchant_connector_id: connector_id, diff --git a/crates/router/src/types/domain.rs b/crates/router/src/types/domain.rs index 21ddf6079cf..1d1f0be637a 100644 --- a/crates/router/src/types/domain.rs +++ b/crates/router/src/types/domain.rs @@ -56,6 +56,10 @@ pub mod vault { pub use hyperswitch_domain_models::vault::*; } +mod routing { + pub use hyperswitch_domain_models::routing::*; +} + pub mod payments; pub mod types; #[cfg(feature = "olap")] @@ -73,6 +77,7 @@ pub use merchant_key_store::*; pub use network_tokenization::*; pub use payment_method_data::*; pub use payment_methods::*; +pub use routing::*; #[cfg(feature = "olap")] pub use user::*; pub use user_key_store::*; diff --git a/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql b/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql index 0e086500cc1..e912b9f9c53 100644 --- a/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql +++ b/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql @@ -129,6 +129,4 @@ ALTER TABLE refund DROP COLUMN IF EXISTS refund_id, DROP COLUMN IF EXISTS merchant_connector_id; --- Run below queries only when V1 is deprecated -ALTER TABLE routing_algorithm - DROP COLUMN IF EXISTS decision_engine_routing_id; +
2025-04-03T06:58:20Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Implemented rule based routing in payments v2. Straight through routing in v2 will be achieved by first configuring a straight through algorithm using `routing` endpoint and then passing the `routing_algorithm_id` field in payment create intent request. * Added validation for `routing_algorithm_id` in payment_inten_create and payment_intent_update. Three diff types of routing - Straight through - routing id sent in request - routing id activated in profile - Default fallback - in the order the MCA's are created. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Please use this log for checking the final list of connectors decided by routing module - `final_selected_connectors_for_routing` - Straight through routing - Create a routing algo entry, with rule and use that routing id in payment intent create create routing algorithm - <img width="1030" alt="Screenshot 2025-05-27 at 2 42 36 PM" src="https://github.com/user-attachments/assets/14786801-f860-4f0c-940c-14e3ff9d9c29" /> request - ``` curl --location 'http://localhost:8080/v2/routing-algorithm' \ --header 'Content-Type: application/json' \ --header 'Authorization: api-key=dev_Ku6SmaxCKhT5paf7bvG0QVtZq9skqpqkn2NznC6Ef5jWLD2aidCDeaby0i4DWThq' \ --header 'X-Profile-Id: pro_kQqIhnCrULOPt4tmuP5v' \ --header 'api-key: dev_Ku6SmaxCKhT5paf7bvG0QVtZq9skqpqkn2NznC6Ef5jWLD2aidCDeaby0i4DWThq' \ --data '{ "name": "newalgo", "description": "It is my ADVANCED config", "algorithm": { "type": "advanced", "data": { "defaultSelection": { "type": "priority", "data": [ {"connector": "bluesnap", "merchant_connector_id":"mca_xMJUJRcvk333cIPrJtdZ"} ] }, "rules": [ { "name": "bluesnap", "connectorSelection": { "type": "priority", "data": [ { "connector": "bluesnap", "merchant_connector_id":"mca_xMJUJRcvk333cIPrJtdZ"}, {"connector": "adyen", "merchant_connector_id":"mca_IpsaFXCRJa2TNYWuVkNx"}, { "connector": "stripe", "merchant_connector_id":"mca_DfyZDqHCZErTASCW170f" } ] }, "statements": [ { "condition": [ { "lhs": "amount", "comparison": "greater_than", "value": { "type": "number", "value": 100077 }, "metadata": {} } ], "nested": null } ] } ], "metadata": {} } }, "profile_id":"pro_kQqIhnCrULOPt4tmuP5v" }' ``` Response - ``` { "id": "routing_bFY4UYfNYLR0pQozeoPX", "profile_id": "pro_kQqIhnCrULOPt4tmuP5v", "name": "newalgo", "kind": "advanced", "description": "It is my ADVANCED config", "created_at": 1748843132, "modified_at": 1748843132, "algorithm_for": "payment", "decision_engine_routing_id": null } ``` Payment intent create - ``` curl --location 'http://localhost:8080/v2/payments/create-intent' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_kQqIhnCrULOPt4tmuP5v' \ --header 'Authorization: api-key=dev_Ku6SmaxCKhT5paf7bvG0QVtZq9skqpqkn2NznC6Ef5jWLD2aidCDeaby0i4DWThq' \ --header 'api-key: dev_Ku6SmaxCKhT5paf7bvG0QVtZq9skqpqkn2NznC6Ef5jWLD2aidCDeaby0i4DWThq' \ --data-raw '{ "amount_details": { "order_amount": 100, "currency": "USD" }, "capture_method":"manual", "authentication_type": "no_three_ds", "billing": { "address": { "first_name": "John", "last_name": "Dough" }, "email": "[email protected]" }, "shipping": { "address": { "first_name": "John", "last_name": "Dough", "city": "Karwar", "zip": "581301", "state": "Karnataka" }, "email": "[email protected]" }, "routing_algorithm_id":"routing_bFY4UYfNYLR0pQozeoPX" }' ``` Confirm intent - ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_01972f2d4b007c119e0373142eac05d3/confirm-intent' \ --header 'x-client-secret: cs_01972f2d4b1a7fa091ec990921d3bea7' \ --header 'x-profile-id: pro_kQqIhnCrULOPt4tmuP5v' \ --header 'Authorization: api-key=dev_Ku6SmaxCKhT5paf7bvG0QVtZq9skqpqkn2NznC6Ef5jWLD2aidCDeaby0i4DWThq' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_47a62e65c5124ddab58d82c3bb4d0072' \ --data-raw '{ "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "01", "card_exp_year": "25", "card_holder_name": "John Doe", "card_cvc": "100" }, "billing": { "address": { "first_name": "John", "last_name": "Dough" }, "email": "[email protected]" } }, "payment_method_type": "card", "payment_method_subtype": "credit", "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" } }' ``` final list of connectors decided by routing module <img width="1361" alt="Screenshot 2025-06-02 at 11 17 12 AM" src="https://github.com/user-attachments/assets/53b8c78d-ebe6-496f-ba6f-65be7bdccfd0" /> payment happened with Bluesnap **Rule based routing activation at profile level -** Creating new routing algo , with adyen as priority. <img width="986" alt="Screenshot 2025-06-02 at 11 20 29 AM" src="https://github.com/user-attachments/assets/93361a49-b17f-46c1-9bc0-158ed63a0fb8" /> Activate the routing algorithm id req - ``` curl --location --request PATCH 'http://localhost:8080/v2/profiles/pro_kQqIhnCrULOPt4tmuP5v/activate-routing-algorithm' \ --header 'Content-Type: application/json' \ --header 'Authorization: api-key=dev_Ku6SmaxCKhT5paf7bvG0QVtZq9skqpqkn2NznC6Ef5jWLD2aidCDeaby0i4DWThq' \ --header 'X-Profile-Id: pro_kQqIhnCrULOPt4tmuP5v' \ --header 'api-key: dev_Ku6SmaxCKhT5paf7bvG0QVtZq9skqpqkn2NznC6Ef5jWLD2aidCDeaby0i4DWThq' \ --data '{ "routing_algorithm_id": "routing_VdGQBkci7Wt5eoFRMJ6L" }' ``` response - ``` { "id": "routing_VdGQBkci7Wt5eoFRMJ6L", "profile_id": "pro_kQqIhnCrULOPt4tmuP5v", "name": "newalgo", "kind": "advanced", "description": "It is my ADVANCED config", "created_at": 1748843407, "modified_at": 1748843407, "algorithm_for": "payment", "decision_engine_routing_id": null } ``` verify from profile entry, the routing algo id will be populated <img width="1540" alt="Screenshot 2025-06-02 at 11 22 11 AM" src="https://github.com/user-attachments/assets/21ec88db-6b48-45c1-b062-93b93be5d2f2" /> Create intent without passing routing id at all in the request <img width="1103" alt="Screenshot 2025-06-02 at 11 23 47 AM" src="https://github.com/user-attachments/assets/80d7bdf2-623b-4e29-b4c1-c57981f1e6d2" /> Final list of connectors - <img width="1558" alt="Screenshot 2025-06-02 at 11 24 27 AM" src="https://github.com/user-attachments/assets/f259e9e5-b40d-4c02-b78f-8798329d31fa" /> Confirm intent <img width="1182" alt="Screenshot 2025-06-02 at 11 24 10 AM" src="https://github.com/user-attachments/assets/577bbf47-ae94-4d7e-88ac-60aad4fb764b" /> **Default Fallback -** Verify in profile <img width="1728" alt="Screenshot 2025-06-02 at 11 10 08 AM" src="https://github.com/user-attachments/assets/3d154892-c583-4c55-ae82-c3048c7debcc" /> <img width="1411" alt="Screenshot 2025-06-02 at 11 11 19 AM" src="https://github.com/user-attachments/assets/c4405bfb-f066-45dd-af07-6ab88f786492" /> Payment Intent create - ``` curl --location 'http://localhost:8080/v2/payments/create-intent' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_kQqIhnCrULOPt4tmuP5v' \ --header 'Authorization: api-key=dev_Ku6SmaxCKhT5paf7bvG0QVtZq9skqpqkn2NznC6Ef5jWLD2aidCDeaby0i4DWThq' \ --header 'api-key: dev_Ku6SmaxCKhT5paf7bvG0QVtZq9skqpqkn2NznC6Ef5jWLD2aidCDeaby0i4DWThq' \ --data-raw '{ "amount_details": { "order_amount": 100, "currency": "USD" }, "capture_method":"manual", "authentication_type": "no_three_ds", "billing": { "address": { "first_name": "John", "last_name": "Dough" }, "email": "[email protected]" }, "shipping": { "address": { "first_name": "John", "last_name": "Dough", "city": "Karwar", "zip": "581301", "state": "Karnataka" }, "email": "[email protected]" } }' ``` use the client secret to confirm the intent Confirm request - ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_01972f2414617513a2b2387237f61eb9/confirm-intent' \ --header 'x-client-secret: cs_01972f2414cb7720be7f596e088f9bfd' \ --header 'x-profile-id: pro_kQqIhnCrULOPt4tmuP5v' \ --header 'Authorization: api-key=dev_Ku6SmaxCKhT5paf7bvG0QVtZq9skqpqkn2NznC6Ef5jWLD2aidCDeaby0i4DWThq' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_47a62e65c5124ddab58d82c3bb4d0072' \ --data-raw '{ "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "01", "card_exp_year": "25", "card_holder_name": "John Doe", "card_cvc": "100" }, "billing": { "address": { "first_name": "John", "last_name": "Dough" }, "email": "[email protected]" } }, "payment_method_type": "card", "payment_method_subtype": "credit", "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" } }' ``` Confirm Intent Response - here the payment went through stripe - ``` { "id": "12345_pay_01972f2414617513a2b2387237f61eb9", "status": "failed", "amount": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 100, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": null }, "customer_id": null, "connector": "stripe", "created": "2025-06-02T05:36:23.178Z", "payment_method_data": { "billing": { "address": { "city": null, "country": null, "line1": null, "line2": null, "line3": null, "zip": null, "state": null, "first_name": "John", "last_name": "Dough" }, "phone": null, "email": "[email protected]" } }, "payment_method_type": "card", "payment_method_subtype": "credit", "connector_transaction_id": null, "connector_reference_id": null, "merchant_connector_id": "mca_DfyZDqHCZErTASCW170f", "browser_info": null, "error": { "code": "No error code", "message": "No error message", "unified_code": null, "unified_message": null, "network_advice_code": null, "network_decline_code": null, "network_error_message": null }, "shipping": null, "billing": null, "attempts": null, "connector_token_details": null, "payment_method_id": null, "next_action": null, "return_url": "https://google.com/success", "authentication_type": "no_three_ds", "authentication_type_applied": "no_three_ds", "is_iframe_redirection_enabled": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
b8e7a868ade62ff21498203d9e14edae094071d9
b8e7a868ade62ff21498203d9e14edae094071d9
juspay/hyperswitch
juspay__hyperswitch-8212
Bug: [FEATURE] Audit trail for routing ### Feature Description Implement audit trail for routing ### Possible Implementation Implement audit trail for routing ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/config.example.toml b/config/config.example.toml index 16846d0c403..12a905e1f56 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -945,6 +945,7 @@ audit_events_topic = "topic" # Kafka topic to be used for Payment Au payout_analytics_topic = "topic" # Kafka topic to be used for Payouts and PayoutAttempt events consolidated_events_topic = "topic" # Kafka topic to be used for Consolidated events authentication_analytics_topic = "topic" # Kafka topic to be used for Authentication events +routing_logs_topic = "topic" # Kafka topic to be used for Routing events # File storage configuration [file_storage] diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 05c1745a6de..022ba701e8b 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -93,6 +93,7 @@ payout_analytics_topic = "topic" # Kafka topic to be used for Payouts an consolidated_events_topic = "topic" # Kafka topic to be used for Consolidated events authentication_analytics_topic = "topic" # Kafka topic to be used for Authentication events fraud_check_analytics_topic = "topic" # Kafka topic to be used for Fraud Check events +routing_logs_topic = "topic" # Kafka topic to be used for Routing events # File storage configuration [file_storage] diff --git a/config/development.toml b/config/development.toml index 158f8b0116e..d090c0aaaaa 100644 --- a/config/development.toml +++ b/config/development.toml @@ -1035,6 +1035,7 @@ audit_events_topic = "hyperswitch-audit-events" payout_analytics_topic = "hyperswitch-payout-events" consolidated_events_topic = "hyperswitch-consolidated-events" authentication_analytics_topic = "hyperswitch-authentication-events" +routing_logs_topic = "hyperswitch-routing-api-events" [debit_routing_config] supported_currencies = "USD" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 5a425bd89ff..c6d40c59e89 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -900,6 +900,7 @@ audit_events_topic = "hyperswitch-audit-events" payout_analytics_topic = "hyperswitch-payout-events" consolidated_events_topic = "hyperswitch-consolidated-events" authentication_analytics_topic = "hyperswitch-authentication-events" +routing_logs_topic = "hyperswitch-routing-api-events" [analytics] source = "sqlx" diff --git a/crates/analytics/docs/clickhouse/scripts/connector_events.sql b/crates/analytics/docs/clickhouse/scripts/connector_events.sql index 61a036bccd5..33826fbaaf9 100644 --- a/crates/analytics/docs/clickhouse/scripts/connector_events.sql +++ b/crates/analytics/docs/clickhouse/scripts/connector_events.sql @@ -1,4 +1,5 @@ -CREATE TABLE connector_events_queue ( +CREATE TABLE connector_events_queue +( `merchant_id` String, `payment_id` Nullable(String), `connector_name` LowCardinality(String), @@ -13,11 +14,9 @@ CREATE TABLE connector_events_queue ( `method` LowCardinality(String), `dispute_id` Nullable(String), `refund_id` Nullable(String) -) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092', -kafka_topic_list = 'hyperswitch-outgoing-connector-events', -kafka_group_name = 'hyper', -kafka_format = 'JSONEachRow', -kafka_handle_error_mode = 'stream'; +) +ENGINE = Kafka +SETTINGS kafka_broker_list = 'kafka0:29092', kafka_topic_list = 'hyperswitch-outgoing-connector-events', kafka_group_name = 'hyper', kafka_format = 'JSONEachRow', kafka_handle_error_mode = 'stream'; CREATE MATERIALIZED VIEW connector_events_parse_errors ( `topic` String, diff --git a/crates/analytics/docs/clickhouse/scripts/routing_events.sql b/crates/analytics/docs/clickhouse/scripts/routing_events.sql new file mode 100644 index 00000000000..d9e2ccd9e54 --- /dev/null +++ b/crates/analytics/docs/clickhouse/scripts/routing_events.sql @@ -0,0 +1,191 @@ +-- Need to discuss with the team about the structure of this table. +CREATE TABLE routing_events_queue +( + `merchant_id` String, + `profile_id` String, + `payment_id` String, + `refund_id` Nullable(String), + `dispute_id` Nullable(String), + `routable_connectors` String, + `payment_connector` Nullable(String), + `request_id` String, + `flow` LowCardinality(String), + `url` Nullable(String), + `request` String, + `response` Nullable(String), + `error` Nullable(String), + `status_code` Nullable(UInt32), + `created_at` DateTime64(9), + `method` LowCardinality(String), + `routing_engine` LowCardinality(String), + `routing_approach` Nullable(String) +) +ENGINE = Kafka +SETTINGS kafka_broker_list = 'kafka0:29092', kafka_topic_list = 'hyperswitch-routing-api-events', kafka_group_name = 'hyper', kafka_format = 'JSONEachRow', kafka_handle_error_mode = 'stream'; + +CREATE MATERIALIZED VIEW routing_events_parse_errors ( + `topic` String, + `partition` Int64, + `offset` Int64, + `raw` String, + `error` String +) ENGINE = MergeTree +ORDER BY + (topic, partition, offset) SETTINGS index_granularity = 8192 AS +SELECT + _topic AS topic, + _partition AS partition, + _offset AS offset, + _raw_message AS raw, + _error AS error +FROM + routing_events_queue +WHERE + length(_error) > 0; + +CREATE TABLE routing_events ( + `merchant_id` String, + `profile_id` String, + `payment_id` String, + `refund_id` Nullable(String), + `dispute_id` Nullable(String), + `routable_connectors` String, + `payment_connector` Nullable(String), + `request_id` String, + `flow` LowCardinality(String), + `url` Nullable(String), + `request` String, + `response` Nullable(String), + `error` Nullable(String), + `status_code` Nullable(UInt32), + `created_at` DateTime64(9), + `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `method` LowCardinality(String), + `routing_engine` LowCardinality(String), + `routing_approach` Nullable(String), + INDEX flowIndex flow TYPE bloom_filter GRANULARITY 1, + INDEX profileIndex profile_id TYPE bloom_filter GRANULARITY 1 +) ENGINE = MergeTree +PARTITION BY toStartOfDay(created_at) +ORDER BY ( created_at, merchant_id, profile_id, payment_id ) +SETTINGS index_granularity = 8192; + +CREATE TABLE routing_events_audit ( + `merchant_id` String, + `profile_id` String, + `payment_id` String, + `refund_id` Nullable(String), + `dispute_id` Nullable(String), + `routable_connectors` String, + `payment_connector` Nullable(String), + `request_id` String, + `flow` LowCardinality(String), + `url` Nullable(String), + `request` String, + `response` Nullable(String), + `error` Nullable(String), + `status_code` Nullable(UInt32), + `created_at` DateTime64(9), + `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `method` LowCardinality(String), + `routing_engine` LowCardinality(String), + `routing_approach` Nullable(String), + INDEX flowIndex flow TYPE bloom_filter GRANULARITY 1, + INDEX profileIndex profile_id TYPE bloom_filter GRANULARITY 1 +) ENGINE = MergeTree +PARTITION BY (merchant_id) +ORDER BY ( merchant_id, payment_id ) +SETTINGS index_granularity = 8192; + + +CREATE MATERIALIZED VIEW routing_events_mv TO routing_events ( + `merchant_id` String, + `profile_id` String, + `payment_id` String, + `refund_id` Nullable(String), + `dispute_id` Nullable(String), + `routable_connectors` String, + `payment_connector` Nullable(String), + `request_id` String, + `flow` LowCardinality(String), + `url` Nullable(String), + `request` String, + `response` Nullable(String), + `error` Nullable(String), + `status_code` Nullable(UInt32), + `created_at` DateTime64(9), + `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `method` LowCardinality(String), + `routing_engine` LowCardinality(String), + `routing_approach` Nullable(String) +) AS +SELECT + merchant_id, + profile_id, + payment_id, + refund_id, + dispute_id, + routable_connectors, + payment_connector, + request_id, + flow, + url, + request, + response, + error, + status_code, + created_at, + now() AS inserted_at, + method, + routing_engine, + routing_approach +FROM + routing_events_queue +WHERE + length(_error) = 0; + +CREATE MATERIALIZED VIEW routing_events_audit_mv TO routing_events_audit ( + `merchant_id` String, + `profile_id` String, + `payment_id` String, + `refund_id` Nullable(String), + `dispute_id` Nullable(String), + `routable_connectors` String, + `payment_connector` Nullable(String), + `request_id` String, + `flow` LowCardinality(String), + `url` Nullable(String), + `request` String, + `response` Nullable(String), + `error` Nullable(String), + `status_code` Nullable(UInt32), + `created_at` DateTime64(9), + `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4), + `method` LowCardinality(String), + `routing_engine` LowCardinality(String), + `routing_approach` Nullable(String) +) AS +SELECT + merchant_id, + profile_id, + payment_id, + refund_id, + dispute_id, + routable_connectors, + payment_connector, + request_id, + flow, + url, + request, + response, + error, + status_code, + created_at, + now() AS inserted_at, + method, + routing_engine, + routing_approach +FROM + routing_events_queue +WHERE + length(_error) = 0; \ No newline at end of file diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs index 1d52cc9e761..f58df9bedfa 100644 --- a/crates/analytics/src/clickhouse.rs +++ b/crates/analytics/src/clickhouse.rs @@ -32,6 +32,7 @@ use crate::{ connector_events::events::ConnectorEventsResult, disputes::{filters::DisputeFilterRow, metrics::DisputeMetricRow}, outgoing_webhook_event::events::OutgoingWebhookLogsResult, + routing_events::events::RoutingEventsResult, sdk_events::events::SdkEventsResult, types::TableEngine, }; @@ -150,6 +151,7 @@ impl AnalyticsDataSource for ClickhouseClient { | AnalyticsCollection::SdkEventsAnalytics | AnalyticsCollection::ApiEvents | AnalyticsCollection::ConnectorEvents + | AnalyticsCollection::RoutingEvents | AnalyticsCollection::ApiEventsAnalytics | AnalyticsCollection::OutgoingWebhookEvent | AnalyticsCollection::ActivePaymentsAnalytics => TableEngine::BasicTree, @@ -187,6 +189,7 @@ impl super::api_event::events::ApiLogsFilterAnalytics for ClickhouseClient {} impl super::api_event::filters::ApiEventFilterAnalytics for ClickhouseClient {} impl super::api_event::metrics::ApiEventMetricAnalytics for ClickhouseClient {} impl super::connector_events::events::ConnectorEventLogAnalytics for ClickhouseClient {} +impl super::routing_events::events::RoutingEventLogAnalytics for ClickhouseClient {} impl super::outgoing_webhook_event::events::OutgoingWebhookLogsFilterAnalytics for ClickhouseClient { @@ -236,6 +239,16 @@ impl TryInto<ConnectorEventsResult> for serde_json::Value { } } +impl TryInto<RoutingEventsResult> for serde_json::Value { + type Error = Report<ParsingError>; + + fn try_into(self) -> Result<RoutingEventsResult, Self::Error> { + serde_json::from_value(self).change_context(ParsingError::StructParseFailure( + "Failed to parse RoutingEventsResult in clickhouse results", + )) + } +} + impl TryInto<PaymentMetricRow> for serde_json::Value { type Error = Report<ParsingError>; @@ -471,6 +484,7 @@ impl ToSql<ClickhouseClient> for AnalyticsCollection { Self::DisputeSessionized => Ok("sessionizer_dispute".to_string()), Self::ActivePaymentsAnalytics => Ok("active_payments".to_string()), Self::Authentications => Ok("authentications".to_string()), + Self::RoutingEvents => Ok("routing_events_audit".to_string()), } } } diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index 2cd2da30e45..1718c5044ae 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -16,6 +16,7 @@ pub mod payment_intents; pub mod payments; mod query; pub mod refunds; +pub mod routing_events; pub mod sdk_events; pub mod search; mod sqlx; @@ -1165,6 +1166,7 @@ pub enum AnalyticsFlow { GetDisputeFilters, GetDisputeMetrics, GetSankey, + GetRoutingEvents, } impl FlowMetric for AnalyticsFlow {} diff --git a/crates/analytics/src/routing_events.rs b/crates/analytics/src/routing_events.rs new file mode 100644 index 00000000000..531af749c97 --- /dev/null +++ b/crates/analytics/src/routing_events.rs @@ -0,0 +1,5 @@ +mod core; +pub mod events; +pub trait RoutingEventAnalytics: events::RoutingEventLogAnalytics {} + +pub use self::core::routing_events_core; diff --git a/crates/analytics/src/routing_events/core.rs b/crates/analytics/src/routing_events/core.rs new file mode 100644 index 00000000000..30efcfaaa9b --- /dev/null +++ b/crates/analytics/src/routing_events/core.rs @@ -0,0 +1,26 @@ +use api_models::analytics::routing_events::RoutingEventsRequest; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; + +use super::events::{get_routing_events, RoutingEventsResult}; +use crate::{errors::AnalyticsResult, types::FiltersError, AnalyticsProvider}; + +pub async fn routing_events_core( + pool: &AnalyticsProvider, + req: RoutingEventsRequest, + merchant_id: &common_utils::id_type::MerchantId, +) -> AnalyticsResult<Vec<RoutingEventsResult>> { + let data = match pool { + AnalyticsProvider::Sqlx(_) => Err(FiltersError::NotImplemented( + "Connector Events not implemented for SQLX", + )) + .attach_printable("SQL Analytics is not implemented for Connector Events"), + AnalyticsProvider::Clickhouse(ckh_pool) + | AnalyticsProvider::CombinedSqlx(_, ckh_pool) + | AnalyticsProvider::CombinedCkh(_, ckh_pool) => { + get_routing_events(merchant_id, req, ckh_pool).await + } + } + .switch()?; + Ok(data) +} diff --git a/crates/analytics/src/routing_events/events.rs b/crates/analytics/src/routing_events/events.rs new file mode 100644 index 00000000000..27b2f251627 --- /dev/null +++ b/crates/analytics/src/routing_events/events.rs @@ -0,0 +1,73 @@ +use api_models::analytics::{routing_events::RoutingEventsRequest, Granularity}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, FiltersError, FiltersResult, LoadRow}, +}; +pub trait RoutingEventLogAnalytics: LoadRow<RoutingEventsResult> {} + +pub async fn get_routing_events<T>( + merchant_id: &common_utils::id_type::MerchantId, + query_param: RoutingEventsRequest, + pool: &T, +) -> FiltersResult<Vec<RoutingEventsResult>> +where + T: AnalyticsDataSource + RoutingEventLogAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::RoutingEvents); + query_builder.add_select_column("*").switch()?; + + query_builder + .add_filter_clause("merchant_id", merchant_id) + .switch()?; + + query_builder + .add_filter_clause("payment_id", &query_param.payment_id) + .switch()?; + + if let Some(refund_id) = query_param.refund_id { + query_builder + .add_filter_clause("refund_id", &refund_id) + .switch()?; + } + + if let Some(dispute_id) = query_param.dispute_id { + query_builder + .add_filter_clause("dispute_id", &dispute_id) + .switch()?; + } + + query_builder + .execute_query::<RoutingEventsResult, _>(pool) + .await + .change_context(FiltersError::QueryBuildingError)? + .change_context(FiltersError::QueryExecutionFailure) +} + +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub struct RoutingEventsResult { + pub merchant_id: common_utils::id_type::MerchantId, + pub profile_id: common_utils::id_type::ProfileId, + pub payment_id: String, + pub routable_connectors: String, + pub payment_connector: Option<String>, + pub request_id: Option<String>, + pub flow: String, + pub url: Option<String>, + pub request: String, + pub response: Option<String>, + pub error: Option<String>, + pub status_code: Option<u16>, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub created_at: PrimitiveDateTime, + pub method: String, + pub routing_engine: String, +} diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index 7934c911848..028a1ddc143 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -1400,6 +1400,8 @@ impl ToSql<SqlxClient> for AnalyticsCollection { .attach_printable("DisputeSessionized table is not implemented for Sqlx"))?, Self::Authentications => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("Authentications table is not implemented for Sqlx"))?, + Self::RoutingEvents => Err(error_stack::report!(ParsingError::UnknownError) + .attach_printable("RoutingEvents table is not implemented for Sqlx"))?, } } } diff --git a/crates/analytics/src/types.rs b/crates/analytics/src/types.rs index 7bf8fc7d3c3..28ff2cec8bd 100644 --- a/crates/analytics/src/types.rs +++ b/crates/analytics/src/types.rs @@ -42,6 +42,7 @@ pub enum AnalyticsCollection { DisputeSessionized, ApiEventsAnalytics, ActivePaymentsAnalytics, + RoutingEvents, } #[allow(dead_code)] diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs index 71d7f80eb7c..fcce19601a3 100644 --- a/crates/api_models/src/analytics.rs +++ b/crates/api_models/src/analytics.rs @@ -25,6 +25,7 @@ pub mod outgoing_webhook_event; pub mod payment_intents; pub mod payments; pub mod refunds; +pub mod routing_events; pub mod sdk_events; pub mod search; diff --git a/crates/api_models/src/analytics/routing_events.rs b/crates/api_models/src/analytics/routing_events.rs new file mode 100644 index 00000000000..e9cec7221b2 --- /dev/null +++ b/crates/api_models/src/analytics/routing_events.rs @@ -0,0 +1,6 @@ +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +pub struct RoutingEventsRequest { + pub payment_id: common_utils::id_type::PaymentId, + pub refund_id: Option<String>, + pub dispute_id: Option<String>, +} diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index e0e57050c4e..0038590a54f 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -29,7 +29,8 @@ use crate::{ admin::*, analytics::{ api_event::*, auth_events::*, connector_events::ConnectorEventsRequest, - outgoing_webhook_event::OutgoingWebhookLogsRequest, sdk_events::*, search::*, *, + outgoing_webhook_event::OutgoingWebhookLogsRequest, routing_events::RoutingEventsRequest, + sdk_events::*, search::*, *, }, api_keys::*, cards_info::*, @@ -142,7 +143,8 @@ impl_api_event_type!( OrganizationCreateRequest, OrganizationUpdateRequest, OrganizationId, - CustomerListRequest + CustomerListRequest, + RoutingEventsRequest ) ); diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index 7068da8edcd..46cd37bc68a 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -1046,7 +1046,7 @@ pub struct CurrentBlockThreshold { pub max_total_count: Option<u64>, } -#[derive(serde::Serialize, serde::Deserialize, Debug, Default, Clone, ToSchema)] +#[derive(serde::Serialize, serde::Deserialize, Debug, Default, Clone, Copy, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SuccessRateSpecificityLevel { #[default] @@ -1283,3 +1283,247 @@ impl RoutableConnectorChoiceWithBucketName { } } } + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct CalSuccessRateConfigEventRequest { + pub min_aggregates_size: Option<u32>, + pub default_success_rate: Option<f64>, + pub specificity_level: SuccessRateSpecificityLevel, + pub exploration_percent: Option<f64>, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct CalSuccessRateEventRequest { + pub id: String, + pub params: String, + pub labels: Vec<String>, + pub config: Option<CalSuccessRateConfigEventRequest>, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct EliminationRoutingEventBucketConfig { + pub bucket_size: Option<u64>, + pub bucket_leak_interval_in_secs: Option<u64>, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct EliminationRoutingEventRequest { + pub id: String, + pub params: String, + pub labels: Vec<String>, + pub config: Option<EliminationRoutingEventBucketConfig>, +} + +/// API-1 types +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct CalContractScoreEventRequest { + pub id: String, + pub params: String, + pub labels: Vec<String>, + pub config: Option<ContractBasedRoutingConfig>, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct LabelWithScoreEventResponse { + pub score: f64, + pub label: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct CalSuccessRateEventResponse { + pub labels_with_score: Vec<LabelWithScoreEventResponse>, + pub routing_apporach: RoutingApproach, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum RoutingApproach { + Exploitation, + Exploration, + Elimination, + ContractBased, + Default, +} + +impl RoutingApproach { + pub fn from_decision_engine_approach(approach: &str) -> Self { + match approach { + "SR_SELECTION_V3_ROUTING" => Self::Exploitation, + "SR_V3_HEDGING" => Self::Exploration, + _ => Self::Default, + } + } +} + +impl std::fmt::Display for RoutingApproach { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Exploitation => write!(f, "Exploitation"), + Self::Exploration => write!(f, "Exploration"), + Self::Elimination => write!(f, "Elimination"), + Self::ContractBased => write!(f, "ContractBased"), + Self::Default => write!(f, "Default"), + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct BucketInformationEventResponse { + pub is_eliminated: bool, + pub bucket_name: Vec<String>, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct EliminationInformationEventResponse { + pub entity: Option<BucketInformationEventResponse>, + pub global: Option<BucketInformationEventResponse>, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct LabelWithStatusEliminationEventResponse { + pub label: String, + pub elimination_information: Option<EliminationInformationEventResponse>, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct EliminationEventResponse { + pub labels_with_status: Vec<LabelWithStatusEliminationEventResponse>, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct ScoreDataEventResponse { + pub score: f64, + pub label: String, + pub current_count: u64, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct CalContractScoreEventResponse { + pub labels_with_score: Vec<ScoreDataEventResponse>, +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct CalGlobalSuccessRateConfigEventRequest { + pub entity_min_aggregates_size: u32, + pub entity_default_success_rate: f64, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct CalGlobalSuccessRateEventRequest { + pub entity_id: String, + pub entity_params: String, + pub entity_labels: Vec<String>, + pub global_labels: Vec<String>, + pub config: Option<CalGlobalSuccessRateConfigEventRequest>, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct UpdateSuccessRateWindowConfig { + pub max_aggregates_size: Option<u32>, + pub current_block_threshold: Option<CurrentBlockThreshold>, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct UpdateLabelWithStatusEventRequest { + pub label: String, + pub status: bool, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct UpdateSuccessRateWindowEventRequest { + pub id: String, + pub params: String, + pub labels_with_status: Vec<UpdateLabelWithStatusEventRequest>, + pub config: Option<UpdateSuccessRateWindowConfig>, + pub global_labels_with_status: Vec<UpdateLabelWithStatusEventRequest>, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct UpdateSuccessRateWindowEventResponse { + pub status: UpdationStatusEventResponse, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum UpdationStatusEventResponse { + WindowUpdationSucceeded, + WindowUpdationFailed, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct LabelWithBucketNameEventRequest { + pub label: String, + pub bucket_name: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct UpdateEliminationBucketEventRequest { + pub id: String, + pub params: String, + pub labels_with_bucket_name: Vec<LabelWithBucketNameEventRequest>, + pub config: Option<EliminationRoutingEventBucketConfig>, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct UpdateEliminationBucketEventResponse { + pub status: EliminationUpdationStatusEventResponse, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum EliminationUpdationStatusEventResponse { + BucketUpdationSucceeded, + BucketUpdationFailed, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct ContractLabelInformationEventRequest { + pub label: String, + pub target_count: u64, + pub target_time: u64, + pub current_count: u64, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct UpdateContractRequestEventRequest { + pub id: String, + pub params: String, + pub labels_information: Vec<ContractLabelInformationEventRequest>, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct UpdateContractEventResponse { + pub status: ContractUpdationStatusEventResponse, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ContractUpdationStatusEventResponse { + ContractUpdationSucceeded, + ContractUpdationFailed, +} diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml index 336a4d64714..34aca99f399 100644 --- a/crates/external_services/Cargo.toml +++ b/crates/external_services/Cargo.toml @@ -13,7 +13,19 @@ email = ["dep:aws-config"] aws_s3 = ["dep:aws-config", "dep:aws-sdk-s3"] hashicorp-vault = ["dep:vaultrs"] v1 = ["hyperswitch_interfaces/v1", "common_utils/v1"] -dynamic_routing = ["dep:prost", "dep:tonic", "dep:tonic-reflection", "dep:tonic-types", "dep:api_models", "tokio/macros", "tokio/rt-multi-thread", "dep:tonic-build", "dep:router_env", "dep:hyper-util", "dep:http-body-util"] +dynamic_routing = [ + "dep:prost", + "dep:tonic", + "dep:tonic-reflection", + "dep:tonic-types", + "dep:api_models", + "tokio/macros", + "tokio/rt-multi-thread", + "dep:tonic-build", + "dep:router_env", + "dep:hyper-util", + "dep:http-body-util", +] [dependencies] async-trait = "0.1.88" @@ -51,7 +63,10 @@ quick-xml = { version = "0.31.0", features = ["serialize"] } common_utils = { version = "0.1.0", path = "../common_utils" } hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces", default-features = false } masking = { version = "0.1.0", path = "../masking" } -router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] } +router_env = { version = "0.1.0", path = "../router_env", features = [ + "log_extra_implicit_fields", + "log_custom_entries_to_extra", +] } api_models = { version = "0.1.0", path = "../api_models", optional = true } diff --git a/crates/hyperswitch_interfaces/src/events.rs b/crates/hyperswitch_interfaces/src/events.rs index 3dcb7519545..54f24c2ec12 100644 --- a/crates/hyperswitch_interfaces/src/events.rs +++ b/crates/hyperswitch_interfaces/src/events.rs @@ -1,3 +1,4 @@ //! Events interface pub mod connector_api_logs; +pub mod routing_api_logs; diff --git a/crates/hyperswitch_interfaces/src/events/routing_api_logs.rs b/crates/hyperswitch_interfaces/src/events/routing_api_logs.rs new file mode 100644 index 00000000000..f7c61e38900 --- /dev/null +++ b/crates/hyperswitch_interfaces/src/events/routing_api_logs.rs @@ -0,0 +1,186 @@ +//! Routing API logs interface + +use std::fmt; + +use api_models::routing::RoutableConnectorChoice; +use common_utils::request::Method; +use router_env::tracing_actix_web::RequestId; +use serde::Serialize; +use serde_json::json; +use time::OffsetDateTime; + +/// RoutingEngine enum +#[derive(Debug, Clone, Copy, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum RoutingEngine { + /// Dynamo for routing + IntelligentRouter, + /// Decision engine for routing + DecisionEngine, +} + +/// Method type enum +#[derive(Debug, Clone, Copy, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum ApiMethod { + /// grpc call + Grpc, + /// Rest call + Rest(Method), +} + +impl fmt::Display for ApiMethod { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Grpc => write!(f, "Grpc"), + Self::Rest(method) => write!(f, "Rest ({})", method), + } + } +} + +#[derive(Debug, Serialize)] +/// RoutingEvent type +pub struct RoutingEvent { + tenant_id: common_utils::id_type::TenantId, + routable_connectors: String, + payment_connector: Option<String>, + flow: String, + request: String, + response: Option<String>, + error: Option<String>, + url: String, + method: String, + payment_id: String, + profile_id: common_utils::id_type::ProfileId, + merchant_id: common_utils::id_type::MerchantId, + created_at: i128, + status_code: Option<u16>, + request_id: String, + routing_engine: RoutingEngine, + routing_approach: Option<String>, +} + +impl RoutingEvent { + /// fn new RoutingEvent + #[allow(clippy::too_many_arguments)] + pub fn new( + tenant_id: common_utils::id_type::TenantId, + routable_connectors: String, + flow: &str, + request: serde_json::Value, + url: String, + method: ApiMethod, + payment_id: String, + profile_id: common_utils::id_type::ProfileId, + merchant_id: common_utils::id_type::MerchantId, + request_id: Option<RequestId>, + routing_engine: RoutingEngine, + ) -> Self { + Self { + tenant_id, + routable_connectors, + flow: flow.to_string(), + request: request.to_string(), + response: None, + error: None, + url, + method: method.to_string(), + payment_id, + profile_id, + merchant_id, + created_at: OffsetDateTime::now_utc().unix_timestamp_nanos(), + status_code: None, + request_id: request_id + .map(|i| i.as_hyphenated().to_string()) + .unwrap_or("NO_REQUEST_ID".to_string()), + routing_engine, + payment_connector: None, + routing_approach: None, + } + } + + /// fn set_response_body + pub fn set_response_body<T: Serialize>(&mut self, response: &T) { + match masking::masked_serialize(response) { + Ok(masked) => { + self.response = Some(masked.to_string()); + } + Err(er) => self.set_error(json!({"error": er.to_string()})), + } + } + + /// fn set_error_response_body + pub fn set_error_response_body<T: Serialize>(&mut self, response: &T) { + match masking::masked_serialize(response) { + Ok(masked) => { + self.error = Some(masked.to_string()); + } + Err(er) => self.set_error(json!({"error": er.to_string()})), + } + } + + /// fn set_error + pub fn set_error(&mut self, error: serde_json::Value) { + self.error = Some(error.to_string()); + } + + /// set response status code + pub fn set_status_code(&mut self, code: u16) { + self.status_code = Some(code); + } + + /// set response status code + pub fn set_routable_connectors(&mut self, connectors: Vec<RoutableConnectorChoice>) { + let connectors = connectors + .into_iter() + .map(|c| { + format!( + "{:?}:{:?}", + c.connector, + c.merchant_connector_id + .map(|id| id.get_string_repr().to_string()) + .unwrap_or(String::from("")) + ) + }) + .collect::<Vec<_>>() + .join(","); + self.routable_connectors = connectors; + } + + /// set payment connector + pub fn set_payment_connector(&mut self, connector: RoutableConnectorChoice) { + self.payment_connector = Some(format!( + "{:?}:{:?}", + connector.connector, + connector + .merchant_connector_id + .map(|id| id.get_string_repr().to_string()) + .unwrap_or(String::from("")) + )); + } + + /// set routing approach + pub fn set_routing_approach(&mut self, approach: String) { + self.routing_approach = Some(approach); + } + + /// Returns the request ID of the event. + pub fn get_request_id(&self) -> &str { + &self.request_id + } + + /// Returns the merchant ID of the event. + pub fn get_merchant_id(&self) -> &str { + self.merchant_id.get_string_repr() + } + + /// Returns the payment ID of the event. + pub fn get_payment_id(&self) -> &str { + &self.payment_id + } + + /// Returns the profile ID of the event. + pub fn get_profile_id(&self) -> &str { + self.profile_id.get_string_repr() + } +} diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index 67722d3e25a..ffac49e7a8e 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -10,8 +10,8 @@ pub mod routes { use analytics::{ api_event::api_events_core, connector_events::connector_events_core, enums::AuthInfo, errors::AnalyticsError, lambda_utils::invoke_lambda, opensearch::OpenSearchError, - outgoing_webhook_event::outgoing_webhook_events_core, sdk_events::sdk_events_core, - AnalyticsFlow, + outgoing_webhook_event::outgoing_webhook_events_core, routing_events::routing_events_core, + sdk_events::sdk_events_core, AnalyticsFlow, }; use api_models::analytics::{ api_event::QueryType, @@ -133,6 +133,10 @@ pub mod routes { web::resource("connector_event_logs") .route(web::get().to(get_profile_connector_events)), ) + .service( + web::resource("routing_event_logs") + .route(web::get().to(get_profile_routing_events)), + ) .service( web::resource("outgoing_webhook_event_logs") .route(web::get().to(get_profile_outgoing_webhook_events)), @@ -307,6 +311,10 @@ pub mod routes { web::resource("connector_event_logs") .route(web::get().to(get_profile_connector_events)), ) + .service( + web::resource("routing_event_logs") + .route(web::get().to(get_profile_routing_events)), + ) .service( web::resource("outgoing_webhook_event_logs") .route(web::get().to(get_profile_outgoing_webhook_events)), @@ -2169,6 +2177,44 @@ pub mod routes { .await } + pub async fn get_profile_routing_events( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Query<api_models::analytics::routing_events::RoutingEventsRequest>, + ) -> impl Responder { + let flow = AnalyticsFlow::GetRoutingEvents; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, auth: AuthenticationData, req, _| async move { + utils::check_if_profile_id_is_present_in_payment_intent( + req.payment_id.clone(), + &state, + &auth, + ) + .await + .change_context(AnalyticsError::AccessForbiddenError)?; + routing_events_core(&state.pool, req, auth.merchant_account.get_id()) + .await + .map(ApplicationResponse::Json) + }, + auth::auth_type( + &auth::HeaderAuth(auth::ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: false, + }), + &auth::JWTAuth { + permission: Permission::ProfileAnalyticsRead, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await + } + pub async fn get_global_search_results( state: web::Data<AppState>, req: actix_web::HttpRequest, diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 0993a6eee3f..6edf2a479dd 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -7539,6 +7539,7 @@ where connectors.clone(), business_profile, dynamic_routing_config_params_interpolator, + payment_data.get_payment_attempt(), ) .await .map_err(|e| logger::error!(dynamic_routing_error=?e)) diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index de1cf0e8a6e..fa161efb212 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -31,10 +31,12 @@ use euclid::{ use external_services::grpc_client::dynamic_routing::{ contract_routing_client::ContractBasedDynamicRouting, elimination_based_client::{EliminationBasedRouting, EliminationResponse}, - success_rate_client::{CalSuccessRateResponse, SuccessBasedDynamicRouting}, + success_rate_client::SuccessBasedDynamicRouting, DynamicRoutingError, }; use hyperswitch_domain_models::address::Address; +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +use hyperswitch_interfaces::events::routing_api_logs::{ApiMethod, RoutingEngine, RoutingEvent}; use kgraph_utils::{ mca as mca_graph, transformers::{IntoContext, IntoDirValue}, @@ -58,6 +60,8 @@ use crate::core::payouts; use crate::core::routing::transformers::OpenRouterDecideGatewayRequestExt; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use crate::headers; +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +use crate::routes::app::SessionStateInfo; use crate::{ core::{ errors, errors as oss_errors, payments::routing::utils::DecisionEngineApiHandler, routing, @@ -1583,6 +1587,7 @@ pub async fn perform_dynamic_routing_with_open_router( state, connector.clone(), profile.get_id(), + &payment_data.merchant_id, &payment_data.payment_id, common_enums::AttemptStatus::AuthenticationPending, ) @@ -1662,6 +1667,7 @@ pub async fn perform_dynamic_routing_with_intelligent_router( routable_connectors: Vec<api_routing::RoutableConnectorChoice>, profile: &domain::Profile, dynamic_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator, + payment_attempt: &oss_storage::PaymentAttempt, ) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> { let dynamic_routing_algo_ref: api_routing::DynamicRoutingAlgorithmRef = profile .dynamic_routing_algorithm @@ -1690,6 +1696,8 @@ pub async fn perform_dynamic_routing_with_intelligent_router( state, routable_connectors.clone(), profile.get_id(), + &payment_attempt.merchant_id, + &payment_attempt.payment_id, dynamic_routing_config_params_interpolator.clone(), algorithm.clone(), ) @@ -1711,6 +1719,8 @@ pub async fn perform_dynamic_routing_with_intelligent_router( state, routable_connectors.clone(), profile.get_id(), + &payment_attempt.merchant_id, + &payment_attempt.payment_id, dynamic_routing_config_params_interpolator.clone(), algorithm.clone(), ) @@ -1732,6 +1742,8 @@ pub async fn perform_dynamic_routing_with_intelligent_router( state, connector_list.clone(), profile.get_id(), + &payment_attempt.merchant_id, + &payment_attempt.payment_id, dynamic_routing_config_params_interpolator.clone(), algorithm.clone(), ) @@ -1767,6 +1779,10 @@ pub async fn perform_decide_gateway_call_with_open_router( is_elimination_enabled, ); + let serialized_request = serde_json::to_value(&open_router_req_body) + .change_context(errors::RoutingError::OpenRouterCallFailed) + .attach_printable("Failed to serialize open_router request body")?; + let url = format!("{}/{}", &state.conf.open_router.url, "decide-gateway"); let mut request = request::Request::new(services::Method::Post, &url); request.add_header(headers::CONTENT_TYPE, "application/json".into()); @@ -1778,8 +1794,27 @@ pub async fn perform_decide_gateway_call_with_open_router( open_router_req_body, ))); + let mut routing_event = RoutingEvent::new( + state.tenant.tenant_id.clone(), + "".to_string(), + "open_router_decide_gateway_call", + serialized_request, + url.clone(), + ApiMethod::Rest(services::Method::Post), + payment_attempt.payment_id.get_string_repr().to_string(), + profile_id.to_owned(), + payment_attempt.merchant_id.to_owned(), + state.request_id, + RoutingEngine::DecisionEngine, + ); + let response = services::call_connector_api(state, request, "open_router_decide_gateway_call") .await + .inspect_err(|err| { + routing_event + .set_error(serde_json::json!({"error": err.current_context().to_string()})); + state.event_handler().log_event(&routing_event); + }) .change_context(errors::RoutingError::OpenRouterCallFailed)?; let sr_sorted_connectors = match response { @@ -1791,6 +1826,15 @@ pub async fn perform_decide_gateway_call_with_open_router( "Failed to parse the response from open_router".into(), ))?; + routing_event.set_status_code(resp.status_code); + routing_event.set_response_body(&decided_gateway); + routing_event.set_routing_approach( + api_routing::RoutingApproach::from_decision_engine_approach( + &decided_gateway.routing_approach, + ) + .to_string(), + ); + if let Some(gateway_priority_map) = decided_gateway.gateway_priority_map { logger::debug!(gateway_priority_map=?gateway_priority_map, routing_approach=decided_gateway.routing_approach, "open_router decide_gateway call response"); routable_connectors.sort_by(|connector_choice_a, connector_choice_b| { @@ -1807,6 +1851,10 @@ pub async fn perform_decide_gateway_call_with_open_router( .unwrap_or(std::cmp::Ordering::Equal) }); } + + routing_event.set_routable_connectors(routable_connectors.clone()); + state.event_handler().log_event(&routing_event); + Ok(routable_connectors) } Err(err) => { @@ -1817,6 +1865,12 @@ pub async fn perform_decide_gateway_call_with_open_router( "Failed to parse the response from open_router".into(), ))?; logger::error!("open_router_error_response: {:?}", err_resp); + + routing_event.set_status_code(err.status_code); + routing_event.set_error(serde_json::json!({"error": err_resp.error_message})); + routing_event.set_error_response_body(&err_resp); + state.event_handler().log_event(&routing_event); + Err(errors::RoutingError::OpenRouterError( "Failed to perform decide_gateway call in open_router".into(), )) @@ -1832,6 +1886,7 @@ pub async fn update_gateway_score_with_open_router( state: &SessionState, payment_connector: api_routing::RoutableConnectorChoice, profile_id: &common_utils::id_type::ProfileId, + merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, payment_status: common_enums::AttemptStatus, ) -> RoutingResult<()> { @@ -1842,6 +1897,10 @@ pub async fn update_gateway_score_with_open_router( payment_id: payment_id.clone(), }; + let serialized_request = serde_json::to_value(&open_router_req_body) + .change_context(errors::RoutingError::OpenRouterCallFailed) + .attach_printable("Failed to serialize open_router request body")?; + let url = format!("{}/{}", &state.conf.open_router.url, "update-gateway-score"); let mut request = request::Request::new(services::Method::Post, &url); request.add_header(headers::CONTENT_TYPE, "application/json".into()); @@ -1853,11 +1912,32 @@ pub async fn update_gateway_score_with_open_router( open_router_req_body, ))); + let mut routing_event = RoutingEvent::new( + state.tenant.tenant_id.clone(), + "".to_string(), + "open_router_update_gateway_score_call", + serialized_request, + url.clone(), + ApiMethod::Rest(services::Method::Post), + payment_id.get_string_repr().to_string(), + profile_id.to_owned(), + merchant_id.to_owned(), + state.request_id, + RoutingEngine::DecisionEngine, + ); + let response = services::call_connector_api(state, request, "open_router_update_gateway_score_call") .await + .inspect_err(|err| { + routing_event + .set_error(serde_json::json!({"error": err.current_context().to_string()})); + state.event_handler().log_event(&routing_event); + }) .change_context(errors::RoutingError::OpenRouterCallFailed)?; + routing_event.set_payment_connector(payment_connector.clone()); // check this in review + match response { Ok(resp) => { let update_score_resp = String::from_utf8(resp.response.to_vec()).change_context( @@ -1872,6 +1952,10 @@ pub async fn update_gateway_score_with_open_router( update_score_resp ); + routing_event.set_status_code(resp.status_code); + routing_event.set_response_body(&update_score_resp); + state.event_handler().log_event(&routing_event); + Ok(()) } Err(err) => { @@ -1882,6 +1966,12 @@ pub async fn update_gateway_score_with_open_router( "Failed to parse the response from open_router".into(), ))?; logger::error!("open_router_update_gateway_score_error: {:?}", err_resp); + + routing_event.set_status_code(err.status_code); + routing_event.set_error(serde_json::json!({"error": err_resp.error_message})); + routing_event.set_error_response_body(&err_resp); + state.event_handler().log_event(&routing_event); + Err(errors::RoutingError::OpenRouterError( "Failed to update gateway score in open_router".into(), )) @@ -1898,6 +1988,8 @@ pub async fn perform_success_based_routing( state: &SessionState, routable_connectors: Vec<api_routing::RoutableConnectorChoice>, profile_id: &common_utils::id_type::ProfileId, + merchant_id: &common_utils::id_type::MerchantId, + payment_id: &common_utils::id_type::PaymentId, success_based_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator, success_based_algo_ref: api_routing::SuccessBasedAlgorithm, ) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> { @@ -1941,7 +2033,42 @@ pub async fn perform_success_based_routing( .ok_or(errors::RoutingError::SuccessBasedRoutingParamsNotFoundError)?, ); - let success_based_connectors: CalSuccessRateResponse = client + let event_request = api_routing::CalSuccessRateEventRequest { + id: profile_id.get_string_repr().to_string(), + params: success_based_routing_config_params.clone(), + labels: routable_connectors + .iter() + .map(|conn_choice| conn_choice.to_string()) + .collect::<Vec<_>>(), + config: success_based_routing_configs.config.as_ref().map(|conf| { + api_routing::CalSuccessRateConfigEventRequest { + min_aggregates_size: conf.min_aggregates_size, + default_success_rate: conf.default_success_rate, + specificity_level: conf.specificity_level, + exploration_percent: conf.exploration_percent, + } + }), + }; + + let serialized_request = serde_json::to_value(&event_request) + .change_context(errors::RoutingError::SuccessBasedRoutingConfigError) + .attach_printable("unable to serialize success_based_routing_config_params")?; + + let mut routing_event = RoutingEvent::new( + state.tenant.tenant_id.clone(), + "".to_string(), + "Intelligent-router FetchSuccessRate", + serialized_request, + "SuccessRateCalculator.FetchSuccessRate".to_string(), + ApiMethod::Grpc, + payment_id.get_string_repr().to_string(), + profile_id.to_owned(), + merchant_id.to_owned(), + state.request_id, + RoutingEngine::IntelligentRouter, + ); + + let success_based_connectors = client .calculate_success_rate( profile_id.get_string_repr().into(), success_based_routing_configs, @@ -1950,11 +2077,45 @@ pub async fn perform_success_based_routing( state.get_grpc_headers(), ) .await + .inspect_err(|e| { + routing_event + .set_error(serde_json::json!({"error": e.current_context().to_string()})); + state.event_handler().log_event(&routing_event); + }) .change_context(errors::RoutingError::SuccessRateCalculationError) .attach_printable( "unable to calculate/fetch success rate from dynamic routing service", )?; + let event_resposne = api_routing::CalSuccessRateEventResponse { + labels_with_score: success_based_connectors + .labels_with_score + .iter() + .map( + |label_with_score| api_routing::LabelWithScoreEventResponse { + label: label_with_score.label.clone(), + score: label_with_score.score, + }, + ) + .collect(), + routing_apporach: match success_based_connectors.routing_approach { + 0 => api_routing::RoutingApproach::Exploration, + 1 => api_routing::RoutingApproach::Exploitation, + _ => { + return Err(errors::RoutingError::GenericNotFoundError { + field: "routing_approach".to_string(), + }) + .change_context(errors::RoutingError::GenericNotFoundError { + field: "unknown routing approach from dynamic routing service".to_string(), + }) + .attach_printable("unknown routing approach from dynamic routing service") + } + }, + }; + + routing_event.set_response_body(&event_resposne); + routing_event.set_routing_approach(event_resposne.routing_apporach.to_string()); + let mut connectors = Vec::with_capacity(success_based_connectors.labels_with_score.len()); for label_with_score in success_based_connectors.labels_with_score { let (connector, merchant_connector_id) = label_with_score.label @@ -1984,6 +2145,10 @@ pub async fn perform_success_based_routing( }); } logger::debug!(success_based_routing_connectors=?connectors); + + routing_event.set_status_code(200); + routing_event.set_routable_connectors(connectors.clone()); + state.event_handler().log_event(&routing_event); Ok(connectors) } else { Ok(routable_connectors) @@ -1996,6 +2161,8 @@ pub async fn perform_elimination_routing( state: &SessionState, routable_connectors: Vec<api_routing::RoutableConnectorChoice>, profile_id: &common_utils::id_type::ProfileId, + merchant_id: &common_utils::id_type::MerchantId, + payment_id: &common_utils::id_type::PaymentId, elimination_routing_configs_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator, elimination_algo_ref: api_routing::EliminationRoutingAlgorithm, ) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> { @@ -2041,6 +2208,40 @@ pub async fn perform_elimination_routing( .ok_or(errors::RoutingError::EliminationBasedRoutingParamsNotFoundError)?, ); + let event_request = api_routing::EliminationRoutingEventRequest { + id: profile_id.get_string_repr().to_string(), + params: elimination_routing_config_params.clone(), + labels: routable_connectors + .iter() + .map(|conn_choice| conn_choice.to_string()) + .collect::<Vec<_>>(), + config: elimination_routing_config + .elimination_analyser_config + .as_ref() + .map(|conf| api_routing::EliminationRoutingEventBucketConfig { + bucket_leak_interval_in_secs: conf.bucket_leak_interval_in_secs, + bucket_size: conf.bucket_size, + }), + }; + + let serialized_request = serde_json::to_value(&event_request) + .change_context(errors::RoutingError::SuccessBasedRoutingConfigError) + .attach_printable("unable to serialize EliminationRoutingEventRequest")?; + + let mut routing_event = RoutingEvent::new( + state.tenant.tenant_id.clone(), + "".to_string(), + "Intelligent-router GetEliminationStatus", + serialized_request, + "EliminationAnalyser.GetEliminationStatus".to_string(), + ApiMethod::Grpc, + payment_id.get_string_repr().to_string(), + profile_id.to_owned(), + merchant_id.to_owned(), + state.request_id, + RoutingEngine::IntelligentRouter, + ); + let elimination_based_connectors: EliminationResponse = client .perform_elimination_routing( profile_id.get_string_repr().to_string(), @@ -2050,10 +2251,48 @@ pub async fn perform_elimination_routing( state.get_grpc_headers(), ) .await + .inspect_err(|e| { + routing_event + .set_error(serde_json::json!({"error": e.current_context().to_string()})); + state.event_handler().log_event(&routing_event); + }) .change_context(errors::RoutingError::EliminationRoutingCalculationError) .attach_printable( "unable to analyze/fetch elimination routing from dynamic routing service", )?; + + let event_response = api_routing::EliminationEventResponse { + labels_with_status: elimination_based_connectors + .labels_with_status + .iter() + .map( + |label_with_status| api_routing::LabelWithStatusEliminationEventResponse { + label: label_with_status.label.clone(), + elimination_information: label_with_status + .elimination_information + .as_ref() + .map(|info| api_routing::EliminationInformationEventResponse { + entity: info.entity.as_ref().map(|entity_info| { + api_routing::BucketInformationEventResponse { + is_eliminated: entity_info.is_eliminated, + bucket_name: entity_info.bucket_name.clone(), + } + }), + global: info.global.as_ref().map(|global_info| { + api_routing::BucketInformationEventResponse { + is_eliminated: global_info.is_eliminated, + bucket_name: global_info.bucket_name.clone(), + } + }), + }), + }, + ) + .collect(), + }; + + routing_event.set_response_body(&event_response); + routing_event.set_routing_approach(api_routing::RoutingApproach::Elimination.to_string()); + let mut connectors = Vec::with_capacity(elimination_based_connectors.labels_with_status.len()); let mut eliminated_connectors = @@ -2105,6 +2344,10 @@ pub async fn perform_elimination_routing( } logger::debug!(dynamic_eliminated_connectors=?eliminated_connectors); logger::debug!(dynamic_elimination_based_routing_connectors=?connectors); + + routing_event.set_status_code(200); + routing_event.set_routable_connectors(connectors.clone()); + state.event_handler().log_event(&routing_event); Ok(connectors) } else { Ok(routable_connectors) @@ -2116,6 +2359,8 @@ pub async fn perform_contract_based_routing( state: &SessionState, routable_connectors: Vec<api_routing::RoutableConnectorChoice>, profile_id: &common_utils::id_type::ProfileId, + merchant_id: &common_utils::id_type::MerchantId, + payment_id: &common_utils::id_type::PaymentId, _dynamic_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator, contract_based_algo_ref: api_routing::ContractRoutingAlgorithm, ) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> { @@ -2176,6 +2421,34 @@ pub async fn perform_contract_based_routing( }) .collect::<Vec<_>>(); + let event_request = api_routing::CalContractScoreEventRequest { + id: profile_id.get_string_repr().to_string(), + params: "".to_string(), + labels: contract_based_connectors + .iter() + .map(|conn_choice| conn_choice.to_string()) + .collect::<Vec<_>>(), + config: Some(contract_based_routing_configs.clone()), + }; + + let serialized_request = serde_json::to_value(&event_request) + .change_context(errors::RoutingError::SuccessBasedRoutingConfigError) + .attach_printable("unable to serialize EliminationRoutingEventRequest")?; + + let mut routing_event = RoutingEvent::new( + state.tenant.tenant_id.clone(), + "".to_string(), + "Intelligent-router CalContractScore", + serialized_request, + "ContractScoreCalculator.FetchContractScore".to_string(), + ApiMethod::Grpc, + payment_id.get_string_repr().to_string(), + profile_id.to_owned(), + merchant_id.to_owned(), + state.request_id, + RoutingEngine::IntelligentRouter, + ); + let contract_based_connectors_result = client .calculate_contract_score( profile_id.get_string_repr().into(), @@ -2185,12 +2458,36 @@ pub async fn perform_contract_based_routing( state.get_grpc_headers(), ) .await + .inspect_err(|e| { + routing_event + .set_error(serde_json::json!({"error": e.current_context().to_string()})); + routing_event + .set_routing_approach(api_routing::RoutingApproach::ContractBased.to_string()); + state.event_handler().log_event(&routing_event); + }) .attach_printable( "unable to calculate/fetch contract score from dynamic routing service", ); let contract_based_connectors = match contract_based_connectors_result { - Ok(resp) => resp, + Ok(resp) => { + let event_response = api_routing::CalContractScoreEventResponse { + labels_with_score: resp + .labels_with_score + .iter() + .map(|label_with_score| api_routing::ScoreDataEventResponse { + score: label_with_score.score, + label: label_with_score.label.clone(), + current_count: label_with_score.current_count, + }) + .collect(), + }; + + routing_event.set_response_body(&event_response); + routing_event + .set_routing_approach(api_routing::RoutingApproach::ContractBased.to_string()); + resp + } Err(err) => match err.current_context() { DynamicRoutingError::ContractNotFound => { client @@ -2255,6 +2552,10 @@ pub async fn perform_contract_based_routing( connectors.append(&mut other_connectors); logger::debug!(contract_based_routing_connectors=?connectors); + + routing_event.set_status_code(200); + routing_event.set_routable_connectors(connectors.clone()); + state.event_handler().log_event(&routing_event); Ok(connectors) } else { Ok(routable_connectors) diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 7ba06ff5e0e..4798cce9b02 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -28,6 +28,8 @@ use external_services::grpc_client::dynamic_routing::{ }; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use hyperswitch_domain_models::api::ApplicationResponse; +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +use hyperswitch_interfaces::events::routing_api_logs as routing_events; #[cfg(all(feature = "dynamic_routing", feature = "v1"))] use router_env::logger; #[cfg(all(feature = "dynamic_routing", feature = "v1"))] @@ -57,6 +59,7 @@ use crate::{ payments::routing::utils::{self as routing_utils, DecisionEngineApiHandler}, routing, }, + routes::app::SessionStateInfo, services, types::transformers::ForeignInto, }; @@ -822,6 +825,7 @@ pub async fn update_gateway_score_helper_with_open_router( state, routable_connector.clone(), profile_id, + &payment_attempt.merchant_id, &payment_attempt.payment_id, payment_attempt.status, ) @@ -1087,23 +1091,80 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( .attach_printable("Unable to push dynamic routing stats to db")?; }; - client + let label_with_status = routing_types::UpdateLabelWithStatusEventRequest { + label: routable_connector.clone().to_string(), + status: payment_status_attribute == common_enums::AttemptStatus::Charged, + }; + let event_request = routing_types::UpdateSuccessRateWindowEventRequest { + id: payment_attempt.profile_id.get_string_repr().to_string(), + params: success_based_routing_config_params.clone(), + labels_with_status: vec![label_with_status.clone()], + global_labels_with_status: vec![label_with_status], + config: success_based_routing_configs.config.as_ref().map(|conf| { + routing_types::UpdateSuccessRateWindowConfig { + max_aggregates_size: conf.max_aggregates_size, + current_block_threshold: conf.current_block_threshold.clone(), + } + }), + }; + + let serialized_request = serde_json::to_value(&event_request) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to serialize success_based_routing_config_params")?; + + let mut routing_event = routing_events::RoutingEvent::new( + state.tenant.tenant_id.clone(), + "".to_string(), + "Intelligent-router UpdateSuccessRateWindow", + serialized_request, + "SuccessRateCalculator.UpdateSuccessRateWindow".to_string(), + routing_events::ApiMethod::Grpc, + payment_attempt.payment_id.get_string_repr().to_string(), + profile_id.to_owned(), + payment_attempt.merchant_id.to_owned(), + state.request_id, + routing_events::RoutingEngine::IntelligentRouter, + ); + + let update_response = client .update_success_rate( profile_id.get_string_repr().into(), success_based_routing_configs, success_based_routing_config_params, vec![routing_types::RoutableConnectorChoiceWithStatus::new( - routable_connector, + routable_connector.clone(), payment_status_attribute == common_enums::AttemptStatus::Charged, )], state.get_grpc_headers(), ) .await + .inspect_err(|e| { + routing_event + .set_error(serde_json::json!({"error": e.current_context().to_string()})); + state.event_handler().log_event(&routing_event); + }) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "unable to update success based routing window in dynamic routing service", )?; + let event_response = routing_types::UpdateSuccessRateWindowEventResponse { + status: match update_response.status { + 0 => routing_types::UpdationStatusEventResponse::WindowUpdationSucceeded, + 1 => routing_types::UpdationStatusEventResponse::WindowUpdationFailed, + _ => { + return Err(errors::ApiErrorResponse::InternalServerError) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unknown status code from dynamic routing service") + } + }, + }; + + routing_event.set_response_body(&event_response); + routing_event.set_status_code(200); + routing_event.set_payment_connector(routable_connector); + state.event_handler().log_event(&routing_event); + Ok(()) } else { Ok(()) @@ -1171,32 +1232,99 @@ pub async fn update_window_for_elimination_routing( .change_context(errors::ApiErrorResponse::InternalServerError)?, ); - client + let labels_with_bucket_name = + vec![routing_types::RoutableConnectorChoiceWithBucketName::new( + routing_types::RoutableConnectorChoice { + choice_kind: api_models::routing::RoutableChoiceKind::FullStruct, + connector: common_enums::RoutableConnectors::from_str( + payment_connector.as_str(), + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to infer routable_connector from connector")?, + merchant_connector_id: payment_attempt.merchant_connector_id.clone(), + }, + gsm_error_category.to_string(), + )]; + + let event_request = routing_types::UpdateEliminationBucketEventRequest { + id: profile_id.get_string_repr().to_string(), + params: elimination_routing_config_params.clone(), + labels_with_bucket_name: labels_with_bucket_name + .iter() + .map( + |conn_choice| routing_types::LabelWithBucketNameEventRequest { + label: conn_choice.routable_connector_choice.to_string(), + bucket_name: conn_choice.bucket_name.clone(), + }, + ) + .collect(), + config: elimination_routing_config + .elimination_analyser_config + .map(|conf| routing_types::EliminationRoutingEventBucketConfig { + bucket_leak_interval_in_secs: conf.bucket_leak_interval_in_secs, + bucket_size: conf.bucket_size, + }), + }; + + let serialized_request = serde_json::to_value(&event_request) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to serialize success_based_routing_config_params")?; + + let mut routing_event = routing_events::RoutingEvent::new( + state.tenant.tenant_id.clone(), + "".to_string(), + "Intelligent-router UpdateEliminationBucket", + serialized_request, + "EliminationAnalyser.UpdateEliminationBucket".to_string(), + routing_events::ApiMethod::Grpc, + payment_attempt.payment_id.get_string_repr().to_string(), + profile_id.to_owned(), + payment_attempt.merchant_id.to_owned(), + state.request_id, + routing_events::RoutingEngine::IntelligentRouter, + ); + + let update_response = client .update_elimination_bucket_config( profile_id.get_string_repr().to_string(), elimination_routing_config_params, - vec![routing_types::RoutableConnectorChoiceWithBucketName::new( - routing_types::RoutableConnectorChoice { - choice_kind: api_models::routing::RoutableChoiceKind::FullStruct, - connector: common_enums::RoutableConnectors::from_str( - payment_connector.as_str(), - ) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable( - "unable to infer routable_connector from connector", - )?, - merchant_connector_id: payment_attempt.merchant_connector_id.clone(), - }, - gsm_error_category.to_string(), - )], + labels_with_bucket_name, elimination_routing_config.elimination_analyser_config, state.get_grpc_headers(), ) .await + .inspect_err(|e| { + routing_event + .set_error(serde_json::json!({"error": e.current_context().to_string()})); + state.event_handler().log_event(&routing_event); + }) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "unable to update elimination based routing buckets in dynamic routing service", )?; + + let event_response = routing_types::UpdateEliminationBucketEventResponse { + status: match update_response.status { + 0 => routing_types::EliminationUpdationStatusEventResponse::BucketUpdationSucceeded, + 1 => routing_types::EliminationUpdationStatusEventResponse::BucketUpdationFailed, + _ => { + return Err(errors::ApiErrorResponse::InternalServerError) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unknown status code from dynamic routing service") + } + }, + }; + + routing_event.set_response_body(&event_response); + routing_event.set_status_code(200); + routing_event.set_payment_connector(routing_types::RoutableConnectorChoice { + choice_kind: api_models::routing::RoutableChoiceKind::FullStruct, + connector: common_enums::RoutableConnectors::from_str(payment_connector.as_str()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to infer routable_connector from connector")?, + merchant_connector_id: payment_attempt.merchant_connector_id.clone(), + }); + state.event_handler().log_event(&routing_event); Ok(()) } else { Ok(()) @@ -1295,7 +1423,36 @@ pub async fn push_metrics_with_update_window_for_contract_based_routing( get_desired_payment_status_for_dynamic_routing_metrics(payment_attempt.status); if payment_status_attribute == common_enums::AttemptStatus::Charged { - client + let event_request = routing_types::UpdateContractRequestEventRequest { + id: profile_id.get_string_repr().to_string(), + params: "".to_string(), + labels_information: vec![routing_types::ContractLabelInformationEventRequest { + label: request_label_info.label.clone(), + target_count: request_label_info.target_count, + target_time: request_label_info.target_time, + current_count: 1, + }], + }; + + let serialized_request = serde_json::to_value(&event_request) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to serialize success_based_routing_config_params")?; + + let mut routing_event = routing_events::RoutingEvent::new( + state.tenant.tenant_id.clone(), + "".to_string(), + "Intelligent-router UpdateContract", + serialized_request, + "ContractScoreCalculator.UpdateContract".to_string(), + routing_events::ApiMethod::Grpc, + payment_attempt.payment_id.get_string_repr().to_string(), + profile_id.to_owned(), + payment_attempt.merchant_id.to_owned(), + state.request_id, + routing_events::RoutingEngine::IntelligentRouter, + ); + + let update_respose = client .update_contracts( profile_id.get_string_repr().into(), vec![request_label_info], @@ -1305,10 +1462,41 @@ pub async fn push_metrics_with_update_window_for_contract_based_routing( state.get_grpc_headers(), ) .await + .inspect_err(|e| { + routing_event.set_error( + serde_json::json!({"error": e.current_context().to_string()}), + ); + state.event_handler().log_event(&routing_event); + }) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "unable to update contract based routing window in dynamic routing service", )?; + + let event_response = routing_types::UpdateContractEventResponse { + status: match update_respose.status { + 0 => routing_types::ContractUpdationStatusEventResponse::ContractUpdationSucceeded, + 1 => routing_types::ContractUpdationStatusEventResponse::ContractUpdationFailed, + _ => { + return Err(errors::ApiErrorResponse::InternalServerError) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unknown status code from dynamic routing service") + } + }, + }; + + routing_event.set_response_body(&event_response); + routing_event.set_payment_connector(routing_types::RoutableConnectorChoice { + choice_kind: api_models::routing::RoutableChoiceKind::FullStruct, + connector: common_enums::RoutableConnectors::from_str( + final_label_info.label.as_str(), + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to infer routable_connector from connector")?, + merchant_connector_id: Some(final_label_info.mca_id.clone()), + }); + routing_event.set_status_code(200); + state.event_handler().log_event(&routing_event); } let contract_based_connectors = routable_connectors diff --git a/crates/router/src/events.rs b/crates/router/src/events.rs index 19aa2cbfaa5..7d77df6871f 100644 --- a/crates/router/src/events.rs +++ b/crates/router/src/events.rs @@ -21,6 +21,7 @@ pub mod audit_events; pub mod connector_api_logs; pub mod event_logger; pub mod outgoing_webhook_logs; +pub mod routing_api_logs; #[derive(Debug, Serialize, Clone, Copy)] #[serde(rename_all = "snake_case")] pub enum EventType { @@ -37,6 +38,7 @@ pub enum EventType { Payout, Consolidated, Authentication, + RoutingApiLogs, } #[derive(Debug, Default, Deserialize, Clone)] diff --git a/crates/router/src/events/routing_api_logs.rs b/crates/router/src/events/routing_api_logs.rs new file mode 100644 index 00000000000..9edfe0ea009 --- /dev/null +++ b/crates/router/src/events/routing_api_logs.rs @@ -0,0 +1,19 @@ +pub use hyperswitch_interfaces::events::routing_api_logs::RoutingEvent; + +use super::EventType; +use crate::services::kafka::KafkaMessage; + +impl KafkaMessage for RoutingEvent { + fn event_type(&self) -> EventType { + EventType::RoutingApiLogs + } + + fn key(&self) -> String { + format!( + "{}-{}-{}", + self.get_merchant_id(), + self.get_profile_id(), + self.get_payment_id() + ) + } +} diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs index 91968510a6b..d1ea929cc8c 100644 --- a/crates/router/src/services/kafka.rs +++ b/crates/router/src/services/kafka.rs @@ -161,6 +161,7 @@ pub struct KafkaSettings { payout_analytics_topic: String, consolidated_events_topic: String, authentication_analytics_topic: String, + routing_logs_topic: String, } impl KafkaSettings { @@ -248,6 +249,12 @@ impl KafkaSettings { }, )?; + common_utils::fp_utils::when(self.routing_logs_topic.is_default_or_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "Kafka Routing Logs topic must not be empty".into(), + )) + })?; + Ok(()) } } @@ -269,6 +276,7 @@ pub struct KafkaProducer { consolidated_events_topic: String, authentication_analytics_topic: String, ckh_database_name: Option<String>, + routing_logs_topic: String, } struct RdKafkaProducer(ThreadedProducer<DefaultProducerContext>); @@ -318,6 +326,7 @@ impl KafkaProducer { consolidated_events_topic: conf.consolidated_events_topic.clone(), authentication_analytics_topic: conf.authentication_analytics_topic.clone(), ckh_database_name: None, + routing_logs_topic: conf.routing_logs_topic.clone(), }) } @@ -653,6 +662,7 @@ impl KafkaProducer { EventType::Payout => &self.payout_analytics_topic, EventType::Consolidated => &self.consolidated_events_topic, EventType::Authentication => &self.authentication_analytics_topic, + EventType::RoutingApiLogs => &self.routing_logs_topic, } } }
2025-05-30T11:58:03Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Audit trail for SR based Routing ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [x] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. toggle SR routing for profile 2. Create a payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_Gu8sdLTO7Dn8raa0FLbX0phVxHwt69RDLxBmgWoLbFv3ixqmVFflLtev8l7f2NC5' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "profile_id": "pro_UYcyDxGOM9D5oFeOmmKg", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` 3. Events should be looged in kafka <img width="1527" alt="image" src="https://github.com/user-attachments/assets/7f09177e-65bb-4d34-bdee-673c193cab45" /> <img width="1728" alt="image" src="https://github.com/user-attachments/assets/cda8a8ca-3dc4-46a2-8d69-3ba7ab91864c" /> <img width="1728" alt="image" src="https://github.com/user-attachments/assets/d8ef3d6d-5941-454b-bb13-7a5fa57aa739" /> <img width="1539" alt="image" src="https://github.com/user-attachments/assets/bbe3599b-d2b1-496d-8f17-fdf929cb1942" /> 4. Hit analytics API for routing events ``` curl -H "api-key: dev_Gu8sdLTO7Dn8raa0FLbX0phVxHwt69RDLxBmgWoLbFv3ixqmVFflLtev8l7f2NC5" "http://localhost:8080/analytics/v1/profile/routing_event_logs?type=Payment&payment_id=pay_PVNCC0PnqoNhXX3yYmys" ``` Resp - ``` [{"merchant_id":"merchant_1748353653","profile_id":"pro_UYcyDxGOM9D5oFeOmmKg","payment_id":"pay_PVNCC0PnqoNhXX3yYmys","routable_connectors":"Stripe:\"mca_XOZVhisCXtszQdEMLSU3\"","payment_connector":null,"request_id":"019731a5-cd02-79f1-8929-794ab94ecaec","flow":"Intelligent-router FetchSuccessRate","url":"SuccessRateCalculator.FetchSuccessRate","request":"{\"id\":\"pro_UYcyDxGOM9D5oFeOmmKg\",\"params\":\"card\",\"labels\":[\"stripe:mca_XOZVhisCXtszQdEMLSU3\"],\"config\":{\"min_aggregates_size\":5,\"default_success_rate\":100.0,\"specificity_level\":\"merchant\",\"exploration_percent\":null}}","response":"{\"labels_with_score\":[{\"score\":100.0,\"label\":\"stripe:mca_XOZVhisCXtszQdEMLSU3\"}],\"routing_apporach\":\"exploitation\"}","error":null,"status_code":200,"created_at":"2025-06-02T17:17:19.029Z","method":"Grpc","routing_engine":"intelligent_router"},{"merchant_id":"merchant_1748353653","profile_id":"pro_UYcyDxGOM9D5oFeOmmKg","payment_id":"pay_PVNCC0PnqoNhXX3yYmys","routable_connectors":"","payment_connector":"Stripe:\"mca_XOZVhisCXtszQdEMLSU3\"","request_id":"019731a5-cd02-79f1-8929-794ab94ecaec","flow":"Intelligent-router UpdateSuccessRateWindow","url":"SuccessRateCalculator.UpdateSuccessRateWindow","request":"{\"id\":\"pro_UYcyDxGOM9D5oFeOmmKg\",\"params\":\"card\",\"labels_with_status\":[{\"label\":\"stripe:mca_XOZVhisCXtszQdEMLSU3\",\"status\":true}],\"config\":{\"max_aggregates_size\":8,\"current_block_threshold\":{\"duration_in_mins\":null,\"max_total_count\":5}},\"global_labels_with_status\":[{\"label\":\"stripe:mca_XOZVhisCXtszQdEMLSU3\",\"status\":true}]}","response":"{\"status\":\"window_updation_succeeded\"}","error":null,"status_code":200,"created_at":"2025-06-02T17:17:20.604Z","method":"Grpc","routing_engine":"intelligent_router"}] ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
1eea83359c43e29f75caa92ad5fe2f22c8dc2829
1eea83359c43e29f75caa92ad5fe2f22c8dc2829
juspay/hyperswitch
juspay__hyperswitch-8196
Bug: refactor: add result type for Program ### Description This PR refactors the conversion from ast::Program<ConnectorSelection> to internal Program by introducing a fallible TryFrom implementation instead of an infallible From. This enables proper error propagation and logging during DSL conversion failures. Supporting conversion functions (convert_rule, convert_if_stmt, convert_comparison, convert_value) now return RoutingResult<T> instead of plain values, allowing fine-grained error handling throughout the conversion pipeline. Also, the core/routing.rs logic has been updated to handle these errors gracefully by logging and skipping invalid programs during routing algorithm creation.
diff --git a/crates/router/src/core/payments/routing/utils.rs b/crates/router/src/core/payments/routing/utils.rs index e82ab1d8bee..01d066e5cf2 100644 --- a/crates/router/src/core/payments/routing/utils.rs +++ b/crates/router/src/core/payments/routing/utils.rs @@ -1,6 +1,9 @@ use std::collections::{HashMap, HashSet}; -use api_models::routing as api_routing; +use api_models::{ + routing as api_routing, + routing::{ConnectorSelection, RoutableConnectorChoice}, +}; use async_trait::async_trait; use common_utils::id_type; use diesel_models::{enums, routing_algorithm}; @@ -712,48 +715,70 @@ impl From<RoutingAlgorithmRecord> for routing_algorithm::RoutingProfileMetadata } } } -use api_models::routing::{ConnectorSelection, RoutableConnectorChoice}; -impl From<ast::Program<ConnectorSelection>> for Program { - fn from(p: ast::Program<ConnectorSelection>) -> Self { - Self { + +impl TryFrom<ast::Program<ConnectorSelection>> for Program { + type Error = error_stack::Report<errors::RoutingError>; + + fn try_from(p: ast::Program<ConnectorSelection>) -> Result<Self, Self::Error> { + let rules = p + .rules + .into_iter() + .map(convert_rule) + .collect::<Result<Vec<_>, _>>()?; + + Ok(Self { globals: HashMap::new(), default_selection: convert_output(p.default_selection), - rules: p.rules.into_iter().map(convert_rule).collect(), + rules, metadata: Some(p.metadata), - } + }) } } -fn convert_rule(rule: ast::Rule<ConnectorSelection>) -> Rule { +fn convert_rule(rule: ast::Rule<ConnectorSelection>) -> RoutingResult<Rule> { let routing_type = match &rule.connector_selection { ConnectorSelection::Priority(_) => RoutingType::Priority, ConnectorSelection::VolumeSplit(_) => RoutingType::VolumeSplit, }; - Rule { + Ok(Rule { name: rule.name, routing_type, output: convert_output(rule.connector_selection), - statements: rule.statements.into_iter().map(convert_if_stmt).collect(), - } + statements: rule + .statements + .into_iter() + .map(convert_if_stmt) + .collect::<RoutingResult<Vec<IfStatement>>>()?, + }) } -fn convert_if_stmt(stmt: ast::IfStatement) -> IfStatement { - IfStatement { - condition: stmt.condition.into_iter().map(convert_comparison).collect(), +fn convert_if_stmt(stmt: ast::IfStatement) -> RoutingResult<IfStatement> { + Ok(IfStatement { + condition: stmt + .condition + .into_iter() + .map(convert_comparison) + .collect::<RoutingResult<Vec<Comparison>>>()?, + nested: stmt .nested - .map(|v| v.into_iter().map(convert_if_stmt).collect()), - } + .map(|v| { + v.into_iter() + .map(convert_if_stmt) + .collect::<RoutingResult<Vec<IfStatement>>>() + }) + .transpose()?, + }) } -fn convert_comparison(c: ast::Comparison) -> Comparison { - Comparison { +fn convert_comparison(c: ast::Comparison) -> RoutingResult<Comparison> { + Ok(Comparison { lhs: c.lhs, comparison: convert_comparison_type(c.comparison), - value: convert_value(c.value), + value: convert_value(c.value)?, metadata: c.metadata, - } + }) } fn convert_comparison_type(ct: ast::ComparisonType) -> ComparisonType { @@ -767,18 +792,21 @@ fn convert_comparison_type(ct: ast::ComparisonType) -> ComparisonType { } } -#[allow(clippy::unimplemented)] -fn convert_value(v: ast::ValueType) -> ValueType { +fn convert_value(v: ast::ValueType) -> RoutingResult<ValueType> { use ast::ValueType::*; match v { - Number(n) => ValueType::Number(n.get_amount_as_i64().try_into().unwrap_or_default()), - EnumVariant(e) => ValueType::EnumVariant(e), - MetadataVariant(m) => ValueType::MetadataVariant(MetadataValue { + Number(n) => Ok(ValueType::Number( + n.get_amount_as_i64().try_into().unwrap_or_default(), + )), + EnumVariant(e) => Ok(ValueType::EnumVariant(e)), + MetadataVariant(m) => Ok(ValueType::MetadataVariant(MetadataValue { key: m.key, value: m.value, - }), - StrValue(s) => ValueType::StrValue(s), - _ => unimplemented!(), // GlobalRef(r) => ValueType::GlobalRef(r), + })), + StrValue(s) => Ok(ValueType::StrValue(s)), + _ => Err(error_stack::Report::new( + errors::RoutingError::InvalidRoutingAlgorithmStructure, + )), } } diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs index 1811f43d51e..e8e87c895d5 100644 --- a/crates/router/src/core/routing.rs +++ b/crates/router/src/core/routing.rs @@ -340,26 +340,32 @@ pub async fn create_routing_algorithm_under_profile( let mut decision_engine_routing_id: Option<String> = None; if let Some(EuclidAlgorithm::Advanced(program)) = request.algorithm.clone() { - let internal_program: Program = program.into(); - let routing_rule = RoutingRule { - name: name.clone(), - description: Some(description.clone()), - created_by: profile_id.get_string_repr().to_string(), - algorithm: internal_program, - metadata: Some(RoutingMetadata { - kind: algorithm.get_kind().foreign_into(), - algorithm_for: transaction_type.to_owned(), - }), - }; - - decision_engine_routing_id = create_de_euclid_routing_algo(&state, &routing_rule) - .await - .map_err(|e| { + match program.try_into() { + Ok(internal_program) => { + let routing_rule = RoutingRule { + name: name.clone(), + description: Some(description.clone()), + created_by: profile_id.get_string_repr().to_string(), + algorithm: internal_program, + metadata: Some(RoutingMetadata { + kind: algorithm.get_kind().foreign_into(), + algorithm_for: transaction_type.to_owned(), + }), + }; + + decision_engine_routing_id = create_de_euclid_routing_algo(&state, &routing_rule) + .await + .map_err(|e| { + // errors are ignored as this is just for diff checking as of now (optional flow). + logger::error!(decision_engine_error=?e,decision_engine_euclid_request=?routing_rule, "failed to create rule in decision_engine"); + }) + .ok(); + } + Err(e) => { // errors are ignored as this is just for diff checking as of now (optional flow). logger::error!(decision_engine_error=?e, "decision_engine_euclid"); - logger::debug!(decision_engine_request=?routing_rule, "decision_engine_euclid"); - }) - .ok(); + } + }; } if decision_engine_routing_id.is_some() {
2025-05-29T13:30:56Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR refactors the conversion from `ast::Program<ConnectorSelection>` to internal `Program` by introducing a fallible `TryFrom` implementation instead of an infallible `From`. This enables proper error propagation and logging during DSL conversion failures. Supporting conversion functions (`convert_rule`, `convert_if_stmt`, `convert_comparison`, `convert_value`) now return `RoutingResult<T>` instead of plain values, allowing fine-grained error handling throughout the conversion pipeline. Also, the `core/routing.rs` logic has been updated to handle these errors gracefully by logging and skipping invalid programs during routing algorithm creation. --- ## Outcomes - Adds **robust error handling** for AST-to-internal structure conversion. - Improves **diagnostic logging** on conversion failures. - Prevents invalid DSL programs from entering routing configuration. - Adheres to idiomatic Rust usage with `TryFrom` and `Result`. --- ## Diff Hunk Explanation ### `crates/router/src/core/payments/routing/utils.rs` - Changed `impl From<ast::Program<ConnectorSelection>> for Program` to `TryFrom`, enabling `Result`-based error handling. - Functions `convert_rule`, `convert_if_stmt`, `convert_comparison`, and `convert_value` were updated to return `RoutingResult<T>`. - Explicit handling of unsupported `ValueType` variants in `convert_value` with an appropriate `RoutingError`. ### `crates/router/src/core/routing.rs` - Replaced direct `.into()` conversion with a `match` on `try_into()` to handle errors without panicking. - Logs any conversion errors using `logger::error!` and `logger::debug!`. - Ensures that the creation of routing algorithms is skipped if DSL conversion fails. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ``` curl --location 'http://127.0.0.1:8080/routing' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_IpYFqCd4DHf7x4ER1GBQrW0mHOZzam3pYyuP2tSRb6q7qvTw7jvEjF7UzjwFPXWu' \ --data ' { "name": "Priority rule with fallback", "description": "It is my ADVANCED config", "profile_id": "pro_INSNcGnV7dSldWXpW1GE", "algorithm": { "type": "advanced", "data": { "defaultSelection": { "type": "priority", "data": [ { "connector": "stripe", "merchant_connector_id": "mca_gtMC3BG1m6YTX0j8hwUU" } ] }, "rules": [ { "name": "cybersource first", "connectorSelection": { "type": "priority", "data": [ { "connector": "stripe", "merchant_connector_id": "mca_gtMC3BG1m6YTX0j8hwUU" } ] }, "statements": [ { "condition": [ { "lhs": "billing_country", "comparison": "equal", "value": { "type": "enum_variant", "value": "Netherlands" }, "metadata": {} }, { "lhs": "amount", "comparison": "greater_than", "value": { "type": "number_array", "value": [1000,2000] }, "metadata": {} } ], "nested": null } ] } ], "metadata": {} } } } ' ``` Response: ``` { "id": "routing_Ti6HxelZEfdijoVSPNXA", "profile_id": "pro_INSNcGnV7dSldWXpW1GE", "name": "Priority rule with fallback", "kind": "advanced", "description": "It is my ADVANCED config", "created_at": 1748515295, "modified_at": 1748515295, "algorithm_for": "payment", "decision_engine_routing_id": null } ``` The log should have this error type. <img width="1453" alt="Screenshot 2025-05-29 at 16 12 03" src="https://github.com/user-attachments/assets/a9001b64-e4ef-44ee-bc9d-63b66552971f" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
b8e7a868ade62ff21498203d9e14edae094071d9
b8e7a868ade62ff21498203d9e14edae094071d9
juspay/hyperswitch
juspay__hyperswitch-8208
Bug: [FIX] Add fallback connectors instead of active routing rule connectors if straight through connector is ineligible Add the fallback connectors to the list of eligible connectors instead of adding connectors configured in the active routing rule in case straight through connector is ineligible
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 0993a6eee3f..f9fea9cdfd7 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -6743,7 +6743,7 @@ where } if let Some(routing_algorithm) = request_straight_through { - let (connectors, check_eligibility) = routing::perform_straight_through_routing( + let (mut connectors, check_eligibility) = routing::perform_straight_through_routing( &routing_algorithm, payment_data.get_creds_identifier(), ) @@ -6751,34 +6751,58 @@ where .attach_printable("Failed execution of straight through routing")?; if check_eligibility { - let new_pd = payment_data.clone(); let transaction_data = core_routing::PaymentsDslInput::new( - new_pd.get_setup_mandate(), - new_pd.get_payment_attempt(), - new_pd.get_payment_intent(), - new_pd.get_payment_method_data(), - new_pd.get_address(), - new_pd.get_recurring_details(), - new_pd.get_currency(), + payment_data.get_setup_mandate(), + payment_data.get_payment_attempt(), + payment_data.get_payment_intent(), + payment_data.get_payment_method_data(), + payment_data.get_address(), + payment_data.get_recurring_details(), + payment_data.get_currency(), ); - return route_connector_v1_for_payments( - &state, - merchant_context, - business_profile, - payment_data, - transaction_data, - routing_data, + connectors = routing::perform_eligibility_analysis_with_fallback( + &state.clone(), + merchant_context.get_merchant_key_store(), + connectors, + &TransactionData::Payment(transaction_data), eligible_connectors, - mandate_type, - Some(connectors), + business_profile, ) - .await; + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed eligibility analysis and fallback")?; } + + let connector_data = connectors + .into_iter() + .map(|conn| { + api::ConnectorData::get_connector_by_name( + &state.conf.connectors, + &conn.connector.to_string(), + api::GetToken::Connector, + conn.merchant_connector_id.clone(), + ) + .map(|connector_data| connector_data.into()) + }) + .collect::<CustomResult<Vec<_>, _>>() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Invalid connector name received")?; + + return decide_multiplex_connector_for_normal_or_recurring_payment( + &state, + payment_data, + routing_data, + connector_data, + mandate_type, + business_profile.is_connector_agnostic_mit_enabled, + business_profile.is_network_tokenization_enabled, + ) + .await; } if let Some(ref routing_algorithm) = routing_data.routing_info.algorithm { - let (connectors, check_eligibility) = routing::perform_straight_through_routing( + let (mut connectors, check_eligibility) = routing::perform_straight_through_routing( routing_algorithm, payment_data.get_creds_identifier(), ) @@ -6786,30 +6810,54 @@ where .attach_printable("Failed execution of straight through routing")?; if check_eligibility { - let new_pd = payment_data.clone(); let transaction_data = core_routing::PaymentsDslInput::new( - new_pd.get_setup_mandate(), - new_pd.get_payment_attempt(), - new_pd.get_payment_intent(), - new_pd.get_payment_method_data(), - new_pd.get_address(), - new_pd.get_recurring_details(), - new_pd.get_currency(), + payment_data.get_setup_mandate(), + payment_data.get_payment_attempt(), + payment_data.get_payment_intent(), + payment_data.get_payment_method_data(), + payment_data.get_address(), + payment_data.get_recurring_details(), + payment_data.get_currency(), ); - return route_connector_v1_for_payments( + connectors = routing::perform_eligibility_analysis_with_fallback( &state, - merchant_context, - business_profile, - payment_data, - transaction_data, - routing_data, + merchant_context.get_merchant_key_store(), + connectors, + &TransactionData::Payment(transaction_data), eligible_connectors, - mandate_type, - Some(connectors), + business_profile, ) - .await; + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed eligibility analysis and fallback")?; } + + let connector_data = connectors + .into_iter() + .map(|conn| { + api::ConnectorData::get_connector_by_name( + &state.conf.connectors, + &conn.connector.to_string(), + api::GetToken::Connector, + conn.merchant_connector_id, + ) + .map(|connector_data| connector_data.into()) + }) + .collect::<CustomResult<Vec<_>, _>>() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Invalid connector name received")?; + + return decide_multiplex_connector_for_normal_or_recurring_payment( + &state, + payment_data, + routing_data, + connector_data, + mandate_type, + business_profile.is_connector_agnostic_mit_enabled, + business_profile.is_network_tokenization_enabled, + ) + .await; } let new_pd = payment_data.clone(); @@ -6832,7 +6880,6 @@ where routing_data, eligible_connectors, mandate_type, - None, ) .await } @@ -7411,7 +7458,6 @@ pub async fn route_connector_v1_for_payments<F, D>( routing_data: &mut storage::RoutingData, eligible_connectors: Option<Vec<enums::RoutableConnectors>>, mandate_type: Option<api::MandateTransactionType>, - connector_list: Option<Vec<api_models::routing::RoutableConnectorChoice>>, ) -> RouterResult<ConnectorCallType> where F: Send + Clone, @@ -7429,7 +7475,7 @@ where algorithm_ref.algorithm_id }; - let mut connectors = routing::perform_static_routing_v1( + let connectors = routing::perform_static_routing_v1( state, merchant_context.get_merchant_account().get_id(), routing_algorithm_id.as_ref(), @@ -7439,20 +7485,10 @@ where .await .change_context(errors::ApiErrorResponse::InternalServerError)?; - // adds straight through connectors to the list of connectors in the active routing algorithm - // and perform eligibility analysis on the combined set of connectors - - connectors = connector_list - .map(|mut straight_through_connectors| { - straight_through_connectors.extend(connectors.clone()); - straight_through_connectors - }) - .unwrap_or_else(|| connectors); - #[cfg(all(feature = "v1", feature = "dynamic_routing"))] let payment_attempt = transaction_data.payment_attempt.clone(); - connectors = routing::perform_eligibility_analysis_with_fallback( + let connectors = routing::perform_eligibility_analysis_with_fallback( &state.clone(), merchant_context.get_merchant_key_store(), connectors,
2025-06-02T13:24:17Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Reverts https://github.com/juspay/hyperswitch/pull/7921 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #8208 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Payment intent create ``` curl --location 'http://localhost:8080/vs/v1/payment_intents' \ --header 'Content-Type: application/x-www-form-urlencoded' \ --header 'User-Agent: helloMozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36' \ --header 'api-key: dev_OCEeDmYFnj7wCLjjWlBk0AsUthfnp3B041GM6Ef0Rl*****' \ --data-urlencode 'amount=5000' \ --data-urlencode 'currency=AED' \ --data-urlencode 'confirm=true' \ --data-urlencode 'payment_method_data%5Btype%5D=card' \ --data-urlencode 'payment_method_data%5Bcard%5D%5Bnumber%5D=4456530000001096' \ --data-urlencode 'payment_method_data%5Bcard%5D%5Bexp_month%5D=12' \ --data-urlencode 'payment_method_data%5Bcard%5D%5Bexp_year%5D=2030' \ --data-urlencode 'payment_method_data%5Bcard%5D%5Bcvc%5D=123' \ --data-urlencode 'connector%5B%5D=noon' \ --data-urlencode 'capture_method=automatic' \ --data-urlencode 'customer=sahkal' \ --data-urlencode 'statementDescriptorSuffix=merchant_101' \ --data-urlencode 'metadata%5BorderId%5D=1677581650' \ --data-urlencode 'payment_method_options%5Bcard%5D%5Brequest_three_d_secure%5D=automatic' \ --data-urlencode 'description=Card Payment' \ --data-urlencode 'off_session=true' \ --data-urlencode 'mandate_data%5Bcustomer_acceptance%5D%5Bonline%5D%5Buser_agent%5D=helloMozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36' \ --data-urlencode 'mandate_data%5Bcustomer_acceptance%5D%5Bonline%5D%5Bip_address%5D=123.32.25.123' \ --data-urlencode 'mandate_data%5Bamount%5D=20877' \ --data-urlencode 'setup_future_usage=off_session' \ --data-urlencode 'mandate_data%5Bmandate_type%5D=single_use' \ --data-urlencode 'mandate_data%5Bstart_date%5D=12127864781' \ --data-urlencode 'mandate_data%5Bend_date%5D=21312434324' \ --data-urlencode 'return_url=https://juspay.in' \ --data-urlencode 'merchant_connector_details%5Bencoded_data%5D=eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIn0.F1IBieprH7aT7fwe7p9ZtYdOv9JgoO87iALDjScYq9Y2H2yTvVEZLJ9aYs6ShMH3iieBdvwL7PwJ5k68qINzmHzKSYZ3cp5jGpyK5FjaoJu4zUAZbLcn-z4O6ajQ5OUZBjkqfkwo4SvQfM7ceg6_dLNbVa2dj9-YBp3pNfudc5eyKxIuvxDSmNSpoXr2Hr5Y2dDV5Z-15yfmcj-IDgZNibsUSSFuwqhHHfxk87HZRLM5-9kayXyfH4i_zdYleGR-iNX_OIzpJBpDeyJ_nbADgyi1NvBiNdDYiR-xCDuS0-DZZLVoOnJkbV23Q4XGkYRQSvI8VnWHKZhvqZi3-Nev7A.s4kCZx2KOzR50uoE.kdStc4m0EQ05J3nXd4EsxFgMj9Yp6Ji4JLRB7zjHGamjsMXwIBXhpFuexx58mqIueecXTOMz6nCjasgng8XKTKNBRsDshgFAzuO690--KQVIoSjADuRVuplTVgvg6xRaZN_cgdhfqo3DYS8MSALzoL0p1ylaAZuV_LGCJOLIcrhrP56xzmTX91tGHU3Dm1md.t-2pfHjICjZdya9g9WAxvQ' \ --data-urlencode 'merchant_connector_details%5Bcreds_identifier%5D=2025-06-04T08:02:45.485Z' \ --data-urlencode 'id=1749041986' \ --data-urlencode 'payment_method_data%5Bbilling_details%5D%5Bname%5D=sahkal' \ --data-urlencode 'payment_method_data%5Bbilling_details%5D%5Bemail%[email protected]' \ --data-urlencode 'payment_method_data%5Bbilling_details%5D%5Baddress%5D%5Bcity%5D=siliguri' \ --data-urlencode 'payment_method_data%5Bbilling_details%5D%5Baddress%5D%5Bcountry%5D=IN' \ --data-urlencode 'payment_method_data%5Bbilling_details%5D%5Baddress%5D%5Bstate%5D=westbengal' \ --data-urlencode 'payment_method_data%5Bbilling_details%5D%5Baddress%5D%5Bline1%5D=pritilata' \ --data-urlencode 'payment_method_data%5Bbilling_details%5D%5Baddress%5D%5Bzip%5D=734006' \ --data-urlencode 'metadata%5Btxn_Id%5D=sahkal_payment' \ --data-urlencode 'metadata%5BtxnUuid%5D=94hfdmoakosdkifdhaisl' \ --data-urlencode 'metadata%5Bmerchant_id%5D=sahkal' \ --data-urlencode 'metadata%5Beuler_merchant_id%5D=global_installment' \ --data-urlencode 'connector_metadata%5Bnoon%5D%5Border_category%5D=pay' \ --data-urlencode 'payment_method_data%5Bcard%5D%5Bholder_name%5D=sahkal' ``` 2. Payment Intent Sync request ``` curl --location 'http://localhost:8080/vs/v1/payment_intents/sync' \ --header 'Content-Type: application/x-www-form-urlencoded' \ --header 'idempodent-key: asfdasf' \ --header 'api-key: dev_OCEeDmYFnj7wCLjjWlBk0AsUthfnp3B041GM6Ef0RlN*****' \ --data-urlencode 'connector%5B%5D=noon' \ --data-urlencode 'merchant_connector_details%5Bencoded_data%5D=eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIn0.F1IBieprH7aT7fwe7p9ZtYdOv9JgoO87iALDjScYq9Y2H2yTvVEZLJ9aYs6ShMH3iieBdvwL7PwJ5k68qINzmHzKSYZ3cp5jGpyK5FjaoJu4zUAZbLcn-z4O6ajQ5OUZBjkqfkwo4SvQfM7ceg6_dLNbVa2dj9-YBp3pNfudc5eyKxIuvxDSmNSpoXr2Hr5Y2dDV5Z-15yfmcj-IDgZNibsUSSFuwqhHHfxk87HZRLM5-9kayXyfH4i_zdYleGR-iNX_OIzpJBpDeyJ_nbADgyi1NvBiNdDYiR-xCDuS0-DZZLVoOnJkbV23Q4XGkYRQSvI8VnWHKZhvqZi3-Nev7A.s4kCZx2KOzR50uoE.kdStc4m0EQ05J3nXd4EsxFgMj9Yp6Ji4JLRB7zjHGamjsMXwIBXhpFuexx58mqIueecXTOMz6nCjasgng8XKTKNBRsDshgFAzuO690--KQVIoSjADuRVuplTVgvg6xRaZN_cgdhfqo3DYS8MSALzoL0p1ylaAZuV_LGCJOLIcrhrP56xzmTX91tGHU3Dm1md.t-2pfHjICjZdya9g9WAxvQ' \ --data-urlencode 'payment_id=1749033737' \ --data-urlencode 'force_sync=true' \ --data-urlencode 'merchant_connector_details%5Bcreds_identifier%5D=2025-06-04T10:43:22.768Z' ``` response ``` { "id": "1749033737", "object": "payment_intent", "amount": 5000, "amount_received": 5000, "amount_capturable": 0, "currency": "aed", "status": "succeeded", "client_secret": "1749033737_secret_Peeso0sEVtUFnjSjN29z", "created": 1749033737, "customer": "sahkal", "refunds": null, "mandate": null, "metadata": { "txn_Id": "sahkal_payment", "orderId": "1677581650", "txnUuid": "94hfdmoakosdkifdhaisl", "merchant_id": "sahkal", "euler_merchant_id": "global_installment" }, "charges": { "object": "list", "data": [], "has_more": false, "total_count": 0, "url": "http://placeholder" }, "connector": "noon", "description": "Card Payment", "mandate_data": null, "setup_future_usage": "on_session", "off_session": true, "authentication_type": "no_three_ds", "next_action": null, "cancellation_reason": null, "payment_method": "card", "payment_method_data": { "card": { "last4": "1096", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "445653", "card_extended_bin": null, "card_exp_month": "12", "card_exp_year": "2030", "card_holder_name": "sahkal", "payment_checks": null, "authentication_data": null } }, "shipping": null, "billing": { "address": { "city": "siliguri", "country": "IN", "line1": "pritilata", "line2": null, "line3": null, "zip": null, "state": "westbengal", "first_name": null, "last_name": null }, "phone": { "number": null, "country_code": "IN" }, "email": "[email protected]" }, "capture_on": null, "payment_token": null, "email": null, "phone": null, "statement_descriptor_suffix": null, "statement_descriptor_name": null, "capture_method": "automatic", "name": null, "last_payment_error": null, "connector_transaction_id": "613939750950" } ``` --- Apple Pay payments request ``` curl --location 'http://localhost:3030/vs/v1/payment_intents' \ --header 'Content-Type: application/x-www-form-urlencoded' \ --header 'User-Agent: EULER' \ --header 'api-key: dev_y2wL6fotKxvIj7dUjOrkGqEV7zLUzzINbc0BkK1J0Vmx4****' \ --data-urlencode 'amount=1000' \ --data-urlencode 'currency=AED' \ --data-urlencode 'confirm=true' \ --data-urlencode 'payment_method_data%5Btype%5D=wallet' \ --data-urlencode 'connector%5B%5D=noon' \ --data-urlencode 'capture_method=automatic' \ --data-urlencode 'customer=sahkal' \ --data-urlencode 'statementDescriptorSuffix=merchant_101' \ --data-urlencode 'metadata%5BorderId%5D=1677581650' \ --data-urlencode 'payment_method_data%5Bbilling_details%5D%5Bname%5D=sahkal' \ --data-urlencode 'payment_method_data%5Bbilling_details%5D%5Bemail%[email protected]' \ --data-urlencode 'description=card Payment' \ --data-urlencode 'off_session=true' \ --data-urlencode 'merchant_connector_details%5Bencoded_data%5D=eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIn0.F1IBieprH7aT7fwe7p9ZtYdOv9JgoO87iALDjScYq9Y2H2yTvVEZLJ9aYs6ShMH3iieBdvwL7PwJ5k68qINzmHzKSYZ3cp5jGpyK5FjaoJu4zUAZbLcn-z4O6ajQ5OUZBjkqfkwo4SvQfM7ceg6_dLNbVa2dj9-YBp3pNfudc5eyKxIuvxDSmNSpoXr2Hr5Y2dDV5Z-15yfmcj-IDgZNibsUSSFuwqhHHfxk87HZRLM5-9kayXyfH4i_zdYleGR-iNX_OIzpJBpDeyJ_nbADgyi1NvBiNdDYiR-xCDuS0-DZZLVoOnJkbV23Q4XGkYRQSvI8VnWHKZhvqZi3-Nev7A.s4kCZx2KOzR50uoE.kdStc4m0EQ05J3nXd4EsxFgMj9Yp6Ji4JLRB7zjHGamjsMXwIBXhpFuexx58mqIueecXTOMz6nCjasgng8XKTKNBRsDshgFAzuO690--KQVIoSjADuRVuplTVgvg6xRaZN_cgdhfqo3DYS8MSALzoL0p1ylaAZuV_LGCJOLIcrhrP56xzmTX91tGHU3Dm1md.t-2pfHjICjZdya9g9WAxvQ' \ --data-urlencode 'merchant_connector_details%5Bcreds_identifier%5D=EulerTest' \ --data-urlencode 'payment_method_data%5Bwallet%5D%5Bapple_pay%5D%5Bpayment_data%5D=eyJkYXRhIjoiUnZRZytEMEVsTElTREpqdFpkbXAxa05QVW9zdWY5ODk1ZDVUK0cvb1pNckRaY2ZXNXdkb1Y0SVBwWHdrRnJaS25LYlhNUktXVVJiNHJua3lZV01UKzRJL01Sc0tNaSt6KzFWbjFGYitQeldVUFErZlNsSUNUMWhTWkxkTDlnOEZGb091S2xQMW8rT0xhSjAyYWlVTVpXYnpFRDlVTVY5ckllWlU5M1pIa3g4Vm1Vdmxkd0hoSEFBVzRBUkFzNDAyaXRReTRYNHNIeEIxWG8xWUtTWUZOWlR1cEFDYnBrQk5QT3JFK1k4OStxdUhDVGtTbDJxL1hVL3hNcUJYcXR1MjJFQTdGMWRHQzBVVDZLV0FvcGpsSUFtMHdHZ1FGRUYvTlJseFlUVFBkd1NKOUV1SHlhbmtrYkZib2VBWk5vdUFtNHplYmw1czlyWG5ZZ3BjT0ZWckxzQjN0OW1tdmhEZEdNYkZJc21oY2o2Ni9OWEplRkR6alM4NG0wK3NVVXZGbWlxMWZ5ZGt0TW9xS1dmbGpnPT0iLCJzaWduYXR1cmUiOiJNSUFHQ1NxR1NJYjNEUUVIQXFDQU1JQUNBUUV4RFRBTEJnbGdoa2dCWlFNRUFnRXdnQVlKS29aSWh2Y05BUWNCQUFDZ2dEQ0NBK013Z2dPSW9BTUNBUUlDQ0V3d1FVbFJuVlEyTUFvR0NDcUdTTTQ5QkFNQ01Ib3hMakFzQmdOVkJBTU1KVUZ3Y0d4bElFRndjR3hwWTJGMGFXOXVJRWx1ZEdWbmNtRjBhVzl1SUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHhPVEExTVRnd01UTXlOVGRhRncweU5EQTFNVFl3TVRNeU5UZGFNRjh4SlRBakJnTlZCQU1NSEdWall5MXpiWEF0WW5KdmEyVnlMWE5wWjI1ZlZVTTBMVkJTVDBReEZEQVNCZ05WQkFzTUMybFBVeUJUZVhOMFpXMXpNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV6QlpNQk1HQnlxR1NNNDlBZ0VHQ0NxR1NNNDlBd0VIQTBJQUJNSVZkKzNyMXNleUlZOW8zWENRb1NHTng3QzlieXdvUFlSZ2xkbEs5S1ZCRzROQ0R0Z1I4MEIrZ3pNZkhGVEQ5K3N5SU5hNjFkVHY5SktKaVQ1OER4T2pnZ0lSTUlJQ0RUQU1CZ05WSFJNQkFmOEVBakFBTUI4R0ExVWRJd1FZTUJhQUZDUHlTY1JQaytUdkorYkU5aWhzUDZLNy9TNUxNRVVHQ0NzR0FRVUZCd0VCQkRrd056QTFCZ2dyQmdFRkJRY3dBWVlwYUhSMGNEb3ZMMjlqYzNBdVlYQndiR1V1WTI5dEwyOWpjM0F3TkMxaGNIQnNaV0ZwWTJFek1ESXdnZ0VkQmdOVkhTQUVnZ0VVTUlJQkVEQ0NBUXdHQ1NxR1NJYjNZMlFGQVRDQi9qQ0J3d1lJS3dZQkJRVUhBZ0l3Z2JZTWdiTlNaV3hwWVc1alpTQnZiaUIwYUdseklHTmxjblJwWm1sallYUmxJR0o1SUdGdWVTQndZWEowZVNCaGMzTjFiV1Z6SUdGalkyVndkR0Z1WTJVZ2IyWWdkR2hsSUhSb1pXNGdZWEJ3YkdsallXSnNaU0J6ZEdGdVpHRnlaQ0IwWlhKdGN5QmhibVFnWTI5dVpHbDBhVzl1Y3lCdlppQjFjMlVzSUdObGNuUnBabWxqWVhSbElIQnZiR2xqZVNCaGJtUWdZMlZ5ZEdsbWFXTmhkR2x2YmlCd2NtRmpkR2xqWlNCemRHRjBaVzFsYm5SekxqQTJCZ2dyQmdFRkJRY0NBUllxYUhSMGNEb3ZMM2QzZHk1aGNIQnNaUzVqYjIwdlkyVnlkR2xtYVdOaGRHVmhkWFJvYjNKcGRIa3ZNRFFHQTFVZEh3UXRNQ3N3S2FBbm9DV0dJMmgwZEhBNkx5OWpjbXd1WVhCd2JHVXVZMjl0TDJGd2NHeGxZV2xqWVRNdVkzSnNNQjBHQTFVZERnUVdCQlNVVjl0djFYU0Job21KZGk5K1Y0VUg1NXRZSkRBT0JnTlZIUThCQWY4RUJBTUNCNEF3RHdZSktvWklodmRqWkFZZEJBSUZBREFLQmdncWhrak9QUVFEQWdOSkFEQkdBaUVBdmdsWEgrY2VIbk5iVmVXdnJMVEhMK3RFWHpBWVVpTEhKUkFDdGg2OWIxVUNJUURSaXpVS1hkYmRickYwWURXeEhyTE9oOCtqNXE5c3ZZT0FpUTNJTE4ycVl6Q0NBdTR3Z2dKMW9BTUNBUUlDQ0VsdEw3ODZtTnFYTUFvR0NDcUdTTTQ5QkFNQ01HY3hHekFaQmdOVkJBTU1Fa0Z3Y0d4bElGSnZiM1FnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUI0WERURTBNRFV3TmpJek5EWXpNRm9YRFRJNU1EVXdOakl6TkRZek1Gb3dlakV1TUN3R0ExVUVBd3dsUVhCd2JHVWdRWEJ3YkdsallYUnBiMjRnU1c1MFpXZHlZWFJwYjI0Z1EwRWdMU0JITXpFbU1DUUdBMVVFQ3d3ZFFYQndiR1VnUTJWeWRHbG1hV05oZEdsdmJpQkJkWFJvYjNKcGRIa3hFekFSQmdOVkJBb01Da0Z3Y0d4bElFbHVZeTR4Q3pBSkJnTlZCQVlUQWxWVE1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRThCY1JoQm5YWklYVkdsNGxnUWQyNklDaTc5NTdyazNnamZ4TGsrRXpWdFZtV3pXdUl0Q1hkZzBpVG51NkNQMTJGODZJeTNhN1puQyt5T2dwaFA5VVJhT0I5ekNCOURCR0JnZ3JCZ0VGQlFjQkFRUTZNRGd3TmdZSUt3WUJCUVVITUFHR0ttaDBkSEE2THk5dlkzTndMbUZ3Y0d4bExtTnZiUzl2WTNOd01EUXRZWEJ3YkdWeWIyOTBZMkZuTXpBZEJnTlZIUTRFRmdRVUkvSkp4RStUNU84bjVzVDJLR3cvb3J2OUxrc3dEd1lEVlIwVEFRSC9CQVV3QXdFQi96QWZCZ05WSFNNRUdEQVdnQlM3c042aFdET0ltcVNLbWQ2K3ZldXYyc3NrcXpBM0JnTlZIUjhFTURBdU1DeWdLcUFvaGlab2RIUndPaTh2WTNKc0xtRndjR3hsTG1OdmJTOWhjSEJzWlhKdmIzUmpZV2N6TG1OeWJEQU9CZ05WSFE4QkFmOEVCQU1DQVFZd0VBWUtLb1pJaHZkalpBWUNEZ1FDQlFBd0NnWUlLb1pJemowRUF3SURad0F3WkFJd09zOXlnMUVXbWJHRyt6WERWc3Bpdi9RWDdka1BkVTJpanI3eG5JRmVRcmVKK0pqM20xbWZtTlZCRFkrZDZjTCtBakF5TGRWRUliQ2pCWGRzWGZNNE81Qm4vUmQ4TENGdGxrL0djbW1DRW05VStIcDlHNW5MbXdtSklXRUdtUThKa2gwQUFER0NBWWd3Z2dHRUFnRUJNSUdHTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVd0lJVERCQlNWR2RWRFl3Q3dZSllJWklBV1VEQkFJQm9JR1RNQmdHQ1NxR1NJYjNEUUVKQXpFTEJna3Foa2lHOXcwQkJ3RXdIQVlKS29aSWh2Y05BUWtGTVE4WERUSXpNRFV4T1RFeU5UUXpNVm93S0FZSktvWklodmNOQVFrME1Sc3dHVEFMQmdsZ2hrZ0JaUU1FQWdHaENnWUlLb1pJemowRUF3SXdMd1lKS29aSWh2Y05BUWtFTVNJRUlIYmttRnArVC8zeVhJczl5Y0hmdzJvZy9sdk0vY0hrd2xaeFZEc2NUV3NLTUFvR0NDcUdTTTQ5QkFNQ0JFY3dSUUlnZk1DK1N0TmVxWW1GV2hUY1oxVmluMHF1bEk0UkZoenoreTlSQjFLSjRONENJUURsSk42V1VqS25sTjVKaks3bUYxMGR4WW40WFZpcjFvcC9VWWFBVkRsdmJnQUFBQUFBQUE9PSIsImhlYWRlciI6eyJwdWJsaWNLZXlIYXNoIjoibncwNDN0SFRhSjhTRWc0R1F1aFhvYzUwcWxCdlM2M2Y2L1d3dmlhZFFUaz0iLCJlcGhlbWVyYWxQdWJsaWNLZXkiOiJNRmt3RXdZSEtvWkl6ajBDQVFZSUtvWkl6ajBEQVFjRFFnQUVrWW1PbWtSZGtac2w2QkFSZ2l0T043bTZFdlBER3FLWjZjRTB5elFJQ0kwUGdmc212Z2dveisvcnU5MGlTNklNeVBmN01Jek1mYUJId295ODRPOWtkZz09IiwidHJhbnNhY3Rpb25JZCI6IjU0OWJiOWEwNThmYjUxNGFiMWQ0ODZjNWMwZmU4NjlmZTlkYjg3MWUxNWY5M2Q3MWE3YTIwMzQxZjU1OTY0ZjQifSwidmVyc2lvbiI6IkVDX3YxIn0=' \ --data-urlencode 'payment_method_data%5Bwallet%5D%5Bapple_pay%5D%5Bpayment_method%5D%5Bdisplay_name%5D=MasterCard 0049' \ --data-urlencode 'payment_method_data%5Bwallet%5D%5Bapple_pay%5D%5Bpayment_method%5D%5Bnetwork%5D=MasterCard ' \ --data-urlencode 'payment_method_data%5Bwallet%5D%5Bapple_pay%5D%5Bpayment_method%5D%5Btype%5D=credit' \ --data-urlencode 'payment_method_data%5Bwallet%5D%5Bapple_pay%5D%5Btransaction_identifier%5D=549BB9A058FB514AB1D486C5C0FE869FE9DB871E15F93D71A7A20341F55964F4' \ --data-urlencode 'id=1749052094' \ --data-urlencode 'payment_method_types=apple_pay' \ --data-urlencode 'connector_metadata%5Bnoon%5D%5Border_category%5D=pay' ``` response ``` { "id": "1749051940", "object": "payment_intent", "amount": 1000, "amount_received": null, "amount_capturable": 0, "currency": "aed", "status": "canceled", "client_secret": "1749051940_secret_0sTFsA7eoUGpFgclZWsg", "created": 1749051940, "customer": "sahkal", "refunds": null, "mandate": null, "metadata": { "orderId": "1677581650" }, "charges": { "object": "list", "data": [], "has_more": false, "total_count": 0, "url": "http://placeholder" }, "connector": "noon", "description": "card Payment", "mandate_data": null, "setup_future_usage": null, "off_session": true, "authentication_type": "no_three_ds", "next_action": null, "cancellation_reason": null, "payment_method": "wallet", "payment_method_data": { "wallet": { "apple_pay": { "last4": "0049", "card_network": "MasterCard ", "type": "credit" } } }, "shipping": null, "billing": { "address": null, "phone": null, "email": "[email protected]" }, "capture_on": null, "payment_token": null, "email": null, "phone": null, "statement_descriptor_suffix": null, "statement_descriptor_name": null, "capture_method": "automatic", "name": null, "last_payment_error": { "charge": null, "code": "16200", "decline_code": null, "message": "Request data is not valid.", "param": null, "payment_method": { "id": "place_holder_id", "object": "payment_method", "card": null, "created": 1749051941, "type": "card", "livemode": false }, "type": "16200" }, "connector_transaction_id": null } ``` apple pay for noon cannot be tested since we need to raise query to their support. But we are able to go to the connector without raising any core error. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
33cd60e64288b2a6bb24cc27b9d319fdbeab46ef
33cd60e64288b2a6bb24cc27b9d319fdbeab46ef
juspay/hyperswitch
juspay__hyperswitch-8203
Bug: [CHORE] Bump Cypress dependencies Current versions are out dated.
2025-06-02T07:43:48Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [x] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR bumps Cypress and its dependencies to its latest versions. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> closes https://github.com/juspay/hyperswitch/issues/8203 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> CI should pass. ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
dbca363f44c0dbce277a337d64dfb82741d423c4
dbca363f44c0dbce277a337d64dfb82741d423c4
juspay/hyperswitch
juspay__hyperswitch-8190
Bug: refactor(dynamic_routing): add logic for creating merchant account in decision engine
diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index 46cd37bc68a..a5448b563b1 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -608,6 +608,8 @@ pub struct DynamicRoutingAlgorithmRef { pub dynamic_routing_volume_split: Option<u8>, pub elimination_routing_algorithm: Option<EliminationRoutingAlgorithm>, pub contract_based_routing: Option<ContractRoutingAlgorithm>, + #[serde(default)] + pub is_merchant_created_in_decision_engine: bool, } pub trait DynamicRoutingAlgoAccessor { @@ -717,6 +719,10 @@ impl DynamicRoutingAlgorithmRef { self.dynamic_routing_volume_split = volume } + pub fn update_merchant_creation_status_in_decision_engine(&mut self, is_created: bool) { + self.is_merchant_created_in_decision_engine = is_created; + } + pub fn is_success_rate_routing_enabled(&self) -> bool { self.success_based_algorithm .as_ref() diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 942a659dcc1..13c219e7eba 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -264,26 +264,6 @@ pub async fn create_merchant_account( .await .to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount)?; - // Call to DE here - // Check if creation should be based on default profile - #[cfg(all(feature = "dynamic_routing", feature = "v1"))] - { - if state.conf.open_router.enabled { - merchant_account - .default_profile - .as_ref() - .async_map(|profile_id| { - routing::helpers::create_decision_engine_merchant(&state, profile_id) - }) - .await - .transpose() - .map_err(|err| { - crate::logger::error!("Failed to create merchant in Decision Engine {err:?}"); - }) - .ok(); - } - } - let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( merchant_account.clone(), key_store.clone(), @@ -3904,6 +3884,22 @@ impl ProfileCreateBridge for api::ProfileCreate { .map(CardTestingGuardConfig::foreign_from) .or(Some(CardTestingGuardConfig::default())); + let mut dynamic_routing_algorithm_ref = + routing_types::DynamicRoutingAlgorithmRef::default(); + + if self.is_debit_routing_enabled == Some(true) { + routing::helpers::create_merchant_in_decision_engine_if_not_exists( + state, + &profile_id, + &mut dynamic_routing_algorithm_ref, + ) + .await; + } + + let dynamic_routing_algorithm = serde_json::to_value(dynamic_routing_algorithm_ref) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("error serializing dynamic_routing_algorithm_ref to JSON Value")?; + Ok(domain::Profile::from(domain::ProfileSetter { profile_id, merchant_id: merchant_context.get_merchant_account().get_id().clone(), @@ -3981,7 +3977,7 @@ impl ProfileCreateBridge for api::ProfileCreate { .always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector: self .always_collect_shipping_details_from_wallet_connector, - dynamic_routing_algorithm: None, + dynamic_routing_algorithm: Some(dynamic_routing_algorithm), is_network_tokenization_enabled: self.is_network_tokenization_enabled, is_auto_retries_enabled: self.is_auto_retries_enabled.unwrap_or_default(), max_auto_retries_enabled: self.max_auto_retries_enabled.map(i16::from), @@ -4414,6 +4410,37 @@ impl ProfileUpdateBridge for api::ProfileUpdate { } }; + let dynamic_routing_algo_ref = if self.is_debit_routing_enabled == Some(true) { + let mut dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef = + business_profile + .dynamic_routing_algorithm + .clone() + .map(|val| val.parse_value("DynamicRoutingAlgorithmRef")) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "unable to deserialize dynamic routing algorithm ref from business profile", + )? + .unwrap_or_default(); + + routing::helpers::create_merchant_in_decision_engine_if_not_exists( + state, + business_profile.get_id(), + &mut dynamic_routing_algo_ref, + ) + .await; + + let dynamic_routing_algo_ref_value = serde_json::to_value(dynamic_routing_algo_ref) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "error serializing dynamic_routing_algorithm_ref to JSON Value", + )?; + + Some(dynamic_routing_algo_ref_value) + } else { + self.dynamic_routing_algorithm + }; + Ok(domain::ProfileUpdate::Update(Box::new( domain::ProfileGeneralUpdate { profile_name: self.profile_name, @@ -4451,7 +4478,7 @@ impl ProfileUpdateBridge for api::ProfileUpdate { .always_collect_shipping_details_from_wallet_connector, tax_connector_id: self.tax_connector_id, is_tax_connector_enabled: self.is_tax_connector_enabled, - dynamic_routing_algorithm: self.dynamic_routing_algorithm, + dynamic_routing_algorithm: dynamic_routing_algo_ref, is_network_tokenization_enabled: self.is_network_tokenization_enabled, is_auto_retries_enabled: self.is_auto_retries_enabled, max_auto_retries_enabled: self.max_auto_retries_enabled.map(i16::from), diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs index 702763ccafb..3a30559336e 100644 --- a/crates/router/src/core/routing.rs +++ b/crates/router/src/core/routing.rs @@ -578,6 +578,7 @@ pub async fn link_routing_config( business_profile.get_id(), routing_algorithm.algorithm_data.clone(), routing_types::DynamicRoutingType::SuccessRateBasedRouting, + &mut dynamic_routing_ref, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -608,6 +609,7 @@ pub async fn link_routing_config( business_profile.get_id(), routing_algorithm.algorithm_data.clone(), routing_types::DynamicRoutingType::EliminationRouting, + &mut dynamic_routing_ref, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -1929,6 +1931,9 @@ pub async fn contract_based_dynamic_routing_setup( elimination_routing_algorithm: None, dynamic_routing_volume_split: None, contract_based_routing: Some(contract_algo), + is_merchant_created_in_decision_engine: dynamic_routing_algo_ref + .as_ref() + .is_some_and(|algo| algo.is_merchant_created_in_decision_engine), } }; diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 4798cce9b02..c4b56e1a8cb 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -30,9 +30,9 @@ use external_services::grpc_client::dynamic_routing::{ use hyperswitch_domain_models::api::ApplicationResponse; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use hyperswitch_interfaces::events::routing_api_logs as routing_events; -#[cfg(all(feature = "dynamic_routing", feature = "v1"))] +#[cfg(feature = "v1")] use router_env::logger; -#[cfg(all(feature = "dynamic_routing", feature = "v1"))] +#[cfg(feature = "v1")] use router_env::{instrument, tracing}; use rustc_hash::FxHashSet; use storage_impl::redis::cache; @@ -52,15 +52,15 @@ use crate::{ types::{domain, storage}, utils::StringExt, }; +#[cfg(feature = "v1")] +use crate::{ + core::payments::routing::utils::{self as routing_utils, DecisionEngineApiHandler}, + services, +}; #[cfg(all(feature = "dynamic_routing", feature = "v1"))] use crate::{ - core::{ - metrics as core_metrics, - payments::routing::utils::{self as routing_utils, DecisionEngineApiHandler}, - routing, - }, + core::{metrics as core_metrics, routing}, routes::app::SessionStateInfo, - services, types::transformers::ForeignInto, }; pub const SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM: &str = @@ -1723,7 +1723,7 @@ pub async fn disable_dynamic_routing_algorithm( let db = state.store.as_ref(); let key_manager_state = &state.into(); let profile_id = business_profile.get_id().clone(); - let (algorithm_id, dynamic_routing_algorithm, cache_entries_to_redact) = + let (algorithm_id, mut dynamic_routing_algorithm, cache_entries_to_redact) = match dynamic_routing_type { routing_types::DynamicRoutingType::SuccessRateBasedRouting => { let Some(algorithm_ref) = dynamic_routing_algo_ref.success_based_algorithm else { @@ -1760,6 +1760,8 @@ pub async fn disable_dynamic_routing_algorithm( contract_based_routing: dynamic_routing_algo_ref.contract_based_routing, dynamic_routing_volume_split: dynamic_routing_algo_ref .dynamic_routing_volume_split, + is_merchant_created_in_decision_engine: dynamic_routing_algo_ref + .is_merchant_created_in_decision_engine, }, cache_entries_to_redact, ) @@ -1800,6 +1802,8 @@ pub async fn disable_dynamic_routing_algorithm( }, ), contract_based_routing: dynamic_routing_algo_ref.contract_based_routing, + is_merchant_created_in_decision_engine: dynamic_routing_algo_ref + .is_merchant_created_in_decision_engine, }, cache_entries_to_redact, ) @@ -1838,6 +1842,8 @@ pub async fn disable_dynamic_routing_algorithm( routing_types::DynamicAlgorithmWithTimestamp::new(None), enabled_feature: routing_types::DynamicRoutingFeatures::None, }), + is_merchant_created_in_decision_engine: dynamic_routing_algo_ref + .is_merchant_created_in_decision_engine, }, cache_entries_to_redact, ) @@ -1850,6 +1856,7 @@ pub async fn disable_dynamic_routing_algorithm( state, business_profile.get_id(), dynamic_routing_type, + &mut dynamic_routing_algorithm, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -2088,6 +2095,7 @@ pub async fn default_specific_dynamic_routing_setup( state, business_profile.get_id(), dynamic_routing_type, + &mut dynamic_routing_algo_ref, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -2203,6 +2211,7 @@ pub async fn enable_decision_engine_dynamic_routing_setup( state: &SessionState, profile_id: &id_type::ProfileId, dynamic_routing_type: routing_types::DynamicRoutingType, + dynamic_routing_algo_ref: &mut routing_types::DynamicRoutingAlgorithmRef, ) -> RouterResult<()> { logger::debug!( "performing call with open_router for profile {}", @@ -2248,6 +2257,10 @@ pub async fn enable_decision_engine_dynamic_routing_setup( } }; + // Create merchant in Decision Engine if it is not already created + create_merchant_in_decision_engine_if_not_exists(state, profile_id, dynamic_routing_algo_ref) + .await; + routing_utils::ConfigApiClient::send_decision_engine_request::<_, String>( state, services::Method::Post, @@ -2269,6 +2282,7 @@ pub async fn update_decision_engine_dynamic_routing_setup( profile_id: &id_type::ProfileId, request: serde_json::Value, dynamic_routing_type: routing_types::DynamicRoutingType, + dynamic_routing_algo_ref: &mut routing_types::DynamicRoutingAlgorithmRef, ) -> RouterResult<()> { logger::debug!( "performing call with open_router for profile {}", @@ -2320,6 +2334,10 @@ pub async fn update_decision_engine_dynamic_routing_setup( } }; + // Create merchant in Decision Engine if it is not already created + create_merchant_in_decision_engine_if_not_exists(state, profile_id, dynamic_routing_algo_ref) + .await; + routing_utils::ConfigApiClient::send_decision_engine_request::<_, String>( state, services::Method::Post, @@ -2340,6 +2358,7 @@ pub async fn disable_decision_engine_dynamic_routing_setup( state: &SessionState, profile_id: &id_type::ProfileId, dynamic_routing_type: routing_types::DynamicRoutingType, + dynamic_routing_algo_ref: &mut routing_types::DynamicRoutingAlgorithmRef, ) -> RouterResult<()> { logger::debug!( "performing call with open_router for profile {}", @@ -2364,6 +2383,10 @@ pub async fn disable_decision_engine_dynamic_routing_setup( }, }; + // Create merchant in Decision Engine if it is not already created + create_merchant_in_decision_engine_if_not_exists(state, profile_id, dynamic_routing_algo_ref) + .await; + routing_utils::ConfigApiClient::send_decision_engine_request::<_, String>( state, services::Method::Post, @@ -2378,7 +2401,32 @@ pub async fn disable_decision_engine_dynamic_routing_setup( Ok(()) } -#[cfg(all(feature = "dynamic_routing", feature = "v1"))] +#[cfg(feature = "v1")] +#[instrument(skip_all)] +pub async fn create_merchant_in_decision_engine_if_not_exists( + state: &SessionState, + profile_id: &id_type::ProfileId, + dynamic_routing_algo_ref: &mut routing_types::DynamicRoutingAlgorithmRef, +) { + if !dynamic_routing_algo_ref.is_merchant_created_in_decision_engine { + logger::debug!( + "Creating merchant_account in decision engine for profile {}", + profile_id.get_string_repr() + ); + + create_decision_engine_merchant(state, profile_id) + .await + .map_err(|err| { + logger::warn!("Merchant creation error in decision_engine: {err:?}"); + }) + .ok(); + + // TODO: Update the status based on the status code or error message from the API call + dynamic_routing_algo_ref.update_merchant_creation_status_in_decision_engine(true); + } +} + +#[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn create_decision_engine_merchant( state: &SessionState,
2025-05-31T08:26:32Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Merchant account creation on decision-engine is pre-requisite for making success based routing calls to it. Since toggle SR endpoint on Hyperswitch is the place where rule creation API of DE is being called, we can check whether merchant_account exists in DE, if exists, toggle endpoint will go ahead with creating the rule. If not, it will first call DE to create a merchant_account and then create the rule. I have created the `is_merchant_created_in_decision_engine` flag inside the `dynamic_routing_algorithm` column which is of type JSON in profile table. I have added a `#[serde(default)]` attribute on top of `is_merchant_created_in_decision_engine`. Hence it shouldn't break for older profiles which doesn't have this field itself. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create merchant_account and API key in Hyperswitch. 2. Toggle SR for the default profile created above. ``` curl --location --request POST 'http://localhost:8080/account/merchant_1748681084/business_profile/pro_3gHXWoq1Xh3AKi6tNZV1/dynamic_routing/success_based/toggle?enable=dynamic_connector_selection' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: xyz' ``` Check logs for toggle call which should have something like `Creating merchant_account in decision engine for profile <profile_id>` 3. Try hitting same API again by disabling the SR, it shouldn't have above merchant_account creation log anymore as it should be created once per profile. 4. Also hit toggle API for the profile which already has SR toggled. Even for it, the merchant_account should be created during first toggle call and not during further calls. #### Create merchant in debit routing flow -> Update business profile by setting is_debit_routing_enabled ``` curl --location 'http://localhost:8080/account/merchant_1748956040/business_profile/pro_6QFJX6m7xjQacyygMmBT' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: ' \ --data '{ "is_debit_routing_enabled": true }' ``` ``` { "merchant_id": "merchant_1748956040", "profile_id": "pro_6QFJX6m7xjQacyygMmBT", "profile_name": "US_default", "return_url": "https://google.com/success", "enable_payment_response_hash": true, "payment_response_hash_key": "THd00F3c6WIXOXufmm6sFsUL0zRUFVL2llcMS1SG9rdco16PFty01OOkLcY8IbSS", "redirect_to_merchant_with_http_post": false, "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "webhook_url": null, "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "metadata": null, "routing_algorithm": null, "intent_fulfillment_time": 900, "frm_routing_algorithm": null, "payout_routing_algorithm": null, "applepay_verified_domains": null, "session_expiry": 900, "payment_link_config": null, "authentication_connector_details": null, "use_billing_as_payment_method_billing": true, "extended_card_info_config": null, "collect_shipping_details_from_wallet_connector": false, "collect_billing_details_from_wallet_connector": false, "always_collect_shipping_details_from_wallet_connector": false, "always_collect_billing_details_from_wallet_connector": false, "is_connector_agnostic_mit_enabled": false, "payout_link_config": null, "outgoing_webhook_custom_http_headers": null, "tax_connector_id": null, "is_tax_connector_enabled": false, "is_network_tokenization_enabled": false, "is_auto_retries_enabled": false, "max_auto_retries_enabled": null, "always_request_extended_authorization": null, "is_click_to_pay_enabled": false, "authentication_product_ids": null, "card_testing_guard_config": { "card_ip_blocking_status": "disabled", "card_ip_blocking_threshold": 3, "guest_user_card_blocking_status": "disabled", "guest_user_card_blocking_threshold": 10, "customer_id_blocking_status": "disabled", "customer_id_blocking_threshold": 5, "card_testing_guard_expiry": 3600 }, "is_clear_pan_retries_enabled": false, "force_3ds_challenge": false, "is_debit_routing_enabled": true, "merchant_business_country": null, "is_pre_network_tokenization_enabled": false } ``` -> Db screenshot ![image](https://github.com/user-attachments/assets/24b05943-8d3c-4add-9931-6f6ce66af57a) -> Db entry when business profile is created ![image](https://github.com/user-attachments/assets/dc6b4d26-549b-414c-9395-929c78303d07) #### Test sr <img width="1728" alt="image" src="https://github.com/user-attachments/assets/f7253d1c-ec55-45cd-93e5-ff0e4503fbee" /> <img width="1490" alt="image" src="https://github.com/user-attachments/assets/e1f01c8f-8f22-4612-83ed-01562bc1dc50" /> -> Update profile to enable debit routing <img width="1480" alt="image" src="https://github.com/user-attachments/assets/adce71c4-179b-4990-b693-c75e8ecad080" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
33cd60e64288b2a6bb24cc27b9d319fdbeab46ef
33cd60e64288b2a6bb24cc27b9d319fdbeab46ef
juspay/hyperswitch
juspay__hyperswitch-8181
Bug: [FEATURE]: build gRPC Client Interface to initiate communication with recovery-trainer gRPC service Implement a gRPC client interface that facilitates communication with the recovery-trainer gRPC service. The client should be capable of initializing and managing the connection to the service, sending requests, and handling responses in accordance with the defined service contract (protobuf definitions).
diff --git a/Cargo.lock b/Cargo.lock index c72b8f1b531..c38b3966051 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3055,12 +3055,14 @@ dependencies = [ "masking", "once_cell", "prost", + "prost-types", "quick-xml", "reqwest 0.11.27", "router_env", "rust-grpc-client", "serde", "thiserror 1.0.69", + "time", "tokio 1.45.1", "tonic 0.13.1", "tonic-build", @@ -6793,6 +6795,7 @@ dependencies = [ "openssl", "payment_methods", "pm_auth", + "prost-types", "rand 0.8.5", "rand_chacha 0.3.1", "rdkafka", diff --git a/config/config.example.toml b/config/config.example.toml index cdcbd43dcba..06302c28f26 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -1154,12 +1154,18 @@ url = "http://localhost:8080" # Open Router URL base_url = "http://localhost:8000" # Unified Connector Service Base URL connection_timeout = 10 # Connection Timeout Duration in Seconds +[grpc_client.recovery_decider_client] # Revenue recovery client base url +base_url = "http://127.0.0.1:8080" #Base URL + [billing_connectors_invoice_sync] billing_connectors_which_requires_invoice_sync_call = "recurly" # List of billing connectors which has invoice sync api call [revenue_recovery] -monitoring_threshold_in_seconds = 2592000 # 30*24*60*60 secs , threshold for monitoring the retry system -retry_algorithm_type = "cascading" # type of retry algorithm +monitoring_threshold_in_seconds = 60 # 60 secs , threshold for monitoring the retry system +retry_algorithm_type = "cascading" # type of retry algorithm + +[revenue_recovery.recovery_timestamp] # Timestamp configuration for Revenue Recovery +initial_timestamp_in_hours = 1 # number of hours added to start time for Decider service of Revenue Recovery [clone_connector_allowlist] merchant_ids = "merchant_ids" # Comma-separated list of allowed merchant IDs diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 46cd59a2d64..6acf697ac4d 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -354,6 +354,9 @@ host = "localhost" # Client Host port = 7000 # Client Port service = "dynamo" # Service name +[grpc_client.recovery_decider_client] # Revenue recovery client base url +base_url = "http://127.0.0.1:8080" #Base URL + [theme.storage] file_storage_backend = "aws_s3" # Theme storage backend to be used @@ -382,6 +385,9 @@ connector_names = "connector_names" # Comma-separated list of allowed connec base_url = "http://localhost:8000" # Unified Connector Service Base URL connection_timeout = 10 # Connection Timeout Duration in Seconds +[revenue_recovery.recovery_timestamp] # Timestamp configuration for Revenue Recovery +initial_timestamp_in_hours = 1 # number of hours added to start time for Decider service of Revenue Recovery + [chat] enabled = false # Enable or disable chat features hyperswitch_ai_host = "http://0.0.0.0:8000" # Hyperswitch ai workflow host diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 7ba10061926..9cca0570e7e 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -820,7 +820,7 @@ billing_connectors_which_requires_invoice_sync_call = "recurly" [revenue_recovery] -monitoring_threshold_in_seconds = 2592000 +monitoring_threshold_in_seconds = 60 retry_algorithm_type = "cascading" [authentication_providers] diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 1bdd2c37f9b..50ab48a47fd 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -836,8 +836,8 @@ click_to_pay = {connector_list = "adyen, cybersource, trustpay"} [revenue_recovery] -monitoring_threshold_in_seconds = 2592000 +monitoring_threshold_in_seconds = 60 retry_algorithm_type = "cascading" [list_dispute_supported_connectors] -connector_list = "worldpayvantiv" \ No newline at end of file +connector_list = "worldpayvantiv" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 04797608af3..57fc5eddf6e 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -841,7 +841,7 @@ billing_connectors_which_requires_invoice_sync_call = "recurly" click_to_pay = {connector_list = "adyen, cybersource, trustpay"} [revenue_recovery] -monitoring_threshold_in_seconds = 2592000 +monitoring_threshold_in_seconds = 60 retry_algorithm_type = "cascading" [list_dispute_supported_connectors] diff --git a/config/development.toml b/config/development.toml index 9105b448e1e..d0a0c7f5a32 100644 --- a/config/development.toml +++ b/config/development.toml @@ -1228,6 +1228,9 @@ host = "localhost" port = 8000 service = "dynamo" +[grpc_client.recovery_decider_client] # Revenue recovery client base url +base_url = "http://127.0.0.1:8080" #Base URL + [theme.storage] file_storage_backend = "file_system" # Theme storage backend to be used @@ -1264,9 +1267,12 @@ ucs_only_connectors = [ ] [revenue_recovery] -monitoring_threshold_in_seconds = 2592000 +monitoring_threshold_in_seconds = 60 retry_algorithm_type = "cascading" +[revenue_recovery.recovery_timestamp] +initial_timestamp_in_hours = 1 + [clone_connector_allowlist] merchant_ids = "merchant_123, merchant_234" # Comma-separated list of allowed merchant IDs connector_names = "stripe, adyen" # Comma-separated list of allowed connector names diff --git a/config/docker_compose.toml b/config/docker_compose.toml index ffb30192bca..15d5b0abba7 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -1156,7 +1156,7 @@ hyperswitch_ai_host = "http://0.0.0.0:8000" click_to_pay = {connector_list = "adyen, cybersource, trustpay"} [revenue_recovery] -monitoring_threshold_in_seconds = 2592000 # threshold for monitoring the retry system +monitoring_threshold_in_seconds = 60 # threshold for monitoring the retry system retry_algorithm_type = "cascading" # type of retry algorithm [clone_connector_allowlist] diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml index 9e83f331b94..b8933003065 100644 --- a/crates/external_services/Cargo.toml +++ b/crates/external_services/Cargo.toml @@ -13,6 +13,16 @@ email = ["dep:aws-config"] aws_s3 = ["dep:aws-config", "dep:aws-sdk-s3"] hashicorp-vault = ["dep:vaultrs"] v1 = ["hyperswitch_interfaces/v1", "common_utils/v1"] +v2 = ["hyperswitch_interfaces/v2", "common_utils/v2"] +revenue_recovery = [ + "dep:prost", + "dep:router_env", + "tokio/macros", + "tokio/rt-multi-thread", + "dep:hyper-util", + "dep:http-body-util", + "dep:prost-types", +] dynamic_routing = [ "dep:prost", "dep:api_models", @@ -43,6 +53,8 @@ serde = { version = "1.0.219", features = ["derive"] } thiserror = "1.0.69" vaultrs = { version = "0.7.4", optional = true } prost = { version = "0.13", optional = true } +prost-types = { version = "0.13", optional = true } +time = { version = "0.3.41", features = ["serde", "serde-well-known", "std"] } tokio = "1.45.1" tonic = "0.13.1" tonic-reflection = "0.13.1" diff --git a/crates/external_services/build.rs b/crates/external_services/build.rs index c9d9017560b..993d25e5ab4 100644 --- a/crates/external_services/build.rs +++ b/crates/external_services/build.rs @@ -1,9 +1,23 @@ #[allow(clippy::expect_used)] fn main() -> Result<(), Box<dyn std::error::Error>> { + // Compilation for revenue recovery protos + #[cfg(feature = "revenue_recovery")] + { + let proto_base_path = router_env::workspace_path().join("proto"); + let out_dir = std::path::PathBuf::from(std::env::var("OUT_DIR")?); + let recovery_proto_files = [proto_base_path.join("recovery_decider.proto")]; + tonic_build::configure() + .out_dir(&out_dir) + .compile_well_known_types(true) + .extern_path(".google.protobuf.Timestamp", "::prost_types::Timestamp") + .compile_protos(&recovery_proto_files, &[&proto_base_path]) + .expect("Failed to compile revenue-recovery proto files"); + } + + // Compilation for dynamic_routing protos #[cfg(feature = "dynamic_routing")] { // Get the directory of the current crate - let proto_path = router_env::workspace_path().join("proto"); let success_rate_proto_file = proto_path.join("success_rate.proto"); let contract_routing_proto_file = proto_path.join("contract_routing.proto"); diff --git a/crates/external_services/src/grpc_client.rs b/crates/external_services/src/grpc_client.rs index 1b93ac6bd89..875b960bf13 100644 --- a/crates/external_services/src/grpc_client.rs +++ b/crates/external_services/src/grpc_client.rs @@ -4,6 +4,10 @@ pub mod dynamic_routing; /// gRPC based Heath Check Client interface implementation #[cfg(feature = "dynamic_routing")] pub mod health_check_client; +/// gRPC based Recovery Trainer Client interface implementation +#[cfg(feature = "revenue_recovery")] +pub mod revenue_recovery; + /// gRPC based Unified Connector Service Client interface implementation pub mod unified_connector_service; use std::{fmt::Debug, sync::Arc}; @@ -14,19 +18,26 @@ use common_utils::consts; use dynamic_routing::{DynamicRoutingClientConfig, RoutingStrategy}; #[cfg(feature = "dynamic_routing")] use health_check_client::HealthCheckClient; -#[cfg(feature = "dynamic_routing")] +#[cfg(any(feature = "dynamic_routing", feature = "revenue_recovery"))] use hyper_util::client::legacy::connect::HttpConnector; -#[cfg(feature = "dynamic_routing")] +#[cfg(any(feature = "dynamic_routing", feature = "revenue_recovery"))] use router_env::logger; -use serde; -#[cfg(feature = "dynamic_routing")] +#[cfg(any(feature = "dynamic_routing", feature = "revenue_recovery"))] use tonic::body::Body; +#[cfg(feature = "revenue_recovery")] +pub use self::revenue_recovery::{ + recovery_decider_client::{ + DeciderRequest, DeciderResponse, RecoveryDeciderClientConfig, + RecoveryDeciderClientInterface, RecoveryDeciderError, RecoveryDeciderResult, + }, + GrpcRecoveryHeaders, +}; use crate::grpc_client::unified_connector_service::{ UnifiedConnectorServiceClient, UnifiedConnectorServiceClientConfig, }; -#[cfg(feature = "dynamic_routing")] +#[cfg(any(feature = "dynamic_routing", feature = "revenue_recovery"))] /// Hyper based Client type for maintaining connection pool for all gRPC services pub type Client = hyper_util::client::legacy::Client<HttpConnector, Body>; @@ -39,15 +50,22 @@ pub struct GrpcClients { /// Health Check client for all gRPC services #[cfg(feature = "dynamic_routing")] pub health_client: HealthCheckClient, + /// Recovery Decider Client + #[cfg(feature = "revenue_recovery")] + pub recovery_decider_client: Option<Box<dyn RecoveryDeciderClientInterface>>, /// Unified Connector Service client pub unified_connector_service_client: Option<UnifiedConnectorServiceClient>, } + /// Type that contains the configs required to construct a gRPC client with its respective services. #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, Default)] pub struct GrpcClientSettings { #[cfg(feature = "dynamic_routing")] /// Configs for Dynamic Routing Client pub dynamic_routing_client: Option<DynamicRoutingClientConfig>, + #[cfg(feature = "revenue_recovery")] + /// Configs for Recovery Decider Client + pub recovery_decider_client: Option<RecoveryDeciderClientConfig>, /// Configs for Unified Connector Service client pub unified_connector_service: Option<UnifiedConnectorServiceClientConfig>, } @@ -59,7 +77,7 @@ impl GrpcClientSettings { /// This function will be called at service startup. #[allow(clippy::expect_used)] pub async fn get_grpc_client_interface(&self) -> Arc<GrpcClients> { - #[cfg(feature = "dynamic_routing")] + #[cfg(any(feature = "dynamic_routing", feature = "revenue_recovery"))] let client = hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new()) .http2_only(true) @@ -75,18 +93,47 @@ impl GrpcClientSettings { .flatten(); #[cfg(feature = "dynamic_routing")] - let health_client = HealthCheckClient::build_connections(self, client) + let health_client = HealthCheckClient::build_connections(self, client.clone()) .await .expect("Failed to build gRPC connections"); let unified_connector_service_client = UnifiedConnectorServiceClient::build_connections(self).await; + #[cfg(feature = "revenue_recovery")] + let recovery_decider_client = { + match &self.recovery_decider_client { + Some(config) => { + // Validate the config first + config + .validate() + .expect("Recovery Decider configuration validation failed"); + + // Create the client + let client = config + .get_recovery_decider_connection(client.clone()) + .expect( + "Failed to establish a connection with the Recovery Decider Server", + ); + + logger::info!("Recovery Decider gRPC client successfully initialized"); + let boxed_client: Box<dyn RecoveryDeciderClientInterface> = Box::new(client); + Some(boxed_client) + } + None => { + logger::debug!("Recovery Decider client configuration not provided, client will be disabled"); + None + } + } + }; + Arc::new(GrpcClients { #[cfg(feature = "dynamic_routing")] dynamic_routing: dynamic_routing_connection, #[cfg(feature = "dynamic_routing")] health_client, + #[cfg(feature = "revenue_recovery")] + recovery_decider_client, unified_connector_service_client, }) } @@ -145,7 +192,7 @@ pub(crate) fn create_grpc_request<T: Debug>(message: T, headers: GrpcHeaders) -> let mut request = tonic::Request::new(message); request.add_headers_to_grpc_request(headers); - logger::info!(dynamic_routing_request=?request); + logger::info!(?request); request } diff --git a/crates/external_services/src/grpc_client/revenue_recovery.rs b/crates/external_services/src/grpc_client/revenue_recovery.rs new file mode 100644 index 00000000000..22c9bf7ffcb --- /dev/null +++ b/crates/external_services/src/grpc_client/revenue_recovery.rs @@ -0,0 +1,49 @@ +/// Recovery Decider client +pub mod recovery_decider_client; + +use std::fmt::Debug; + +use common_utils::consts; +use router_env::logger; + +/// Contains recovery grpc headers +#[derive(Debug)] +pub struct GrpcRecoveryHeaders { + /// Request id + pub request_id: Option<String>, +} + +/// Trait to add necessary recovery headers to the tonic Request +pub(crate) trait AddRecoveryHeaders { + /// Add necessary recovery header fields to the tonic Request + fn add_recovery_headers(&mut self, headers: GrpcRecoveryHeaders); +} + +impl<T> AddRecoveryHeaders for tonic::Request<T> { + #[track_caller] + fn add_recovery_headers(&mut self, headers: GrpcRecoveryHeaders) { + headers.request_id.map(|request_id| { + request_id + .parse() + .map(|request_id_val| { + self + .metadata_mut() + .append(consts::X_REQUEST_ID, request_id_val) + }) + .inspect_err( + |err| logger::warn!(header_parse_error=?err,"invalid {} received",consts::X_REQUEST_ID), + ) + .ok(); + }); + } +} + +/// Creates a tonic::Request with recovery headers added. +pub(crate) fn create_revenue_recovery_grpc_request<T: Debug>( + message: T, + recovery_headers: GrpcRecoveryHeaders, +) -> tonic::Request<T> { + let mut request = tonic::Request::new(message); + request.add_recovery_headers(recovery_headers); + request +} diff --git a/crates/external_services/src/grpc_client/revenue_recovery/recovery_decider_client.rs b/crates/external_services/src/grpc_client/revenue_recovery/recovery_decider_client.rs new file mode 100644 index 00000000000..877de2bc77b --- /dev/null +++ b/crates/external_services/src/grpc_client/revenue_recovery/recovery_decider_client.rs @@ -0,0 +1,117 @@ +use std::fmt::Debug; + +use common_utils::errors::CustomResult; +use error_stack::{Report, ResultExt}; +use router_env::logger; + +use crate::grpc_client::Client; + +#[allow( + missing_docs, + unused_qualifications, + clippy::unwrap_used, + clippy::as_conversions, + clippy::use_self +)] +pub mod decider { + tonic::include_proto!("decider"); +} + +use decider::decider_client::DeciderClient; +pub use decider::{DeciderRequest, DeciderResponse}; + +/// Recovery Decider result +pub type RecoveryDeciderResult<T> = CustomResult<T, RecoveryDeciderError>; + +/// Recovery Decider Error +#[derive(Debug, Clone, thiserror::Error)] +pub enum RecoveryDeciderError { + /// Error establishing gRPC connection + #[error("Failed to establish connection with Recovery Decider service: {0}")] + ConnectionError(String), + /// Error received from the gRPC service + #[error("Recovery Decider service returned an error: {0}")] + ServiceError(String), + /// Missing configuration for the client + #[error("Recovery Decider client configuration is missing or invalid")] + ConfigError(String), +} + +/// Recovery Decider Client type +#[async_trait::async_trait] +pub trait RecoveryDeciderClientInterface: dyn_clone::DynClone + Send + Sync + Debug { + /// fn to call gRPC service + async fn decide_on_retry( + &mut self, + request_payload: DeciderRequest, + recovery_headers: super::GrpcRecoveryHeaders, + ) -> RecoveryDeciderResult<DeciderResponse>; +} + +dyn_clone::clone_trait_object!(RecoveryDeciderClientInterface); + +/// Configuration for the Recovery Decider gRPC client. +#[derive(Debug, Default, Clone, serde::Deserialize, serde::Serialize)] +pub struct RecoveryDeciderClientConfig { + /// Base URL of the Recovery Decider service + pub base_url: String, +} + +impl RecoveryDeciderClientConfig { + /// Validate the configuration + pub fn validate(&self) -> Result<(), RecoveryDeciderError> { + use common_utils::fp_utils::when; + + when(self.base_url.is_empty(), || { + Err(RecoveryDeciderError::ConfigError( + "Recovery Decider base URL cannot be empty when configuration is provided" + .to_string(), + )) + }) + } + + /// create a connection + pub fn get_recovery_decider_connection( + &self, + hyper_client: Client, + ) -> Result<DeciderClient<Client>, Report<RecoveryDeciderError>> { + let uri = self + .base_url + .parse::<tonic::transport::Uri>() + .map_err(Report::from) + .change_context(RecoveryDeciderError::ConfigError(format!( + "Invalid URI: {}", + self.base_url + )))?; + + let service_client = DeciderClient::with_origin(hyper_client, uri); + + Ok(service_client) + } +} + +#[async_trait::async_trait] +impl RecoveryDeciderClientInterface for DeciderClient<Client> { + async fn decide_on_retry( + &mut self, + request_payload: DeciderRequest, + recovery_headers: super::GrpcRecoveryHeaders, + ) -> RecoveryDeciderResult<DeciderResponse> { + let request = + super::create_revenue_recovery_grpc_request(request_payload, recovery_headers); + + logger::debug!(decider_request =?request); + + let grpc_response = self + .decide(request) + .await + .change_context(RecoveryDeciderError::ServiceError( + "Decider service call failed".to_string(), + ))? + .into_inner(); + + logger::debug!(grpc_decider_response =?grpc_response); + + Ok(grpc_response) + } +} diff --git a/crates/external_services/src/lib.rs b/crates/external_services/src/lib.rs index 3d9f1bcf933..f63d2227053 100644 --- a/crates/external_services/src/lib.rs +++ b/crates/external_services/src/lib.rs @@ -28,6 +28,42 @@ pub mod managers; /// crm module pub mod crm; +#[cfg(feature = "revenue_recovery")] +/// date_time module +pub mod date_time { + use error_stack::ResultExt; + + /// Errors in time conversion + #[derive(Debug, thiserror::Error)] + pub enum DateTimeConversionError { + #[error("Invalid timestamp value from prost Timestamp: out of representable range")] + /// Error for out of range + TimestampOutOfRange, + } + + /// Converts a `time::PrimitiveDateTime` to a `prost_types::Timestamp`. + pub fn convert_to_prost_timestamp(dt: time::PrimitiveDateTime) -> prost_types::Timestamp { + let odt = dt.assume_utc(); + prost_types::Timestamp { + seconds: odt.unix_timestamp(), + // This conversion is safe as nanoseconds (0..999_999_999) always fit within an i32. + #[allow(clippy::as_conversions)] + nanos: odt.nanosecond() as i32, + } + } + + /// Converts a `prost_types::Timestamp` to an `time::PrimitiveDateTime`. + pub fn convert_from_prost_timestamp( + ts: &prost_types::Timestamp, + ) -> error_stack::Result<time::PrimitiveDateTime, DateTimeConversionError> { + let timestamp_nanos = i128::from(ts.seconds) * 1_000_000_000 + i128::from(ts.nanos); + + time::OffsetDateTime::from_unix_timestamp_nanos(timestamp_nanos) + .map(|offset_dt| time::PrimitiveDateTime::new(offset_dt.date(), offset_dt.time())) + .change_context(DateTimeConversionError::TimestampOutOfRange) + } +} + /// Crate specific constants pub mod consts { /// General purpose base64 engine diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 4d1e9917ad1..4c59c8e952b 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -36,7 +36,7 @@ retry = [] v2 = [ "common_default", "api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "kgraph_utils/v2", "common_utils/v2", "hyperswitch_connectors/v2", "hyperswitch_interfaces/v2", "common_types/v2", "revenue_recovery", "scheduler/v2", "euclid/v2", "payment_methods/v2", "tokenization_v2"] v1 = ["common_default", "api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "storage_impl/v1", "hyperswitch_interfaces/v1", "kgraph_utils/v1", "common_utils/v1", "hyperswitch_connectors/v1", "common_types/v1", "scheduler/v1", "payment_methods/v1"] dynamic_routing = ["external_services/dynamic_routing", "storage_impl/dynamic_routing", "api_models/dynamic_routing"] -revenue_recovery = ["api_models/revenue_recovery", "hyperswitch_interfaces/revenue_recovery", "hyperswitch_domain_models/revenue_recovery", "hyperswitch_connectors/revenue_recovery"] +revenue_recovery = ["api_models/revenue_recovery", "hyperswitch_interfaces/revenue_recovery", "hyperswitch_domain_models/revenue_recovery", "hyperswitch_connectors/revenue_recovery", "external_services/revenue_recovery", "dep:prost-types"] tokenization_v2 = ["api_models/tokenization_v2", "diesel_models/tokenization_v2", "hyperswitch_domain_models/tokenization_v2", "storage_impl/tokenization_v2"] # Partial Auth @@ -59,6 +59,7 @@ blake3 = "1.8.2" bytes = "1.10.1" clap = { version = "4.5.38", default-features = false, features = ["std", "derive", "help", "usage"] } config = { version = "0.14.1", features = ["toml"] } +prost-types = { version = "0.13", optional = true } cookie = "0.18.1" csv = "1.3.1" diesel = { version = "2.2.10", features = ["postgres"] } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 6bc5b35d2b8..7d897ef7c86 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -1121,6 +1121,15 @@ impl Settings<SecuredSecret> { self.open_router.validate()?; + // Validate gRPC client settings + #[cfg(feature = "revenue_recovery")] + self.grpc_client + .recovery_decider_client + .as_ref() + .map(|config| config.validate()) + .transpose() + .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?; + Ok(()) } } diff --git a/crates/router/src/core/payments/operations/proxy_payments_intent.rs b/crates/router/src/core/payments/operations/proxy_payments_intent.rs index 9170b36462a..c9721186ab8 100644 --- a/crates/router/src/core/payments/operations/proxy_payments_intent.rs +++ b/crates/router/src/core/payments/operations/proxy_payments_intent.rs @@ -257,6 +257,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentConfirmData<F>, ProxyPaymentsR ), ), }; + let payment_data = PaymentConfirmData { flow: std::marker::PhantomData, payment_intent, diff --git a/crates/router/src/core/revenue_recovery/types.rs b/crates/router/src/core/revenue_recovery/types.rs index 1e533751f0e..00a661527a1 100644 --- a/crates/router/src/core/revenue_recovery/types.rs +++ b/crates/router/src/core/revenue_recovery/types.rs @@ -12,14 +12,16 @@ use common_utils::{ ext_traits::{OptionExt, ValueExt}, id_type, }; -use diesel_models::{enums, process_tracker::business_status, types as diesel_types}; +use diesel_models::{ + enums, payment_intent, process_tracker::business_status, types as diesel_types, +}; use error_stack::{self, ResultExt}; use hyperswitch_domain_models::{ business_profile, merchant_connector_account, merchant_context::{Context, MerchantContext}, payments::{ - self as domain_payments, payment_attempt, PaymentConfirmData, PaymentIntent, - PaymentIntentData, + self as domain_payments, payment_attempt::PaymentAttempt, PaymentConfirmData, + PaymentIntent, PaymentIntentData, }, router_data_v2::{self, flow_common_types}, router_flow_types, @@ -97,7 +99,7 @@ impl RevenueRecoveryPaymentsAttemptStatus { payment_intent: &PaymentIntent, process_tracker: storage::ProcessTracker, revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, - payment_attempt: payment_attempt::PaymentAttempt, + payment_attempt: PaymentAttempt, revenue_recovery_metadata: &mut PaymentRevenueRecoveryMetadata, ) -> Result<(), errors::ProcessTrackerError> { let db = &*state.store; @@ -199,7 +201,7 @@ impl RevenueRecoveryPaymentsAttemptStatus { let action = Box::pin(Action::payment_sync_call( state, revenue_recovery_payment_data, - payment_intent.get_id(), + payment_intent, &process_tracker, payment_attempt, )) @@ -297,10 +299,10 @@ impl Decision { #[derive(Debug, Clone)] pub enum Action { - SyncPayment(payment_attempt::PaymentAttempt), + SyncPayment(PaymentAttempt), RetryPayment(PrimitiveDateTime), - TerminalFailure(payment_attempt::PaymentAttempt), - SuccessfulPayment(payment_attempt::PaymentAttempt), + TerminalFailure(PaymentAttempt), + SuccessfulPayment(PaymentAttempt), ReviewPayment, ManualReviewAction, } @@ -313,7 +315,6 @@ impl Action { revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, revenue_recovery_metadata: &PaymentRevenueRecoveryMetadata, ) -> RecoveryResult<Self> { - let db = &*state.store; let response = revenue_recovery_core::api::call_proxy_api( state, payment_intent, @@ -382,11 +383,12 @@ impl Action { }; Self::decide_retry_failure_action( - db, + state, merchant_id, process.clone(), revenue_recovery_payment_data, &payment_data.payment_attempt, + payment_intent, ) .await } @@ -547,13 +549,13 @@ impl Action { pub async fn payment_sync_call( state: &SessionState, revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, - global_payment_id: &id_type::GlobalPaymentId, + payment_intent: &PaymentIntent, process: &storage::ProcessTracker, - payment_attempt: payment_attempt::PaymentAttempt, + payment_attempt: PaymentAttempt, ) -> RecoveryResult<Self> { let response = revenue_recovery_core::api::call_psync_api( state, - global_payment_id, + payment_intent.get_id(), revenue_recovery_payment_data, ) .await; @@ -565,11 +567,12 @@ impl Action { } RevenueRecoveryPaymentsAttemptStatus::Failed => { Self::decide_retry_failure_action( - db, + state, revenue_recovery_payment_data.merchant_account.get_id(), process.clone(), revenue_recovery_payment_data, &payment_attempt, + payment_intent, ) .await } @@ -747,15 +750,22 @@ impl Action { } pub(crate) async fn decide_retry_failure_action( - db: &dyn StorageInterface, + state: &SessionState, merchant_id: &id_type::MerchantId, pt: storage::ProcessTracker, revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, - payment_attempt: &payment_attempt::PaymentAttempt, + payment_attempt: &PaymentAttempt, + payment_intent: &PaymentIntent, ) -> RecoveryResult<Self> { let next_retry_count = pt.retry_count + 1; let schedule_time = revenue_recovery_payment_data - .get_schedule_time_based_on_retry_type(db, merchant_id, next_retry_count) + .get_schedule_time_based_on_retry_type( + state, + merchant_id, + next_retry_count, + payment_attempt, + payment_intent, + ) .await; match schedule_time { @@ -769,7 +779,7 @@ impl Action { // TODO: Move these to impl based functions async fn record_back_to_billing_connector( state: &SessionState, - payment_attempt: &payment_attempt::PaymentAttempt, + payment_attempt: &PaymentAttempt, payment_intent: &PaymentIntent, billing_mca: &merchant_connector_account::MerchantConnectorAccount, ) -> RecoveryResult<()> { @@ -822,7 +832,7 @@ async fn record_back_to_billing_connector( pub fn construct_recovery_record_back_router_data( state: &SessionState, billing_mca: &merchant_connector_account::MerchantConnectorAccount, - payment_attempt: &payment_attempt::PaymentAttempt, + payment_attempt: &PaymentAttempt, payment_intent: &PaymentIntent, ) -> RecoveryResult<hyperswitch_domain_models::types::RevenueRecoveryRecordBackRouterData> { let auth_type: types::ConnectorAuthType = diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index d4bee7276af..18044b371f5 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -13,6 +13,8 @@ use common_utils::id_type; use external_services::email::{ no_email::NoEmailClient, ses::AwsSes, smtp::SmtpServer, EmailClientConfigs, EmailService, }; +#[cfg(all(feature = "revenue_recovery", feature = "v2"))] +use external_services::grpc_client::revenue_recovery::GrpcRecoveryHeaders; use external_services::{ file_storage::FileStorageInterface, grpc_client::{GrpcClients, GrpcHeaders}, @@ -151,6 +153,12 @@ impl SessionState { request_id: self.request_id.map(|req_id| (*req_id).to_string()), } } + #[cfg(all(feature = "revenue_recovery", feature = "v2"))] + pub fn get_recovery_grpc_headers(&self) -> GrpcRecoveryHeaders { + GrpcRecoveryHeaders { + request_id: self.request_id.map(|req_id| (*req_id).to_string()), + } + } } pub trait SessionStateInfo { diff --git a/crates/router/src/types/storage/revenue_recovery.rs b/crates/router/src/types/storage/revenue_recovery.rs index c672c5ecffb..4b0dd2f2bc8 100644 --- a/crates/router/src/types/storage/revenue_recovery.rs +++ b/crates/router/src/types/storage/revenue_recovery.rs @@ -1,13 +1,17 @@ use std::fmt::Debug; use common_enums::enums; -use common_utils::id_type; +use common_utils::{ext_traits::ValueExt, id_type}; +use external_services::grpc_client::{self as external_grpc_client, GrpcHeaders}; use hyperswitch_domain_models::{ business_profile, merchant_account, merchant_connector_account, merchant_key_store, + payment_method_data::{Card, PaymentMethodData}, + payments::{payment_attempt::PaymentAttempt, PaymentIntent}, }; +use masking::PeekInterface; use router_env::logger; -use crate::{db::StorageInterface, workflows::revenue_recovery}; +use crate::{db::StorageInterface, routes::SessionState, workflows::revenue_recovery}; #[derive(serde::Serialize, serde::Deserialize, Debug)] pub struct RevenueRecoveryWorkflowTrackingData { pub merchant_id: id_type::MerchantId, @@ -29,9 +33,11 @@ pub struct RevenueRecoveryPaymentData { impl RevenueRecoveryPaymentData { pub async fn get_schedule_time_based_on_retry_type( &self, - db: &dyn StorageInterface, + state: &SessionState, merchant_id: &id_type::MerchantId, retry_count: i32, + payment_attempt: &PaymentAttempt, + payment_intent: &PaymentIntent, ) -> Option<time::PrimitiveDateTime> { match self.retry_algorithm { enums::RevenueRecoveryAlgorithmType::Monitoring => { @@ -40,21 +46,41 @@ impl RevenueRecoveryPaymentData { } enums::RevenueRecoveryAlgorithmType::Cascading => { revenue_recovery::get_schedule_time_to_retry_mit_payments( - db, + state.store.as_ref(), merchant_id, retry_count, ) .await } enums::RevenueRecoveryAlgorithmType::Smart => { - // TODO: Integrate the smart retry call to return back a schedule time - None + revenue_recovery::get_schedule_time_for_smart_retry( + state, + payment_attempt, + payment_intent, + retry_count, + ) + .await } } } } + #[derive(Debug, serde::Deserialize, Clone, Default)] pub struct RevenueRecoverySettings { pub monitoring_threshold_in_seconds: i64, pub retry_algorithm_type: enums::RevenueRecoveryAlgorithmType, + pub recovery_timestamp: RecoveryTimestamp, +} + +#[derive(Debug, serde::Deserialize, Clone)] +pub struct RecoveryTimestamp { + pub initial_timestamp_in_hours: i64, +} + +impl Default for RecoveryTimestamp { + fn default() -> Self { + Self { + initial_timestamp_in_hours: 1, + } + } } diff --git a/crates/router/src/workflows/revenue_recovery.rs b/crates/router/src/workflows/revenue_recovery.rs index 792251de496..c962aeb68e5 100644 --- a/crates/router/src/workflows/revenue_recovery.rs +++ b/crates/router/src/workflows/revenue_recovery.rs @@ -6,9 +6,23 @@ use common_utils::{ id_type, }; #[cfg(feature = "v2")] +use diesel_models::types::BillingConnectorPaymentMethodDetails; +#[cfg(feature = "v2")] use error_stack::ResultExt; +#[cfg(all(feature = "revenue_recovery", feature = "v2"))] +use external_services::{ + date_time, grpc_client::revenue_recovery::recovery_decider_client as external_grpc_client, +}; #[cfg(feature = "v2")] -use hyperswitch_domain_models::payments::PaymentIntentData; +use hyperswitch_domain_models::{ + payment_method_data::PaymentMethodData, + payments::{ + payment_attempt::PaymentAttempt, PaymentConfirmData, PaymentIntent, PaymentIntentData, + }, + router_flow_types::Authorize, +}; +#[cfg(feature = "v2")] +use masking::{ExposeInterface, PeekInterface, Secret}; #[cfg(feature = "v2")] use router_env::logger; use scheduler::{consumer::workflows::ProcessTrackerWorkflow, errors}; @@ -200,3 +214,279 @@ pub(crate) async fn get_schedule_time_to_retry_mit_payments( scheduler_utils::get_time_from_delta(time_delta) } + +#[cfg(feature = "v2")] +pub(crate) async fn get_schedule_time_for_smart_retry( + state: &SessionState, + payment_attempt: &PaymentAttempt, + payment_intent: &PaymentIntent, + retry_count: i32, +) -> Option<time::PrimitiveDateTime> { + let first_error_message = match payment_attempt.error.as_ref() { + Some(error) => error.message.clone(), + None => { + logger::error!( + payment_intent_id = ?payment_intent.get_id(), + attempt_id = ?payment_attempt.get_id(), + "Payment attempt error information not found - cannot proceed with smart retry" + ); + return None; + } + }; + + let billing_state = payment_intent + .billing_address + .as_ref() + .and_then(|addr_enc| addr_enc.get_inner().address.as_ref()) + .and_then(|details| details.state.as_ref()) + .cloned(); + + // Check if payment_method_data itself is None + if payment_attempt.payment_method_data.is_none() { + logger::debug!( + payment_intent_id = ?payment_intent.get_id(), + attempt_id = ?payment_attempt.get_id(), + message = "payment_attempt.payment_method_data is None" + ); + } + + let billing_connector_payment_method_details = payment_intent + .feature_metadata + .as_ref() + .and_then(|revenue_recovery_data| { + revenue_recovery_data + .payment_revenue_recovery_metadata + .as_ref() + }) + .and_then(|payment_metadata| { + payment_metadata + .billing_connector_payment_method_details + .as_ref() + }); + + let revenue_recovery_metadata = payment_intent + .feature_metadata + .as_ref() + .and_then(|metadata| metadata.payment_revenue_recovery_metadata.as_ref()); + + let card_network_str = billing_connector_payment_method_details + .and_then(|details| match details { + BillingConnectorPaymentMethodDetails::Card(card_info) => card_info.card_network.clone(), + }) + .map(|cn| cn.to_string()); + + let card_issuer_str = + billing_connector_payment_method_details.and_then(|details| match details { + BillingConnectorPaymentMethodDetails::Card(card_info) => card_info.card_issuer.clone(), + }); + + let card_funding_str = payment_intent + .feature_metadata + .as_ref() + .and_then(|revenue_recovery_data| { + revenue_recovery_data + .payment_revenue_recovery_metadata + .as_ref() + }) + .map(|payment_metadata| payment_metadata.payment_method_subtype.to_string()); + + let start_time_primitive = payment_intent.created_at; + let recovery_timestamp_config = &state.conf.revenue_recovery.recovery_timestamp; + + let modified_start_time_primitive = start_time_primitive.saturating_add(time::Duration::hours( + recovery_timestamp_config.initial_timestamp_in_hours, + )); + let start_time_proto = date_time::convert_to_prost_timestamp(modified_start_time_primitive); + + let merchant_id = Some(payment_intent.merchant_id.get_string_repr().to_string()); + let invoice_amount = Some( + payment_intent + .amount_details + .order_amount + .get_amount_as_i64(), + ); + let invoice_currency = Some(payment_intent.amount_details.currency.to_string()); + + let billing_country = payment_intent + .billing_address + .as_ref() + .and_then(|addr_enc| addr_enc.get_inner().address.as_ref()) + .and_then(|details| details.country.as_ref()) + .map(|country| country.to_string()); + + let billing_city = payment_intent + .billing_address + .as_ref() + .and_then(|addr_enc| addr_enc.get_inner().address.as_ref()) + .and_then(|details| details.city.as_ref()) + .cloned(); + + let attempt_currency = Some(payment_intent.amount_details.currency.to_string()); + let attempt_status = Some(payment_attempt.status.to_string()); + let attempt_amount = Some( + payment_attempt + .amount_details + .get_net_amount() + .get_amount_as_i64(), + ); + let attempt_response_time = Some(date_time::convert_to_prost_timestamp( + payment_attempt.created_at, + )); + let payment_method_type = Some(payment_attempt.payment_method_type.to_string()); + let payment_gateway = payment_attempt.connector.clone(); + + let pg_error_code = payment_attempt + .error + .as_ref() + .map(|error| error.code.clone()); + let network_advice_code = payment_attempt + .error + .as_ref() + .and_then(|error| error.network_advice_code.clone()); + let network_error_code = payment_attempt + .error + .as_ref() + .and_then(|error| error.network_decline_code.clone()); + + let first_pg_error_code = revenue_recovery_metadata + .and_then(|metadata| metadata.first_payment_attempt_pg_error_code.clone()); + let first_network_advice_code = revenue_recovery_metadata + .and_then(|metadata| metadata.first_payment_attempt_network_advice_code.clone()); + let first_network_error_code = revenue_recovery_metadata + .and_then(|metadata| metadata.first_payment_attempt_network_decline_code.clone()); + + let invoice_due_date = revenue_recovery_metadata + .and_then(|metadata| metadata.invoice_next_billing_time) + .map(date_time::convert_to_prost_timestamp); + + let decider_request = InternalDeciderRequest { + first_error_message, + billing_state, + card_funding: card_funding_str, + card_network: card_network_str, + card_issuer: card_issuer_str, + invoice_start_time: start_time_proto, + retry_count: Some(retry_count.into()), + merchant_id, + invoice_amount, + invoice_currency, + invoice_due_date, + billing_country, + billing_city, + attempt_currency, + attempt_status, + attempt_amount, + pg_error_code, + network_advice_code, + network_error_code, + first_pg_error_code, + first_network_advice_code, + first_network_error_code, + attempt_response_time, + payment_method_type, + payment_gateway, + retry_count_left: None, + first_error_msg_time: None, + wait_time: None, + }; + + if let Some(mut client) = state.grpc_client.recovery_decider_client.clone() { + match client + .decide_on_retry(decider_request.into(), state.get_recovery_grpc_headers()) + .await + { + Ok(grpc_response) => grpc_response + .retry_flag + .then_some(()) + .and(grpc_response.retry_time) + .and_then(|prost_ts| { + match date_time::convert_from_prost_timestamp(&prost_ts) { + Ok(pdt) => Some(pdt), + Err(e) => { + logger::error!( + "Failed to convert retry_time from prost::Timestamp: {e:?}" + ); + None // If conversion fails, treat as no valid retry time + } + } + }), + + Err(e) => { + logger::error!("Recovery decider gRPC call failed: {e:?}"); + None + } + } + } else { + logger::debug!("Recovery decider client is not configured"); + None + } +} + +#[cfg(feature = "v2")] +#[derive(Debug)] +struct InternalDeciderRequest { + first_error_message: String, + billing_state: Option<Secret<String>>, + card_funding: Option<String>, + card_network: Option<String>, + card_issuer: Option<String>, + invoice_start_time: prost_types::Timestamp, + retry_count: Option<i64>, + merchant_id: Option<String>, + invoice_amount: Option<i64>, + invoice_currency: Option<String>, + invoice_due_date: Option<prost_types::Timestamp>, + billing_country: Option<String>, + billing_city: Option<String>, + attempt_currency: Option<String>, + attempt_status: Option<String>, + attempt_amount: Option<i64>, + pg_error_code: Option<String>, + network_advice_code: Option<String>, + network_error_code: Option<String>, + first_pg_error_code: Option<String>, + first_network_advice_code: Option<String>, + first_network_error_code: Option<String>, + attempt_response_time: Option<prost_types::Timestamp>, + payment_method_type: Option<String>, + payment_gateway: Option<String>, + retry_count_left: Option<i64>, + first_error_msg_time: Option<prost_types::Timestamp>, + wait_time: Option<prost_types::Timestamp>, +} + +#[cfg(feature = "v2")] +impl From<InternalDeciderRequest> for external_grpc_client::DeciderRequest { + fn from(internal_request: InternalDeciderRequest) -> Self { + Self { + first_error_message: internal_request.first_error_message, + billing_state: internal_request.billing_state.map(|s| s.peek().to_string()), + card_funding: internal_request.card_funding, + card_network: internal_request.card_network, + card_issuer: internal_request.card_issuer, + invoice_start_time: Some(internal_request.invoice_start_time), + retry_count: internal_request.retry_count, + merchant_id: internal_request.merchant_id, + invoice_amount: internal_request.invoice_amount, + invoice_currency: internal_request.invoice_currency, + invoice_due_date: internal_request.invoice_due_date, + billing_country: internal_request.billing_country, + billing_city: internal_request.billing_city, + attempt_currency: internal_request.attempt_currency, + attempt_status: internal_request.attempt_status, + attempt_amount: internal_request.attempt_amount, + pg_error_code: internal_request.pg_error_code, + network_advice_code: internal_request.network_advice_code, + network_error_code: internal_request.network_error_code, + first_pg_error_code: internal_request.first_pg_error_code, + first_network_advice_code: internal_request.first_network_advice_code, + first_network_error_code: internal_request.first_network_error_code, + attempt_response_time: internal_request.attempt_response_time, + payment_method_type: internal_request.payment_method_type, + payment_gateway: internal_request.payment_gateway, + retry_count_left: internal_request.retry_count_left, + first_error_msg_time: internal_request.first_error_msg_time, + wait_time: internal_request.wait_time, + } + } +} diff --git a/proto/recovery_decider.proto b/proto/recovery_decider.proto new file mode 100644 index 00000000000..28543b8fa28 --- /dev/null +++ b/proto/recovery_decider.proto @@ -0,0 +1,45 @@ +syntax = "proto3"; + +package decider; + +import "google/protobuf/timestamp.proto"; + +service Decider { + rpc Decide (DeciderRequest) returns (DeciderResponse); +} + +message DeciderRequest { + string first_error_message = 1; + optional string billing_state = 2; + optional string card_funding = 3; + optional string card_network = 4; + optional string card_issuer = 5; + google.protobuf.Timestamp invoice_start_time = 6; + optional int64 retry_count = 7; + optional string merchant_id = 8; + optional int64 invoice_amount = 9; + optional string invoice_currency = 10; + optional google.protobuf.Timestamp invoice_due_date = 11; + optional string billing_country = 12; + optional string billing_city = 13; + optional string attempt_currency = 14; + optional string attempt_status = 15; + optional int64 attempt_amount = 16; + optional string pg_error_code = 17; + optional string network_advice_code = 18; + optional string network_error_code = 19; + optional string first_pg_error_code = 20; + optional string first_network_advice_code = 21; + optional string first_network_error_code = 22; + optional google.protobuf.Timestamp attempt_response_time = 23; + optional string payment_method_type = 24; + optional string payment_gateway = 25; + optional int64 retry_count_left = 26; + optional google.protobuf.Timestamp first_error_msg_time = 27; + optional google.protobuf.Timestamp wait_time = 28; +} + +message DeciderResponse { + bool retry_flag = 1; + google.protobuf.Timestamp retry_time = 2; +}
2025-05-29T10:34:56Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> I have implemented a gRPC client that facilitates communication with the recovery-decider gRPC service. The client should be capable of initializing and managing the connection to the service, sending requests, and handling responses in accordance with the defined service contract (protobuf definitions). ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Decider gRPC server:- <img width="1227" alt="Screenshot 2025-06-11 at 01 16 34" src="https://github.com/user-attachments/assets/b4887ed0-4315-406e-b393-cbd9bf480c95" /> Decider gRPC client(HS):- <img width="1159" alt="Screenshot 2025-06-05 at 02 05 20" src="https://github.com/user-attachments/assets/bbddd857-29e8-49bc-bb73-9797f8837b5b" /> Predictor gRPC server:- <img width="1201" alt="Screenshot 2025-06-05 at 02 03 06" src="https://github.com/user-attachments/assets/a3afdb68-33e7-4c4c-8117-8a3a501ecdb8" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Introduced support for a gRPC client: Recovery Decider, enabling external retry decisioning. - Integrated dynamic scheduling for smart retry logic based on external gRPC service responses. - Added new protobuf definition for Recovery Decider. - **Improvements** - Enhanced revenue recovery payment flow with richer payment intent context and smarter retry scheduling. - Expanded logging and API flow tracking with new flow types. - **Configuration** - Added configuration options for new gRPC clients in the development environment. - **Bug Fixes** - Improved error handling and logging for gRPC client interactions.
v1.115.0
640d0552f96721d63c14fda4a07fc5987cea29a0
640d0552f96721d63c14fda4a07fc5987cea29a0
juspay/hyperswitch
juspay__hyperswitch-8173
Bug: update(ci): update S3 Source File Name in Postman Collection Runner Workflow The S3 source file name in the Postman Collection Runner workflow needs to be updated due to changes in the Connector Auth File. This modification ensures that the correct file is referenced in CI/CD workflows, maintaining authentication integrity.
2025-05-29T08:10:44Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [x] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> The S3 Source File Name in Postman Collection Runner Workflow has been changed because the Connector Auth File has been updated. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> The connector auth file has been updated, so updating the S3 source file name is required. ## How can we test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Stripe Test cases on Jenkins should pass. ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
b8e7a868ade62ff21498203d9e14edae094071d9
b8e7a868ade62ff21498203d9e14edae094071d9
juspay/hyperswitch
juspay__hyperswitch-8168
Bug: [BUG] payout routing for Sepa transactions result in a 4xx error ### Bug Description Creating payout transactions for SEPA are resulting in a 4xx error with below message. ``` { "error": { "type": "invalid_request", "message": "No eligible connector was found for the current payment method configuration", "code": "IR_39" } } ``` ### Expected Behavior Payout transactions for SEPA should be routed through eligible connectors. ### Actual Behavior Payout routing fails to get an eligible connector for SEPA bank transfers. ### Steps To Reproduce 1. Create Wise connector 2. Try creating a SEPA payout 3. It should throw below error response ``` { "error": { "type": "invalid_request", "message": "No eligible connector was found for the current payment method configuration", "code": "IR_39" } } ``` ### Context For The Bug This is happening due to a mismatch in what is configured for available payment methods during MCA creation - which stores `sepa` as payment method type in DB - vs what is used during payout routing - which uses `sepa_bank_transfer` for SEPA transactions. MCA creation on dashboard uses a wasm build which contains the info for enabling the right payment method types for payouts. It is configured to use `sepa` instead of `sepa_bank_transfer` (which is being used in the payout flow). There was an activity to rename `Sepa` to `SepaBankTransfer` recently. More details [here](https://github.com/juspay/hyperswitch/pull/7575). ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/euclid/src/enums.rs b/crates/euclid/src/enums.rs index cfd410f0d3b..22fb997530c 100644 --- a/crates/euclid/src/enums.rs +++ b/crates/euclid/src/enums.rs @@ -123,7 +123,7 @@ pub enum MandateType { pub enum PayoutBankTransferType { Ach, Bacs, - Sepa, + SepaBankTransfer, } #[cfg(feature = "payouts")]
2025-07-28T04:52:10Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix ## Description This PR fixes SEPA payout routing failures by updating database configurations to use `sepa_bank_transfer` instead of `sepa` for payout flows. This was missed as part of the refactoring in https://github.com/juspay/hyperswitch/pull/7575 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## Motivation and Context SEPA payout transactions were failing with IR_39 error "No eligible connector was found" due to mismatch between MCA creation (storing `sepa`) and payout routing (expecting `sepa_bank_transfer`). ## How did you test it? <details> <summary>1. Create payout MCA with correct payment method types</summary> cURL curl --location --request POST 'http://localhost:8080/account/merchant_1753677780/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_fz41TYdizfMTp52AI6fK3rVBgJBOCBTDPJb5L60zwrwjWtl1L4Kowt6vjDDMtlHh' \ --data '{"connector_type":"payout_processor","connector_name":"adyenplatform","connector_account_details":{"auth_type":"HeaderKey","api_key":"--REDACTED--"},"test_mode":true,"disabled":false,"connector_webhook_details":{"merchant_secret":"--REDACTED--"},"metadata":{"city":"NY","unit":"245","source_balance_account":"--REDACTED--"},"payment_methods_enabled":[{"payment_method":"card","payment_method_types":[{"payment_method_type":"credit","payment_experience":null,"card_networks":null,"accepted_currencies":null,"accepted_countries":null,"minimum_amount":1,"maximum_amount":68607706,"recurring_enabled":true,"installment_payment_enabled":true},{"payment_method_type":"debit","payment_experience":null,"card_networks":null,"accepted_currencies":null,"accepted_countries":null,"minimum_amount":1,"maximum_amount":68607706,"recurring_enabled":true,"installment_payment_enabled":true}]},{"payment_method":"bank_transfer","payment_method_types":[{"payment_method_type":"sepa_bank_transfer","payment_experience":null,"card_networks":null,"accepted_currencies":null,"accepted_countries":null,"minimum_amount":1,"maximum_amount":68607706,"recurring_enabled":true,"installment_payment_enabled":true}]}]}' Response {"connector_type":"payout_processor","connector_name":"adyenplatform","connector_label":"adyenplatform_IN_default","merchant_connector_id":"mca_YloX72LoDYUkHncGiPPZ","profile_id":"pro_33khv5M29zLwL9wtxsqw","connector_account_details":{"auth_type":"HeaderKey","api_key":"AQ*********************************************************************************************************************************************************************aH"},"payment_methods_enabled":[{"payment_method":"card","payment_method_types":[{"payment_method_type":"credit","payment_experience":null,"card_networks":null,"accepted_currencies":null,"accepted_countries":null,"minimum_amount":1,"maximum_amount":68607706,"recurring_enabled":true,"installment_payment_enabled":true},{"payment_method_type":"debit","payment_experience":null,"card_networks":null,"accepted_currencies":null,"accepted_countries":null,"minimum_amount":1,"maximum_amount":68607706,"recurring_enabled":true,"installment_payment_enabled":true}]},{"payment_method":"bank_transfer","payment_method_types":[{"payment_method_type":"sepa_bank_transfer","payment_experience":null,"card_networks":null,"accepted_currencies":null,"accepted_countries":null,"minimum_amount":1,"maximum_amount":68607706,"recurring_enabled":true,"installment_payment_enabled":true}]}],"connector_webhook_details":{"merchant_secret":"--REDACTED--","additional_secret":null},"metadata":{"city":"NY","unit":"245","source_balance_account":"--REDACTED--"},"test_mode":true,"disabled":false,"frm_configs":null,"business_country":null,"business_label":null,"business_sub_label":null,"applepay_verified_domains":null,"pm_auth_config":null,"status":"active","additional_merchant_data":null,"connector_wallets_details":null} </details> <details> <summary>2. Process SEPA payout</summary> cURL curl --location --request POST 'http://localhost:8080/payouts/create' \ --header 'Accept-Language: fr' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_fz41TYdizfMTp52AI6fK3rVBgJBOCBTDPJb5L60zwrwjWtl1L4Kowt6vjDDMtlHh' \ --data '{"amount":1,"currency":"EUR","customer_id":"cus_EqPGPc4wDSFQaccgd1LH","description":"Its my first payout request","payout_type":"bank","priority":"instant","payout_method_data":{"bank":{"iban":"FR6410096000403534259742Y90"}},"connector":["adyenplatform"],"billing":{"address":{"line1":"Raadhuisplein","line2":"92","city":"Hoogeveen","state":"FL","zip":"7901 BW","country":"NL","first_name":"John","last_name":"Doe"}},"entity_type":"Individual","recurring":true,"metadata":{"ref":"123"},"confirm":true,"auto_fulfill":true,"profile_id":"pro_33khv5M29zLwL9wtxsqw"}' Response {"payout_id":"payout_e6ksBET8el30f3dx0h3c","merchant_id":"merchant_1753677780","merchant_order_reference_id":null,"amount":1,"currency":"EUR","connector":"adyenplatform","payout_type":"bank","payout_method_data":{"bank":{"iban":"FR641*****************42Y90","bank_name":null,"bank_country_code":null,"bank_city":null,"bic":null}},"billing":{"address":{"city":"Hoogeveen","country":"NL","line1":"Raadhuisplein","line2":"92","line3":null,"zip":"7901 BW","state":"FL","first_name":"John","last_name":"Doe"},"phone":null,"email":null},"auto_fulfill":true,"customer_id":"cus_EqPGPc4wDSFQaccgd1LH","customer":{"id":"cus_EqPGPc4wDSFQaccgd1LH","name":"John Nether","email":null,"phone":"6168205362","phone_country_code":"+1"},"client_secret":"payout_payout_e6ksBET8el30f3dx0h3c_secret_v3aGZrFuRRmGgsUx6IzH","return_url":null,"business_country":null,"business_label":null,"description":"Its my first payout request","entity_type":"Individual","recurring":true,"metadata":{"ref":"123"},"merchant_connector_id":"mca_YloX72LoDYUkHncGiPPZ","status":"initiated","error_message":null,"error_code":null,"profile_id":"pro_33khv5M29zLwL9wtxsqw","created":"2025-07-28T04:45:54.833Z","connector_transaction_id":"38E99D67SA9RK52A","priority":"instant","payout_link":null,"email":null,"name":"John Nether","phone":"6168205362","phone_country_code":"+1","unified_code":null,"unified_message":null,"payout_method_id":"pm_uQh6dJST71ojH7qKyqfb"} </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.115.0
7667ec1ca95f278d9d762294da170ae05eda6c56
7667ec1ca95f278d9d762294da170ae05eda6c56
juspay/hyperswitch
juspay__hyperswitch-8174
Bug: filter debit networks based on merchant connector account configuration Once the open router call is completed for the co-badged card lookup in a debit routing flow, it returns all the debit networks eligible for the card. These networks must be validated against the merchant-enabled debit networks for each merchant connector account.
diff --git a/crates/router/src/core/debit_routing.rs b/crates/router/src/core/debit_routing.rs index adbd663c5c1..a929c146cec 100644 --- a/crates/router/src/core/debit_routing.rs +++ b/crates/router/src/core/debit_routing.rs @@ -2,7 +2,9 @@ use std::{collections::HashSet, fmt::Debug}; use api_models::{enums as api_enums, open_router}; use common_enums::enums; -use common_utils::id_type; +use common_utils::{ + errors::CustomResult, ext_traits::ValueExt, id_type, types::keymanager::KeyManagerState, +}; use error_stack::ResultExt; use masking::Secret; @@ -22,6 +24,7 @@ use crate::{ api::{self, ConnectorCallType}, domain, }, + utils::id_type::MerchantConnectorAccountId, }; pub struct DebitRoutingResult { @@ -65,7 +68,6 @@ where logger::info!("Performing debit routing for PreDetermined connector"); handle_pre_determined_connector( state, - &debit_routing_config, debit_routing_supported_connectors, &connector_data, payment_data, @@ -77,7 +79,6 @@ where logger::info!("Performing debit routing for Retryable connector"); handle_retryable_connector( state, - &debit_routing_config, debit_routing_supported_connectors, connector_data, payment_data, @@ -234,7 +235,6 @@ pub async fn check_for_debit_routing_connector_in_profile< async fn handle_pre_determined_connector<F, D>( state: &SessionState, - debit_routing_config: &settings::DebitRoutingConfig, debit_routing_supported_connectors: HashSet<api_enums::Connector>, connector_data: &api::ConnectorRoutingData, payment_data: &mut D, @@ -244,6 +244,11 @@ where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { + let db = state.store.as_ref(); + let key_manager_state = &(state).into(); + let merchant_id = payment_data.get_payment_attempt().merchant_id.clone(); + let profile_id = payment_data.get_payment_attempt().profile_id.clone(); + if debit_routing_supported_connectors.contains(&connector_data.connector_data.connector_name) { logger::debug!("Chosen connector is supported for debit routing"); @@ -255,15 +260,43 @@ where debit_routing_output.co_badged_card_networks ); - let valid_connectors = build_connector_routing_data( - connector_data, - debit_routing_config, - &debit_routing_output.co_badged_card_networks, - ); + let key_store = db + .get_merchant_key_store_by_merchant_id( + key_manager_state, + &merchant_id, + &db.get_master_key().to_vec().into(), + ) + .await + .change_context(errors::ApiErrorResponse::MerchantAccountNotFound) + .map_err(|error| { + logger::error!( + "Failed to get merchant key store by merchant_id {:?}", + error + ) + }) + .ok()?; + + let connector_routing_data = build_connector_routing_data( + state, + &profile_id, + &key_store, + vec![connector_data.clone()], + debit_routing_output.co_badged_card_networks.clone(), + ) + .await + .map_err(|error| { + logger::error!( + "Failed to build connector routing data for debit routing {:?}", + error + ) + }) + .ok()?; - if !valid_connectors.is_empty() { + if !connector_routing_data.is_empty() { return Some(DebitRoutingResult { - debit_routing_connector_call_type: ConnectorCallType::Retryable(valid_connectors), + debit_routing_connector_call_type: ConnectorCallType::Retryable( + connector_routing_data, + ), debit_routing_output, }); } @@ -377,44 +410,8 @@ where } } -fn check_connector_support_for_network( - debit_routing_config: &settings::DebitRoutingConfig, - connector_name: api_enums::Connector, - network: &enums::CardNetwork, -) -> Option<enums::CardNetwork> { - debit_routing_config - .connector_supported_debit_networks - .get(&connector_name) - .and_then(|supported_networks| { - (supported_networks.contains(network) || network.is_global_network()) - .then(|| network.clone()) - }) -} - -fn build_connector_routing_data( - connector_data: &api::ConnectorRoutingData, - debit_routing_config: &settings::DebitRoutingConfig, - fee_sorted_debit_networks: &[enums::CardNetwork], -) -> Vec<api::ConnectorRoutingData> { - fee_sorted_debit_networks - .iter() - .filter_map(|network| { - check_connector_support_for_network( - debit_routing_config, - connector_data.connector_data.connector_name, - network, - ) - .map(|valid_network| api::ConnectorRoutingData { - connector_data: connector_data.connector_data.clone(), - network: Some(valid_network), - }) - }) - .collect() -} - async fn handle_retryable_connector<F, D>( state: &SessionState, - debit_routing_config: &settings::DebitRoutingConfig, debit_routing_supported_connectors: HashSet<api_enums::Connector>, connector_data_list: Vec<api::ConnectorRoutingData>, payment_data: &mut D, @@ -424,6 +421,10 @@ where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { + let key_manager_state = &(state).into(); + let db = state.store.as_ref(); + let profile_id = payment_data.get_payment_attempt().profile_id.clone(); + let merchant_id = payment_data.get_payment_attempt().merchant_id.clone(); let is_any_debit_routing_connector_supported = connector_data_list.iter().any(|connector_data| { debit_routing_supported_connectors @@ -433,32 +434,212 @@ where if is_any_debit_routing_connector_supported { let debit_routing_output = get_debit_routing_output::<F, D>(state, payment_data, acquirer_country).await?; - - logger::debug!( - "Sorted co-badged networks: {:?}", - debit_routing_output.co_badged_card_networks - ); - - let supported_connectors: Vec<_> = connector_data_list - .iter() - .flat_map(|connector_data| { - build_connector_routing_data( - connector_data, - debit_routing_config, - &debit_routing_output.co_badged_card_networks, + let key_store = db + .get_merchant_key_store_by_merchant_id( + key_manager_state, + &merchant_id, + &db.get_master_key().to_vec().into(), + ) + .await + .change_context(errors::ApiErrorResponse::MerchantAccountNotFound) + .map_err(|error| { + logger::error!( + "Failed to get merchant key store by merchant_id {:?}", + error ) }) - .collect(); + .ok()?; + + let connector_routing_data = build_connector_routing_data( + state, + &profile_id, + &key_store, + connector_data_list.clone(), + debit_routing_output.co_badged_card_networks.clone(), + ) + .await + .map_err(|error| { + logger::error!( + "Failed to build connector routing data for debit routing {:?}", + error + ) + }) + .ok()?; - if !supported_connectors.is_empty() { + if !connector_routing_data.is_empty() { return Some(DebitRoutingResult { debit_routing_connector_call_type: ConnectorCallType::Retryable( - supported_connectors, + connector_routing_data, ), debit_routing_output, }); - } + }; } None } + +async fn build_connector_routing_data( + state: &SessionState, + profile_id: &id_type::ProfileId, + key_store: &domain::MerchantKeyStore, + eligible_connector_data_list: Vec<api::ConnectorRoutingData>, + fee_sorted_debit_networks: Vec<common_enums::CardNetwork>, +) -> CustomResult<Vec<api::ConnectorRoutingData>, errors::ApiErrorResponse> { + let key_manager_state = &state.into(); + let debit_routing_config = &state.conf.debit_routing_config; + + let mcas_for_profile = + fetch_merchant_connector_accounts(state, key_manager_state, profile_id, key_store).await?; + + let mut connector_routing_data = Vec::new(); + let mut has_us_local_network = false; + + for connector_data in eligible_connector_data_list { + if let Some(routing_data) = process_connector_for_networks( + &connector_data, + &mcas_for_profile, + &fee_sorted_debit_networks, + debit_routing_config, + &mut has_us_local_network, + )? { + connector_routing_data.extend(routing_data); + } + } + + validate_us_local_network_requirement(has_us_local_network)?; + Ok(connector_routing_data) +} + +/// Fetches merchant connector accounts for the given profile +async fn fetch_merchant_connector_accounts( + state: &SessionState, + key_manager_state: &KeyManagerState, + profile_id: &id_type::ProfileId, + key_store: &domain::MerchantKeyStore, +) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::ApiErrorResponse> { + state + .store + .list_enabled_connector_accounts_by_profile_id( + key_manager_state, + profile_id, + key_store, + common_enums::ConnectorType::PaymentProcessor, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to fetch merchant connector accounts") +} + +/// Processes a single connector to find matching networks +fn process_connector_for_networks( + connector_data: &api::ConnectorRoutingData, + mcas_for_profile: &[domain::MerchantConnectorAccount], + fee_sorted_debit_networks: &[common_enums::CardNetwork], + debit_routing_config: &settings::DebitRoutingConfig, + has_us_local_network: &mut bool, +) -> CustomResult<Option<Vec<api::ConnectorRoutingData>>, errors::ApiErrorResponse> { + let Some(merchant_connector_id) = &connector_data.connector_data.merchant_connector_id else { + logger::warn!("Skipping connector with missing merchant_connector_id"); + return Ok(None); + }; + + let Some(account) = find_merchant_connector_account(mcas_for_profile, merchant_connector_id) + else { + logger::warn!( + "No MCA found for merchant_connector_id: {:?}", + merchant_connector_id + ); + return Ok(None); + }; + + let merchant_debit_networks = extract_debit_networks(&account)?; + let matching_networks = find_matching_networks( + &merchant_debit_networks, + fee_sorted_debit_networks, + &connector_data.connector_data, + debit_routing_config, + has_us_local_network, + ); + + Ok(Some(matching_networks)) +} + +/// Finds a merchant connector account by ID +fn find_merchant_connector_account( + mcas: &[domain::MerchantConnectorAccount], + merchant_connector_id: &MerchantConnectorAccountId, +) -> Option<domain::MerchantConnectorAccount> { + mcas.iter() + .find(|mca| mca.merchant_connector_id == *merchant_connector_id) + .cloned() +} + +/// Finds networks that match between merchant and fee-sorted networks +fn find_matching_networks( + merchant_debit_networks: &HashSet<common_enums::CardNetwork>, + fee_sorted_debit_networks: &[common_enums::CardNetwork], + connector_data: &api::ConnectorData, + debit_routing_config: &settings::DebitRoutingConfig, + has_us_local_network: &mut bool, +) -> Vec<api::ConnectorRoutingData> { + let is_routing_enabled = debit_routing_config + .supported_connectors + .contains(&connector_data.connector_name); + + fee_sorted_debit_networks + .iter() + .filter(|network| merchant_debit_networks.contains(network)) + .filter(|network| is_routing_enabled || network.is_global_network()) + .map(|network| { + if network.is_us_local_network() { + *has_us_local_network = true; + } + + api::ConnectorRoutingData { + connector_data: connector_data.clone(), + network: Some(network.clone()), + } + }) + .collect() +} + +/// Validates that at least one US local network is present +fn validate_us_local_network_requirement( + has_us_local_network: bool, +) -> CustomResult<(), errors::ApiErrorResponse> { + if !has_us_local_network { + return Err(errors::ApiErrorResponse::InternalServerError) + .attach_printable("At least one US local network is required in routing"); + } + Ok(()) +} + +fn extract_debit_networks( + account: &domain::MerchantConnectorAccount, +) -> CustomResult<HashSet<common_enums::CardNetwork>, errors::ApiErrorResponse> { + let mut networks = HashSet::new(); + + if let Some(values) = &account.payment_methods_enabled { + for val in values { + let payment_methods_enabled: api_models::admin::PaymentMethodsEnabled = + val.to_owned().parse_value("PaymentMethodsEnabled") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to parse enabled payment methods for a merchant connector account in debit routing flow")?; + + if let Some(types) = payment_methods_enabled.payment_method_types { + for method_type in types { + if method_type.payment_method_type + == api_models::enums::PaymentMethodType::Debit + { + if let Some(card_networks) = method_type.card_networks { + networks.extend(card_networks); + } + } + } + } + } + } + + Ok(networks) +}
2025-05-29T09:01:11Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Once the open router call is completed for the co-badged card lookup in a debit routing flow, it returns all the debit networks eligible for the card. These networks must be validated against the merchant-enabled debit networks for each merchant connector account. This PR adds the necessary filtering logic to enforce this validation. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create a profile and enable debit routing ``` curl --location 'http://localhost:8080/account/merchant_1748851578/business_profile/pro_gEwS6ve9KVqywWL0hmAq' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: ' \ --data '{ "is_debit_routing_enabled": true }' ``` ``` { "merchant_id": "merchant_1748851578", "profile_id": "pro_gEwS6ve9KVqywWL0hmAq", "profile_name": "US_default", "return_url": "https://google.com/success", "enable_payment_response_hash": true, "payment_response_hash_key": "ksFwEBEmzqH60K5XvD60le6J3S742RIcTLKHyZF3O8TwniOm7ldxztuZvFet7Zpb", "redirect_to_merchant_with_http_post": false, "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "webhook_url": null, "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "metadata": null, "routing_algorithm": null, "intent_fulfillment_time": 900, "frm_routing_algorithm": null, "payout_routing_algorithm": null, "applepay_verified_domains": null, "session_expiry": 900, "payment_link_config": null, "authentication_connector_details": null, "use_billing_as_payment_method_billing": true, "extended_card_info_config": null, "collect_shipping_details_from_wallet_connector": false, "collect_billing_details_from_wallet_connector": false, "always_collect_shipping_details_from_wallet_connector": false, "always_collect_billing_details_from_wallet_connector": false, "is_connector_agnostic_mit_enabled": false, "payout_link_config": null, "outgoing_webhook_custom_http_headers": null, "tax_connector_id": null, "is_tax_connector_enabled": false, "is_network_tokenization_enabled": false, "is_auto_retries_enabled": false, "max_auto_retries_enabled": null, "always_request_extended_authorization": null, "is_click_to_pay_enabled": false, "authentication_product_ids": null, "card_testing_guard_config": { "card_ip_blocking_status": "disabled", "card_ip_blocking_threshold": 3, "guest_user_card_blocking_status": "disabled", "guest_user_card_blocking_threshold": 10, "customer_id_blocking_status": "disabled", "customer_id_blocking_threshold": 5, "card_testing_guard_expiry": 3600 }, "is_clear_pan_retries_enabled": false, "force_3ds_challenge": false, "is_debit_routing_enabled": true, "merchant_business_country": null, "is_pre_network_tokenization_enabled": false } ``` -> Create a mca with local debit networks enabled ``` { "payment_method_type": "debit", "card_networks": [ "Nyce", "Star", "Accel" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ``` ``` { "connector_type": "payment_processor", "connector_name": "adyen", "connector_label": "adyen_US_default", "merchant_connector_id": "mca_zMyPaKk9qUVauLL7wFrV", "profile_id": "pro_gEwS6ve9KVqywWL0hmAq", "connector_account_details": { "auth_type": "SignatureKey", "api_key": "AQ*************************************************************************************************************************************************7$", "key1": "Ju********OM", "api_secret": "AQ**********************************************************************************************************************************************************eb" }, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard", "Discover" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ "Nyce", "Star", "Accel" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "paypal", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "samsung_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "connector_webhook_details": null, "test_mode": false, "disabled": false, "frm_configs": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "applepay_verified_domains": null, "pm_auth_config": null, "status": "active", "additional_merchant_data": null } ``` -> Make a payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-feature: router-custom' \ --header 'x-tenant-id: hyperswitch' \ --header 'api-key: ' \ --data-raw '{ "amount": 10000, "amount_to_capture": 10000, "currency": "USD", "confirm": true, "capture_method": "automatic", "setup_future_usage": "on_session", "capture_on": "2022-09-10T10:11:12Z", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "customer_id": "cu_1748852614", "return_url": "http://127.0.0.1:4040", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4000033003300335", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "737" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX", "last_name": "ss" }, "email": "[email protected]" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ``` { "payment_id": "pay_Q769H87jQ58yIcQC73sv", "merchant_id": "merchant_1748851578", "status": "succeeded", "amount": 10000, "net_amount": 10000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 10000, "connector": "adyen", "client_secret": "pay_Q769H87jQ58yIcQC73sv_secret_WiHYRmir48iHRQKZ4lEl", "created": "2025-06-02T08:14:21.393Z", "currency": "USD", "customer_id": "cu_1748852061", "customer": { "id": "cu_1748852061", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0335", "card_type": "DEBIT", "card_network": "Nyce", "card_issuer": "VISA U.S.A. INC.", "card_issuing_country": "UNITEDSTATES", "card_isin": "400003", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": "ss" }, "phone": null, "email": "[email protected]" }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "http://127.0.0.1:4040/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1748852061", "created_at": 1748852061, "expires": 1748855661, "secret": "epk_da558f5301a24518abd1a5199f29b516" }, "manual_retry_allowed": false, "connector_transaction_id": "LZ57WXZRDMJFMZ65", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_Q769H87jQ58yIcQC73sv_1", "payment_link": null, "profile_id": "pro_gEwS6ve9KVqywWL0hmAq", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_zMyPaKk9qUVauLL7wFrV", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-06-02T08:29:21.393Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "125.0.0.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-06-02T08:14:22.686Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` For the above payment the eligible connector is visa, pulse and nyce. Since nyce is the cheapest network for the payment the payment went through it. -> Now in order to test the filtering logic update the mca my removing nyce ``` { "payment_method_type": "debit", "card_networks": [ "Star", "Accel" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ``` -> Make a payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-feature: router-custom' \ --header 'x-tenant-id: hyperswitch' \ --header 'api-key: ' \ --data-raw '{ "amount": 10000, "amount_to_capture": 10000, "currency": "USD", "confirm": true, "capture_method": "automatic", "setup_future_usage": "on_session", "capture_on": "2022-09-10T10:11:12Z", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "customer_id": "cu_1748852960", "return_url": "http://127.0.0.1:4040", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4000033003300335", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "737" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX", "last_name": "ss" }, "email": "[email protected]" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ``` { "payment_id": "pay_wJSrmVAbpj6s9YpaH6oo", "merchant_id": "merchant_1748851578", "status": "succeeded", "amount": 10000, "net_amount": 10000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 10000, "connector": "adyen", "client_secret": "pay_wJSrmVAbpj6s9YpaH6oo_secret_ddu0dC5yz2jePhmhRXwU", "created": "2025-06-02T08:29:13.189Z", "currency": "USD", "customer_id": "cu_1748852953", "customer": { "id": "cu_1748852953", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0335", "card_type": "DEBIT", "card_network": "Visa", "card_issuer": "VISA U.S.A. INC.", "card_issuing_country": "UNITEDSTATES", "card_isin": "400003", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": "ss" }, "phone": null, "email": "[email protected]" }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "http://127.0.0.1:4040/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1748852953", "created_at": 1748852953, "expires": 1748856553, "secret": "epk_d82b5b921478431fb6739e549f75a175" }, "manual_retry_allowed": false, "connector_transaction_id": "ZPGN742WSN32HF75", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_wJSrmVAbpj6s9YpaH6oo_1", "payment_link": null, "profile_id": "pro_gEwS6ve9KVqywWL0hmAq", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_zMyPaKk9qUVauLL7wFrV", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-06-02T08:44:13.189Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "125.0.0.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-06-02T08:29:15.270Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` Since nyce and pulse is not enabled for a mca payment was processed with visa. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **Refactor** - Enhanced debit routing to be profile- and merchant-aware, improving connector and network selection accuracy. - Enforced US local network presence requirement for debit routing compliance. - Improved error handling and logging for better diagnostics. - **Bug Fixes** - Resolved network selection issues by filtering connectors and networks based on merchant account eligibility. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
v1.114.0
b159a1d23dd37a038debaa0538355e14a3847249
b159a1d23dd37a038debaa0538355e14a3847249
juspay/hyperswitch
juspay__hyperswitch-8161
Bug: refactor(success_based): add support for exploration
diff --git a/api-reference/hyperswitch_intelligent_router_open_api_spec.yml b/api-reference/hyperswitch_intelligent_router_open_api_spec.yml index 58bff737f3e..7372a083b88 100644 --- a/api-reference/hyperswitch_intelligent_router_open_api_spec.yml +++ b/api-reference/hyperswitch_intelligent_router_open_api_spec.yml @@ -44,6 +44,7 @@ paths: min_aggregates_size: 5 default_success_rate: 0.95 specificity_level: ENTITY + exploration_percent: 20.0 responses: "200": description: Success rate calculated successfully @@ -758,6 +759,17 @@ components: items: $ref: "#/components/schemas/LabelWithScore" description: List of labels with their calculated success rates + routing_approach: + $ref: "#/components/schemas/RoutingApproach" + + RoutingApproach: + type: string + description: > + Defines the routing approach based on the success rate calculation. + enum: + - EXPLORATION + - EXPLOITATION + example: EXPLOITATION UpdateSuccessRateWindowRequest: type: object diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 19b15a63a81..5e738e6b382 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -27309,6 +27309,11 @@ }, "specificity_level": { "$ref": "#/components/schemas/SuccessRateSpecificityLevel" + }, + "exploration_percent": { + "type": "number", + "format": "double", + "nullable": true } } }, diff --git a/crates/api_models/src/open_router.rs b/crates/api_models/src/open_router.rs index f15d9cbcfeb..cfcb45ef97b 100644 --- a/crates/api_models/src/open_router.rs +++ b/crates/api_models/src/open_router.rs @@ -62,6 +62,7 @@ pub struct PaymentInfo { pub struct DecidedGateway { pub gateway_priority_map: Option<HashMap<String, f64>>, pub debit_routing_output: Option<DebitRoutingOutput>, + pub routing_approach: String, } #[derive(Debug, Serialize, Deserialize, PartialEq)] diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index 12075935cd4..a247e6ad9ca 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -944,6 +944,7 @@ impl Default for SuccessBasedRoutingConfig { max_total_count: Some(5), }), specificity_level: SuccessRateSpecificityLevel::default(), + exploration_percent: Some(20.0), }), decision_engine_configs: None, } @@ -969,6 +970,7 @@ pub struct SuccessBasedRoutingConfigBody { pub current_block_threshold: Option<CurrentBlockThreshold>, #[serde(default)] pub specificity_level: SuccessRateSpecificityLevel, + pub exploration_percent: Option<f64>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] @@ -1094,7 +1096,10 @@ impl SuccessBasedRoutingConfigBody { .as_mut() .map(|threshold| threshold.update(current_block_threshold)); } - self.specificity_level = new.specificity_level + self.specificity_level = new.specificity_level; + if let Some(exploration_percent) = new.exploration_percent { + self.exploration_percent = Some(exploration_percent); + } } } diff --git a/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs b/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs index 278a2b50d15..b63f435327e 100644 --- a/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs +++ b/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs @@ -290,6 +290,7 @@ impl ForeignTryFrom<SuccessBasedRoutingConfigBody> for CalSuccessRateConfig { SuccessRateSpecificityLevel::Merchant => Some(ProtoSpecificityLevel::Entity.into()), SuccessRateSpecificityLevel::Global => Some(ProtoSpecificityLevel::Global.into()), }, + exploration_percent: config.exploration_percent, }) } } diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 2b851c192b0..265a518f244 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -1776,10 +1776,7 @@ pub async fn perform_decide_gateway_call_with_open_router( ))?; if let Some(gateway_priority_map) = decided_gateway.gateway_priority_map { - logger::debug!( - "open_router decide_gateway call response: {:?}", - gateway_priority_map - ); + logger::debug!(gateway_priority_map=?gateway_priority_map, routing_approach=decided_gateway.routing_approach, "open_router decide_gateway call response"); routable_connectors.sort_by(|connector_choice_a, connector_choice_b| { let connector_choice_a_score = gateway_priority_map .get(&connector_choice_a.to_string()) diff --git a/proto/success_rate.proto b/proto/success_rate.proto index 17d566af356..efdd439cac9 100644 --- a/proto/success_rate.proto +++ b/proto/success_rate.proto @@ -23,6 +23,7 @@ message CalSuccessRateConfig { uint32 min_aggregates_size = 1; double default_success_rate = 2; optional SuccessRateSpecificityLevel specificity_level = 3; + optional double exploration_percent = 4; } enum SuccessRateSpecificityLevel { @@ -32,6 +33,12 @@ enum SuccessRateSpecificityLevel { message CalSuccessRateResponse { repeated LabelWithScore labels_with_score = 1; + RoutingApproach routing_approach = 2; +} + +enum RoutingApproach { + EXPLORATION = 0; + EXPLOITATION = 1; } message LabelWithScore {
2025-05-27T18:08:26Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Original PR - https://github.com/juspay/hyperswitch/pull/8158 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
a830a070ba6786201a26aeeb7cf21a2d44528684
a830a070ba6786201a26aeeb7cf21a2d44528684
juspay/hyperswitch
juspay__hyperswitch-8176
Bug: Properly Handle encoded_data in PSync flow [v2] PSync is failing for adyen with error: `validate_psync_reference_id failed`. We need to pass the `encoded_data` in payment_attempt
diff --git a/crates/router/src/core/payments/operations/payment_get.rs b/crates/router/src/core/payments/operations/payment_get.rs index ebf8205ea9b..716030c8f43 100644 --- a/crates/router/src/core/payments/operations/payment_get.rs +++ b/crates/router/src/core/payments/operations/payment_get.rs @@ -177,7 +177,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentStatusData<F>, PaymentsRetriev } })?; - let payment_attempt = db + let mut payment_attempt = db .find_payment_attempt_by_id( key_manager_state, merchant_context.get_merchant_key_store(), @@ -188,6 +188,11 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentStatusData<F>, PaymentsRetriev .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not find payment attempt given the attempt id")?; + payment_attempt.encoded_data = request + .param + .as_ref() + .map(|val| masking::Secret::new(val.clone())); + let should_sync_with_connector = request.force_sync && payment_intent.status.should_force_sync_with_connector();
2025-05-29T10:29:06Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Add `encoded_data` from `PaymentsRetrieveRequest` in `payment_attempt` inside `get_trackers` for PSync ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #8176 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> No visible changes in API response. Verified that payment status changes to `succeeded`. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
d91cf70ae346cbf613ce5c1cfad2ae8a28c71d1c
d91cf70ae346cbf613ce5c1cfad2ae8a28c71d1c
juspay/hyperswitch
juspay__hyperswitch-8180
Bug: [FEATURE] Authentication Analytics Enhancement for 3DS Intelligence Engine ### Feature Description Add new query filters for refined 3DS analytics Expose exemption data (exemption_requested, exemption_approved) in the response Support Sankey-chart metrics by returning flow-ready data ### Possible Implementation Changed auth analytics APIs. ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/analytics/src/auth_events.rs b/crates/analytics/src/auth_events.rs index 3aa23d0793d..2ce5d52f9b1 100644 --- a/crates/analytics/src/auth_events.rs +++ b/crates/analytics/src/auth_events.rs @@ -2,7 +2,8 @@ pub mod accumulator; mod core; pub mod filters; pub mod metrics; +pub mod sankey; pub mod types; pub use accumulator::{AuthEventMetricAccumulator, AuthEventMetricsAccumulator}; -pub use self::core::{get_filters, get_metrics}; +pub use self::core::{get_filters, get_metrics, get_sankey}; diff --git a/crates/analytics/src/auth_events/accumulator.rs b/crates/analytics/src/auth_events/accumulator.rs index 13818d2bd43..2ee5d242d63 100644 --- a/crates/analytics/src/auth_events/accumulator.rs +++ b/crates/analytics/src/auth_events/accumulator.rs @@ -14,6 +14,8 @@ pub struct AuthEventMetricsAccumulator { pub frictionless_flow_count: CountAccumulator, pub frictionless_success_count: CountAccumulator, pub authentication_funnel: CountAccumulator, + pub authentication_exemption_approved_count: CountAccumulator, + pub authentication_exemption_requested_count: CountAccumulator, } #[derive(Debug, Default)] @@ -80,6 +82,12 @@ impl AuthEventMetricsAccumulator { frictionless_success_count: self.frictionless_success_count.collect(), error_message_count: self.authentication_error_message.collect(), authentication_funnel: self.authentication_funnel.collect(), + authentication_exemption_approved_count: self + .authentication_exemption_approved_count + .collect(), + authentication_exemption_requested_count: self + .authentication_exemption_requested_count + .collect(), } } } diff --git a/crates/analytics/src/auth_events/core.rs b/crates/analytics/src/auth_events/core.rs index 4d11f19d531..41b7b724954 100644 --- a/crates/analytics/src/auth_events/core.rs +++ b/crates/analytics/src/auth_events/core.rs @@ -8,15 +8,18 @@ use api_models::analytics::{ AuthEventFilterValue, AuthEventFiltersResponse, AuthEventMetricsResponse, AuthEventsAnalyticsMetadata, GetAuthEventFilterRequest, GetAuthEventMetricRequest, }; +use common_utils::types::TimeRange; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; use super::{ filters::{get_auth_events_filter_for_dimension, AuthEventFilterRow}, + sankey::{get_sankey_data, SankeyRow}, AuthEventMetricsAccumulator, }; use crate::{ auth_events::AuthEventMetricAccumulator, + enums::AuthInfo, errors::{AnalyticsError, AnalyticsResult}, AnalyticsProvider, }; @@ -92,6 +95,12 @@ pub async fn get_metrics( AuthEventMetrics::AuthenticationFunnel => metrics_builder .authentication_funnel .add_metrics_bucket(&value), + AuthEventMetrics::AuthenticationExemptionApprovedCount => metrics_builder + .authentication_exemption_approved_count + .add_metrics_bucket(&value), + AuthEventMetrics::AuthenticationExemptionRequestedCount => metrics_builder + .authentication_exemption_requested_count + .add_metrics_bucket(&value), } } } @@ -170,6 +179,27 @@ pub async fn get_filters( AuthEventDimensions::AuthenticationConnector => fil.authentication_connector.map(|i| i.as_ref().to_string()), AuthEventDimensions::MessageVersion => fil.message_version, AuthEventDimensions::AcsReferenceNumber => fil.acs_reference_number, + AuthEventDimensions::Platform => fil.platform, + AuthEventDimensions::Mcc => fil.mcc, + AuthEventDimensions::Currency => fil.currency.map(|i| i.as_ref().to_string()), + AuthEventDimensions::MerchantCountry => fil.merchant_country, + AuthEventDimensions::BillingCountry => fil.billing_country, + AuthEventDimensions::ShippingCountry => fil.shipping_country, + AuthEventDimensions::IssuerCountry => fil.issuer_country, + AuthEventDimensions::EarliestSupportedVersion => fil.earliest_supported_version, + AuthEventDimensions::LatestSupportedVersion => fil.latest_supported_version, + AuthEventDimensions::WhitelistDecision => fil.whitelist_decision.map(|i| i.to_string()), + AuthEventDimensions::DeviceManufacturer => fil.device_manufacturer, + AuthEventDimensions::DeviceType => fil.device_type, + AuthEventDimensions::DeviceBrand => fil.device_brand, + AuthEventDimensions::DeviceOs => fil.device_os, + AuthEventDimensions::DeviceDisplay => fil.device_display, + AuthEventDimensions::BrowserName => fil.browser_name, + AuthEventDimensions::BrowserVersion => fil.browser_version, + AuthEventDimensions::IssuerId => fil.issuer_id, + AuthEventDimensions::SchemeName => fil.scheme_name, + AuthEventDimensions::ExemptionRequested => fil.exemption_requested.map(|i| i.to_string()), + AuthEventDimensions::ExemptionAccepted => fil.exemption_accepted.map(|i| i.to_string()), }) .collect::<Vec<String>>(); res.query_data.push(AuthEventFilterValue { @@ -179,3 +209,24 @@ pub async fn get_filters( } Ok(res) } + +#[instrument(skip_all)] +pub async fn get_sankey( + pool: &AnalyticsProvider, + auth: &AuthInfo, + req: TimeRange, +) -> AnalyticsResult<Vec<SankeyRow>> { + match pool { + AnalyticsProvider::Sqlx(_) => Err(AnalyticsError::NotImplemented( + "Sankey not implemented for sqlx", + ))?, + AnalyticsProvider::Clickhouse(ckh_pool) + | AnalyticsProvider::CombinedCkh(_, ckh_pool) + | AnalyticsProvider::CombinedSqlx(_, ckh_pool) => { + let sankey_rows = get_sankey_data(ckh_pool, auth, &req) + .await + .change_context(AnalyticsError::UnknownError)?; + Ok(sankey_rows) + } + } +} diff --git a/crates/analytics/src/auth_events/filters.rs b/crates/analytics/src/auth_events/filters.rs index 1961116b84c..92496131727 100644 --- a/crates/analytics/src/auth_events/filters.rs +++ b/crates/analytics/src/auth_events/filters.rs @@ -1,5 +1,5 @@ use api_models::analytics::{auth_events::AuthEventDimensions, Granularity, TimeRange}; -use common_enums::DecoupledAuthenticationType; +use common_enums::{Currency, DecoupledAuthenticationType}; use common_utils::errors::ReportSwitchExt; use diesel_models::enums::{AuthenticationConnectors, AuthenticationStatus, TransactionStatus}; use error_stack::ResultExt; @@ -60,4 +60,25 @@ pub struct AuthEventFilterRow { pub authentication_connector: Option<DBEnumWrapper<AuthenticationConnectors>>, pub message_version: Option<String>, pub acs_reference_number: Option<String>, + pub platform: Option<String>, + pub mcc: Option<String>, + pub currency: Option<DBEnumWrapper<Currency>>, + pub merchant_country: Option<String>, + pub billing_country: Option<String>, + pub shipping_country: Option<String>, + pub issuer_country: Option<String>, + pub earliest_supported_version: Option<String>, + pub latest_supported_version: Option<String>, + pub whitelist_decision: Option<bool>, + pub device_manufacturer: Option<String>, + pub device_type: Option<String>, + pub device_brand: Option<String>, + pub device_os: Option<String>, + pub device_display: Option<String>, + pub browser_name: Option<String>, + pub browser_version: Option<String>, + pub issuer_id: Option<String>, + pub scheme_name: Option<String>, + pub exemption_requested: Option<bool>, + pub exemption_accepted: Option<bool>, } diff --git a/crates/analytics/src/auth_events/metrics.rs b/crates/analytics/src/auth_events/metrics.rs index 6315c1338ee..46c3805662a 100644 --- a/crates/analytics/src/auth_events/metrics.rs +++ b/crates/analytics/src/auth_events/metrics.rs @@ -17,6 +17,8 @@ use crate::{ mod authentication_attempt_count; mod authentication_count; mod authentication_error_message; +mod authentication_exemption_approved_count; +mod authentication_exemption_requested_count; mod authentication_funnel; mod authentication_success_count; mod challenge_attempt_count; @@ -28,6 +30,8 @@ mod frictionless_success_count; use authentication_attempt_count::AuthenticationAttemptCount; use authentication_count::AuthenticationCount; use authentication_error_message::AuthenticationErrorMessage; +use authentication_exemption_approved_count::AuthenticationExemptionApprovedCount; +use authentication_exemption_requested_count::AuthenticationExemptionRequestedCount; use authentication_funnel::AuthenticationFunnel; use authentication_success_count::AuthenticationSuccessCount; use challenge_attempt_count::ChallengeAttemptCount; @@ -46,6 +50,27 @@ pub struct AuthEventMetricRow { pub authentication_connector: Option<DBEnumWrapper<storage_enums::AuthenticationConnectors>>, pub message_version: Option<String>, pub acs_reference_number: Option<String>, + pub platform: Option<String>, + pub mcc: Option<String>, + pub currency: Option<DBEnumWrapper<storage_enums::Currency>>, + pub merchant_country: Option<String>, + pub billing_country: Option<String>, + pub shipping_country: Option<String>, + pub issuer_country: Option<String>, + pub earliest_supported_version: Option<String>, + pub latest_supported_version: Option<String>, + pub whitelist_decision: Option<bool>, + pub device_manufacturer: Option<String>, + pub device_type: Option<String>, + pub device_brand: Option<String>, + pub device_os: Option<String>, + pub device_display: Option<String>, + pub browser_name: Option<String>, + pub browser_version: Option<String>, + pub issuer_id: Option<String>, + pub scheme_name: Option<String>, + pub exemption_requested: Option<bool>, + pub exemption_accepted: Option<bool>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub start_bucket: Option<PrimitiveDateTime>, #[serde(with = "common_utils::custom_serde::iso8601::option")] @@ -210,6 +235,30 @@ where ) .await } + Self::AuthenticationExemptionApprovedCount => { + AuthenticationExemptionApprovedCount + .load_metrics( + merchant_id, + dimensions, + filters, + granularity, + time_range, + pool, + ) + .await + } + Self::AuthenticationExemptionRequestedCount => { + AuthenticationExemptionRequestedCount + .load_metrics( + merchant_id, + dimensions, + filters, + granularity, + time_range, + pool, + ) + .await + } } } } diff --git a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs index fbdc4b75b3e..967513af32c 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs @@ -111,6 +111,26 @@ where i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), i.acs_reference_number.clone(), + i.mcc.clone(), + i.currency.as_ref().map(|i| i.0), + i.merchant_country.clone(), + i.billing_country.clone(), + i.shipping_country.clone(), + i.issuer_country.clone(), + i.earliest_supported_version.clone(), + i.latest_supported_version.clone(), + i.whitelist_decision, + i.device_manufacturer.clone(), + i.device_type.clone(), + i.device_brand.clone(), + i.device_os.clone(), + i.device_display.clone(), + i.browser_name.clone(), + i.browser_version.clone(), + i.issuer_id.clone(), + i.scheme_name.clone(), + i.exemption_requested, + i.exemption_accepted, TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/authentication_count.rs b/crates/analytics/src/auth_events/metrics/authentication_count.rs index b4c0a5c5957..0334f732f23 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_count.rs @@ -101,6 +101,26 @@ where i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), i.acs_reference_number.clone(), + i.mcc.clone(), + i.currency.as_ref().map(|i| i.0), + i.merchant_country.clone(), + i.billing_country.clone(), + i.shipping_country.clone(), + i.issuer_country.clone(), + i.earliest_supported_version.clone(), + i.latest_supported_version.clone(), + i.whitelist_decision, + i.device_manufacturer.clone(), + i.device_type.clone(), + i.device_brand.clone(), + i.device_os.clone(), + i.device_display.clone(), + i.browser_name.clone(), + i.browser_version.clone(), + i.issuer_id.clone(), + i.scheme_name.clone(), + i.exemption_requested, + i.exemption_accepted, TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/authentication_error_message.rs b/crates/analytics/src/auth_events/metrics/authentication_error_message.rs index b064cb7ab30..ac0adc7bbff 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_error_message.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_error_message.rs @@ -120,6 +120,26 @@ where i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), i.acs_reference_number.clone(), + i.mcc.clone(), + i.currency.as_ref().map(|i| i.0), + i.merchant_country.clone(), + i.billing_country.clone(), + i.shipping_country.clone(), + i.issuer_country.clone(), + i.earliest_supported_version.clone(), + i.latest_supported_version.clone(), + i.whitelist_decision, + i.device_manufacturer.clone(), + i.device_type.clone(), + i.device_brand.clone(), + i.device_os.clone(), + i.device_display.clone(), + i.browser_name.clone(), + i.browser_version.clone(), + i.issuer_id.clone(), + i.scheme_name.clone(), + i.exemption_requested, + i.exemption_accepted, TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/authentication_exemption_approved_count.rs b/crates/analytics/src/auth_events/metrics/authentication_exemption_approved_count.rs new file mode 100644 index 00000000000..89ec3affe6b --- /dev/null +++ b/crates/analytics/src/auth_events/metrics/authentication_exemption_approved_count.rs @@ -0,0 +1,148 @@ +use std::collections::HashSet; + +use api_models::analytics::{ + auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::AuthEventMetricRow; +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(super) struct AuthenticationExemptionApprovedCount; + +#[async_trait::async_trait] +impl<T> super::AuthEventMetric<T> for AuthenticationExemptionApprovedCount +where + T: AnalyticsDataSource + super::AuthEventMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + merchant_id: &common_utils::id_type::MerchantId, + dimensions: &[AuthEventDimensions], + filters: &AuthEventFilters, + granularity: Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::Authentications); + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("count"), + }) + .switch()?; + + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + query_builder + .add_filter_clause("merchant_id", merchant_id) + .switch()?; + + query_builder + .add_filter_clause(AuthEventDimensions::ExemptionAccepted, true) + .switch()?; + filters.set_filter_clause(&mut query_builder).switch()?; + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + for dim in dimensions.iter() { + query_builder + .add_group_by_clause(dim) + .attach_printable("Error grouping by dimensions") + .switch()?; + } + + if let Some(granularity) = granularity { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<AuthEventMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + AuthEventMetricsBucketIdentifier::new( + i.authentication_status.as_ref().map(|i| i.0), + i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), + i.error_message.clone(), + i.authentication_connector.as_ref().map(|i| i.0), + i.message_version.clone(), + i.acs_reference_number.clone(), + i.mcc.clone(), + i.currency.as_ref().map(|i| i.0), + i.merchant_country.clone(), + i.billing_country.clone(), + i.shipping_country.clone(), + i.issuer_country.clone(), + i.earliest_supported_version.clone(), + i.latest_supported_version.clone(), + i.whitelist_decision, + i.device_manufacturer.clone(), + i.device_type.clone(), + i.device_brand.clone(), + i.device_os.clone(), + i.device_display.clone(), + i.browser_name.clone(), + i.browser_version.clone(), + i.issuer_id.clone(), + i.scheme_name.clone(), + i.exemption_requested, + i.exemption_accepted, + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result< + HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/auth_events/metrics/authentication_exemption_requested_count.rs b/crates/analytics/src/auth_events/metrics/authentication_exemption_requested_count.rs new file mode 100644 index 00000000000..aa4af1a47ff --- /dev/null +++ b/crates/analytics/src/auth_events/metrics/authentication_exemption_requested_count.rs @@ -0,0 +1,149 @@ +use std::collections::HashSet; + +use api_models::analytics::{ + auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::AuthEventMetricRow; +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(super) struct AuthenticationExemptionRequestedCount; + +#[async_trait::async_trait] +impl<T> super::AuthEventMetric<T> for AuthenticationExemptionRequestedCount +where + T: AnalyticsDataSource + super::AuthEventMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + merchant_id: &common_utils::id_type::MerchantId, + dimensions: &[AuthEventDimensions], + filters: &AuthEventFilters, + granularity: Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::Authentications); + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("count"), + }) + .switch()?; + + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + query_builder + .add_filter_clause("merchant_id", merchant_id) + .switch()?; + + query_builder + .add_filter_clause(AuthEventDimensions::ExemptionRequested, true) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + for dim in dimensions.iter() { + query_builder + .add_group_by_clause(dim) + .attach_printable("Error grouping by dimensions") + .switch()?; + } + + if let Some(granularity) = granularity { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<AuthEventMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + AuthEventMetricsBucketIdentifier::new( + i.authentication_status.as_ref().map(|i| i.0), + i.trans_status.as_ref().map(|i| i.0.clone()), + i.authentication_type.as_ref().map(|i| i.0), + i.error_message.clone(), + i.authentication_connector.as_ref().map(|i| i.0), + i.message_version.clone(), + i.acs_reference_number.clone(), + i.mcc.clone(), + i.currency.as_ref().map(|i| i.0), + i.merchant_country.clone(), + i.billing_country.clone(), + i.shipping_country.clone(), + i.issuer_country.clone(), + i.earliest_supported_version.clone(), + i.latest_supported_version.clone(), + i.whitelist_decision, + i.device_manufacturer.clone(), + i.device_type.clone(), + i.device_brand.clone(), + i.device_os.clone(), + i.device_display.clone(), + i.browser_name.clone(), + i.browser_version.clone(), + i.issuer_id.clone(), + i.scheme_name.clone(), + i.exemption_requested, + i.exemption_accepted, + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result< + HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/auth_events/metrics/authentication_funnel.rs b/crates/analytics/src/auth_events/metrics/authentication_funnel.rs index 3a122fd42a9..145a70a542a 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_funnel.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_funnel.rs @@ -112,6 +112,26 @@ where i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), i.acs_reference_number.clone(), + i.mcc.clone(), + i.currency.as_ref().map(|i| i.0), + i.merchant_country.clone(), + i.billing_country.clone(), + i.shipping_country.clone(), + i.issuer_country.clone(), + i.earliest_supported_version.clone(), + i.latest_supported_version.clone(), + i.whitelist_decision, + i.device_manufacturer.clone(), + i.device_type.clone(), + i.device_brand.clone(), + i.device_os.clone(), + i.device_display.clone(), + i.browser_name.clone(), + i.browser_version.clone(), + i.issuer_id.clone(), + i.scheme_name.clone(), + i.exemption_requested, + i.exemption_accepted, TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs index 37435123623..9788b6477c1 100644 --- a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs @@ -106,6 +106,26 @@ where i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), i.acs_reference_number.clone(), + i.mcc.clone(), + i.currency.as_ref().map(|i| i.0), + i.merchant_country.clone(), + i.billing_country.clone(), + i.shipping_country.clone(), + i.issuer_country.clone(), + i.earliest_supported_version.clone(), + i.latest_supported_version.clone(), + i.whitelist_decision, + i.device_manufacturer.clone(), + i.device_type.clone(), + i.device_brand.clone(), + i.device_os.clone(), + i.device_display.clone(), + i.browser_name.clone(), + i.browser_version.clone(), + i.issuer_id.clone(), + i.scheme_name.clone(), + i.exemption_requested, + i.exemption_accepted, TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs index 0265fc7e457..d3d7dcc7471 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs @@ -116,6 +116,26 @@ where i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), i.acs_reference_number.clone(), + i.mcc.clone(), + i.currency.as_ref().map(|i| i.0), + i.merchant_country.clone(), + i.billing_country.clone(), + i.shipping_country.clone(), + i.issuer_country.clone(), + i.earliest_supported_version.clone(), + i.latest_supported_version.clone(), + i.whitelist_decision, + i.device_manufacturer.clone(), + i.device_type.clone(), + i.device_brand.clone(), + i.device_os.clone(), + i.device_display.clone(), + i.browser_name.clone(), + i.browser_version.clone(), + i.issuer_id.clone(), + i.scheme_name.clone(), + i.exemption_requested, + i.exemption_accepted, TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs index 178dcba20bf..5b951e1fa85 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs @@ -108,6 +108,26 @@ where i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), i.acs_reference_number.clone(), + i.mcc.clone(), + i.currency.as_ref().map(|i| i.0), + i.merchant_country.clone(), + i.billing_country.clone(), + i.shipping_country.clone(), + i.issuer_country.clone(), + i.earliest_supported_version.clone(), + i.latest_supported_version.clone(), + i.whitelist_decision, + i.device_manufacturer.clone(), + i.device_type.clone(), + i.device_brand.clone(), + i.device_os.clone(), + i.device_display.clone(), + i.browser_name.clone(), + i.browser_version.clone(), + i.issuer_id.clone(), + i.scheme_name.clone(), + i.exemption_requested, + i.exemption_accepted, TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs index b78f84326de..2bbd4d81982 100644 --- a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs @@ -113,6 +113,26 @@ where i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), i.acs_reference_number.clone(), + i.mcc.clone(), + i.currency.as_ref().map(|i| i.0), + i.merchant_country.clone(), + i.billing_country.clone(), + i.shipping_country.clone(), + i.issuer_country.clone(), + i.earliest_supported_version.clone(), + i.latest_supported_version.clone(), + i.whitelist_decision, + i.device_manufacturer.clone(), + i.device_type.clone(), + i.device_brand.clone(), + i.device_os.clone(), + i.device_display.clone(), + i.browser_name.clone(), + i.browser_version.clone(), + i.issuer_id.clone(), + i.scheme_name.clone(), + i.exemption_requested, + i.exemption_accepted, TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs index d114e36f140..da8a119d226 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs @@ -109,6 +109,26 @@ where i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), i.acs_reference_number.clone(), + i.mcc.clone(), + i.currency.as_ref().map(|i| i.0), + i.merchant_country.clone(), + i.billing_country.clone(), + i.shipping_country.clone(), + i.issuer_country.clone(), + i.earliest_supported_version.clone(), + i.latest_supported_version.clone(), + i.whitelist_decision, + i.device_manufacturer.clone(), + i.device_type.clone(), + i.device_brand.clone(), + i.device_os.clone(), + i.device_display.clone(), + i.browser_name.clone(), + i.browser_version.clone(), + i.issuer_id.clone(), + i.scheme_name.clone(), + i.exemption_requested, + i.exemption_accepted, TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs index a56d5b660aa..b4fb18e48f6 100644 --- a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs +++ b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs @@ -113,6 +113,26 @@ where i.authentication_connector.as_ref().map(|i| i.0), i.message_version.clone(), i.acs_reference_number.clone(), + i.mcc.clone(), + i.currency.as_ref().map(|i| i.0), + i.merchant_country.clone(), + i.billing_country.clone(), + i.shipping_country.clone(), + i.issuer_country.clone(), + i.earliest_supported_version.clone(), + i.latest_supported_version.clone(), + i.whitelist_decision, + i.device_manufacturer.clone(), + i.device_type.clone(), + i.device_brand.clone(), + i.device_os.clone(), + i.device_display.clone(), + i.browser_name.clone(), + i.browser_version.clone(), + i.issuer_id.clone(), + i.scheme_name.clone(), + i.exemption_requested, + i.exemption_accepted, TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/auth_events/sankey.rs b/crates/analytics/src/auth_events/sankey.rs new file mode 100644 index 00000000000..ede90ad9a81 --- /dev/null +++ b/crates/analytics/src/auth_events/sankey.rs @@ -0,0 +1,88 @@ +use common_enums::AuthenticationStatus; +use common_utils::{ + errors::ParsingError, + types::{authentication::AuthInfo, TimeRange}, +}; +use error_stack::ResultExt; +use router_env::logger; + +use crate::{ + clickhouse::ClickhouseClient, + query::{Aggregate, QueryBuilder, QueryFilter}, + types::{AnalyticsCollection, MetricsError, MetricsResult}, +}; + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct SankeyRow { + pub count: i64, + pub authentication_status: Option<AuthenticationStatus>, + pub exemption_requested: Option<bool>, + pub exemption_accepted: Option<bool>, +} + +impl TryInto<SankeyRow> for serde_json::Value { + type Error = error_stack::Report<ParsingError>; + + fn try_into(self) -> Result<SankeyRow, Self::Error> { + logger::debug!("Parsing SankeyRow from {:?}", self); + serde_json::from_value(self).change_context(ParsingError::StructParseFailure( + "Failed to parse Sankey in clickhouse results", + )) + } +} + +pub async fn get_sankey_data( + clickhouse_client: &ClickhouseClient, + auth: &AuthInfo, + time_range: &TimeRange, +) -> MetricsResult<Vec<SankeyRow>> { + let mut query_builder = + QueryBuilder::<ClickhouseClient>::new(AnalyticsCollection::Authentications); + + query_builder + .add_select_column(Aggregate::<String>::Count { + field: None, + alias: Some("count"), + }) + .change_context(MetricsError::QueryBuildingError)?; + + query_builder + .add_select_column("exemption_requested") + .change_context(MetricsError::QueryBuildingError)?; + + query_builder + .add_select_column("exemption_accepted") + .change_context(MetricsError::QueryBuildingError)?; + + query_builder + .add_select_column("authentication_status") + .change_context(MetricsError::QueryBuildingError)?; + + auth.set_filter_clause(&mut query_builder) + .change_context(MetricsError::QueryBuildingError)?; + + time_range + .set_filter_clause(&mut query_builder) + .change_context(MetricsError::QueryBuildingError)?; + + query_builder + .add_group_by_clause("exemption_requested") + .change_context(MetricsError::QueryBuildingError)?; + + query_builder + .add_group_by_clause("exemption_accepted") + .change_context(MetricsError::QueryBuildingError)?; + + query_builder + .add_group_by_clause("authentication_status") + .change_context(MetricsError::QueryBuildingError)?; + + query_builder + .execute_query::<SankeyRow, _>(clickhouse_client) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(Ok) + .collect() +} diff --git a/crates/analytics/src/auth_events/types.rs b/crates/analytics/src/auth_events/types.rs index 863e50a0af2..4aaa2622676 100644 --- a/crates/analytics/src/auth_events/types.rs +++ b/crates/analytics/src/auth_events/types.rs @@ -54,6 +54,12 @@ where .attach_printable("Error adding message version filter")?; } + if !self.platform.is_empty() { + builder + .add_filter_in_range_clause(AuthEventDimensions::Platform, &self.platform) + .attach_printable("Error adding platform filter")?; + } + if !self.acs_reference_number.is_empty() { builder .add_filter_in_range_clause( @@ -62,6 +68,144 @@ where ) .attach_printable("Error adding acs reference number filter")?; } + + if !self.mcc.is_empty() { + builder + .add_filter_in_range_clause(AuthEventDimensions::Mcc, &self.mcc) + .attach_printable("Failed to add MCC filter")?; + } + if !self.currency.is_empty() { + builder + .add_filter_in_range_clause(AuthEventDimensions::Currency, &self.currency) + .attach_printable("Failed to add currency filter")?; + } + if !self.merchant_country.is_empty() { + builder + .add_filter_in_range_clause( + AuthEventDimensions::MerchantCountry, + &self.merchant_country, + ) + .attach_printable("Failed to add merchant country filter")?; + } + if !self.billing_country.is_empty() { + builder + .add_filter_in_range_clause( + AuthEventDimensions::BillingCountry, + &self.billing_country, + ) + .attach_printable("Failed to add billing country filter")?; + } + if !self.shipping_country.is_empty() { + builder + .add_filter_in_range_clause( + AuthEventDimensions::ShippingCountry, + &self.shipping_country, + ) + .attach_printable("Failed to add shipping country filter")?; + } + if !self.issuer_country.is_empty() { + builder + .add_filter_in_range_clause( + AuthEventDimensions::IssuerCountry, + &self.issuer_country, + ) + .attach_printable("Failed to add issuer country filter")?; + } + if !self.earliest_supported_version.is_empty() { + builder + .add_filter_in_range_clause( + AuthEventDimensions::EarliestSupportedVersion, + &self.earliest_supported_version, + ) + .attach_printable("Failed to add earliest supported version filter")?; + } + if !self.latest_supported_version.is_empty() { + builder + .add_filter_in_range_clause( + AuthEventDimensions::LatestSupportedVersion, + &self.latest_supported_version, + ) + .attach_printable("Failed to add latest supported version filter")?; + } + if !self.whitelist_decision.is_empty() { + builder + .add_filter_in_range_clause( + AuthEventDimensions::WhitelistDecision, + &self.whitelist_decision, + ) + .attach_printable("Failed to add whitelist decision filter")?; + } + if !self.device_manufacturer.is_empty() { + builder + .add_filter_in_range_clause( + AuthEventDimensions::DeviceManufacturer, + &self.device_manufacturer, + ) + .attach_printable("Failed to add device manufacturer filter")?; + } + if !self.device_type.is_empty() { + builder + .add_filter_in_range_clause(AuthEventDimensions::DeviceType, &self.device_type) + .attach_printable("Failed to add device type filter")?; + } + if !self.device_brand.is_empty() { + builder + .add_filter_in_range_clause(AuthEventDimensions::DeviceBrand, &self.device_brand) + .attach_printable("Failed to add device brand filter")?; + } + if !self.device_os.is_empty() { + builder + .add_filter_in_range_clause(AuthEventDimensions::DeviceOs, &self.device_os) + .attach_printable("Failed to add device OS filter")?; + } + if !self.device_display.is_empty() { + builder + .add_filter_in_range_clause( + AuthEventDimensions::DeviceDisplay, + &self.device_display, + ) + .attach_printable("Failed to add device display filter")?; + } + if !self.browser_name.is_empty() { + builder + .add_filter_in_range_clause(AuthEventDimensions::BrowserName, &self.browser_name) + .attach_printable("Failed to add browser name filter")?; + } + if !self.browser_version.is_empty() { + builder + .add_filter_in_range_clause( + AuthEventDimensions::BrowserVersion, + &self.browser_version, + ) + .attach_printable("Failed to add browser version filter")?; + } + if !self.issuer_id.is_empty() { + builder + .add_filter_in_range_clause(AuthEventDimensions::IssuerId, &self.issuer_id) + .attach_printable("Failed to add issuer ID filter")?; + } + if !self.scheme_name.is_empty() { + builder + .add_filter_in_range_clause(AuthEventDimensions::SchemeName, &self.scheme_name) + .attach_printable("Failed to add scheme name filter")?; + } + if !self.exemption_requested.is_empty() { + builder + .add_filter_in_range_clause( + AuthEventDimensions::ExemptionRequested, + &self.exemption_requested, + ) + .attach_printable("Failed to add exemption requested filter")?; + } + if !self.exemption_accepted.is_empty() { + builder + .add_filter_in_range_clause( + AuthEventDimensions::ExemptionAccepted, + &self.exemption_accepted, + ) + .attach_printable("Failed to add exemption accepted filter")?; + } + Ok(()) } } diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index 5a2f097bb0d..7934c911848 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -231,6 +231,11 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::metrics::AuthEventMetricRow ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + + let platform: Option<String> = row.try_get("platform").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; let acs_reference_number: Option<String> = row.try_get("acs_reference_number").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), @@ -247,6 +252,102 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::metrics::AuthEventMetricRow let end_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("end_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); + let mcc: Option<String> = row.try_get("mcc").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let currency: Option<DBEnumWrapper<Currency>> = + row.try_get("currency").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let merchant_country: Option<String> = + row.try_get("merchant_country").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let billing_country: Option<String> = + row.try_get("billing_country").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let shipping_country: Option<String> = + row.try_get("shipping_country").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let issuer_country: Option<String> = + row.try_get("issuer_country").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let earliest_supported_version: Option<String> = row + .try_get("earliest_supported_version") + .or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let latest_supported_version: Option<String> = row + .try_get("latest_supported_version") + .or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let whitelist_decision: Option<bool> = + row.try_get("whitelist_decision").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let device_manufacturer: Option<String> = + row.try_get("device_manufacturer").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let device_type: Option<String> = row.try_get("device_type").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let device_brand: Option<String> = row.try_get("device_brand").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let device_os: Option<String> = row.try_get("device_os").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let device_display: Option<String> = + row.try_get("device_display").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let browser_name: Option<String> = row.try_get("browser_name").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let browser_version: Option<String> = + row.try_get("browser_version").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let issuer_id: Option<String> = row.try_get("issuer_id").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let scheme_name: Option<String> = row.try_get("scheme_name").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let exemption_requested: Option<bool> = + row.try_get("exemption_requested").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let exemption_accepted: Option<bool> = + row.try_get("exemption_accepted").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + Ok(Self { authentication_status, trans_status, @@ -255,9 +356,30 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::metrics::AuthEventMetricRow authentication_connector, message_version, acs_reference_number, + platform, count, start_bucket, end_bucket, + mcc, + currency, + merchant_country, + billing_country, + shipping_country, + issuer_country, + earliest_supported_version, + latest_supported_version, + whitelist_decision, + device_manufacturer, + device_type, + device_brand, + device_os, + device_display, + browser_name, + browser_version, + issuer_id, + scheme_name, + exemption_requested, + exemption_accepted, }) } } @@ -299,6 +421,106 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::filters::AuthEventFilterRow ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let platform: Option<String> = row.try_get("platform").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let mcc: Option<String> = row.try_get("mcc").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let currency: Option<DBEnumWrapper<Currency>> = + row.try_get("currency").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let merchant_country: Option<String> = + row.try_get("merchant_country").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let billing_country: Option<String> = + row.try_get("billing_country").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let shipping_country: Option<String> = + row.try_get("shipping_country").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let issuer_country: Option<String> = + row.try_get("issuer_country").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let earliest_supported_version: Option<String> = row + .try_get("earliest_supported_version") + .or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let latest_supported_version: Option<String> = row + .try_get("latest_supported_version") + .or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let whitelist_decision: Option<bool> = + row.try_get("whitelist_decision").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let device_manufacturer: Option<String> = + row.try_get("device_manufacturer").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let device_type: Option<String> = row.try_get("device_type").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let device_brand: Option<String> = row.try_get("device_brand").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let device_os: Option<String> = row.try_get("device_os").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let device_display: Option<String> = + row.try_get("device_display").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let browser_name: Option<String> = row.try_get("browser_name").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let browser_version: Option<String> = + row.try_get("browser_version").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let issuer_id: Option<String> = row.try_get("issuer_id").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let scheme_name: Option<String> = row.try_get("scheme_name").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let exemption_requested: Option<bool> = + row.try_get("exemption_requested").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let exemption_accepted: Option<bool> = + row.try_get("exemption_accepted").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + Ok(Self { authentication_status, trans_status, @@ -306,7 +528,28 @@ impl<'a> FromRow<'a, PgRow> for super::auth_events::filters::AuthEventFilterRow error_message, authentication_connector, message_version, + platform, acs_reference_number, + mcc, + currency, + merchant_country, + billing_country, + shipping_country, + issuer_country, + earliest_supported_version, + latest_supported_version, + whitelist_decision, + device_manufacturer, + device_type, + device_brand, + device_os, + device_display, + browser_name, + browser_version, + issuer_id, + scheme_name, + exemption_requested, + exemption_accepted, }) } } diff --git a/crates/analytics/src/utils.rs b/crates/analytics/src/utils.rs index 0832788e261..06cc998f3da 100644 --- a/crates/analytics/src/utils.rs +++ b/crates/analytics/src/utils.rs @@ -52,6 +52,27 @@ pub fn get_auth_event_dimensions() -> Vec<NameDescription> { AuthEventDimensions::AuthenticationConnector, AuthEventDimensions::MessageVersion, AuthEventDimensions::AcsReferenceNumber, + AuthEventDimensions::Platform, + AuthEventDimensions::Mcc, + AuthEventDimensions::Currency, + AuthEventDimensions::MerchantCountry, + AuthEventDimensions::BillingCountry, + AuthEventDimensions::ShippingCountry, + AuthEventDimensions::IssuerCountry, + AuthEventDimensions::IssuerId, + AuthEventDimensions::EarliestSupportedVersion, + AuthEventDimensions::LatestSupportedVersion, + AuthEventDimensions::WhitelistDecision, + AuthEventDimensions::DeviceManufacturer, + AuthEventDimensions::DeviceType, + AuthEventDimensions::DeviceBrand, + AuthEventDimensions::DeviceOs, + AuthEventDimensions::DeviceDisplay, + AuthEventDimensions::BrowserName, + AuthEventDimensions::BrowserVersion, + AuthEventDimensions::SchemeName, + AuthEventDimensions::ExemptionRequested, + AuthEventDimensions::ExemptionAccepted, ] .into_iter() .map(Into::into) diff --git a/crates/api_models/src/analytics/auth_events.rs b/crates/api_models/src/analytics/auth_events.rs index 8a1c168aa2f..f1062e0269e 100644 --- a/crates/api_models/src/analytics/auth_events.rs +++ b/crates/api_models/src/analytics/auth_events.rs @@ -4,7 +4,8 @@ use std::{ }; use common_enums::{ - AuthenticationConnectors, AuthenticationStatus, DecoupledAuthenticationType, TransactionStatus, + AuthenticationConnectors, AuthenticationStatus, Currency, DecoupledAuthenticationType, + TransactionStatus, }; use super::{NameDescription, TimeRange}; @@ -24,7 +25,49 @@ pub struct AuthEventFilters { #[serde(default)] pub message_version: Vec<String>, #[serde(default)] + pub platform: Vec<String>, + #[serde(default)] pub acs_reference_number: Vec<String>, + #[serde(default)] + pub mcc: Vec<String>, + #[serde(default)] + pub currency: Vec<Currency>, + #[serde(default)] + pub merchant_country: Vec<String>, + #[serde(default)] + pub billing_country: Vec<String>, + #[serde(default)] + pub shipping_country: Vec<String>, + #[serde(default)] + pub issuer_country: Vec<String>, + #[serde(default)] + pub earliest_supported_version: Vec<String>, + #[serde(default)] + pub latest_supported_version: Vec<String>, + #[serde(default)] + pub whitelist_decision: Vec<bool>, + #[serde(default)] + pub device_manufacturer: Vec<String>, + #[serde(default)] + pub device_type: Vec<String>, + #[serde(default)] + pub device_brand: Vec<String>, + #[serde(default)] + pub device_os: Vec<String>, + #[serde(default)] + pub device_display: Vec<String>, + #[serde(default)] + pub browser_name: Vec<String>, + #[serde(default)] + pub browser_version: Vec<String>, + #[serde(default)] + pub issuer_id: Vec<String>, + #[serde(default)] + pub scheme_name: Vec<String>, + #[serde(default)] + pub exemption_requested: Vec<bool>, + #[serde(default)] + pub exemption_accepted: Vec<bool>, } #[derive( @@ -53,6 +96,27 @@ pub enum AuthEventDimensions { AuthenticationConnector, MessageVersion, AcsReferenceNumber, + Platform, + Mcc, + Currency, + MerchantCountry, + BillingCountry, + ShippingCountry, + IssuerCountry, + EarliestSupportedVersion, + LatestSupportedVersion, + WhitelistDecision, + DeviceManufacturer, + DeviceType, + DeviceBrand, + DeviceOs, + DeviceDisplay, + BrowserName, + BrowserVersion, + IssuerId, + SchemeName, + ExemptionRequested, + ExemptionAccepted, } #[derive( @@ -80,6 +144,8 @@ pub enum AuthEventMetrics { ChallengeSuccessCount, AuthenticationErrorMessage, AuthenticationFunnel, + AuthenticationExemptionApprovedCount, + AuthenticationExemptionRequestedCount, } #[derive( @@ -139,6 +205,26 @@ pub struct AuthEventMetricsBucketIdentifier { pub authentication_connector: Option<AuthenticationConnectors>, pub message_version: Option<String>, pub acs_reference_number: Option<String>, + pub mcc: Option<String>, + pub currency: Option<Currency>, + pub merchant_country: Option<String>, + pub billing_country: Option<String>, + pub shipping_country: Option<String>, + pub issuer_country: Option<String>, + pub earliest_supported_version: Option<String>, + pub latest_supported_version: Option<String>, + pub whitelist_decision: Option<bool>, + pub device_manufacturer: Option<String>, + pub device_type: Option<String>, + pub device_brand: Option<String>, + pub device_os: Option<String>, + pub device_display: Option<String>, + pub browser_name: Option<String>, + pub browser_version: Option<String>, + pub issuer_id: Option<String>, + pub scheme_name: Option<String>, + pub exemption_requested: Option<bool>, + pub exemption_accepted: Option<bool>, #[serde(rename = "time_range")] pub time_bucket: TimeRange, #[serde(rename = "time_bucket")] @@ -156,6 +242,26 @@ impl AuthEventMetricsBucketIdentifier { authentication_connector: Option<AuthenticationConnectors>, message_version: Option<String>, acs_reference_number: Option<String>, + mcc: Option<String>, + currency: Option<Currency>, + merchant_country: Option<String>, + billing_country: Option<String>, + shipping_country: Option<String>, + issuer_country: Option<String>, + earliest_supported_version: Option<String>, + latest_supported_version: Option<String>, + whitelist_decision: Option<bool>, + device_manufacturer: Option<String>, + device_type: Option<String>, + device_brand: Option<String>, + device_os: Option<String>, + device_display: Option<String>, + browser_name: Option<String>, + browser_version: Option<String>, + issuer_id: Option<String>, + scheme_name: Option<String>, + exemption_requested: Option<bool>, + exemption_accepted: Option<bool>, normalized_time_range: TimeRange, ) -> Self { Self { @@ -166,6 +272,26 @@ impl AuthEventMetricsBucketIdentifier { authentication_connector, message_version, acs_reference_number, + mcc, + currency, + merchant_country, + billing_country, + shipping_country, + issuer_country, + earliest_supported_version, + latest_supported_version, + whitelist_decision, + device_manufacturer, + device_type, + device_brand, + device_os, + device_display, + browser_name, + browser_version, + issuer_id, + scheme_name, + exemption_requested, + exemption_accepted, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } @@ -181,6 +307,26 @@ impl Hash for AuthEventMetricsBucketIdentifier { self.message_version.hash(state); self.acs_reference_number.hash(state); self.error_message.hash(state); + self.mcc.hash(state); + self.currency.hash(state); + self.merchant_country.hash(state); + self.billing_country.hash(state); + self.shipping_country.hash(state); + self.issuer_country.hash(state); + self.earliest_supported_version.hash(state); + self.latest_supported_version.hash(state); + self.whitelist_decision.hash(state); + self.device_manufacturer.hash(state); + self.device_type.hash(state); + self.device_brand.hash(state); + self.device_os.hash(state); + self.device_display.hash(state); + self.browser_name.hash(state); + self.browser_version.hash(state); + self.issuer_id.hash(state); + self.scheme_name.hash(state); + self.exemption_requested.hash(state); + self.exemption_accepted.hash(state); self.time_bucket.hash(state); } } @@ -207,6 +353,8 @@ pub struct AuthEventMetricsBucketValue { pub frictionless_success_count: Option<u64>, pub error_message_count: Option<u64>, pub authentication_funnel: Option<u64>, + pub authentication_exemption_approved_count: Option<u64>, + pub authentication_exemption_requested_count: Option<u64>, } #[derive(Debug, serde::Serialize)] diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index 7aaebfc07c1..67722d3e25a 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -110,6 +110,10 @@ pub mod routes { web::resource("metrics/auth_events") .route(web::post().to(get_auth_event_metrics)), ) + .service( + web::resource("metrics/auth_events/sankey") + .route(web::post().to(get_auth_event_sankey)), + ) .service( web::resource("filters/auth_events") .route(web::post().to(get_merchant_auth_events_filters)), @@ -2727,6 +2731,37 @@ pub mod routes { .await } + pub async fn get_auth_event_sankey( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<TimeRange>, + ) -> impl Responder { + let flow = AnalyticsFlow::GetSankey; + let payload = json_payload.into_inner(); + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, auth: AuthenticationData, req, _| async move { + let org_id = auth.merchant_account.get_org_id(); + let merchant_id = auth.merchant_account.get_id(); + let auth: AuthInfo = AuthInfo::MerchantLevel { + org_id: org_id.clone(), + merchant_ids: vec![merchant_id.clone()], + }; + analytics::auth_events::get_sankey(&state.pool, &auth, req) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth { + permission: Permission::MerchantAnalyticsRead, + }, + api_locking::LockAction::NotApplicable, + )) + .await + } + #[cfg(feature = "v1")] pub async fn get_org_sankey( state: web::Data<AppState>,
2025-05-28T10:49:41Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Added exemption_requested and exemption_approved fields to the auth_events metrics, extended the auth-analytics API with new filters for 3DS Intelligence, and created a dedicated endpoint to serve SCA-exemption Sankey chart data. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? Tested it locally by ingesting some test data in authentications tables in CKH. CURL for /metrics/auth_events introduced two new fields authentication_exemption_approved_count and authentication_exemption_requested_count here ``` curl 'http://localhost:8080/analytics/v1/metrics/auth_events' \ -H 'Accept: */*' \ -H 'Accept-Language: en-US,en' \ -H 'Cache-Control: no-cache' \ -H 'Connection: keep-alive' \ -H 'Content-Type: application/json' \ -H 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiY2IzYjdjNGQtYjQ0Mi00ZDk0LWJkMjQtNjk5NjI4ZjQ1MzBkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ4Mjg1ODc1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0ODY5NDkwNywib3JnX2lkIjoib3JnX1VBQnlpWmZ4TW44dFpuSnZUemlvIiwicHJvZmlsZV9pZCI6InByb19Pcjh5cmlGYzBPY1pJZHFBOVFVVyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.Bfo6nVoKTUl0I3Bzn2qg-kFxkiU3cWj-gHInHXpHneU' \ -H 'Origin: http://localhost:9000/' \ -H 'Pragma: no-cache' \ -H 'Referer: http://localhost:9000/dashboard/analytics-authentication' \ -H 'Sec-Fetch-Dest: empty' \ -H 'Sec-Fetch-Mode: cors' \ -H 'Sec-Fetch-Site: same-origin' \ -H 'Sec-GPC: 1' \ -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36' \ -H 'X-Merchant-Id: merchant_1748285875' \ -H 'X-Profile-Id: pro_Or8yriFc0OcZIdqA9QUW' \ -H 'api-key: hyperswitch' \ -H 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiY2IzYjdjNGQtYjQ0Mi00ZDk0LWJkMjQtNjk5NjI4ZjQ1MzBkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ4Mjg1ODc1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0ODY5NDkwNywib3JnX2lkIjoib3JnX1VBQnlpWmZ4TW44dFpuSnZUemlvIiwicHJvZmlsZV9pZCI6InByb19Pcjh5cmlGYzBPY1pJZHFBOVFVVyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.Bfo6nVoKTUl0I3Bzn2qg-kFxkiU3cWj-gHInHXpHneU' \ -H 'sec-ch-ua: "Chromium";v="130", "Brave";v="130", "Not?A_Brand";v="99"' \ -H 'sec-ch-ua-mobile: ?0' \ -H 'sec-ch-ua-platform: "macOS"' \ --data-raw '[{"timeRange":{"startTime":"2025-05-22T18:30:00Z","endTime":"2025-05-30T13:10:30Z"},"mode":"ORDER","source":"BATCH","metrics":["authentication_count","authentication_attempt_count","authentication_success_count","challenge_flow_count","frictionless_flow_count","frictionless_success_count","challenge_attempt_count","challenge_success_count"],"delta":true}]' ``` CURL for /metrics/auth_events/sankey this is required to build an exmemption analytics sankey chart on dashboard ``` curl 'http://localhost:8080/analytics/v1/metrics/auth_events/sankey' \ -H 'Accept: */*' \ -H 'Accept-Language: en-US,en' \ -H 'Cache-Control: no-cache' \ -H 'Connection: keep-alive' \ -H 'Content-Type: application/json' \ -H 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiY2IzYjdjNGQtYjQ0Mi00ZDk0LWJkMjQtNjk5NjI4ZjQ1MzBkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ4Mjg1ODc1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0ODY5NDkwNywib3JnX2lkIjoib3JnX1VBQnlpWmZ4TW44dFpuSnZUemlvIiwicHJvZmlsZV9pZCI6InByb19Pcjh5cmlGYzBPY1pJZHFBOVFVVyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.Bfo6nVoKTUl0I3Bzn2qg-kFxkiU3cWj-gHInHXpHneU' \ -H 'Origin: http://localhost:9000/' \ -H 'Pragma: no-cache' \ -H 'Referer: http://localhost:9000/dashboard/analytics-authentication' \ -H 'Sec-Fetch-Dest: empty' \ -H 'Sec-Fetch-Mode: cors' \ -H 'Sec-Fetch-Site: same-origin' \ -H 'Sec-GPC: 1' \ -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36' \ -H 'X-Merchant-Id: merchant_1748285875' \ -H 'X-Profile-Id: pro_Or8yriFc0OcZIdqA9QUW' \ -H 'api-key: hyperswitch' \ -H 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiY2IzYjdjNGQtYjQ0Mi00ZDk0LWJkMjQtNjk5NjI4ZjQ1MzBkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ4Mjg1ODc1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0ODY5NDkwNywib3JnX2lkIjoib3JnX1VBQnlpWmZ4TW44dFpuSnZUemlvIiwicHJvZmlsZV9pZCI6InByb19Pcjh5cmlGYzBPY1pJZHFBOVFVVyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.Bfo6nVoKTUl0I3Bzn2qg-kFxkiU3cWj-gHInHXpHneU' \ -H 'sec-ch-ua: "Chromium";v="130", "Brave";v="130", "Not?A_Brand";v="99"' \ -H 'sec-ch-ua-mobile: ?0' \ -H 'sec-ch-ua-platform: "macOS"' \ --data-raw '{"startTime": "2025-01-22T18:30:00Z","endTime": "2025-05-29T12:59:33Z"}' ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
dbca363f44c0dbce277a337d64dfb82741d423c4
dbca363f44c0dbce277a337d64dfb82741d423c4
juspay/hyperswitch
juspay__hyperswitch-8144
Bug: [BUG] Confirm and PSync call not giving whole_connector_response when all_keys_required is true and connector gives an error ### Bug Description Confirm and PSync call not giving whole_connector_response when all_keys_required is true and connector gives an error ### Expected Behavior Confirm and PSync call should give whole_connector_response when all_keys_required is true and connector gives an error ### Actual Behavior Confirm and PSync call not giving whole_connector_response when all_keys_required is true and connector gives an error ### Steps To Reproduce Give invalid API Keys for any connector and do a payment will `all_keys_required` as `true`. `whole_connector_response` will be null. ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: MacOS 2. Rust version (output of `rustc --version`): 3. App version (output of `cargo r --features vergen -- --version`): ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 6ec0ff9fe75..41a12f35576 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -127,6 +127,27 @@ pub type BoxedBillingConnectorPaymentsSyncIntegrationInterface<T, Req, Res> = pub type BoxedVaultConnectorIntegrationInterface<T, Req, Res> = BoxedConnectorIntegrationInterface<T, common_types::VaultConnectorFlowData, Req, Res>; +fn store_raw_connector_response_if_required<T, Req, Resp>( + return_raw_connector_response: Option<bool>, + router_data: &mut types::RouterData<T, Req, Resp>, + body: &types::Response, +) -> CustomResult<(), errors::ConnectorError> +where + T: Clone + Debug + 'static, + Req: Debug + Clone + 'static, + Resp: Debug + Clone + 'static, +{ + if return_raw_connector_response == Some(true) { + let mut decoded = String::from_utf8(body.response.as_ref().to_vec()) + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + if decoded.starts_with('\u{feff}') { + decoded = decoded.trim_start_matches('\u{feff}').to_string(); + } + router_data.raw_connector_response = Some(Secret::new(decoded)); + } + Ok(()) +} + /// Handle the flow by interacting with connector module /// `connector_request` is applicable only in case if the `CallConnectorAction` is `Trigger` /// In other cases, It will be created if required, even if it is not passed @@ -305,17 +326,13 @@ where val + external_latency }), ); - if return_raw_connector_response == Some(true) { - let mut decoded = String::from_utf8(body.response.as_ref().to_vec()) - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - if decoded.starts_with('\u{feff}') { - decoded = decoded - .trim_start_matches('\u{feff}') - .to_string(); - } - data.raw_connector_response = - Some(Secret::new(decoded)); - } + + store_raw_connector_response_if_required( + return_raw_connector_response, + &mut data, + &body, + )?; + Ok(data) } Err(err) => { @@ -342,6 +359,12 @@ where )), ); + store_raw_connector_response_if_required( + return_raw_connector_response, + &mut router_data, + &body, + )?; + let error = match body.status_code { 500..=511 => { let error_res = connector_integration
2025-08-24T19:55:06Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD Closes this [issue](https://github.com/juspay/hyperswitch/issues/8144) ## Description <!-- Describe your changes in detail --> send whole_connector_response even when connector sends an error ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Postman Test 1. Payments - Create (with invalid creds, `confirm`: `true` and `all_keys_required`: `true`) Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_6zQcrKUzlenHXPheZtIUO3WbxTAiPtBxxrLFw1sSRmjRIn0QGPJ1z6NnwlHUKKVa' \ --data-raw '{ "amount": 35308, "currency": "USD", "confirm": true, "all_keys_required": true, "capture_method": "automatic", "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "profile_id": "pro_RdVLVWtGWBgd9sMam8Dg", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "370000000000002", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country":"US", "first_name": "PiX" } } }' ``` Response: ``` { "payment_id": "pay_78k7Xn25MnMHMwoFsJPX", "merchant_id": "merchant_1748265048", "status": "failed", "amount": 35308, "net_amount": 35308, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "authorizedotnet", "client_secret": "pay_78k7Xn25MnMHMwoFsJPX_secret_BlNgMRRNeA6Wre5jbtWr", "created": "2025-05-26T13:33:49.037Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0002", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "370000", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": "E00003", "error_message": "The 'AnetApi/xml/v1/schema/AnetApiSchema.xsd:transactionKey' element is invalid - The value XXXXXXXXXXXXXXXXXXX is invalid according to its datatype 'String' - The actual length is greater than the MaxLength value.", "unified_code": "UE_9000", "unified_message": "Something went wrong", "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1748266429, "expires": 1748270029, "secret": "epk_3c034be0d8934ec98fcde1b244d55ed6" }, "manual_retry_allowed": true, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_RdVLVWtGWBgd9sMam8Dg", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_FvbbC2wYxwcnbvoXrSFL", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-05-26T13:48:49.037Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-05-26T13:33:50.999Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": "{\"messages\":{\"resultCode\":\"Error\",\"message\":[{\"code\":\"E00003\",\"text\":\"The 'AnetApi/xml/v1/schema/AnetApiSchema.xsd:transactionKey' element is invalid - The value XXXXXXXXXXXXXXXXXXX is invalid according to its datatype 'String' - The actual length is greater than the MaxLength value.\"}]}}" } ``` 2.. Payments - Create (with valid API Keys, `confirm`: `true` and `all_keys_required`: `true`) Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_6zQcrKUzlenHXPheZtIUO3WbxTAiPtBxxrLFw1sSRmjRIn0QGPJ1z6NnwlHUKKVa' \ --data-raw '{ "amount": 35308, "currency": "USD", "confirm": true, "all_keys_required": true, "capture_method": "automatic", "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "profile_id": "pro_RdVLVWtGWBgd9sMam8Dg", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "370000000000002", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country":"US", "first_name": "PiX" } } }' ``` Response: ``` { "payment_id": "pay_hxQGHpxW3F5DNxeyiY8z", "merchant_id": "merchant_1748267173", "status": "succeeded", "amount": 35308, "net_amount": 35308, "shipping_cost": null, "amount_capturable": 0, "amount_received": 35308, "connector": "authorizedotnet", "client_secret": "pay_hxQGHpxW3F5DNxeyiY8z_secret_da5n53bB7Kb1exV85EK2", "created": "2025-05-26T13:46:40.052Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0002", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "370000", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1748267200, "expires": 1748270800, "secret": "epk_fad60adb28944cf8be7a3d64bbce0672" }, "manual_retry_allowed": false, "connector_transaction_id": "120063944184", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "120063944184", "payment_link": null, "profile_id": "pro_zHrEr9z5qskGtTpA1ZPg", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_NnVBGa1fNbiNyFfGuadr", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-05-26T14:01:40.052Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-05-26T13:46:42.017Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": "{\"transactionResponse\":{\"responseCode\":\"1\",\"authCode\":\"UA8PIX\",\"avsResultCode\":\"Y\",\"cvvResultCode\":\"P\",\"cavvResultCode\":\"2\",\"transId\":\"120063944184\",\"refTransID\":\"\",\"transHash\":\"\",\"testRequest\":\"0\",\"accountNumber\":\"XXXX0002\",\"accountType\":\"AmericanExpress\",\"messages\":[{\"code\":\"1\",\"description\":\"This transaction has been approved.\"}],\"transHashSha2\":\"7028AF831EAF78761E94F39C2F6D1544D0916D8330C75AED524A99A2917BBA17D76305F51183A97E15D9E30A206EC869F0F5D45903F5C7928A454176060439D7\",\"SupplementalDataQualificationIndicator\":0,\"networkTransId\":\"73WA8F79F6PERAJ1F57SWAB\"},\"profileResponse\":{\"messages\":{\"resultCode\":\"Ok\",\"message\":[{\"code\":\"I00001\",\"text\":\"Successful.\"}]},\"customerProfileId\":\"931062475\",\"customerPaymentProfileIdList\":[\"930352630\"],\"customerShippingAddressIdList\":[]},\"refId\":\"\",\"messages\":{\"resultCode\":\"Ok\",\"message\":[{\"code\":\"I00001\",\"text\":\"Successful.\"}]}}" } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.116.0
7047c3faa1e71c7ad13592cd41b77be3cdc1a8a2
7047c3faa1e71c7ad13592cd41b77be3cdc1a8a2
juspay/hyperswitch
juspay__hyperswitch-8157
Bug: refactor(success_based): add support for exploration
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 039981f661b..fbabc864672 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -23374,9 +23374,13 @@ }, "specificity_level": { "$ref": "#/components/schemas/SuccessRateSpecificityLevel" + }, + "exploration_percent": { + "type": "number", + "format": "double", + "nullable": true } - }, - "additionalProperties": false + } }, "SuccessRateSpecificityLevel": { "type": "string", diff --git a/api-reference/hyperswitch_intelligent_router_open_api_spec.yml b/api-reference/hyperswitch_intelligent_router_open_api_spec.yml index 58bff737f3e..7372a083b88 100644 --- a/api-reference/hyperswitch_intelligent_router_open_api_spec.yml +++ b/api-reference/hyperswitch_intelligent_router_open_api_spec.yml @@ -44,6 +44,7 @@ paths: min_aggregates_size: 5 default_success_rate: 0.95 specificity_level: ENTITY + exploration_percent: 20.0 responses: "200": description: Success rate calculated successfully @@ -758,6 +759,17 @@ components: items: $ref: "#/components/schemas/LabelWithScore" description: List of labels with their calculated success rates + routing_approach: + $ref: "#/components/schemas/RoutingApproach" + + RoutingApproach: + type: string + description: > + Defines the routing approach based on the success rate calculation. + enum: + - EXPLORATION + - EXPLOITATION + example: EXPLOITATION UpdateSuccessRateWindowRequest: type: object diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 70c8ed1e8c7..de3a3eb2323 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -27383,9 +27383,13 @@ }, "specificity_level": { "$ref": "#/components/schemas/SuccessRateSpecificityLevel" + }, + "exploration_percent": { + "type": "number", + "format": "double", + "nullable": true } - }, - "additionalProperties": false + } }, "SuccessRateSpecificityLevel": { "type": "string", diff --git a/crates/api_models/src/open_router.rs b/crates/api_models/src/open_router.rs index f15d9cbcfeb..cfcb45ef97b 100644 --- a/crates/api_models/src/open_router.rs +++ b/crates/api_models/src/open_router.rs @@ -62,6 +62,7 @@ pub struct PaymentInfo { pub struct DecidedGateway { pub gateway_priority_map: Option<HashMap<String, f64>>, pub debit_routing_output: Option<DebitRoutingOutput>, + pub routing_approach: String, } #[derive(Debug, Serialize, Deserialize, PartialEq)] diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index a15b135ac1f..7633f44156e 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -960,6 +960,7 @@ impl Default for SuccessBasedRoutingConfig { max_total_count: Some(5), }), specificity_level: SuccessRateSpecificityLevel::default(), + exploration_percent: Some(20.0), }), decision_engine_configs: None, } @@ -980,7 +981,6 @@ pub enum DynamicRoutingConfigParams { } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] -#[serde(deny_unknown_fields)] pub struct SuccessBasedRoutingConfigBody { pub min_aggregates_size: Option<u32>, pub default_success_rate: Option<f64>, @@ -988,6 +988,7 @@ pub struct SuccessBasedRoutingConfigBody { pub current_block_threshold: Option<CurrentBlockThreshold>, #[serde(default)] pub specificity_level: SuccessRateSpecificityLevel, + pub exploration_percent: Option<f64>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] @@ -1113,7 +1114,10 @@ impl SuccessBasedRoutingConfigBody { .as_mut() .map(|threshold| threshold.update(current_block_threshold)); } - self.specificity_level = new.specificity_level + self.specificity_level = new.specificity_level; + if let Some(exploration_percent) = new.exploration_percent { + self.exploration_percent = Some(exploration_percent); + } } } diff --git a/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs b/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs index 278a2b50d15..b63f435327e 100644 --- a/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs +++ b/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs @@ -290,6 +290,7 @@ impl ForeignTryFrom<SuccessBasedRoutingConfigBody> for CalSuccessRateConfig { SuccessRateSpecificityLevel::Merchant => Some(ProtoSpecificityLevel::Entity.into()), SuccessRateSpecificityLevel::Global => Some(ProtoSpecificityLevel::Global.into()), }, + exploration_percent: config.exploration_percent, }) } } diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index b4ac7d4421d..86925cff09f 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -1776,10 +1776,7 @@ pub async fn perform_decide_gateway_call_with_open_router( ))?; if let Some(gateway_priority_map) = decided_gateway.gateway_priority_map { - logger::debug!( - "open_router decide_gateway call response: {:?}", - gateway_priority_map - ); + logger::debug!(gateway_priority_map=?gateway_priority_map, routing_approach=decided_gateway.routing_approach, "open_router decide_gateway call response"); routable_connectors.sort_by(|connector_choice_a, connector_choice_b| { let connector_choice_a_score = gateway_priority_map .get(&connector_choice_a.to_string()) diff --git a/proto/success_rate.proto b/proto/success_rate.proto index 17d566af356..efdd439cac9 100644 --- a/proto/success_rate.proto +++ b/proto/success_rate.proto @@ -23,6 +23,7 @@ message CalSuccessRateConfig { uint32 min_aggregates_size = 1; double default_success_rate = 2; optional SuccessRateSpecificityLevel specificity_level = 3; + optional double exploration_percent = 4; } enum SuccessRateSpecificityLevel { @@ -32,6 +33,12 @@ enum SuccessRateSpecificityLevel { message CalSuccessRateResponse { repeated LabelWithScore labels_with_score = 1; + RoutingApproach routing_approach = 2; +} + +enum RoutingApproach { + EXPLORATION = 0; + EXPLOITATION = 1; } message LabelWithScore {
2025-05-27T14:52:09Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This pull request introduces a new feature to support an "exploration percentage" parameter in success-based routing configurations and adds a "RoutingApproach" enum to define routing strategies. These changes span multiple files, including API specifications, Rust models, and protocol buffer definitions, ensuring end-to-end support for the new functionality. ### New Feature: Exploration Percentage in Routing Configurations * Added `exploration_percent` parameter to the `SuccessBasedRoutingConfig` struct in Rust models (`crates/api_models/src/routing.rs`) and updated its default implementation. [[1]](diffhunk://#diff-6eb6e93a94555e904f304999acc96ab6125769971da9ec3dcbb30d5912b4fc45R963) [[2]](diffhunk://#diff-6eb6e93a94555e904f304999acc96ab6125769971da9ec3dcbb30d5912b4fc45R992) * Modified the `update` method in `SuccessBasedRoutingConfigBody` to handle updates to the `exploration_percent` field. * Updated the gRPC client (`crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs`) to include the `exploration_percent` field in the `CalSuccessRateConfig` mapping. * Enhanced the protocol buffer definition (`proto/success_rate.proto`) to include `exploration_percent` as an optional field in the `CalSuccessRateConfig` message. ### New Enum: Routing Approach * Introduced a `RoutingApproach` enum with values `EXPLORATION` and `EXPLOITATION` in the protocol buffer definition (`proto/success_rate.proto`) and added it to the `CalSuccessRateResponse` message. * Updated the OpenAPI specification (`api-reference/hyperswitch_intelligent_router_open_api_spec.yml`) to include the `RoutingApproach` type and its usage in API responses. ### API Specification Enhancements * Added `exploration_percent` to the API's routing configuration schema in the OpenAPI spec. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Toggle success based routing for a profile, Check the business profile table in DB, get the routing_algorithm_id active for that profile and check in routing_algorithm table. it should have exploration set to 20.0 ``` curl --location --request POST 'http://localhost:8080/account/merchant_1747851996/business_profile/pro_Rbh3PEV8EITILLoKDC6N/dynamic_routing/success_based/toggle?enable=dynamic_connector_selection' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: xyz' \ --data '' ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
e637b214e348216d30c9af59cce85a1264badebf
e637b214e348216d30c9af59cce85a1264badebf
juspay/hyperswitch
juspay__hyperswitch-8142
Bug: chore(docs): remove old add_connector.md file Remove old add_connector.md file
diff --git a/add_connector.md b/add_connector.md index 4d6e885b7ed..4ee8c895656 100644 --- a/add_connector.md +++ b/add_connector.md @@ -1,384 +1,314 @@ -# Guide to Integrate a Connector +# Guide to Integrating a Connector + +## Table of Contents + +1. [Introduction](#introduction) +2. [Prerequisites](#prerequisites) +3. [Understanding Connectors and Payment Methods](#understanding-connectors-and-payment-methods) +4. [Integration Steps](#integration-steps) + - [Generate Template](#generate-template) + - [Implement Request & Response Types](#implement-request--response-types) + - [Implement transformers.rs](#implementing-transformersrs) + - [Handle Response Mapping](#handle-response-mapping) + - [Recommended Fields for Connector Request and Response](#recommended-fields-for-connector-request-and-response) + - [Error Handling](#error-handling) +5. [Implementing the Traits](#implementing-the-traits) + - [ConnectorCommon](#connectorcommon) + - [ConnectorIntegration](#connectorintegration) + - [ConnectorCommonExt](#connectorcommonext) + - [Other Traits](#othertraits) +6. [Set the Currency Unit](#set-the-currency-unit) +7. [Connector utility functions](#connector-utility-functions) +8. [Connector configs for control center](#connector-configs-for-control-center) +9. [Update `ConnectorTypes.res` and `ConnectorUtils.res`](#update-connectortypesres-and-connectorutilsres) +10. [Add Connector Icon](#add-connector-icon) +11. [Test the Connector](#test-the-connector) +12. [Build Payment Request and Response from JSON Schema](#build-payment-request-and-response-from-json-schema) ## Introduction -This is a guide to contributing new connector to Router. This guide includes instructions on checking out the source code, integrating and testing the new connector, and finally contributing the new connector back to the project. +This guide provides instructions on integrating a new connector with Router, from setting up the environment to implementing API interactions. ## Prerequisites -- Understanding of the Connector APIs which you wish to integrate with Router -- Setup of Router repository and running it on local -- Access to API credentials for testing the Connector API (you can quickly sign up for sandbox/uat credentials by visiting the website of the connector you wish to integrate) -- Ensure that you have the nightly toolchain installed because the connector template script includes code formatting. - -Install it using `rustup`: - -```bash +- Familiarity with the Connector API you’re integrating +- A locally set up and running Router repository +- API credentials for testing (sign up for sandbox/UAT credentials on the connector’s website). +- Rust nightly toolchain installed for code formatting: + ```bash rustup toolchain install nightly -``` - -In Router, there are Connectors and Payment Methods, examples of both are shown below from which the difference is apparent. - -### What is a Connector ? + ``` -A connector is an integration to fulfill payments. Related use cases could be any of the below +## Understanding Connectors and Payment Methods -- Payment processor (Stripe, Adyen, ChasePaymentTech etc.,) -- Fraud and Risk management platform (like Signifyd, Riskified etc.,) -- Payment network (Visa, Master) -- Payment authentication services (Cardinal etc.,) - Currently, the router is compatible with 'Payment Processors' and 'Fraud and Risk Management' platforms. Support for additional categories will be expanded in the near future. +A **Connector** processes payments (e.g., Stripe, Adyen) or manages fraud risk (e.g., Signifyd). A **Payment Method** is a specific way to transact (e.g., credit card, PayPal). See the [Hyperswitch Payment Matrix](https://hyperswitch.io/pm-list) for details. -### What is a Payment Method ? +## Integration Steps -Every Payment Processor has the capability to accommodate various payment methods. Refer to the [Hyperswitch Payment matrix](https://hyperswitch.io/pm-list) to discover the supported processors and payment methods. +Integrating a connector is mainly an API integration task. You'll define request and response types and implement required traits. -The above mentioned payment methods are already included in Router. Hence, adding a new connector which offers payment_methods available in Router is easy and requires almost no breaking changes. -Adding a new payment method might require some changes in core business logic of Router, which we are actively working upon. +This tutorial covers card payments via [Billwerk](https://optimize-docs.billwerk.com/). Review the API reference and test APIs before starting. -## How to Integrate a Connector +Follow these steps to integrate a new connector. -Most of the code to be written is just another API integration. You have to write request and response types for API of the connector you wish to integrate and implement required traits. +### Generate Template -For this tutorial we will be integrating card payment through the [Checkout.com connector](https://www.checkout.com/). -Go through the [Checkout.com API reference](https://api-reference.checkout.com/). It would also be helpful to try out the API's, using tools like on postman, or any other API testing tool before starting the integration. - -Below is a step-by-step tutorial for integrating a new connector. - -### **Generate the template** +Run the following script to create the connector structure: ```bash sh scripts/add_connector.sh <connector-name> <connector-base-url> ``` -For this tutorial `<connector-name>` would be `checkout`. - -The folder structure will be modified as below +Example folder structure: ``` -crates/router/src/connector -├── checkout +hyperswitch_connectors/src/connectors +├── billwerk │ └── transformers.rs -└── checkout.rs +└── billwerk.rs crates/router/tests/connectors -└── checkout.rs +└── billwerk.rs ``` -`crates/router/src/connector/checkout/transformers.rs` will contain connectors API Request and Response types, and conversion between the router and connector API types. -`crates/router/src/connector/checkout.rs` will contain the trait implementations for the connector. -`crates/router/tests/connectors/checkout.rs` will contain the basic tests for the payments flows. +**Note:** move the file `crates/hyperswitch_connectors/src/connectors/connector_name/test.rs` to `crates/router/tests/connectors/connector_name.rs` -There is boiler plate code with `todo!()` in the above mentioned files. Go through the rest of the guide and fill in code wherever necessary. -### **Implementing Request and Response types** +Define API request/response types and conversions in `hyperswitch_connectors/src/connector/billwerk/transformers.rs` -Adding new Connector is all about implementing the data transformation from Router's core to Connector's API request format. -The Connector module is implemented as a stateless module, so that you will not have to worry about persistence of data. Router core will automatically take care of data persistence. +Implement connector traits in `hyperswitch_connectors/src/connector/billwerk.rs` -Lets add code in `transformers.rs` file. -A little planning and designing is required for implementing the Requests and Responses of the connector, as it depends on the API spec of the connector. +Write basic payment flow tests in `crates/router/tests/connectors/billwerk.rs` -For example, in case of checkout, the [request](https://api-reference.checkout.com/#tag/Payments) has a required parameter `currency` and few other required parameters in `source`. But the fields in “source” vary depending on the `source type`. An enum is needed to accommodate this in the Request type. You may need to add the serde tags to convert enum into json or url encoded based on your requirements. Here `serde(untagged)` is added to make the whole structure into the proper json acceptable to the connector. +Boilerplate code with todo!() is provided—follow the guide and complete the necessary implementations. -Now let's implement Request type for checkout +### Implement Request & Response Types -```rust -#[derive(Debug, Serialize)] -pub struct CardSource { - #[serde(rename = "type")] - pub source_type: CheckoutSourceTypes, - pub number: cards::CardNumber, - pub expiry_month: Secret<String>, - pub expiry_year: Secret<String>, - pub cvv: Secret<String>, -} +Integrating a new connector involves transforming Router's core data into the connector's API format. Since the Connector module is stateless, Router handles data persistence. + +#### Implementing transformers.rs + +Design request/response structures based on the connector's API spec. +Define request format in `transformers.rs`: + +```rust #[derive(Debug, Serialize)] -#[serde(untagged)] -pub enum PaymentSource { - Card(CardSource), - Wallets(WalletSource), - ApplePayPredecrypt(Box<ApplePayPredecrypt>), +pub struct BillwerkCustomerObject { + handle: Option<id_type::CustomerId>, + email: Option<Email>, + address: Option<Secret<String>>, + address2: Option<Secret<String>>, + city: Option<String>, + country: Option<common_enums::CountryAlpha2>, + first_name: Option<Secret<String>>, + last_name: Option<Secret<String>>, } #[derive(Debug, Serialize)] -pub struct PaymentsRequest { - pub source: PaymentSource, - pub amount: i64, - pub currency: String, - pub processing_channel_id: Secret<String>, - #[serde(rename = "3ds")] - pub three_ds: CheckoutThreeDS, - #[serde(flatten)] - pub return_url: ReturnUrl, - pub capture: bool, - pub reference: String, +pub struct BillwerkPaymentsRequest { + handle: String, + amount: MinorUnit, + source: Secret<String>, + currency: common_enums::Currency, + customer: BillwerkCustomerObject, + metadata: Option<SecretSerdeValue>, + settle: bool, } ``` Since Router is connector agnostic, only minimal data is sent to connector and optional fields may be ignored. -Here processing_channel_id, is specific to checkout and implementations of such functions should be inside the checkout directory. -Let's define `PaymentSource` - -`PaymentSource` is an enum type. Request types will need to derive `Serialize` and response types will need to derive `Deserialize`. For request types `From<RouterData>` needs to be implemented. - -For request types that involve an amount, the implementation of `TryFrom<&ConnectorRouterData<&T>>` is required: - -```rust -impl TryFrom<&CheckoutRouterData<&T>> for PaymentsRequest -``` - -else +We transform our `PaymentsAuthorizeRouterData` into Billwerk's `PaymentsRequest` structure by employing the `try_from` function. ```rust -impl TryFrom<T> for PaymentsRequest -``` - -where `T` is a generic type which can be `types::PaymentsAuthorizeRouterData`, `types::PaymentsCaptureRouterData`, etc. - -In this impl block we build the request type from RouterData which will almost always contain all the required information you need for payment processing. -`RouterData` contains all the information required for processing the payment. - -An example implementation for checkout.com is given below. - -```rust -impl<'a> From<&types::RouterData<'a>> for CheckoutPaymentsRequest { - fn from(item: &types::RouterData) -> Self { - - let ccard = match item.payment_method_data { - Some(api::PaymentMethod::Card(ref ccard)) => Some(ccard), - Some(api::PaymentMethod::BankTransfer) | None => None, +impl TryFrom<&BillwerkRouterData<&types::PaymentsAuthorizeRouterData>> for BillwerkPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &BillwerkRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + if item.router_data.is_three_ds() { + return Err(errors::ConnectorError::NotImplemented( + "Three_ds payments through Billwerk".to_string(), + ) + .into()); }; - - let source_var = Source::Card(CardSource { - source_type: Some("card".to_owned()), - number: ccard.map(|x| x.card_number.clone()), - expiry_month: ccard.map(|x| x.card_exp_month.clone()), - expiry_year: ccard.map(|x| x.card_exp_year.clone()), - }); - - CheckoutPaymentsRequest { - source: source_var, + let source = match item.router_data.get_payment_method_token()? { + PaymentMethodToken::Token(pm_token) => Ok(pm_token), + _ => Err(errors::ConnectorError::MissingRequiredField { + field_name: "payment_method_token", + }), + }?; + Ok(Self { + handle: item.router_data.connector_request_reference_id.clone(), amount: item.amount, - currency: item.currency.to_string(), - processing_channel_id: generate_processing_channel_id(), - } - + source, + currency: item.router_data.request.currency, + customer: BillwerkCustomerObject { + handle: item.router_data.customer_id.clone(), + email: item.router_data.request.email.clone(), + address: item.router_data.get_optional_billing_line1(), + address2: item.router_data.get_optional_billing_line2(), + city: item.router_data.get_optional_billing_city(), + country: item.router_data.get_optional_billing_country(), + first_name: item.router_data.get_optional_billing_first_name(), + last_name: item.router_data.get_optional_billing_last_name(), + }, + metadata: item.router_data.request.metadata.clone().map(Into::into), + settle: item.router_data.request.is_auto_capture()?, + }) } } ``` -Request side is now complete. -Similar changes are now needed to handle response side. - -While implementing the Response Type, the important Enum to be defined for every connector is `PaymentStatus`. +### Handle Response Mapping -It stores the different status types that the connector can give in its response that is listed in its API spec. Below is the definition for checkout +When implementing the response type, the key enum to define for each connector is `PaymentStatus`. It represents the different status types returned by the connector, as specified in its API spec. Below is the definition for Billwerk. ```rust -#[derive(Default, Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] -pub enum CheckoutPaymentStatus { +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum BillwerkPaymentState { + Created, Authorized, - #[default] Pending, - #[serde(rename = "Card Verified")] - CardVerified, - Declined, - Captured, + Settled, + Failed, + Cancelled, } -``` -The important part is mapping it to the Router status codes. - -```rust -impl ForeignFrom<(CheckoutPaymentStatus, Option<Balances>)> for enums::AttemptStatus { - fn foreign_from(item: (CheckoutPaymentStatus, Option<Balances>)) -> Self { - let (status, balances) = item; - - match status { - CheckoutPaymentStatus::Authorized => { - if let Some(Balances { - available_to_capture: 0, - }) = balances - { - Self::Charged - } else { - Self::Authorized - } - } - CheckoutPaymentStatus::Captured => Self::Charged, - CheckoutPaymentStatus::Declined => Self::Failure, - CheckoutPaymentStatus::Pending => Self::AuthenticationPending, - CheckoutPaymentStatus::CardVerified => Self::Pending, +impl From<BillwerkPaymentState> for enums::AttemptStatus { + fn from(item: BillwerkPaymentState) -> Self { + match item { + BillwerkPaymentState::Created | BillwerkPaymentState::Pending => Self::Pending, + BillwerkPaymentState::Authorized => Self::Authorized, + BillwerkPaymentState::Settled => Self::Charged, + BillwerkPaymentState::Failed => Self::Failure, + BillwerkPaymentState::Cancelled => Self::Voided, } } } ``` -If you're converting ConnectorPaymentStatus to AttemptStatus without any additional conditions, you can employ the `impl From<ConnectorPaymentStatus> for enums::AttemptStatus`. +Here are common payment attempt statuses: -Note: A payment intent can have multiple payment attempts. `enums::AttemptStatus` represents the status of a payment attempt. +- **Charged:** Payment succeeded. +- **Pending:** Payment is processing. +- **Failure:** Payment failed. +- **Authorized:** Payment authorized; can be voided, captured, or partially captured. +- **AuthenticationPending:** Customer action required. +- **Voided:** Payment voided, funds returned to the customer. -Some of the attempt status are given below +**Note:** Default status should be `Pending`. Only explicit success or failure from the connector should mark the payment as `Charged` or `Failure`. -- **Charged :** The payment attempt has succeeded. -- **Pending :** Payment is in processing state. -- **Failure :** The payment attempt has failed. -- **Authorized :** Payment is authorized. Authorized payment can be voided, captured and partial captured. -- **AuthenticationPending :** Customer action is required. -- **Voided :** The payment was voided and never captured; the funds were returned to the customer. - -It is highly recommended that the default status is Pending. Only explicit failure and explicit success from the connector shall be marked as success or failure respectively. +Define response format in `transformers.rs`: ```rust -// Default should be Pending -impl Default for CheckoutPaymentStatus { - fn default() -> Self { - CheckoutPaymentStatus::Pending - } +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct BillwerkPaymentsResponse { + state: BillwerkPaymentState, + handle: String, + error: Option<String>, + error_state: Option<String>, } ``` -Below is rest of the response type implementation for checkout +We transform our `ResponseRouterData` into `PaymentsResponseData` by employing the `try_from` function. ```rust -#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] -pub struct PaymentsResponse { - id: String, - amount: Option<i32>, - action_id: Option<String>, - status: CheckoutPaymentStatus, - #[serde(rename = "_links")] - links: Links, - balances: Option<Balances>, - reference: Option<String>, - response_code: Option<String>, - response_summary: Option<String>, -} - -#[derive(Deserialize, Debug)] -pub struct ActionResponse { - #[serde(rename = "id")] - pub action_id: String, - pub amount: i64, - #[serde(rename = "type")] - pub action_type: ActionType, - pub approved: Option<bool>, - pub reference: Option<String>, -} - -#[derive(Debug, Deserialize)] -#[serde(untagged)] -pub enum PaymentsResponseEnum { - ActionResponse(Vec<ActionResponse>), - PaymentResponse(Box<PaymentsResponse>), -} - -impl TryFrom<types::PaymentsResponseRouterData<PaymentsResponse>> - for types::PaymentsAuthorizeRouterData +impl<F, T> TryFrom<ResponseRouterData<F, BillwerkPaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::PaymentsResponseRouterData<PaymentsResponse>, + item: ResponseRouterData<F, BillwerkPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { - let redirection_data = item.response.links.redirect.map(|href| { - services::RedirectForm::from((href.redirection_url, services::Method::Get)) - }); - let status = enums::AttemptStatus::foreign_from(( - item.response.status, - item.data.request.capture_method, - )); - let error_response = if status == enums::AttemptStatus::Failure { - Some(types::ErrorResponse { - status_code: item.http_code, + let error_response = if item.response.error.is_some() || item.response.error_state.is_some() + { + Some(ErrorResponse { code: item .response - .response_code - .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + .error_state + .clone() + .unwrap_or(NO_ERROR_CODE.to_string()), message: item .response - .response_summary - .clone() - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), - reason: item.response.response_summary, + .error_state + .unwrap_or(NO_ERROR_MESSAGE.to_string()), + reason: item.response.error, + status_code: item.http_code, attempt_status: None, - connector_transaction_id: None, + connector_transaction_id: Some(item.response.handle.clone()), }) } else { None }; - let payments_response_data = types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), - redirection_data, + let payments_response = PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.handle.clone()), + redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, - connector_response_reference_id: Some( - item.response.reference.unwrap_or(item.response.id), - ), + connector_response_reference_id: Some(item.response.handle), + incremental_authorization_allowed: None, + charges: None, }; Ok(Self { - status, - response: error_response.map_or_else(|| Ok(payments_response_data), Err), + status: enums::AttemptStatus::from(item.response.state), + response: error_response.map_or_else(|| Ok(payments_response), Err), ..item.data }) } } ``` -Using an enum for a response struct in Rust is not recommended due to potential deserialization issues where the deserializer attempts to deserialize into all the enum variants. A preferable alternative is to employ a separate enum for the possible response variants and include it as a field within the response struct. - -Some recommended fields that needs to be set on connector request and response +### Recommended Fields for Connector Request and Response -- **connector_request_reference_id :** Most of the connectors anticipate merchants to include their own reference ID in payment requests. For instance, the merchant's reference ID in the checkout `PaymentRequest` is specified as `reference`. +- **connector_request_reference_id:** Merchant's reference ID in the payment request (e.g., `reference` in Checkout). ```rust reference: item.router_data.connector_request_reference_id.clone(), ``` - -- **connector_response_reference_id :** Merchants might face ambiguity when deciding which ID to use in the connector dashboard for payment identification. It is essential to populate the connector_response_reference_id with the appropriate reference ID, allowing merchants to recognize the transaction. This field can be linked to either `merchant_reference` or `connector_transaction_id`, depending on the field that the connector dashboard search functionality supports. +- **connector_response_reference_id:** ID used for transaction identification in the connector dashboard, linked to merchant_reference or connector_transaction_id. ```rust - connector_response_reference_id: item.response.reference.or(Some(item.response.id)) + connector_response_reference_id: item.response.reference.or(Some(item.response.id)), ``` -- **resource_id :** The connector assigns an identifier to a payment attempt, referred to as `connector_transaction_id`. This identifier is represented as an enum variant for the `resource_id`. If the connector does not provide a `connector_transaction_id`, the resource_id is set to `NoResponseId`. +- **resource_id:** The connector's connector_transaction_id is used as the resource_id. If unavailable, set to NoResponseId. ```rust - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), ``` -- **redirection_data :** For the implementation of a redirection flow (3D Secure, bank redirects, etc.), assign the redirection link to the `redirection_data`. +- **redirection_data:** For redirection flows (e.g., 3D Secure), assign the redirection link. ```rust - let redirection_data = item.response.links.redirect.map(|href| { - services::RedirectForm::from((href.redirection_url, services::Method::Get)) - }); + let redirection_data = item.response.links.redirect.map(|href| { + services::RedirectForm::from((href.redirection_url, services::Method::Get)) + }); ``` -And finally the error type implementation +### Error Handling + +Define error responses: ```rust -#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] -pub struct CheckoutErrorResponse { - pub request_id: Option<String>, - #[serde(rename = "type")] - pub error_type: Option<String>, - pub error_codes: Option<Vec<String>>, +#[derive(Debug, Serialize, Deserialize)] +pub struct BillwerkErrorResponse { + pub code: Option<i32>, + pub error: String, + pub message: Option<String>, } ``` -Similarly for every API endpoint you can implement request and response types. - -### **Implementing the traits** +By following these steps, you can integrate a new connector efficiently while ensuring compatibility with Router's architecture. -The `mod.rs` file contains the trait implementations where we use the types in transformers. +## Implementing the Traits -We create a struct with the connector name and have trait implementations for it. -The following trait implementations are mandatory +The `mod.rs` file contains trait implementations using connector types in transformers. A struct with the connector name holds these implementations. Below are the mandatory traits: -**ConnectorCommon :** contains common description of the connector, like the base endpoint, content-type, error response handling, id, currency unit. +### ConnectorCommon +Contains common description of the connector, like the base endpoint, content-type, error response handling, id, currency unit. Within the `ConnectorCommon` trait, you'll find the following methods : @@ -386,7 +316,7 @@ Within the `ConnectorCommon` trait, you'll find the following methods : ```rust fn id(&self) -> &'static str { - "checkout" + "Billwerk" } ``` @@ -409,126 +339,99 @@ Within the `ConnectorCommon` trait, you'll find the following methods : - `get_auth_header` method accepts common HTTP Authorization headers that are accepted in all `ConnectorIntegration` flows. ```rust - fn get_auth_header( - &self, - auth_type: &types::ConnectorAuthType, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - let auth: checkout::CheckoutAuthType = auth_type - .try_into() - .change_context(errors::ConnectorError::FailedToObtainAuthType)?; - Ok(vec![( - headers::AUTHORIZATION.to_string(), - format!("Bearer {}", auth.api_secret.peek()).into_masked(), - )]) - } + fn get_auth_header( + &self, + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let auth = BillwerkAuthType::try_from(auth_type) + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + let encoded_api_key = BASE64_ENGINE.encode(format!("{}:", auth.api_key.peek())); + Ok(vec![( + headers::AUTHORIZATION.to_string(), + format!("Basic {encoded_api_key}").into_masked(), + )]) + } ``` - `base_url` method is for fetching the base URL of connector's API. Base url needs to be consumed from configs. ```rust - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { - connectors.checkout.base_url.as_ref() - } + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { + connectors.billwerk.base_url.as_ref() + } ``` - `build_error_response` method is common error response handling for a connector if it is same in all cases ```rust - fn build_error_response( - &self, - res: types::Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - let response: checkout::ErrorResponse = if res.response.is_empty() { - let (error_codes, error_type) = if res.status_code == 401 { - ( - Some(vec!["Invalid api key".to_string()]), - Some("invalid_api_key".to_string()), - ) - } else { - (None, None) - }; - checkout::ErrorResponse { - request_id: None, - error_codes, - error_type, - } - } else { - res.response - .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)? - }; - - router_env::logger::info!(error_response=?response); - let errors_list = response.error_codes.clone().unwrap_or_default(); - let option_error_code_message = conn_utils::get_error_code_error_message_based_on_priority( - self.clone(), - errors_list - .into_iter() - .map(|errors| errors.into()) - .collect(), - ); - Ok(types::ErrorResponse { - status_code: res.status_code, - code: option_error_code_message - .clone() - .map(|error_code_message| error_code_message.error_code) - .unwrap_or(consts::NO_ERROR_CODE.to_string()), - message: option_error_code_message - .map(|error_code_message| error_code_message.error_message) - .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), - reason: response - .error_codes - .map(|errors| errors.join(" & ")) - .or(response.error_type), - attempt_status: None, - connector_transaction_id: None, - }) - } + fn build_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: BillwerkErrorResponse = res + .response + .parse_struct("BillwerkErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + + Ok(ErrorResponse { + status_code: res.status_code, + code: response + .code + .map_or(NO_ERROR_CODE.to_string(), |code| code.to_string()), + message: response.message.unwrap_or(NO_ERROR_MESSAGE.to_string()), + reason: Some(response.error), + attempt_status: None, + connector_transaction_id: None, + }) + } ``` -**ConnectorIntegration :** For every api endpoint contains the url, using request transform and response transform and headers. +### ConnectorIntegration +For every api endpoint contains the url, using request transform and response transform and headers. Within the `ConnectorIntegration` trait, you'll find the following methods implemented(below mentioned is example for authorized flow): - `get_url` method defines endpoint for authorize flow, base url is consumed from `ConnectorCommon` trait. ```rust - fn get_url( - &self, - _req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!("{}{}", self.base_url(connectors), "payments")) - } + fn get_url( + &self, + _req: &TokenizationRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let base_url = connectors + .billwerk + .secondary_base_url + .as_ref() + .ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?; + Ok(format!("{base_url}v1/token")) + } ``` - `get_headers` method accepts HTTP headers that are accepted for authorize flow. In this context, it is utilized from the `ConnectorCommonExt` trait, as the connector adheres to common headers across various flows. ```rust - fn get_headers( - &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, connectors) - } + fn get_headers( + &self, + req: &TokenizationRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } ``` -- `get_request_body` method calls transformers where hyperswitch payment request data is transformed into connector payment request. If the conversion and construction processes are successful, the function wraps the constructed connector_req in a Box and returns it as `RequestContent::Json`. The `RequestContent` enum defines different types of request content that can be sent. It includes variants for JSON, form-urlencoded, XML, raw bytes, and potentially other formats. +- `get_request_body` method uses transformers to convert the Hyperswitch payment request to the connector's format. If successful, it returns the request as `RequestContent::Json`, supporting formats like JSON, form-urlencoded, XML, and raw bytes. ```rust - fn get_request_body( + fn get_request_body( &self, - req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, + req: &TokenizationRouterData, + _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = checkout::CheckoutRouterData::try_from(( - &self.get_currency_unit(), - req.request.currency, - req.request.amount, - req, - ))?; - let connector_req = checkout::PaymentsRequest::try_from(&connector_router_data)?; + let connector_req = BillwerkTokenRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } ``` @@ -536,91 +439,89 @@ Within the `ConnectorIntegration` trait, you'll find the following methods imple - `build_request` method assembles the API request by providing the method, URL, headers, and request body as parameters. ```rust - fn build_request( - &self, - req: &types::RouterData< - api::Authorize, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, - >, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsAuthorizeType::get_url( - self, req, connectors, - )?) - .attach_default_headers() - .headers(types::PaymentsAuthorizeType::get_headers( - self, req, connectors, - )?) - .body(types::PaymentsAuthorizeType::get_request_body( - self, req, connectors, - )?) - .build(), - )) - } + fn build_request( + &self, + req: &TokenizationRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::TokenizationType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::TokenizationType::get_headers(self, req, connectors)?) + .set_body(types::TokenizationType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } ``` - `handle_response` method calls transformers where connector response data is transformed into hyperswitch response. ```rust - fn handle_response( - &self, - data: &types::PaymentsAuthorizeRouterData, - event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { - let response: checkout::PaymentsResponse = res - .response - .parse_struct("PaymentIntentResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + fn handle_response( + &self, + data: &TokenizationRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<TokenizationRouterData, errors::ConnectorError> + where + PaymentsResponseData: Clone, + { + let response: BillwerkTokenResponse = res + .response + .parse_struct("BillwerkTokenResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - .change_context(errors::ConnectorError::ResponseHandlingFailed) - } + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } ``` - `get_error_response` method to manage error responses. As the handling of checkout errors remains consistent across various flows, we've incorporated it from the `build_error_response` method within the `ConnectorCommon` trait. ```rust - fn get_error_response( - &self, - res: types::Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - self.build_error_response(res, event_builder) - } + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } ``` -**ConnectorCommonExt :** An enhanced trait for `ConnectorCommon` that enables functions with a generic type. This trait includes the `build_headers` method, responsible for constructing both the common headers and the Authorization headers (retrieved from the `get_auth_header` method), returning them as a vector. +### ConnectorCommonExt +Adds functions with a generic type, including the `build_headers` method. This method constructs both common headers and Authorization headers (from `get_auth_header`), returning them as a vector. ```rust - where - Self: ConnectorIntegration<Flow, Request, Response>, -{ - fn build_headers( - &self, - req: &types::RouterData<Flow, Request, Response>, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - let header = vec![( - headers::CONTENT_TYPE.to_string(), - self.get_content_type().to_string().into(), - )]; - let mut api_key = self.get_auth_header(&req.connector_auth_type)?; - header.append(&mut api_key); - Ok(header) - } -} + impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Billwerk + where + Self: ConnectorIntegration<Flow, Request, Response>, + { + fn build_headers( + &self, + req: &RouterData<Flow, Request, Response>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let mut header = vec![( + headers::CONTENT_TYPE.to_string(), + self.get_content_type().to_string().into(), + )]; + let mut api_key = self.get_auth_header(&req.connector_auth_type)?; + header.append(&mut api_key); + Ok(header) + } + } ``` +### OtherTraits **Payment :** This trait includes several other traits and is meant to represent the functionality related to payments. **PaymentAuthorize :** This trait extends the `api::ConnectorIntegration `trait with specific types related to payment authorization. @@ -641,14 +542,9 @@ And the below derive traits - **Clone** - **Copy** -There is a trait bound to implement refunds, if you don't want to implement refunds you can mark them as `todo!()` but code panics when you initiate refunds then. - -Refer to other connector code for trait implementations. Mostly the rust compiler will guide you to do it easily. -Feel free to connect with us in case of any queries and if you want to confirm the status mapping. - ### **Set the currency Unit** -The `get_currency_unit` function, part of the ConnectorCommon trait, enables connectors to specify their accepted currency unit as either `Base` or `Minor`. For instance, Paypal designates its currency in the base unit (for example, USD), whereas Hyperswitch processes amounts in the minor unit (for example, cents). If a connector accepts amounts in the base unit, conversion is required, as illustrated. +Part of the `ConnectorCommon` trait, it allows connectors to specify their accepted currency unit as either `Base` or `Minor`. For example, PayPal uses the base unit (e.g., USD), while Hyperswitch uses the minor unit (e.g., cents). Conversion is required if the connector uses the base unit. ```rust impl<T> @@ -677,21 +573,19 @@ impl<T> } ``` -**Note:** Since the amount is being converted in the aforementioned `try_from`, it is necessary to retrieve amounts from `ConnectorRouterData` in all other `try_from` instances. - ### **Connector utility functions** -In the `connector/utils.rs` file, you'll discover utility functions that aid in constructing connector requests and responses. We highly recommend using these helper functions for retrieving payment request fields, such as `get_billing_country`, `get_browser_info`, and `get_expiry_date_as_yyyymm`, as well as for validations, including `is_three_ds`, `is_auto_capture`, and more. +Contains utility functions for constructing connector requests and responses. Use these helpers for retrieving fields like `get_billing_country`, `get_browser_info`, and `get_expiry_date_as_yyyymm`, as well as for validations like `is_three_ds` and `is_auto_capture`. ```rust - let json_wallet_data: CheckoutGooglePayData =wallet_data.get_wallet_token_as_json()?; + let json_wallet_data: CheckoutGooglePayData = wallet_data.get_wallet_token_as_json()?; ``` ### **Connector configs for control center** -This section is explicitly for developers who are using the [Hyperswitch Control Center](https://github.com/juspay/hyperswitch-control-center). Below is a more detailed documentation that guides you through updating the connector configuration in the `development.toml` file in Hyperswitch and running the wasm-pack build command. Please replace placeholders such as `/absolute/path/to/` with the actual absolute paths. +This section is for developers using the [Hyperswitch Control Center](https://github.com/juspay/hyperswitch-control-center). Update the connector configuration in development.toml and run the wasm-pack build command. Replace placeholders with actual paths. -1. Install wasm-pack: Run the following command to install wasm-pack: +1. Install wasm-pack: ```bash cargo install wasm-pack @@ -699,11 +593,10 @@ cargo install wasm-pack 2. Add connector configuration: - Open the `development.toml` file located at `crates/connector_configs/toml/development.toml` in your Hyperswitch project. - - Locate the [stripe] section as an example and add the configuration for the `example_connector`. Here's an example: + Open the development.toml file located at crates/connector_configs/toml/development.toml in your Hyperswitch project. + Find the [stripe] section and add the configuration for example_connector. Example: - ```toml + ```toml # crates/connector_configs/toml/development.toml # Other connector configurations... @@ -720,144 +613,57 @@ cargo install wasm-pack ``` - provide the necessary configuration details for the `example_connector`. Don't forget to save the file. - 3. Update paths: - - Replace `/absolute/path/to/hyperswitch-control-center` with the absolute path to your Hyperswitch Control Center repository and `/absolute/path/to/hyperswitch` with the absolute path to your Hyperswitch repository. + Replace /absolute/path/to/hyperswitch-control-center and /absolute/path/to/hyperswitch with actual paths. 4. Run `wasm-pack` build: - - Execute the following command in your terminal: - - ```bash - wasm-pack build --target web --out-dir /absolute/path/to/hyperswitch-control-center/public/hyperswitch/wasm --out-name euclid /absolute/path/to/hyperswitch/crates/euclid_wasm -- --features dummy_connector - ``` - - This command builds the WebAssembly files for the `dummy_connector` feature and places them in the specified directory. - -Notes: - -- Ensure that you replace placeholders like `/absolute/path/to/` with the actual absolute paths in your file system. -- Verify that your connector configurations in `development.toml` are correct and saved before running the `wasm-pack` command. -- Check for any error messages during the build process and resolve them accordingly. + wasm-pack build --target web --out-dir /absolute/path/to/hyperswitch-control-center/public/hyperswitch/wasm --out-name euclid /absolute/path/to/hyperswitch/crates/euclid_wasm -- --features dummy_connector By following these steps, you should be able to update the connector configuration and build the WebAssembly files successfully. -Certainly! Below is a detailed documentation guide on updating the `ConnectorTypes.res` and `ConnectorUtils.res` files in your [Hyperswitch Control Center](https://github.com/juspay/hyperswitch-control-center) project. - -Update `ConnectorTypes.res`: - -1. Open `ConnectorTypes.res`: - - Open the `ConnectorTypes.res` file located at `src/screens/HyperSwitch/Connectors/ConnectorTypes.res` in your Hyperswitch-Control-Center project. - -2. Add Connector enum: - - Add the new connector name enum under the `type connectorName` section. Here's an example: - - ```reason - /* src/screens/HyperSwitch/Connectors/ConnectorTypes.res */ - - type connectorName = - | Stripe - | DummyConnector - | YourNewConnector - /* Add any other connector enums as needed */ - ``` - - Replace `YourNewConnector` with the name of your newly added connector. - -3. Save the file: - - Save the changes made to `ConnectorTypes.res`. - -Update `ConnectorUtils.res`: - -1. Open `ConnectorUtils.res`: - - Open the `ConnectorUtils.res` file located at `src/screens/HyperSwitch/Connectors/ConnectorUtils.res` in your [Hyperswitch Control Center](https://github.com/juspay/hyperswitch-control-center) project. - -2. Add Connector Description: - - Update the following functions in `ConnectorUtils.res`: - - ```reason - /* src/screens/HyperSwitch/Connectors/ConnectorUtils.res */ - - - let connectorList : array<connectorName> = [Stripe,YourNewConnector] - - - let getConnectorNameString = (connectorName: connectorName) => - switch connectorName { - | Stripe => "Stripe" - | DummyConnector => "Dummy Connector" - | YourNewConnector => "Your New Connector" - /* Add cases for other connectors */ - }; - - let getConnectorNameTypeFromString = (str: string) => - switch str { - | "Stripe" => Stripe - | "Dummy Connector" => DummyConnector - | "Your New Connector" => YourNewConnector - /* Add cases for other connectors */ - }; - - let getConnectorInfo = (connectorName: connectorName) => - switch connectorName { - | Stripe => "Stripe connector description." - | DummyConnector => "Dummy Connector description." - | YourNewConnector => "Your New Connector description." - /* Add descriptions for other connectors */ - }; - - let getDisplayNameForConnectors = (connectorName: connectorName) => - switch connectorName { - | Stripe => "Stripe" - | DummyConnector => "Dummy Connector" - | YourNewConnector => "Your New Connector" - /* Add display names for other connectors */ - }; - ``` - - Adjust the strings and descriptions according to your actual connector names and descriptions. - - -4. Save the File: - - Save the changes made to `ConnectorUtils.res`. - -Notes: - -- Ensure that you replace placeholders like `YourNewConnector` with the actual names of your connectors. -- Verify that your connector enums and descriptions are correctly updated. -- Save the files after making the changes. - -By following these steps, you should be able to update the `ConnectorTypes.res` and `ConnectorUtils.res` files with the new connector enum and its related information. - - - -Certainly! Below is a detailed documentation guide on how to add a new connector icon under the `public/hyperswitch/Gateway` folder in your Hyperswitch-Control-Center project. - -Add Connector icon: - -1. Prepare the icon: - - Prepare your connector icon in SVG format. Ensure that the icon is named in uppercase, following the convention. For example, name it `YOURCONNECTOR.SVG`. - -2. Open file explorer: - - Open your file explorer and navigate to the `public/hyperswitch/Gateway` folder in your Hyperswitch-Control-Center project. - -3. Add Icon file: - - Copy and paste your SVG icon file (e.g., `YOURCONNECTOR.SVG`) into the `Gateway` folder. - -4. Verify file structure: - - Ensure that the file structure in the `Gateway` folder follows the uppercase convention. For example: +### Update `ConnectorTypes.res` and `ConnectorUtils.res` + +1. **Update `ConnectorTypes.res`**: + - Open `src/screens/HyperSwitch/Connectors/ConnectorTypes.res`. + - Add your connector to the `connectorName` enum: + ```reason + type connectorName = + | Stripe + | DummyConnector + | YourNewConnector + ``` + - Save the file. + +2. **Update `ConnectorUtils.res`**: + - Open `src/screens/HyperSwitch/Connectors/ConnectorUtils.res`. + - Update functions with your connector: + ```reason + let connectorList : array<connectorName> = [Stripe, YourNewConnector] + + let getConnectorNameString = (connectorName: connectorName) => + switch connectorName { + | Stripe => "Stripe" + | YourNewConnector => "Your New Connector" + }; + + let getConnectorInfo = (connectorName: connectorName) => + switch connectorName { + | Stripe => "Stripe description." + | YourNewConnector => "Your New Connector description." + }; + ``` + - Save the file. + +### Add Connector Icon + +1. **Prepare the Icon**: + Name your connector icon in uppercase (e.g., `YOURCONNECTOR.SVG`). + +2. **Add the Icon**: + Navigate to `public/hyperswitch/Gateway` and copy your SVG icon file there. + +3. **Verify Structure**: + Ensure the file is correctly placed in `public/hyperswitch/Gateway`: ``` public @@ -865,122 +671,50 @@ Add Connector icon: └── Gateway └── YOURCONNECTOR.SVG ``` - Save the changes made to the `Gateway` folder. + Save the changes made to the `Gateway` folder. +### **Test the Connector** -### **Test the connector** +1. **Template Code** -The template code script generates a test file for the connector, containing 20 sanity tests. We anticipate that you will implement these tests when adding a new connector. + The template script generates a test file with 20 sanity tests. Implement these tests when adding a new connector. -```rust -// Cards Positive Tests -// Creates a payment using the manual capture flow (Non 3DS). -#[serial_test::serial] -#[actix_web::test] -async fn should_only_authorize_payment() { - let response = CONNECTOR - .authorize_payment(payment_method_details(), get_default_payment_info()) - .await - .expect("Authorize payment response"); - assert_eq!(response.status, enums::AttemptStatus::Authorized); -} -``` - -Utility functions for tests are also available at `tests/connector/utils`. These functions enable you to write tests with ease. - -```rust - /// For initiating payments when `CaptureMethod` is set to `Manual` - /// This doesn't complete the transaction, `PaymentsCapture` needs to be done manually - async fn authorize_payment( - &self, - payment_data: Option<types::PaymentsAuthorizeData>, - payment_info: Option<PaymentInfo>, - ) -> Result<types::PaymentsAuthorizeRouterData, Report<ConnectorError>> { - let integration = self.get_data().connector.get_connector_integration(); - let mut request = self.generate_data( - types::PaymentsAuthorizeData { - confirm: true, - capture_method: Some(diesel_models::enums::CaptureMethod::Manual), - ..(payment_data.unwrap_or(PaymentAuthorizeType::default().0)) - }, - payment_info, - ); - let tx: oneshot::Sender<()> = oneshot::channel().0; - let state = routes::AppState::with_storage( - Settings::new().unwrap(), - StorageImpl::PostgresqlTest, - tx, - Box::new(services::MockApiClient), - ) - .await; - Box::pin(call_connector(request, integration)).await + Example test: + ```rust + #[serial_test::serial] + #[actix_web::test] + async fn should_only_authorize_payment() { + let response = CONNECTOR + .authorize_payment(payment_method_details(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + assert_eq!(response.status, enums::AttemptStatus::Authorized); } -``` + ``` -Prior to executing tests in the shell, ensure that the API keys are configured in `crates/router/tests/connectors/sample_auth.toml` and set the environment variable `CONNECTOR_AUTH_FILE_PATH` using the export command. Avoid pushing code with exposed API keys. +2. **Utility Functions** -```rust - export CONNECTOR_AUTH_FILE_PATH="/hyperswitch/crates/router/tests/connectors/sample_auth.toml" - cargo test --package router --test connectors -- checkout --test-threads=1 -``` + Helper functions for tests are available in `tests/connector/utils`, making test writing easier. -All tests should pass and add appropriate tests for connector specific payment flows. +3. **Set API Keys** -### **Build payment request and response from json schema** + Before running tests, configure API keys in sample_auth.toml and set the environment variable: -Some connectors will provide [json schema](https://developer.worldpay.com/docs/access-worldpay/api/references/payments) for each request and response supported. We can directly convert that schema to rust code by using below script. On running the script a `temp.rs` file will be created in `src/connector/<connector-name>` folder + ```bash + export CONNECTOR_AUTH_FILE_PATH="/hyperswitch/crates/router/tests/connectors/sample_auth.toml" + cargo test --package router --test connectors -- checkout --test-threads=1 + ``` -_Note: The code generated may not be production ready and might fail for some case, we have to clean up the code as per our standards._ +### **Build Payment Request and Response from JSON Schema** -```bash -brew install openapi-generator -export CONNECTOR_NAME="<CONNECTOR-NAME>" #Change it to appropriate connector name -export SCHEMA_PATH="<PATH-TO-JSON-SCHEMA-FILE>" #it can be json or yaml, Refer samples below -openapi-generator generate -g rust -i ${SCHEMA_PATH} -o temp && cat temp/src/models/* > crates/router/src/connector/${CONNECTOR_NAME}/temp.rs && rm -rf temp && sed -i'' -r "s/^pub use.*//;s/^pub mod.*//;s/^\/.*//;s/^.\*.*//;s/crate::models:://g;" crates/router/src/connector/${CONNECTOR_NAME}/temp.rs && cargo +nightly fmt -``` - -JSON example - -```json -{ - "openapi": "3.0.1", - "paths": {}, - "info": { - "title": "", - "version": "" - }, - "components": { - "schemas": { - "PaymentsResponse": { - "type": "object", - "properties": { - "outcome": { - "type": "string" - } - }, - "required": ["outcome"] - } - } - } -} -``` +1. **Install OpenAPI Generator:** + ```bash + brew install openapi-generator + ``` -YAML example - -```yaml ---- -openapi: 3.0.1 -paths: {} -info: - title: "" - version: "" -components: - schemas: - PaymentsResponse: - type: object - properties: - outcome: - type: string - required: - - outcome -``` +2. **Generate Rust Code:** + ```bash + export CONNECTOR_NAME="<CONNECTOR-NAME>" + export SCHEMA_PATH="<PATH-TO-SCHEMA>" + openapi-generator generate -g rust -i ${SCHEMA_PATH} -o temp && cat temp/src/models/* > crates/router/src/connector/${CONNECTOR_NAME}/temp.rs && rm -rf temp && sed -i'' -r "s/^pub use.*//;s/^pub mod.*//;s/^\/.*//;s/^.\*.*//;s/crate::models:://g;" crates/router/src/connector/${CONNECTOR_NAME}/temp.rs && cargo +nightly fmt + ``` \ No newline at end of file diff --git a/add_connector_updated.md b/add_connector_updated.md index 4ee8c895656..3220cac5c5f 100644 --- a/add_connector_updated.md +++ b/add_connector_updated.md @@ -1,720 +1,5 @@ -# Guide to Integrating a Connector +# 📦 File Moved -## Table of Contents +This file has been renamed. Please visit the updated version here: -1. [Introduction](#introduction) -2. [Prerequisites](#prerequisites) -3. [Understanding Connectors and Payment Methods](#understanding-connectors-and-payment-methods) -4. [Integration Steps](#integration-steps) - - [Generate Template](#generate-template) - - [Implement Request & Response Types](#implement-request--response-types) - - [Implement transformers.rs](#implementing-transformersrs) - - [Handle Response Mapping](#handle-response-mapping) - - [Recommended Fields for Connector Request and Response](#recommended-fields-for-connector-request-and-response) - - [Error Handling](#error-handling) -5. [Implementing the Traits](#implementing-the-traits) - - [ConnectorCommon](#connectorcommon) - - [ConnectorIntegration](#connectorintegration) - - [ConnectorCommonExt](#connectorcommonext) - - [Other Traits](#othertraits) -6. [Set the Currency Unit](#set-the-currency-unit) -7. [Connector utility functions](#connector-utility-functions) -8. [Connector configs for control center](#connector-configs-for-control-center) -9. [Update `ConnectorTypes.res` and `ConnectorUtils.res`](#update-connectortypesres-and-connectorutilsres) -10. [Add Connector Icon](#add-connector-icon) -11. [Test the Connector](#test-the-connector) -12. [Build Payment Request and Response from JSON Schema](#build-payment-request-and-response-from-json-schema) - -## Introduction - -This guide provides instructions on integrating a new connector with Router, from setting up the environment to implementing API interactions. - -## Prerequisites - -- Familiarity with the Connector API you’re integrating -- A locally set up and running Router repository -- API credentials for testing (sign up for sandbox/UAT credentials on the connector’s website). -- Rust nightly toolchain installed for code formatting: - ```bash - rustup toolchain install nightly - ``` - -## Understanding Connectors and Payment Methods - -A **Connector** processes payments (e.g., Stripe, Adyen) or manages fraud risk (e.g., Signifyd). A **Payment Method** is a specific way to transact (e.g., credit card, PayPal). See the [Hyperswitch Payment Matrix](https://hyperswitch.io/pm-list) for details. - -## Integration Steps - -Integrating a connector is mainly an API integration task. You'll define request and response types and implement required traits. - -This tutorial covers card payments via [Billwerk](https://optimize-docs.billwerk.com/). Review the API reference and test APIs before starting. - -Follow these steps to integrate a new connector. - -### Generate Template - -Run the following script to create the connector structure: - -```bash -sh scripts/add_connector.sh <connector-name> <connector-base-url> -``` - -Example folder structure: - -``` -hyperswitch_connectors/src/connectors -├── billwerk -│ └── transformers.rs -└── billwerk.rs -crates/router/tests/connectors -└── billwerk.rs -``` - -**Note:** move the file `crates/hyperswitch_connectors/src/connectors/connector_name/test.rs` to `crates/router/tests/connectors/connector_name.rs` - - -Define API request/response types and conversions in `hyperswitch_connectors/src/connector/billwerk/transformers.rs` - -Implement connector traits in `hyperswitch_connectors/src/connector/billwerk.rs` - -Write basic payment flow tests in `crates/router/tests/connectors/billwerk.rs` - -Boilerplate code with todo!() is provided—follow the guide and complete the necessary implementations. - -### Implement Request & Response Types - -Integrating a new connector involves transforming Router's core data into the connector's API format. Since the Connector module is stateless, Router handles data persistence. - -#### Implementing transformers.rs - -Design request/response structures based on the connector's API spec. - -Define request format in `transformers.rs`: - -```rust -#[derive(Debug, Serialize)] -pub struct BillwerkCustomerObject { - handle: Option<id_type::CustomerId>, - email: Option<Email>, - address: Option<Secret<String>>, - address2: Option<Secret<String>>, - city: Option<String>, - country: Option<common_enums::CountryAlpha2>, - first_name: Option<Secret<String>>, - last_name: Option<Secret<String>>, -} - -#[derive(Debug, Serialize)] -pub struct BillwerkPaymentsRequest { - handle: String, - amount: MinorUnit, - source: Secret<String>, - currency: common_enums::Currency, - customer: BillwerkCustomerObject, - metadata: Option<SecretSerdeValue>, - settle: bool, -} -``` - -Since Router is connector agnostic, only minimal data is sent to connector and optional fields may be ignored. - -We transform our `PaymentsAuthorizeRouterData` into Billwerk's `PaymentsRequest` structure by employing the `try_from` function. - -```rust -impl TryFrom<&BillwerkRouterData<&types::PaymentsAuthorizeRouterData>> for BillwerkPaymentsRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - item: &BillwerkRouterData<&types::PaymentsAuthorizeRouterData>, - ) -> Result<Self, Self::Error> { - if item.router_data.is_three_ds() { - return Err(errors::ConnectorError::NotImplemented( - "Three_ds payments through Billwerk".to_string(), - ) - .into()); - }; - let source = match item.router_data.get_payment_method_token()? { - PaymentMethodToken::Token(pm_token) => Ok(pm_token), - _ => Err(errors::ConnectorError::MissingRequiredField { - field_name: "payment_method_token", - }), - }?; - Ok(Self { - handle: item.router_data.connector_request_reference_id.clone(), - amount: item.amount, - source, - currency: item.router_data.request.currency, - customer: BillwerkCustomerObject { - handle: item.router_data.customer_id.clone(), - email: item.router_data.request.email.clone(), - address: item.router_data.get_optional_billing_line1(), - address2: item.router_data.get_optional_billing_line2(), - city: item.router_data.get_optional_billing_city(), - country: item.router_data.get_optional_billing_country(), - first_name: item.router_data.get_optional_billing_first_name(), - last_name: item.router_data.get_optional_billing_last_name(), - }, - metadata: item.router_data.request.metadata.clone().map(Into::into), - settle: item.router_data.request.is_auto_capture()?, - }) - } -} -``` - -### Handle Response Mapping - -When implementing the response type, the key enum to define for each connector is `PaymentStatus`. It represents the different status types returned by the connector, as specified in its API spec. Below is the definition for Billwerk. - -```rust -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -#[serde(rename_all = "lowercase")] -pub enum BillwerkPaymentState { - Created, - Authorized, - Pending, - Settled, - Failed, - Cancelled, -} - -impl From<BillwerkPaymentState> for enums::AttemptStatus { - fn from(item: BillwerkPaymentState) -> Self { - match item { - BillwerkPaymentState::Created | BillwerkPaymentState::Pending => Self::Pending, - BillwerkPaymentState::Authorized => Self::Authorized, - BillwerkPaymentState::Settled => Self::Charged, - BillwerkPaymentState::Failed => Self::Failure, - BillwerkPaymentState::Cancelled => Self::Voided, - } - } -} -``` - -Here are common payment attempt statuses: - -- **Charged:** Payment succeeded. -- **Pending:** Payment is processing. -- **Failure:** Payment failed. -- **Authorized:** Payment authorized; can be voided, captured, or partially captured. -- **AuthenticationPending:** Customer action required. -- **Voided:** Payment voided, funds returned to the customer. - -**Note:** Default status should be `Pending`. Only explicit success or failure from the connector should mark the payment as `Charged` or `Failure`. - -Define response format in `transformers.rs`: - -```rust -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct BillwerkPaymentsResponse { - state: BillwerkPaymentState, - handle: String, - error: Option<String>, - error_state: Option<String>, -} -``` - -We transform our `ResponseRouterData` into `PaymentsResponseData` by employing the `try_from` function. - -```rust -impl<F, T> TryFrom<ResponseRouterData<F, BillwerkPaymentsResponse, T, PaymentsResponseData>> - for RouterData<F, T, PaymentsResponseData> -{ - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - item: ResponseRouterData<F, BillwerkPaymentsResponse, T, PaymentsResponseData>, - ) -> Result<Self, Self::Error> { - let error_response = if item.response.error.is_some() || item.response.error_state.is_some() - { - Some(ErrorResponse { - code: item - .response - .error_state - .clone() - .unwrap_or(NO_ERROR_CODE.to_string()), - message: item - .response - .error_state - .unwrap_or(NO_ERROR_MESSAGE.to_string()), - reason: item.response.error, - status_code: item.http_code, - attempt_status: None, - connector_transaction_id: Some(item.response.handle.clone()), - }) - } else { - None - }; - let payments_response = PaymentsResponseData::TransactionResponse { - resource_id: ResponseId::ConnectorTransactionId(item.response.handle.clone()), - redirection_data: Box::new(None), - mandate_reference: Box::new(None), - connector_metadata: None, - network_txn_id: None, - connector_response_reference_id: Some(item.response.handle), - incremental_authorization_allowed: None, - charges: None, - }; - Ok(Self { - status: enums::AttemptStatus::from(item.response.state), - response: error_response.map_or_else(|| Ok(payments_response), Err), - ..item.data - }) - } -} -``` - -### Recommended Fields for Connector Request and Response - -- **connector_request_reference_id:** Merchant's reference ID in the payment request (e.g., `reference` in Checkout). - -```rust - reference: item.router_data.connector_request_reference_id.clone(), -``` -- **connector_response_reference_id:** ID used for transaction identification in the connector dashboard, linked to merchant_reference or connector_transaction_id. - -```rust - connector_response_reference_id: item.response.reference.or(Some(item.response.id)), -``` - -- **resource_id:** The connector's connector_transaction_id is used as the resource_id. If unavailable, set to NoResponseId. - -```rust - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), -``` - -- **redirection_data:** For redirection flows (e.g., 3D Secure), assign the redirection link. - -```rust - let redirection_data = item.response.links.redirect.map(|href| { - services::RedirectForm::from((href.redirection_url, services::Method::Get)) - }); -``` - -### Error Handling - -Define error responses: - -```rust -#[derive(Debug, Serialize, Deserialize)] -pub struct BillwerkErrorResponse { - pub code: Option<i32>, - pub error: String, - pub message: Option<String>, -} -``` - -By following these steps, you can integrate a new connector efficiently while ensuring compatibility with Router's architecture. - -## Implementing the Traits - -The `mod.rs` file contains trait implementations using connector types in transformers. A struct with the connector name holds these implementations. Below are the mandatory traits: - -### ConnectorCommon -Contains common description of the connector, like the base endpoint, content-type, error response handling, id, currency unit. - -Within the `ConnectorCommon` trait, you'll find the following methods : - -- `id` method corresponds directly to the connector name. - -```rust - fn id(&self) -> &'static str { - "Billwerk" - } -``` - -- `get_currency_unit` method anticipates you to [specify the accepted currency unit](#set-the-currency-unit) for the connector. - -```rust - fn get_currency_unit(&self) -> api::CurrencyUnit { - api::CurrencyUnit::Minor - } -``` - -- `common_get_content_type` method requires you to provide the accepted content type for the connector API. - -```rust - fn common_get_content_type(&self) -> &'static str { - "application/json" - } -``` - -- `get_auth_header` method accepts common HTTP Authorization headers that are accepted in all `ConnectorIntegration` flows. - -```rust - fn get_auth_header( - &self, - auth_type: &ConnectorAuthType, - ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { - let auth = BillwerkAuthType::try_from(auth_type) - .change_context(errors::ConnectorError::FailedToObtainAuthType)?; - let encoded_api_key = BASE64_ENGINE.encode(format!("{}:", auth.api_key.peek())); - Ok(vec![( - headers::AUTHORIZATION.to_string(), - format!("Basic {encoded_api_key}").into_masked(), - )]) - } -``` - -- `base_url` method is for fetching the base URL of connector's API. Base url needs to be consumed from configs. - -```rust - fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { - connectors.billwerk.base_url.as_ref() - } -``` - -- `build_error_response` method is common error response handling for a connector if it is same in all cases - -```rust - fn build_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - let response: BillwerkErrorResponse = res - .response - .parse_struct("BillwerkErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - - Ok(ErrorResponse { - status_code: res.status_code, - code: response - .code - .map_or(NO_ERROR_CODE.to_string(), |code| code.to_string()), - message: response.message.unwrap_or(NO_ERROR_MESSAGE.to_string()), - reason: Some(response.error), - attempt_status: None, - connector_transaction_id: None, - }) - } -``` - -### ConnectorIntegration -For every api endpoint contains the url, using request transform and response transform and headers. -Within the `ConnectorIntegration` trait, you'll find the following methods implemented(below mentioned is example for authorized flow): - -- `get_url` method defines endpoint for authorize flow, base url is consumed from `ConnectorCommon` trait. - -```rust - fn get_url( - &self, - _req: &TokenizationRouterData, - connectors: &Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - let base_url = connectors - .billwerk - .secondary_base_url - .as_ref() - .ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?; - Ok(format!("{base_url}v1/token")) - } -``` - -- `get_headers` method accepts HTTP headers that are accepted for authorize flow. In this context, it is utilized from the `ConnectorCommonExt` trait, as the connector adheres to common headers across various flows. - -```rust - fn get_headers( - &self, - req: &TokenizationRouterData, - connectors: &Connectors, - ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, connectors) - } -``` - -- `get_request_body` method uses transformers to convert the Hyperswitch payment request to the connector's format. If successful, it returns the request as `RequestContent::Json`, supporting formats like JSON, form-urlencoded, XML, and raw bytes. - -```rust - fn get_request_body( - &self, - req: &TokenizationRouterData, - _connectors: &Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = BillwerkTokenRequest::try_from(req)?; - Ok(RequestContent::Json(Box::new(connector_req))) - } -``` - -- `build_request` method assembles the API request by providing the method, URL, headers, and request body as parameters. - -```rust - fn build_request( - &self, - req: &TokenizationRouterData, - connectors: &Connectors, - ) -> CustomResult<Option<Request>, errors::ConnectorError> { - Ok(Some( - RequestBuilder::new() - .method(Method::Post) - .url(&types::TokenizationType::get_url(self, req, connectors)?) - .attach_default_headers() - .headers(types::TokenizationType::get_headers(self, req, connectors)?) - .set_body(types::TokenizationType::get_request_body( - self, req, connectors, - )?) - .build(), - )) - } -``` - -- `handle_response` method calls transformers where connector response data is transformed into hyperswitch response. - -```rust - fn handle_response( - &self, - data: &TokenizationRouterData, - event_builder: Option<&mut ConnectorEvent>, - res: Response, - ) -> CustomResult<TokenizationRouterData, errors::ConnectorError> - where - PaymentsResponseData: Clone, - { - let response: BillwerkTokenResponse = res - .response - .parse_struct("BillwerkTokenResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - RouterData::try_from(ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - .change_context(errors::ConnectorError::ResponseHandlingFailed) - } -``` - -- `get_error_response` method to manage error responses. As the handling of checkout errors remains consistent across various flows, we've incorporated it from the `build_error_response` method within the `ConnectorCommon` trait. - -```rust - fn get_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res, event_builder) - } -``` - -### ConnectorCommonExt -Adds functions with a generic type, including the `build_headers` method. This method constructs both common headers and Authorization headers (from `get_auth_header`), returning them as a vector. - -```rust - impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Billwerk - where - Self: ConnectorIntegration<Flow, Request, Response>, - { - fn build_headers( - &self, - req: &RouterData<Flow, Request, Response>, - _connectors: &Connectors, - ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { - let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - self.get_content_type().to_string().into(), - )]; - let mut api_key = self.get_auth_header(&req.connector_auth_type)?; - header.append(&mut api_key); - Ok(header) - } - } -``` - -### OtherTraits -**Payment :** This trait includes several other traits and is meant to represent the functionality related to payments. - -**PaymentAuthorize :** This trait extends the `api::ConnectorIntegration `trait with specific types related to payment authorization. - -**PaymentCapture :** This trait extends the `api::ConnectorIntegration `trait with specific types related to manual payment capture. - -**PaymentSync :** This trait extends the `api::ConnectorIntegration `trait with specific types related to payment retrieve. - -**Refund :** This trait includes several other traits and is meant to represent the functionality related to Refunds. - -**RefundExecute :** This trait extends the `api::ConnectorIntegration `trait with specific types related to refunds create. - -**RefundSync :** This trait extends the `api::ConnectorIntegration `trait with specific types related to refunds retrieve. - -And the below derive traits - -- **Debug** -- **Clone** -- **Copy** - -### **Set the currency Unit** - -Part of the `ConnectorCommon` trait, it allows connectors to specify their accepted currency unit as either `Base` or `Minor`. For example, PayPal uses the base unit (e.g., USD), while Hyperswitch uses the minor unit (e.g., cents). Conversion is required if the connector uses the base unit. - -```rust -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for PaypalRouterData<T> -{ - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - (currency_unit, currency, amount, item): ( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - ), - ) -> Result<Self, Self::Error> { - let amount = utils::get_amount_as_string(currency_unit, amount, currency)?; - Ok(Self { - amount, - router_data: item, - }) - } -} -``` - -### **Connector utility functions** - -Contains utility functions for constructing connector requests and responses. Use these helpers for retrieving fields like `get_billing_country`, `get_browser_info`, and `get_expiry_date_as_yyyymm`, as well as for validations like `is_three_ds` and `is_auto_capture`. - -```rust - let json_wallet_data: CheckoutGooglePayData = wallet_data.get_wallet_token_as_json()?; -``` - -### **Connector configs for control center** - -This section is for developers using the [Hyperswitch Control Center](https://github.com/juspay/hyperswitch-control-center). Update the connector configuration in development.toml and run the wasm-pack build command. Replace placeholders with actual paths. - -1. Install wasm-pack: - -```bash -cargo install wasm-pack -``` - -2. Add connector configuration: - - Open the development.toml file located at crates/connector_configs/toml/development.toml in your Hyperswitch project. - Find the [stripe] section and add the configuration for example_connector. Example: - - ```toml - # crates/connector_configs/toml/development.toml - - # Other connector configurations... - - [stripe] - [stripe.connector_auth.HeaderKey] - api_key="Secret Key" - - # Add any other Stripe-specific configuration here - - [example_connector] - # Your specific connector configuration for reference - # ... - - ``` - -3. Update paths: - Replace /absolute/path/to/hyperswitch-control-center and /absolute/path/to/hyperswitch with actual paths. - -4. Run `wasm-pack` build: - wasm-pack build --target web --out-dir /absolute/path/to/hyperswitch-control-center/public/hyperswitch/wasm --out-name euclid /absolute/path/to/hyperswitch/crates/euclid_wasm -- --features dummy_connector - -By following these steps, you should be able to update the connector configuration and build the WebAssembly files successfully. - -### Update `ConnectorTypes.res` and `ConnectorUtils.res` - -1. **Update `ConnectorTypes.res`**: - - Open `src/screens/HyperSwitch/Connectors/ConnectorTypes.res`. - - Add your connector to the `connectorName` enum: - ```reason - type connectorName = - | Stripe - | DummyConnector - | YourNewConnector - ``` - - Save the file. - -2. **Update `ConnectorUtils.res`**: - - Open `src/screens/HyperSwitch/Connectors/ConnectorUtils.res`. - - Update functions with your connector: - ```reason - let connectorList : array<connectorName> = [Stripe, YourNewConnector] - - let getConnectorNameString = (connectorName: connectorName) => - switch connectorName { - | Stripe => "Stripe" - | YourNewConnector => "Your New Connector" - }; - - let getConnectorInfo = (connectorName: connectorName) => - switch connectorName { - | Stripe => "Stripe description." - | YourNewConnector => "Your New Connector description." - }; - ``` - - Save the file. - -### Add Connector Icon - -1. **Prepare the Icon**: - Name your connector icon in uppercase (e.g., `YOURCONNECTOR.SVG`). - -2. **Add the Icon**: - Navigate to `public/hyperswitch/Gateway` and copy your SVG icon file there. - -3. **Verify Structure**: - Ensure the file is correctly placed in `public/hyperswitch/Gateway`: - - ``` - public - └── hyperswitch - └── Gateway - └── YOURCONNECTOR.SVG - ``` - Save the changes made to the `Gateway` folder. - -### **Test the Connector** - -1. **Template Code** - - The template script generates a test file with 20 sanity tests. Implement these tests when adding a new connector. - - Example test: - ```rust - #[serial_test::serial] - #[actix_web::test] - async fn should_only_authorize_payment() { - let response = CONNECTOR - .authorize_payment(payment_method_details(), get_default_payment_info()) - .await - .expect("Authorize payment response"); - assert_eq!(response.status, enums::AttemptStatus::Authorized); - } - ``` - -2. **Utility Functions** - - Helper functions for tests are available in `tests/connector/utils`, making test writing easier. - -3. **Set API Keys** - - Before running tests, configure API keys in sample_auth.toml and set the environment variable: - - ```bash - export CONNECTOR_AUTH_FILE_PATH="/hyperswitch/crates/router/tests/connectors/sample_auth.toml" - cargo test --package router --test connectors -- checkout --test-threads=1 - ``` - -### **Build Payment Request and Response from JSON Schema** - -1. **Install OpenAPI Generator:** - ```bash - brew install openapi-generator - ``` - -2. **Generate Rust Code:** - ```bash - export CONNECTOR_NAME="<CONNECTOR-NAME>" - export SCHEMA_PATH="<PATH-TO-SCHEMA>" - openapi-generator generate -g rust -i ${SCHEMA_PATH} -o temp && cat temp/src/models/* > crates/router/src/connector/${CONNECTOR_NAME}/temp.rs && rm -rf temp && sed -i'' -r "s/^pub use.*//;s/^pub mod.*//;s/^\/.*//;s/^.\*.*//;s/crate::models:://g;" crates/router/src/connector/${CONNECTOR_NAME}/temp.rs && cargo +nightly fmt - ``` \ No newline at end of file +👉 [add_connector.md](./add_connector.md) \ No newline at end of file
2025-05-26T11:59:28Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Removed old add_connector.md file ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes this [issue](https://github.com/juspay/hyperswitch/issues/8142) ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
5642080025524ed2dee363984359aa9275036035
5642080025524ed2dee363984359aa9275036035
juspay/hyperswitch
juspay__hyperswitch-8140
Bug: Handle missing merchant_business_country by defaulting to US If the business profile does not have a country set, we cannot perform debit routing, because the merchant_business_country will be treated as the acquirer_country, which is used to determine whether a transaction is local or global in the open router. For now, since debit routing is only implemented for USD, we can safely assume the acquirer_country is US if not provided by the merchant.
diff --git a/crates/router/src/core/debit_routing.rs b/crates/router/src/core/debit_routing.rs index 5824946c3e7..adbd663c5c1 100644 --- a/crates/router/src/core/debit_routing.rs +++ b/crates/router/src/core/debit_routing.rs @@ -49,10 +49,17 @@ where let debit_routing_config = state.conf.debit_routing_config.clone(); let debit_routing_supported_connectors = debit_routing_config.supported_connectors.clone(); - if let Some((call_connector_type, acquirer_country)) = connector - .clone() - .zip(business_profile.merchant_business_country) - { + // If the business profile does not have a country set, we cannot perform debit routing, + // because the merchant_business_country will be treated as the acquirer_country, + // which is used to determine whether a transaction is local or global in the open router. + // For now, since debit routing is only implemented for USD, we can safely assume the + // acquirer_country is US if not provided by the merchant. + + let acquirer_country = business_profile + .merchant_business_country + .unwrap_or_default(); + + if let Some(call_connector_type) = connector.clone() { debit_routing_output = match call_connector_type { ConnectorCallType::PreDetermined(connector_data) => { logger::info!("Performing debit routing for PreDetermined connector"); @@ -115,10 +122,7 @@ where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { - if business_profile.is_debit_routing_enabled - && state.conf.open_router.enabled - && business_profile.merchant_business_country.is_some() - { + if business_profile.is_debit_routing_enabled && state.conf.open_router.enabled { logger::info!("Debit routing is enabled for the profile"); let debit_routing_config = &state.conf.debit_routing_config;
2025-05-26T11:30:40Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> If the business profile does not have a country set, we cannot perform debit routing, because the merchant_business_country will be treated as the acquirer_country, which is used to determine whether a transaction is local or global in the open router. For now, since debit routing is only implemented for USD, we can safely assume the acquirer_country is US if not provided by the merchant. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Update the business profile to set is_debit_routing_enabled to true whereas the merchant_business_country will still be null. ``` curl --location 'http://localhost:8080/account/merchant_1748264799/business_profile/pro_15JiSFiM9m6TM3yuxgMI' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: ' \ --data '{ "is_debit_routing_enabled": true }' ``` ``` { "merchant_id": "merchant_1748264799", "profile_id": "pro_15JiSFiM9m6TM3yuxgMI", "profile_name": "US_default", "return_url": "https://google.com/success", "enable_payment_response_hash": true, "payment_response_hash_key": "5l7IJEsRsndG8yfoTGMsbnnxXAfRwjIMYBo2wbA1MMcGekcbTNn9tH3KueaXAjQJ", "redirect_to_merchant_with_http_post": false, "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "webhook_url": null, "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "metadata": null, "routing_algorithm": null, "intent_fulfillment_time": 900, "frm_routing_algorithm": null, "payout_routing_algorithm": null, "applepay_verified_domains": null, "session_expiry": 900, "payment_link_config": null, "authentication_connector_details": null, "use_billing_as_payment_method_billing": true, "extended_card_info_config": null, "collect_shipping_details_from_wallet_connector": false, "collect_billing_details_from_wallet_connector": false, "always_collect_shipping_details_from_wallet_connector": false, "always_collect_billing_details_from_wallet_connector": false, "is_connector_agnostic_mit_enabled": false, "payout_link_config": null, "outgoing_webhook_custom_http_headers": null, "tax_connector_id": null, "is_tax_connector_enabled": false, "is_network_tokenization_enabled": false, "is_auto_retries_enabled": false, "max_auto_retries_enabled": null, "always_request_extended_authorization": null, "is_click_to_pay_enabled": false, "authentication_product_ids": null, "card_testing_guard_config": { "card_ip_blocking_status": "disabled", "card_ip_blocking_threshold": 3, "guest_user_card_blocking_status": "disabled", "guest_user_card_blocking_threshold": 10, "customer_id_blocking_status": "disabled", "customer_id_blocking_threshold": 5, "card_testing_guard_expiry": 3600 }, "is_clear_pan_retries_enabled": false, "force_3ds_challenge": false, "is_debit_routing_enabled": true, "merchant_business_country": null, "is_pre_network_tokenization_enabled": false } ``` -> Make a payment and it should go through debit routing flow ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-tenant-id: hyperswitch' \ --header 'api-key: ' \ --data-raw '{ "amount": 100, "amount_to_capture": 100, "currency": "USD", "confirm": true, "capture_method": "automatic", "setup_future_usage": "on_session", "capture_on": "2022-09-10T10:11:12Z", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "customer_id": "cu_1747729092", "return_url": "http://127.0.0.1:4040", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4400002000000004", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "737" } }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX", "last_name": "ss" }, "email": "[email protected]" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ``` { "payment_id": "pay_bUuuAvxcM8GZyiXUK01M", "merchant_id": "merchant_1748264799", "status": "succeeded", "amount": 100, "net_amount": 100, "shipping_cost": null, "amount_capturable": 0, "amount_received": 100, "connector": "adyen", "client_secret": "pay_bUuuAvxcM8GZyiXUK01M_secret_kpTGYz66ll5bYgWZdfzK", "created": "2025-05-26T13:09:15.219Z", "currency": "USD", "customer_id": "cu_1747729092", "customer": { "id": "cu_1747729092", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0004", "card_type": "DEBIT", "card_network": "Accel", "card_issuer": "Wells Fargo Bank", "card_issuing_country": "UNITEDSTATES", "card_isin": "440000", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": "ss" }, "phone": null, "email": "[email protected]" }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "http://127.0.0.1:4040/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1747729092", "created_at": 1748264955, "expires": 1748268555, "secret": "epk_4f3cb7ba24a7432e9524c958ba3e167c" }, "manual_retry_allowed": false, "connector_transaction_id": "K7ZPG2FFPZBK6R65", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_bUuuAvxcM8GZyiXUK01M_1", "payment_link": null, "profile_id": "pro_15JiSFiM9m6TM3yuxgMI", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_2VuIwuvgf5y58mK3873Q", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-05-26T13:24:15.219Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "125.0.0.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-05-26T13:09:16.661Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` -> decision engine logs showing `acquirer_country` being considered US by default <img width="1175" alt="image" src="https://github.com/user-attachments/assets/44e4174a-18d5-4c32-9230-67cc8319861f" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
5642080025524ed2dee363984359aa9275036035
5642080025524ed2dee363984359aa9275036035
juspay/hyperswitch
juspay__hyperswitch-8138
Bug: [REFACTOR] Payment Attempt as mandatory field in PaymentStatusData Payment Attempt as mandatory field in PaymentStatusData as the endpoint /payments/{payment_id} is called after confirmation.
diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index 047fe7fb2cf..42d1ef1a426 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -881,7 +881,7 @@ where { pub flow: PhantomData<F>, pub payment_intent: PaymentIntent, - pub payment_attempt: Option<PaymentAttempt>, + pub payment_attempt: PaymentAttempt, pub payment_address: payment_address::PaymentAddress, pub attempts: Option<Vec<PaymentAttempt>>, /// Should the payment status be synced with connector diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs index 793808b1342..955ddca3662 100644 --- a/crates/hyperswitch_domain_models/src/router_data.rs +++ b/crates/hyperswitch_domain_models/src/router_data.rs @@ -1129,11 +1129,7 @@ impl .get_captured_amount(payment_data) .unwrap_or(MinorUnit::zero()); - let total_amount = payment_data - .payment_attempt - .as_ref() - .map(|attempt| attempt.amount_details.get_net_amount()) - .unwrap_or(MinorUnit::zero()); + let total_amount = payment_data.payment_attempt.amount_details.get_net_amount(); if amount_captured == total_amount { common_enums::AttemptStatus::Charged @@ -1149,7 +1145,7 @@ impl &self, payment_data: &payments::PaymentStatusData<router_flow_types::PSync>, ) -> Option<MinorUnit> { - let payment_attempt = payment_data.payment_attempt.as_ref()?; + let payment_attempt = &payment_data.payment_attempt; // Based on the status of the response, we can determine the amount capturable let intent_status = common_enums::IntentStatus::from(self.status); @@ -1179,7 +1175,7 @@ impl &self, payment_data: &payments::PaymentStatusData<router_flow_types::PSync>, ) -> Option<MinorUnit> { - let payment_attempt = payment_data.payment_attempt.as_ref()?; + let payment_attempt = &payment_data.payment_attempt; // Based on the status of the response, we can determine the amount capturable let intent_status = common_enums::IntentStatus::from(self.status); diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index bfe7f7962d2..2cc738d263f 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -1808,7 +1808,7 @@ pub async fn record_attempt_core( let default_payment_status_data = PaymentStatusData { flow: PhantomData, payment_intent: payment_data.payment_intent.clone(), - payment_attempt: Some(payment_data.payment_attempt.clone()), + payment_attempt: payment_data.payment_attempt.clone(), attempts: None, should_sync_with_connector: false, payment_address: payment_data.payment_address.clone(), @@ -1839,7 +1839,7 @@ pub async fn record_attempt_core( payment_data: PaymentStatusData { flow: PhantomData, payment_intent: payment_data.payment_intent.clone(), - payment_attempt: Some(payment_data.payment_attempt.clone()), + payment_attempt: payment_data.payment_attempt.clone(), attempts: None, should_sync_with_connector: true, payment_address: payment_data.payment_address.clone(), @@ -1863,9 +1863,7 @@ pub async fn record_attempt_core( let record_payment_data = domain_payments::PaymentAttemptRecordData { flow: PhantomData, payment_intent: payment_status_data.payment_intent, - payment_attempt: payment_status_data - .payment_attempt - .unwrap_or(payment_data.payment_attempt.clone()), + payment_attempt: payment_status_data.payment_attempt, revenue_recovery_data: payment_data.revenue_recovery_data.clone(), payment_address: payment_data.payment_address.clone(), }; @@ -2730,11 +2728,7 @@ impl PaymentRedirectFlow for PaymentRedirectSync { let payment_data = &get_tracker_response.payment_data; self.validate_status_for_operation(payment_data.payment_intent.status)?; - let payment_attempt = payment_data - .payment_attempt - .as_ref() - .ok_or(errors::ApiErrorResponse::InternalServerError) - .attach_printable("payment_attempt not found in get_tracker_response")?; + let payment_attempt = payment_data.payment_attempt.clone(); let connector = payment_attempt .connector @@ -9112,7 +9106,7 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentConfirmData<F> { impl<F: Clone> OperationSessionGetters<F> for PaymentStatusData<F> { #[track_caller] fn get_payment_attempt(&self) -> &storage::PaymentAttempt { - todo!() + &self.payment_attempt } fn get_client_secret(&self) -> &Option<Secret<String>> { todo!() @@ -9241,7 +9235,7 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentStatusData<F> { } fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt> { - self.payment_attempt.as_ref() + Some(&self.payment_attempt) } fn get_all_keys_required(&self) -> Option<bool> { @@ -9262,7 +9256,7 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentStatusData<F> { todo!() } fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) { - self.payment_attempt = Some(payment_attempt); + self.payment_attempt = payment_attempt; } fn set_payment_method_data(&mut self, _payment_method_data: Option<domain::PaymentMethodData>) { diff --git a/crates/router/src/core/payments/operations/payment_get.rs b/crates/router/src/core/payments/operations/payment_get.rs index 05536c56296..ebf8205ea9b 100644 --- a/crates/router/src/core/payments/operations/payment_get.rs +++ b/crates/router/src/core/payments/operations/payment_get.rs @@ -30,9 +30,41 @@ impl ValidateStatusForOperation for PaymentGet { /// Validate if the current operation can be performed on the current status of the payment intent fn validate_status_for_operation( &self, - _intent_status: common_enums::IntentStatus, + intent_status: common_enums::IntentStatus, ) -> Result<(), errors::ApiErrorResponse> { - Ok(()) + match intent_status { + common_enums::IntentStatus::RequiresCapture + | common_enums::IntentStatus::RequiresCustomerAction + | common_enums::IntentStatus::RequiresMerchantAction + | common_enums::IntentStatus::Processing + | common_enums::IntentStatus::Succeeded + | common_enums::IntentStatus::Failed + | common_enums::IntentStatus::PartiallyCapturedAndCapturable + | common_enums::IntentStatus::PartiallyCaptured + | common_enums::IntentStatus::Cancelled => Ok(()), + // These statuses are not valid for this operation + common_enums::IntentStatus::RequiresConfirmation + | common_enums::IntentStatus::RequiresPaymentMethod => { + Err(errors::ApiErrorResponse::PaymentUnexpectedState { + current_flow: format!("{self:?}"), + field_name: "status".to_string(), + current_value: intent_status.to_string(), + states: [ + common_enums::IntentStatus::RequiresCapture, + common_enums::IntentStatus::RequiresCustomerAction, + common_enums::IntentStatus::RequiresMerchantAction, + common_enums::IntentStatus::Processing, + common_enums::IntentStatus::Succeeded, + common_enums::IntentStatus::Failed, + common_enums::IntentStatus::PartiallyCapturedAndCapturable, + common_enums::IntentStatus::PartiallyCaptured, + common_enums::IntentStatus::Cancelled, + ] + .map(|enum_value| enum_value.to_string()) + .join(", "), + }) + } + } } } @@ -137,22 +169,24 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentStatusData<F>, PaymentsRetriev .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - let payment_attempt = payment_intent - .active_attempt_id - .as_ref() - .async_map(|active_attempt| async { - db.find_payment_attempt_by_id( - key_manager_state, - merchant_context.get_merchant_key_store(), - active_attempt, - storage_scheme, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Could not find payment attempt given the attempt id") - }) + self.validate_status_for_operation(payment_intent.status)?; + + let active_attempt_id = payment_intent.active_attempt_id.as_ref().ok_or_else(|| { + errors::ApiErrorResponse::MissingRequiredField { + field_name: ("active_attempt_id"), + } + })?; + + let payment_attempt = db + .find_payment_attempt_by_id( + key_manager_state, + merchant_context.get_merchant_key_store(), + active_attempt_id, + storage_scheme, + ) .await - .transpose()?; + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Could not find payment attempt given the attempt id")?; let should_sync_with_connector = request.force_sync && payment_intent.status.should_force_sync_with_connector(); @@ -168,9 +202,8 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentStatusData<F>, PaymentsRetriev .clone() .map(|address| address.into_inner()), payment_attempt - .as_ref() - .and_then(|payment_attempt| payment_attempt.payment_method_billing_address.as_ref()) - .cloned() + .payment_method_billing_address + .clone() .map(|address| address.into_inner()), Some(true), ); @@ -268,34 +301,37 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsRetrieveRequest, PaymentStatusDat // TODO: do not take the whole payment data here payment_data: &mut PaymentStatusData<F>, ) -> CustomResult<ConnectorCallType, errors::ApiErrorResponse> { - match &payment_data.payment_attempt { - Some(payment_attempt) if payment_data.should_sync_with_connector => { - let connector = payment_attempt - .connector - .as_ref() - .get_required_value("connector") - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Connector is none when constructing response")?; + let payment_attempt = &payment_data.payment_attempt; - let merchant_connector_id = payment_attempt - .merchant_connector_id - .as_ref() - .get_required_value("merchant_connector_id") - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Merchant connector id is none when constructing response")?; + if payment_data.should_sync_with_connector { + let connector = payment_attempt + .connector + .as_ref() + .get_required_value("connector") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Connector is none when constructing response")?; - let connector_data = api::ConnectorData::get_connector_by_name( - &state.conf.connectors, - connector, - api::GetToken::Connector, - Some(merchant_connector_id.to_owned()), - ) + let merchant_connector_id = payment_attempt + .merchant_connector_id + .as_ref() + .get_required_value("merchant_connector_id") .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Invalid connector name received")?; + .attach_printable("Merchant connector id is none when constructing response")?; - Ok(ConnectorCallType::PreDetermined(connector_data.into())) - } - None | Some(_) => Ok(ConnectorCallType::Skip), + let connector_data = api::ConnectorData::get_connector_by_name( + &state.conf.connectors, + connector, + api::GetToken::Connector, + Some(merchant_connector_id.to_owned()), + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Invalid connector name received")?; + + Ok(ConnectorCallType::PreDetermined( + api::ConnectorRoutingData::from(connector_data), + )) + } else { + Ok(ConnectorCallType::Skip) } } } diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index da0c397fc9e..40285ee5ce4 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -2593,12 +2593,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentStatusData<F>, types::PaymentsSyncDat let payment_attempt_update = response_router_data.get_payment_attempt_update(&payment_data, storage_scheme); - let payment_attempt = payment_data - .payment_attempt - .ok_or(errors::ApiErrorResponse::InternalServerError) - .attach_printable( - "Payment attempt not found in payment data in post update trackers", - )?; + let payment_attempt = payment_data.payment_attempt; let updated_payment_intent = db .update_payment_intent( @@ -2625,7 +2620,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentStatusData<F>, types::PaymentsSyncDat .attach_printable("Unable to update payment attempt")?; payment_data.payment_intent = updated_payment_intent; - payment_data.payment_attempt = Some(updated_payment_attempt); + payment_data.payment_attempt = updated_payment_attempt; Ok(payment_data) } diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 91dc162b912..4dff52acb4c 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -587,11 +587,7 @@ pub async fn construct_router_data_for_psync<'a>( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while parsing value for ConnectorAuthType")?; - let attempt = &payment_data - .payment_attempt - .get_required_value("attempt") - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Payment Attempt is not available in payment data")?; + let attempt = &payment_data.payment_attempt; let connector_request_reference_id = payment_intent .merchant_reference_id @@ -1913,21 +1909,19 @@ where profile: &domain::Profile, ) -> RouterResponse<api_models::payments::PaymentsResponse> { let payment_intent = self.payment_intent; - let optional_payment_attempt = self.payment_attempt.as_ref(); + let payment_attempt = &self.payment_attempt; let amount = api_models::payments::PaymentAmountDetailsResponse::foreign_from(( &payment_intent.amount_details, - optional_payment_attempt.map(|payment_attempt| &payment_attempt.amount_details), + &payment_attempt.amount_details, )); - let connector = - optional_payment_attempt.and_then(|payment_attempt| payment_attempt.connector.clone()); + let connector = payment_attempt.connector.clone(); - let merchant_connector_id = optional_payment_attempt - .and_then(|payment_attempt| payment_attempt.merchant_connector_id.clone()); + let merchant_connector_id = payment_attempt.merchant_connector_id.clone(); - let error = optional_payment_attempt - .and_then(|payment_attempt| payment_attempt.error.clone()) + let error = payment_attempt + .error .as_ref() .map(api_models::payments::ErrorDetails::foreign_from); let attempts = self.attempts.as_ref().map(|attempts| { @@ -1949,8 +1943,8 @@ where let connector_token_details = self .payment_attempt - .as_ref() - .and_then(|attempt| attempt.connector_token_details.clone()) + .connector_token_details + .clone() .and_then(Option::<api_models::payments::ConnectorTokenDetails>::foreign_from); let return_url = payment_intent.return_url.or(profile.return_url.clone()); @@ -1969,31 +1963,16 @@ where shipping: self.payment_address.get_shipping().cloned().map(From::from), created: payment_intent.created_at, payment_method_data, - payment_method_type: self - .payment_attempt - .as_ref() - .map(|attempt| attempt.payment_method_type), - payment_method_subtype: self - .payment_attempt - .as_ref() - .map(|attempt| attempt.payment_method_subtype), - connector_transaction_id: self - .payment_attempt - .as_ref() - .and_then(|attempt| attempt.connector_payment_id.clone()), + payment_method_type: Some(payment_attempt.payment_method_type), + payment_method_subtype: Some(payment_attempt.payment_method_subtype), + connector_transaction_id: payment_attempt.connector_payment_id.clone(), connector_reference_id: None, merchant_connector_id, browser_info: None, connector_token_details, - payment_method_id: self - .payment_attempt - .as_ref() - .and_then(|attempt| attempt.payment_method_id.clone()), + payment_method_id: payment_attempt.payment_method_id.clone(), error, - authentication_type_applied: self - .payment_attempt - .as_ref() - .and_then(|attempt| attempt.authentication_applied), + authentication_type_applied: payment_attempt.authentication_applied, authentication_type: payment_intent.authentication_type, next_action: None, attempts, diff --git a/crates/router/src/core/revenue_recovery.rs b/crates/router/src/core/revenue_recovery.rs index d6091d8aa1a..590abcfce21 100644 --- a/crates/router/src/core/revenue_recovery.rs +++ b/crates/router/src/core/revenue_recovery.rs @@ -259,10 +259,8 @@ pub async fn perform_payments_sync( revenue_recovery_payment_data, ) .await?; - // If there is an active_attempt id then there will be a payment attempt - let payment_attempt = psync_data - .payment_attempt - .get_required_value("Payment Attempt")?; + + let payment_attempt = psync_data.payment_attempt; let mut revenue_recovery_metadata = payment_intent .feature_metadata .as_ref() diff --git a/crates/router/src/core/revenue_recovery/types.rs b/crates/router/src/core/revenue_recovery/types.rs index e8adf91e07c..6d66a8b500c 100644 --- a/crates/router/src/core/revenue_recovery/types.rs +++ b/crates/router/src/core/revenue_recovery/types.rs @@ -229,11 +229,7 @@ impl Decision { .await .change_context(errors::RecoveryError::PaymentCallFailed) .attach_printable("Error while executing the Psync call")?; - let payment_attempt = psync_data - .payment_attempt - .get_required_value("Payment Attempt") - .change_context(errors::RecoveryError::ValueNotFound) - .attach_printable("Error while executing the Psync call")?; + let payment_attempt = psync_data.payment_attempt; Self::Psync(payment_attempt.status, payment_attempt.get_id().clone()) } ( @@ -250,11 +246,7 @@ impl Decision { .change_context(errors::RecoveryError::PaymentCallFailed) .attach_printable("Error while executing the Psync call")?; - let payment_attempt = psync_data - .payment_attempt - .get_required_value("Payment Attempt") - .change_context(errors::RecoveryError::ValueNotFound) - .attach_printable("Error while executing the Psync call")?; + let payment_attempt = psync_data.payment_attempt; let attempt_triggered_by = payment_attempt .feature_metadata diff --git a/crates/router/src/core/webhooks/incoming_v2.rs b/crates/router/src/core/webhooks/incoming_v2.rs index b4ac1fbc805..d1207b7cb94 100644 --- a/crates/router/src/core/webhooks/incoming_v2.rs +++ b/crates/router/src/core/webhooks/incoming_v2.rs @@ -671,7 +671,7 @@ where payment_data: PaymentStatusData { flow: PhantomData, payment_intent, - payment_attempt: Some(payment_attempt), + payment_attempt, attempts: None, should_sync_with_connector: true, payment_address,
2025-05-23T13:44:25Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Currently, we have two endpoints for retrieving payment information in v2: - GET /payments/:id - GET /payments/:id:/get-intent The endpoint /payments/{payment_id} is called after confirmation, at which point a payment attempt always exists. Currently, payment_attempt in PaymentStatusData is stored as an optional field requiring implementation for get_payment_attempt(). This PR refactors the PaymentStatusData struct to make payment_attempt a required field ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Payments Create 2. Payments Confirm 3. Payments Retrieve ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_0196fd5c3d7a7502a39002fd8ce86a03?force_sync=true' \ --header 'x-profile-id: pro_zpak30UxH06EvzDWoXsW' \ --header 'Authorization: api-key=dev_Qi7ZsoVS4uccUf9Zy3pbS3eqvHjledzayfBn3i74bic6JHGMXNGpuY4wwN1xEMoQ' \ --data '' ``` Response ``` { "id": "12345_pay_0196fd5c3d7a7502a39002fd8ce86a03", "status": "succeeded", "amount": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 100, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": 100 }, "customer_id": null, "connector": "stripe", "created": "2025-05-23T13:36:42.987Z", "payment_method_data": { "billing": null }, "payment_method_type": "card", "payment_method_subtype": "credit", "connector_transaction_id": "pi_3RRvmED5R7gDAGff0qqjNSfu", "connector_reference_id": null, "merchant_connector_id": "mca_8S2I5IjIiW6MnlXUleeZ", "browser_info": null, "error": null, "shipping": { "address": { "city": "Karwar", "country": null, "line1": null, "line2": null, "line3": null, "zip": "581301", "state": "Karnataka", "first_name": "John", "last_name": "Dough" }, "phone": null, "email": "[email protected]" }, "billing": { "address": { "city": null, "country": null, "line1": null, "line2": null, "line3": null, "zip": null, "state": null, "first_name": "John", "last_name": "Dough" }, "phone": null, "email": "[email protected]" }, "attempts": null, "connector_token_details": { "token": "pm_1RRvmED5R7gDAGffXf71G5j2", "connector_token_request_reference_id": "waAfJPIqPwCZbPN4xC" }, "payment_method_id": null, "next_action": null, "return_url": "https://google.com/success", "authentication_type": "no_three_ds", "authentication_type_applied": null, "is_iframe_redirection_enabled": null } ``` 1. Payments Create 2. Payments Retrieve ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_01970c2d2a3c71e19ac6e9d20e9b5cb5?force_sync=true' \ --header 'x-profile-id: pro_3gDRiJh3bRKWv7ba0NYE' \ --header 'Authorization: api-key=dev_O5tsf4SGjEusjWDUE56oLxR8HIGNrQJoA4Rxp8LpNYFFNxoxo8j74KexSKWmeRbs' \ --data '' ``` Response ``` { "error": { "type": "invalid_request", "message": "This Payment could not be PaymentGet because it has a status of requires_payment_method. The expected state is requires_capture, requires_customer_action, requires_merchant_action, processing, succeeded, failed, partially_captured_and_capturable, partially_captured, cancelled", "code": "IR_14" } } ``` 3. Payments Retrieve (get-intent) ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_01970c2d2a3c71e19ac6e9d20e9b5cb5/get-intent' \ --header 'x-profile-id: pro_3gDRiJh3bRKWv7ba0NYE' \ --header 'Authorization: api-key=dev_O5tsf4SGjEusjWDUE56oLxR8HIGNrQJoA4Rxp8LpNYFFNxoxo8j74KexSKWmeRbs' \ --data '' ``` Response ``` { "id": "12345_pay_01970c2d2a3c71e19ac6e9d20e9b5cb5", "status": "requires_payment_method", "amount_details": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null }, "client_secret": null, "profile_id": "pro_3gDRiJh3bRKWv7ba0NYE", "merchant_reference_id": null, "routing_algorithm_id": null, "capture_method": "automatic", "authentication_type": "no_three_ds", "billing": { "address": { "city": null, "country": null, "line1": null, "line2": null, "line3": null, "zip": null, "state": null, "first_name": "John", "last_name": "Dough" }, "phone": null, "email": "[email protected]" }, "shipping": { "address": { "city": "Karwar", "country": null, "line1": null, "line2": null, "line3": null, "zip": "581301", "state": "Karnataka", "first_name": "John", "last_name": "Dough" }, "phone": null, "email": "[email protected]" }, "customer_id": null, "customer_present": "present", "description": null, "return_url": null, "setup_future_usage": "on_session", "apply_mit_exemption": "Skip", "statement_descriptor": null, "order_details": null, "allowed_payment_method_types": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "payment_link_enabled": "Skip", "payment_link_config": null, "request_incremental_authorization": "default", "expires_on": "2025-05-26T10:54:36.032Z", "frm_metadata": null, "request_external_three_ds_authentication": "Skip" } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
e272e7ab23845b664857ee729bb0eb7d05faac36
e272e7ab23845b664857ee729bb0eb7d05faac36
juspay/hyperswitch
juspay__hyperswitch-8134
Bug: [FEAT] [CONNECTOR: NORDEA] Implement SEPA Bank Debit ## Relevant Docs - [Access Authorization API](https://developer.nordeaopenbanking.com/documentation?api=Access%20Authorization%20API) (To get Access Token) - [Payments API SEPA Credit Transfer](https://developer.nordeaopenbanking.com/documentation?api=Payments%20API%20SEPA%20Credit%20Transfer) - [Payment Common API](https://developer.nordeaopenbanking.com/documentation?api=Payments%20Common%20API) (I assume this doc gets updated first often) - [Nordea developer FAQ](https://support.nordeaopenbanking.com/hc/en-us) ### Digest and Signature creation Docs - [Digest creation and calculation FAQ](https://support.nordeaopenbanking.com/hc/en-us/articles/7951756726044-Digest-creation-calculation-FAQ) - [eIDAS certificate](https://developer.nordeaopenbanking.com/documentation?api=Access%20Authorization%20API#authentication_with_eidas_certificate) - [Generation of Signature](https://developer.nordeaopenbanking.com/documentation?api=Access%20Authorization%20API#testing_eidas_signature) (postman JavaScript code) ## Testing - Nordea Playground (Try API Console): https://developer.nordeaopenbanking.com/console/ - [Personal API Postman collection v5](https://raw.githubusercontent.com/NordeaOB/swaggers/master/Nordea%20Open%20Banking%20v5%20Personal%20API.postman_collection.json) - [Personal API Postman collection v4](https://raw.githubusercontent.com/NordeaOB/swaggers/master/Nordea%20Open%20Banking%20v4%20Personal%20API%20Example%20FI%2CDK%2CNO%20and%20SE.postman_collection.json)
diff --git a/Cargo.lock b/Cargo.lock index c38b3966051..474d6d6f1d5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4048,6 +4048,7 @@ dependencies = [ "mime", "num-traits", "openssl", + "pem", "qrcode", "quick-xml", "rand 0.8.5", @@ -5692,9 +5693,9 @@ dependencies = [ [[package]] name = "pem" -version = "3.0.4" +version = "3.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e459365e590736a54c3fa561947c84837534b8e9af6fc5bf781307e82658fae" +checksum = "38af38e8470ac9dee3ce1bae1af9c1671fffc44ddfd8bd1d0a3445bf349a8ef3" dependencies = [ "base64 0.22.1", "serde", diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json index df042d2df8d..5a8e9b214ae 100644 --- a/api-reference/v1/openapi_spec_v1.json +++ b/api-reference/v1/openapi_spec_v1.json @@ -11868,6 +11868,7 @@ "nmi", "nomupay", "noon", + "nordea", "novalnet", "nuvei", "opennode", @@ -29799,6 +29800,7 @@ "nmi", "nomupay", "noon", + "nordea", "novalnet", "nuvei", "opennode", diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json index c1b43bb74b5..6b7fa4eae9f 100644 --- a/api-reference/v2/openapi_spec_v2.json +++ b/api-reference/v2/openapi_spec_v2.json @@ -8359,6 +8359,7 @@ "nmi", "nomupay", "noon", + "nordea", "novalnet", "nuvei", "opennode", @@ -23282,6 +23283,7 @@ "nmi", "nomupay", "noon", + "nordea", "novalnet", "nuvei", "opennode", diff --git a/config/config.example.toml b/config/config.example.toml index 3fdb96eb437..2685331d0b3 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -812,6 +812,9 @@ paypal = { country = "AD,AE,AL,AM,AR,AT,AU,AZ,BA,BB,BD,BE,BG,BH,BI,BM,BN,BO,BR,B [pm_filters.mifinity] mifinity = { country = "BR,CN,SG,MY,DE,CH,DK,GB,ES,AD,GI,FI,FR,GR,HR,IT,JP,MX,AR,CO,CL,PE,VE,UY,PY,BO,EC,GT,HN,SV,NI,CR,PA,DO,CU,PR,NL,NO,PL,PT,SE,RU,TR,TW,HK,MO,AX,AL,DZ,AS,AO,AI,AG,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BE,BZ,BJ,BM,BT,BQ,BA,BW,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CX,CC,KM,CG,CK,CI,CW,CY,CZ,DJ,DM,EG,GQ,ER,EE,ET,FK,FO,FJ,GF,PF,TF,GA,GM,GE,GH,GL,GD,GP,GU,GG,GN,GW,GY,HT,HM,VA,IS,IN,ID,IE,IM,IL,JE,JO,KZ,KE,KI,KW,KG,LA,LV,LB,LS,LI,LT,LU,MK,MG,MW,MV,ML,MT,MH,MQ,MR,MU,YT,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NC,NZ,NE,NG,NU,NF,MP,OM,PK,PW,PS,PG,PH,PN,QA,RE,RO,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SX,SK,SI,SB,SO,ZA,GS,KR,LK,SR,SJ,SZ,TH,TL,TG,TK,TO,TT,TN,TM,TC,TV,UG,UA,AE,UZ,VU,VN,VG,VI,WF,EH,ZM", currency = "AUD,CAD,CHF,CNY,CZK,DKK,EUR,GBP,INR,JPY,NOK,NZD,PLN,RUB,SEK,ZAR,USD,EGP,UYU,UZS" } +[pm_filters.nordea] +sepa = { country = "DK,FI,NO,SE", currency = "DKK,EUR,NOK,SEK" } + [pm_filters.fiuu] duit_now = { country = "MY", currency = "MYR" } @@ -1188,4 +1191,4 @@ hyperswitch_ai_host = "http://0.0.0.0:8000" # Hyperswitch ai workflow host [proxy_status_mapping] proxy_connector_http_status_code = false # If enabled, the http status code of the connector will be proxied in the response [list_dispute_supported_connectors] -connector_list = "worldpayvantiv" \ No newline at end of file +connector_list = "worldpayvantiv" diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 4607d92000a..1ae71b20ddf 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -637,6 +637,9 @@ red_pagos = { country = "UY", currency = "UYU" } [pm_filters.zsl] local_bank_transfer = { country = "CN", currency = "CNY" } +[pm_filters.nordea] +sepa = { country = "DK,FI,NO,SE", currency = "DKK,EUR,NOK,SEK" } + [pm_filters.fiuu] duit_now = { country = "MY", currency = "MYR" } apple_pay = { country = "MY", currency = "MYR" } @@ -832,4 +835,4 @@ retry_algorithm_type = "cascading" click_to_pay = {connector_list = "adyen, cybersource, trustpay"} [list_dispute_supported_connectors] -connector_list = "worldpayvantiv" \ No newline at end of file +connector_list = "worldpayvantiv" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 7a1521001c0..e6d29112a0e 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -103,7 +103,7 @@ nexixpay.base_url = "https://xpay.nexigroup.com/api/phoenix-0.0/psp/api/v1" nmi.base_url = "https://secure.nmi.com/" nomupay.base_url = "https://payout-api.nomupay.com" noon.base_url = "https://api.noonpayments.com/" -nordea.base_url = "https://openapi.portal.nordea.com" +nordea.base_url = "https://open.nordeaopenbanking.com" noon.key_mode = "Live" novalnet.base_url = "https://payport.novalnet.de/v2" nuvei.base_url = "https://secure.safecharge.com/" @@ -654,6 +654,8 @@ red_pagos = { country = "UY", currency = "UYU" } [pm_filters.zsl] local_bank_transfer = { country = "CN", currency = "CNY" } +[pm_filters.nordea] +sepa = { country = "DK,FI,NO,SE", currency = "DKK,EUR,NOK,SEK" } [pm_filters.fiuu] duit_now = { country = "MY", currency = "MYR" } @@ -843,4 +845,4 @@ click_to_pay = {connector_list = "adyen, cybersource, trustpay"} [revenue_recovery] monitoring_threshold_in_seconds = 60 -retry_algorithm_type = "cascading" \ No newline at end of file +retry_algorithm_type = "cascading" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 88e7d4115e6..ccd5e003695 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -661,6 +661,9 @@ red_pagos = { country = "UY", currency = "UYU" } [pm_filters.zsl] local_bank_transfer = { country = "CN", currency = "CNY" } +[pm_filters.nordea] +sepa = { country = "DK,FI,NO,SE", currency = "DKK,EUR,NOK,SEK" } + [pm_filters.fiuu] duit_now = { country = "MY", currency = "MYR" } apple_pay = { country = "MY", currency = "MYR" } @@ -812,7 +815,7 @@ globalpay = { long_lived_token = false, payment_method = "card", flow = "mandate outgoing_enabled = true redis_lock_expiry_seconds = 180 -[l2_l3_data_config] +[l2_l3_data_config] enabled = "true" [webhook_source_verification_call] @@ -851,4 +854,4 @@ monitoring_threshold_in_seconds = 60 retry_algorithm_type = "cascading" [list_dispute_supported_connectors] -connector_list = "worldpayvantiv" \ No newline at end of file +connector_list = "worldpayvantiv" diff --git a/config/development.toml b/config/development.toml index 9020c89ef86..76031da5951 100644 --- a/config/development.toml +++ b/config/development.toml @@ -844,6 +844,9 @@ region = "" credit = { country = "US, CA", currency = "CAD,USD"} debit = { country = "US, CA", currency = "CAD,USD"} +[pm_filters.nordea] +sepa = { country = "DK,FI,NO,SE", currency = "DKK,EUR,NOK,SEK" } + [pm_filters.fiuu] duit_now = { country = "MY", currency = "MYR" } apple_pay = { country = "MY", currency = "MYR" } @@ -1258,7 +1261,7 @@ dynamic_routing_enabled = false static_routing_enabled = false url = "http://localhost:8080" -[l2_l3_data_config] +[l2_l3_data_config] enabled = "true" [grpc_client.unified_connector_service] @@ -1293,4 +1296,4 @@ hyperswitch_ai_host = "http://0.0.0.0:8000" [proxy_status_mapping] proxy_connector_http_status_code = false # If enabled, the http status code of the connector will be proxied in the response [list_dispute_supported_connectors] -connector_list = "worldpayvantiv" \ No newline at end of file +connector_list = "worldpayvantiv" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index c518574435b..d06eb47d03f 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -770,6 +770,9 @@ credit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,K debit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" } credit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" } +[pm_filters.nordea] +sepa = { country = "DK,FI,NO,SE", currency = "DKK,EUR,NOK,SEK" } + [pm_filters.fiuu] duit_now = { country = "MY", currency = "MYR" } apple_pay = { country = "MY", currency = "MYR" } @@ -1172,4 +1175,4 @@ version = "HOSTNAME" # value of HOSTNAME from deployment which tells its [proxy_status_mapping] proxy_connector_http_status_code = false # If enabled, the http status code of the connector will be proxied in the response [list_dispute_supported_connectors] -connector_list = "worldpayvantiv" \ No newline at end of file +connector_list = "worldpayvantiv" diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 50ba4dce612..3bdc756dc89 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -1210,7 +1210,9 @@ pub enum ConnectorAuthType { auth_key_map: HashMap<common_enums::Currency, pii::SecretSerdeValue>, }, CertificateAuth { + // certificate should be base64 encoded certificate: Secret<String>, + // private_key should be base64 encoded private_key: Secret<String>, }, #[default] diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index 37d9ee4b318..9e00ff366a6 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -119,7 +119,7 @@ pub enum RoutableConnectors { Nmi, Nomupay, Noon, - // Nordea, + Nordea, Novalnet, Nuvei, // Opayo, added as template code for future usage @@ -292,7 +292,7 @@ pub enum Connector { Nmi, Nomupay, Noon, - // Nordea, + Nordea, Novalnet, Nuvei, // Opayo, added as template code for future usage @@ -385,6 +385,7 @@ impl Connector { | (Self::Globalpay, _) | (Self::Jpmorgan, _) | (Self::Moneris, _) + | (Self::Nordea, _) | (Self::Paypal, _) | (Self::Payu, _) | ( @@ -478,7 +479,7 @@ impl Connector { | Self::Nexinets | Self::Nexixpay | Self::Nomupay - // | Self::Nordea + | Self::Nordea | Self::Novalnet | Self::Nuvei | Self::Opennode @@ -649,7 +650,7 @@ impl From<RoutableConnectors> for Connector { RoutableConnectors::Nmi => Self::Nmi, RoutableConnectors::Nomupay => Self::Nomupay, RoutableConnectors::Noon => Self::Noon, - // RoutableConnectors::Nordea => Self::Nordea, + RoutableConnectors::Nordea => Self::Nordea, RoutableConnectors::Novalnet => Self::Novalnet, RoutableConnectors::Nuvei => Self::Nuvei, RoutableConnectors::Opennode => Self::Opennode, @@ -779,7 +780,7 @@ impl TryFrom<Connector> for RoutableConnectors { Connector::Nmi => Ok(Self::Nmi), Connector::Nomupay => Ok(Self::Nomupay), Connector::Noon => Ok(Self::Noon), - // Connector::Nordea => Ok(Self::Nordea), + Connector::Nordea => Ok(Self::Nordea), Connector::Novalnet => Ok(Self::Novalnet), Connector::Nuvei => Ok(Self::Nuvei), Connector::Opennode => Ok(Self::Opennode), diff --git a/crates/common_utils/src/lib.rs b/crates/common_utils/src/lib.rs index 3f491d3e9a6..d6a9475b179 100644 --- a/crates/common_utils/src/lib.rs +++ b/crates/common_utils/src/lib.rs @@ -110,6 +110,17 @@ pub mod date_time { now().assume_utc().format(&Iso8601::<ISO_CONFIG>) } + /// Return the current date and time in UTC formatted as "ddd, DD MMM YYYY HH:mm:ss GMT". + pub fn now_rfc7231_http_date() -> Result<String, time::error::Format> { + let now_utc = OffsetDateTime::now_utc(); + // Desired format: ddd, DD MMM YYYY HH:mm:ss GMT + // Example: Fri, 23 May 2025 06:19:35 GMT + let format = time::macros::format_description!( + "[weekday repr:short], [day padding:zero] [month repr:short] [year repr:full] [hour padding:zero repr:24]:[minute padding:zero]:[second padding:zero] GMT" + ); + now_utc.format(&format) + } + impl From<DateFormat> for &[BorrowedFormatItem<'_>] { fn from(format: DateFormat) -> Self { match format { diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index 7289e6d4a98..9a5c7edb2ca 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -460,6 +460,7 @@ impl ConnectorConfig { Connector::Nexixpay => Ok(connector_data.nexixpay), Connector::Prophetpay => Ok(connector_data.prophetpay), Connector::Nmi => Ok(connector_data.nmi), + Connector::Nordea => Ok(connector_data.nordea), Connector::Nomupay => Err("Use get_payout_connector_config".to_string()), Connector::Novalnet => Ok(connector_data.novalnet), Connector::Noon => Ok(connector_data.noon), diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 5f38b42d4a1..4646e73f71c 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -6355,7 +6355,31 @@ placeholder = "Enter Acquirer Merchant ID" required = false type = "Text" - +[nordea] +[[nordea.bank_debit]] + payment_method_type = "sepa" +[nordea.connector_auth.SignatureKey] + api_key="Client Secret" + key1="Client ID" + api_secret="eIDAS Private Key" +[nordea.metadata.creditor_account_type] + name="creditor_account_type" + label="Creditor Account Type" + placeholder="Enter Beneficiary Account Type e.g. IBAN" + required=true + type="Text" +[nordea.metadata.creditor_account_value] + name="creditor_account_value" + label="Creditor Account Type" + placeholder="Enter Beneficiary Account Number" + required=true + type="Text" +[nordea.metadata.creditor_beneficiary_name] + name="creditor_beneficiary_name" + label="Creditor Account Beneficiary Name" + placeholder="Enter Beneficiary Name" + required=true + type="Text" [worldpayxml] [[worldpayxml.credit]] diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 4bb725ed128..6bb5497957a 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -4923,6 +4923,33 @@ placeholder = "Enter Acquirer Merchant ID" required = false type = "Text" +[nordea] +[[nordea.bank_debit]] + payment_method_type = "sepa" +[nordea.connector_auth.SignatureKey] + api_key="Client Secret" + key1="Client ID" + api_secret="eIDAS Private Key" +[nordea.metadata.creditor_account_type] + name="creditor_account_type" + label="Creditor Account Type" + placeholder="Enter Beneficiary Account Type e.g. IBAN" + required=true + type="Text" +[nordea.metadata.creditor_account_value] + name="creditor_account_value" + label="Creditor Account Type" + placeholder="Enter Beneficiary Account Number" + required=true + type="Text" +[nordea.metadata.creditor_beneficiary_name] + name="creditor_beneficiary_name" + label="Creditor Account Beneficiary Name" + placeholder="Enter Beneficiary Name" + required=true + type="Text" + + [worldpayxml] [[worldpayxml.credit]] payment_method_type = "Mastercard" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 3b17bfca44e..37b63f84066 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -6335,6 +6335,32 @@ placeholder = "Enter Acquirer Merchant ID" required = false type = "Text" +[nordea] +[[nordea.bank_debit]] + payment_method_type = "sepa" +[nordea.connector_auth.SignatureKey] + api_key="Client Secret" + key1="Client ID" + api_secret="eIDAS Private Key" +[nordea.metadata.creditor_account_type] + name="creditor_account_type" + label="Creditor Account Type" + placeholder="Enter Beneficiary Account Type e.g. IBAN" + required=true + type="Text" +[nordea.metadata.creditor_account_value] + name="creditor_account_value" + label="Creditor Account Type" + placeholder="Enter Beneficiary Account Number" + required=true + type="Text" +[nordea.metadata.creditor_beneficiary_name] + name="creditor_beneficiary_name" + label="Creditor Account Beneficiary Name" + placeholder="Enter Beneficiary Name" + required=true + type="Text" + [worldpayxml] [[worldpayxml.credit]] diff --git a/crates/hyperswitch_connectors/Cargo.toml b/crates/hyperswitch_connectors/Cargo.toml index 63e98299c39..d06d6f299d6 100644 --- a/crates/hyperswitch_connectors/Cargo.toml +++ b/crates/hyperswitch_connectors/Cargo.toml @@ -37,6 +37,7 @@ lazy_static = "1.5.0" mime = "0.3.17" num-traits = "0.2.19" openssl = {version = "0.10.70"} +pem = "3.0.5" qrcode = "0.14.1" quick-xml = { version = "0.31.0", features = ["serialize"] } rand = "0.8.5" diff --git a/crates/hyperswitch_connectors/src/connectors/nordea.rs b/crates/hyperswitch_connectors/src/connectors/nordea.rs index 9230d856f8d..fb0d9e0f625 100644 --- a/crates/hyperswitch_connectors/src/connectors/nordea.rs +++ b/crates/hyperswitch_connectors/src/connectors/nordea.rs @@ -1,28 +1,39 @@ +mod requests; +mod responses; pub mod transformers; +use base64::Engine; +use common_enums::enums; use common_utils::{ + consts, date_time, errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, - types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}, + types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ - router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, + router_data::{AccessToken, AccessTokenAuthenticationResponse, ErrorResponse, RouterData}, router_flow_types::{ access_token_auth::AccessTokenAuth, payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, refunds::{Execute, RSync}, + AccessTokenAuthentication, PreProcessing, }, router_request_types::{ - AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, - PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, + AccessTokenAuthenticationRequestData, AccessTokenRequestData, + PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, + PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, + }, types::{ - PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, - RefundSyncRouterData, RefundsRouterData, + AccessTokenAuthenticationRouterData, PaymentsAuthorizeRouterData, + PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefreshTokenRouterData, + RefundsRouterData, }, }; use hyperswitch_interfaces::{ @@ -31,31 +42,204 @@ use hyperswitch_interfaces::{ ConnectorValidation, }, configs::Connectors, + consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}, errors, events::connector_api_logs::ConnectorEvent, - types::{self, Response}, + types::{self, AuthenticationTokenType, RefreshTokenType, Response}, webhooks, }; -use masking::{ExposeInterface, Mask}; -use transformers as nordea; +use lazy_static::lazy_static; +use masking::{ExposeInterface, Mask, PeekInterface, Secret}; +use ring::{ + digest, + signature::{RsaKeyPair, RSA_PKCS1_SHA256}, +}; +use transformers::{get_error_data, NordeaAuthType}; +use url::Url; -use crate::{constants::headers, types::ResponseRouterData, utils}; +use crate::{ + connectors::nordea::{ + requests::{ + NordeaOAuthExchangeRequest, NordeaOAuthRequest, NordeaPaymentsConfirmRequest, + NordeaPaymentsRequest, NordeaRouterData, + }, + responses::{ + NordeaOAuthExchangeResponse, NordeaPaymentsConfirmResponse, + NordeaPaymentsInitiateResponse, + }, + }, + constants::headers, + types::ResponseRouterData, + utils::{self, RouterData as OtherRouterData}, +}; #[derive(Clone)] pub struct Nordea { - amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), + amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), +} + +struct SignatureParams<'a> { + content_type: &'a str, + host: &'a str, + path: &'a str, + payload_digest: Option<&'a str>, + date: &'a str, + http_method: Method, } impl Nordea { pub fn new() -> &'static Self { &Self { - amount_converter: &StringMinorUnitForConnector, + amount_converter: &StringMajorUnitForConnector, } } + + pub fn generate_digest(&self, payload: &[u8]) -> String { + let payload_digest = digest::digest(&digest::SHA256, payload); + format!("sha-256={}", consts::BASE64_ENGINE.encode(payload_digest)) + } + + pub fn generate_digest_from_request(&self, payload: &RequestContent) -> String { + let payload_bytes = match payload { + RequestContent::RawBytes(bytes) => bytes.clone(), + _ => payload.get_inner_value().expose().as_bytes().to_vec(), + }; + + self.generate_digest(&payload_bytes) + } + + fn format_private_key( + &self, + private_key_str: &str, + ) -> CustomResult<String, errors::ConnectorError> { + let key = private_key_str.to_string(); + + // Check if it already has PEM headers + let pem_data = + if key.contains("BEGIN") && key.contains("END") && key.contains("PRIVATE KEY") { + key + } else { + // Remove whitespace and format with 64-char lines + let cleaned_key = key + .chars() + .filter(|c| !c.is_whitespace()) + .collect::<String>(); + + let formatted_key = cleaned_key + .chars() + .collect::<Vec<char>>() + .chunks(64) + .map(|chunk| chunk.iter().collect::<String>()) + .collect::<Vec<String>>() + .join("\n"); + + format!( + "-----BEGIN RSA PRIVATE KEY-----\n{formatted_key}\n-----END RSA PRIVATE KEY-----", + ) + }; + + Ok(pem_data) + } + + // For non-production environments, signature generation can be skipped and instead `SKIP_SIGNATURE_VALIDATION_FOR_SANDBOX` can be passed. + fn generate_signature( + &self, + auth: &NordeaAuthType, + signature_params: SignatureParams<'_>, + ) -> CustomResult<String, errors::ConnectorError> { + const REQUEST_WITHOUT_CONTENT_HEADERS: &str = + "(request-target) x-nordea-originating-host x-nordea-originating-date"; + const REQUEST_WITH_CONTENT_HEADERS: &str = "(request-target) x-nordea-originating-host x-nordea-originating-date content-type digest"; + + let method_string = signature_params.http_method.to_string().to_lowercase(); + let mut normalized_string = format!( + "(request-target): {} {}\nx-nordea-originating-host: {}\nx-nordea-originating-date: {}", + method_string, signature_params.path, signature_params.host, signature_params.date + ); + + let headers = if matches!( + signature_params.http_method, + Method::Post | Method::Put | Method::Patch + ) { + let digest = signature_params.payload_digest.unwrap_or(""); + normalized_string.push_str(&format!( + "\ncontent-type: {}\ndigest: {}", + signature_params.content_type, digest + )); + REQUEST_WITH_CONTENT_HEADERS + } else { + REQUEST_WITHOUT_CONTENT_HEADERS + }; + + let signature_base64 = { + let private_key_pem = + self.format_private_key(&auth.eidas_private_key.clone().expose())?; + + let private_key_der = pem::parse(&private_key_pem).change_context( + errors::ConnectorError::InvalidConnectorConfig { + config: "eIDAS Private Key", + }, + )?; + let private_key_der_contents = private_key_der.contents(); + let key_pair = RsaKeyPair::from_der(private_key_der_contents).change_context( + errors::ConnectorError::InvalidConnectorConfig { + config: "eIDAS Private Key", + }, + )?; + + let mut signature = vec![0u8; key_pair.public().modulus_len()]; + key_pair + .sign( + &RSA_PKCS1_SHA256, + &ring::rand::SystemRandom::new(), + normalized_string.as_bytes(), + &mut signature, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + consts::BASE64_ENGINE.encode(signature) + }; + + Ok(format!( + r#"keyId="{}",algorithm="rsa-sha256",headers="{}",signature="{}""#, + auth.client_id.peek(), + headers, + signature_base64 + )) + } + + // This helper function correctly serializes a struct into the required + // non-percent-encoded form URL string. + fn get_form_urlencoded_payload<T: serde::Serialize>( + &self, + form_data: &T, + ) -> Result<Vec<u8>, error_stack::Report<errors::ConnectorError>> { + let json_value = serde_json::to_value(form_data) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + let btree_map: std::collections::BTreeMap<String, serde_json::Value> = + serde_json::from_value(json_value) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + Ok(btree_map + .iter() + .map(|(k, v)| { + // Remove quotes from string values for proper form encoding + let value = match v { + serde_json::Value::String(s) => s.clone(), + _ => v.to_string(), + }; + format!("{k}={value}") + }) + .collect::<Vec<_>>() + .join("&") + .into_bytes()) + } } impl api::Payment for Nordea {} impl api::PaymentSession for Nordea {} +impl api::ConnectorAuthenticationToken for Nordea {} impl api::ConnectorAccessToken for Nordea {} impl api::MandateSetup for Nordea {} impl api::PaymentAuthorize for Nordea {} @@ -66,13 +250,15 @@ impl api::Refund for Nordea {} impl api::RefundExecute for Nordea {} impl api::RefundSync for Nordea {} impl api::PaymentToken for Nordea {} +impl api::PaymentsPreProcessing for Nordea {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Nordea { - // Not Implemented (R) } +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Nordea {} + impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Nordea where Self: ConnectorIntegration<Flow, Request, Response>, @@ -80,15 +266,105 @@ where fn build_headers( &self, req: &RouterData<Flow, Request, Response>, - _connectors: &Connectors, + connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { - let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - self.get_content_type().to_string().into(), - )]; - let mut api_key = self.get_auth_header(&req.connector_auth_type)?; - header.append(&mut api_key); - Ok(header) + let access_token = req + .access_token + .clone() + .ok_or(errors::ConnectorError::FailedToObtainAuthType)?; + let auth = NordeaAuthType::try_from(&req.connector_auth_type)?; + let content_type = self.get_content_type().to_string(); + let http_method = self.get_http_method(); + + // Extract host from base URL + let nordea_host = Url::parse(self.base_url(connectors)) + .change_context(errors::ConnectorError::RequestEncodingFailed)? + .host_str() + .ok_or(errors::ConnectorError::RequestEncodingFailed)? + .to_string(); + + let nordea_origin_date = date_time::now_rfc7231_http_date() + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + let full_url = self.get_url(req, connectors)?; + let url_parsed = + Url::parse(&full_url).change_context(errors::ConnectorError::RequestEncodingFailed)?; + let path = url_parsed.path(); + let path_with_query = if let Some(query) = url_parsed.query() { + format!("{path}?{query}") + } else { + path.to_string() + }; + + let mut required_headers = vec![ + ( + headers::CONTENT_TYPE.to_string(), + content_type.clone().into(), + ), + ( + headers::AUTHORIZATION.to_string(), + format!("Bearer {}", access_token.token.peek()).into_masked(), + ), + ( + "X-IBM-Client-ID".to_string(), + auth.client_id.clone().expose().into_masked(), + ), + ( + "X-IBM-Client-Secret".to_string(), + auth.client_secret.clone().expose().into_masked(), + ), + ( + "X-Nordea-Originating-Date".to_string(), + nordea_origin_date.clone().into_masked(), + ), + ( + "X-Nordea-Originating-Host".to_string(), + nordea_host.clone().into_masked(), + ), + ]; + + if matches!(http_method, Method::Post | Method::Put | Method::Patch) { + let nordea_request = self.get_request_body(req, connectors)?; + + let sha256_digest = self.generate_digest_from_request(&nordea_request); + + // Add Digest header + required_headers.push(( + "Digest".to_string(), + sha256_digest.to_string().into_masked(), + )); + + let signature = self.generate_signature( + &auth, + SignatureParams { + content_type: &content_type, + host: &nordea_host, + path, + payload_digest: Some(&sha256_digest), + date: &nordea_origin_date, + http_method, + }, + )?; + + required_headers.push(("Signature".to_string(), signature.into_masked())); + } else { + // Generate signature without digest for GET requests + let signature = self.generate_signature( + &auth, + SignatureParams { + content_type: &content_type, + host: &nordea_host, + path: &path_with_query, + payload_digest: None, + date: &nordea_origin_date, + http_method, + }, + )?; + + required_headers.push(("Signature".to_string(), signature.into_masked())); + } + + Ok(required_headers) } } @@ -109,24 +385,12 @@ impl ConnectorCommon for Nordea { connectors.nordea.base_url.as_ref() } - fn get_auth_header( - &self, - auth_type: &ConnectorAuthType, - ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { - let auth = nordea::NordeaAuthType::try_from(auth_type) - .change_context(errors::ConnectorError::FailedToObtainAuthType)?; - Ok(vec![( - headers::AUTHORIZATION.to_string(), - auth.api_key.expose().into_masked(), - )]) - } - fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - let response: nordea::NordeaErrorResponse = res + let response: responses::NordeaErrorResponse = res .response .parse_struct("NordeaErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; @@ -136,9 +400,14 @@ impl ConnectorCommon for Nordea { Ok(ErrorResponse { status_code: res.status_code, - code: response.code, - message: response.message, - reason: response.reason, + code: get_error_data(response.error.as_ref()) + .and_then(|failure| failure.code.clone()) + .unwrap_or(NO_ERROR_CODE.to_string()), + message: get_error_data(response.error.as_ref()) + .and_then(|failure| failure.description.clone()) + .unwrap_or(NO_ERROR_MESSAGE.to_string()), + reason: get_error_data(response.error.as_ref()) + .and_then(|failure| failure.failure_type.clone()), attempt_status: None, connector_transaction_id: None, network_decline_code: None, @@ -148,94 +417,167 @@ impl ConnectorCommon for Nordea { } } -impl ConnectorValidation for Nordea { - //TODO: implement functions when support enabled -} +impl ConnectorValidation for Nordea {} -impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Nordea { - //TODO: implement sessions flow -} - -impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Nordea {} - -impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Nordea {} - -impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Nordea { - fn get_headers( +impl + ConnectorIntegration< + AccessTokenAuthentication, + AccessTokenAuthenticationRequestData, + AccessTokenAuthenticationResponse, + > for Nordea +{ + fn get_url( &self, - req: &PaymentsAuthorizeRouterData, + _req: &AccessTokenAuthenticationRouterData, connectors: &Connectors, - ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, connectors) + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}/personal/v5/authorize", + self.base_url(connectors) + )) } fn get_content_type(&self) -> &'static str { - self.common_get_content_type() - } - - fn get_url( - &self, - _req: &PaymentsAuthorizeRouterData, - _connectors: &Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + "application/json" } fn get_request_body( &self, - req: &PaymentsAuthorizeRouterData, + req: &AccessTokenAuthenticationRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let amount = utils::convert_amount( - self.amount_converter, - req.request.minor_amount, - req.request.currency, - )?; - - let connector_router_data = nordea::NordeaRouterData::from((amount, req)); - let connector_req = nordea::NordeaPaymentsRequest::try_from(&connector_router_data)?; + let connector_req = NordeaOAuthRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, - req: &PaymentsAuthorizeRouterData, + req: &AccessTokenAuthenticationRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { - Ok(Some( + let auth = NordeaAuthType::try_from(&req.connector_auth_type)?; + let content_type = self.common_get_content_type().to_string(); + let http_method = Method::Post; + + // Extract host from base URL + let nordea_host = Url::parse(self.base_url(connectors)) + .change_context(errors::ConnectorError::RequestEncodingFailed)? + .host_str() + .ok_or(errors::ConnectorError::RequestEncodingFailed)? + .to_string(); + + let nordea_origin_date = date_time::now_rfc7231_http_date() + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + let full_url = self.get_url(req, connectors)?; + let url_parsed = + Url::parse(&full_url).change_context(errors::ConnectorError::RequestEncodingFailed)?; + let path = url_parsed.path(); + + let request_body = self.get_request_body(req, connectors)?; + + let mut required_headers = vec![ + ( + headers::CONTENT_TYPE.to_string(), + content_type.clone().into(), + ), + ( + "X-IBM-Client-ID".to_string(), + auth.client_id.clone().expose().into_masked(), + ), + ( + "X-IBM-Client-Secret".to_string(), + auth.client_secret.clone().expose().into_masked(), + ), + ( + "X-Nordea-Originating-Date".to_string(), + nordea_origin_date.clone().into_masked(), + ), + ( + "X-Nordea-Originating-Host".to_string(), + nordea_host.clone().into_masked(), + ), + ]; + + let sha256_digest = self.generate_digest_from_request(&request_body); + + // Add Digest header + required_headers.push(( + "Digest".to_string(), + sha256_digest.to_string().into_masked(), + )); + + let signature = self.generate_signature( + &auth, + SignatureParams { + content_type: &content_type, + host: &nordea_host, + path, + payload_digest: Some(&sha256_digest), + date: &nordea_origin_date, + http_method, + }, + )?; + + required_headers.push(("Signature".to_string(), signature.into_masked())); + + let request = Some( RequestBuilder::new() - .method(Method::Post) - .url(&types::PaymentsAuthorizeType::get_url( - self, req, connectors, - )?) + .method(http_method) .attach_default_headers() - .headers(types::PaymentsAuthorizeType::get_headers( - self, req, connectors, - )?) - .set_body(types::PaymentsAuthorizeType::get_request_body( - self, req, connectors, - )?) + .headers(required_headers) + .url(&AuthenticationTokenType::get_url(self, req, connectors)?) + .set_body(request_body) .build(), - )) + ); + Ok(request) } fn handle_response( &self, - data: &PaymentsAuthorizeRouterData, - event_builder: Option<&mut ConnectorEvent>, + data: &AccessTokenAuthenticationRouterData, + _event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { - let response: nordea::NordeaPaymentsResponse = res - .response - .parse_struct("Nordea PaymentsAuthorizeResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - RouterData::try_from(ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) + ) -> CustomResult<AccessTokenAuthenticationRouterData, errors::ConnectorError> { + // Handle 302 redirect response + if res.status_code == 302 { + // Extract Location header + let headers = + res.headers + .as_ref() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "headers", + })?; + let location_header = headers + .get("Location") + .map(|value| value.to_str()) + .and_then(|location_value| location_value.ok()) + .ok_or(errors::ConnectorError::ParsingFailed)?; + + // Parse auth code from query params + let url = Url::parse(location_header) + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + let code = url + .query_pairs() + .find(|(key, _)| key == "code") + .map(|(_, value)| value.to_string()) + .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "code" })?; + + // Return auth code as "token" with short expiry + Ok(RouterData { + response: Ok(AccessTokenAuthenticationResponse { + code: Secret::new(code), + expires: 60, // 60 seconds - auth code validity + }), + ..data.clone() + }) + } else { + Err( + errors::ConnectorError::UnexpectedResponseError("Expected 302 redirect".into()) + .into(), + ) + } } fn get_error_response( @@ -247,54 +589,127 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData } } -impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Nordea { - fn get_headers( +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Nordea { + fn get_url( &self, - req: &PaymentsSyncRouterData, + _req: &RefreshTokenRouterData, connectors: &Connectors, - ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, connectors) - } - - fn get_content_type(&self) -> &'static str { - self.common_get_content_type() + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}/personal/v5/authorize/token", + self.base_url(connectors) + )) } - fn get_url( + fn get_request_body( &self, - _req: &PaymentsSyncRouterData, + req: &RefreshTokenRouterData, _connectors: &Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_req = NordeaOAuthExchangeRequest::try_from(req)?; + let body_bytes = self.get_form_urlencoded_payload(&Box::new(connector_req))?; + Ok(RequestContent::RawBytes(body_bytes)) } fn build_request( &self, - req: &PaymentsSyncRouterData, + req: &RefreshTokenRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { - Ok(Some( + // For the OAuth token exchange request, we don't have a bearer token yet + // We're exchanging the auth code for an access token + let auth = NordeaAuthType::try_from(&req.connector_auth_type)?; + let content_type = "application/x-www-form-urlencoded".to_string(); + let http_method = Method::Post; + + // Extract host from base URL + let nordea_host = Url::parse(self.base_url(connectors)) + .change_context(errors::ConnectorError::RequestEncodingFailed)? + .host_str() + .ok_or(errors::ConnectorError::RequestEncodingFailed)? + .to_string(); + + let nordea_origin_date = date_time::now_rfc7231_http_date() + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + let full_url = self.get_url(req, connectors)?; + let url_parsed = + Url::parse(&full_url).change_context(errors::ConnectorError::RequestEncodingFailed)?; + let path = url_parsed.path(); + + let request_body = self.get_request_body(req, connectors)?; + + let mut required_headers = vec![ + ( + headers::CONTENT_TYPE.to_string(), + content_type.clone().into(), + ), + ( + "X-IBM-Client-ID".to_string(), + auth.client_id.clone().expose().into_masked(), + ), + ( + "X-IBM-Client-Secret".to_string(), + auth.client_secret.clone().expose().into_masked(), + ), + ( + "X-Nordea-Originating-Date".to_string(), + nordea_origin_date.clone().into_masked(), + ), + ( + "X-Nordea-Originating-Host".to_string(), + nordea_host.clone().into_masked(), + ), + ]; + + let sha256_digest = self.generate_digest_from_request(&request_body); + + // Add Digest header + required_headers.push(( + "Digest".to_string(), + sha256_digest.to_string().into_masked(), + )); + + let signature = self.generate_signature( + &auth, + SignatureParams { + content_type: &content_type, + host: &nordea_host, + path, + payload_digest: Some(&sha256_digest), + date: &nordea_origin_date, + http_method, + }, + )?; + + required_headers.push(("Signature".to_string(), signature.into_masked())); + + let request = Some( RequestBuilder::new() - .method(Method::Get) - .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) + .method(http_method) .attach_default_headers() - .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) + .headers(required_headers) + .url(&RefreshTokenType::get_url(self, req, connectors)?) + .set_body(request_body) .build(), - )) + ); + Ok(request) } fn handle_response( &self, - data: &PaymentsSyncRouterData, + data: &RefreshTokenRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { - let response: nordea::NordeaPaymentsResponse = res + ) -> CustomResult<RefreshTokenRouterData, errors::ConnectorError> { + let response: NordeaOAuthExchangeResponse = res .response - .parse_struct("nordea PaymentsSyncResponse") + .parse_struct("NordeaOAuthExchangeResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { response, data: data.clone(), @@ -311,10 +726,25 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Nor } } -impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Nordea { +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Nordea { + fn build_request( + &self, + _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Err( + errors::ConnectorError::NotImplemented("Setup Mandate flow for Nordea".to_string()) + .into(), + ) + } +} + +impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData> + for Nordea +{ fn get_headers( &self, - req: &PaymentsCaptureRouterData, + req: &PaymentsPreProcessingRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) @@ -326,34 +756,85 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo fn get_url( &self, - _req: &PaymentsCaptureRouterData, - _connectors: &Connectors, + req: &PaymentsPreProcessingRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + // Determine the payment endpoint based on country and currency + let country = req.get_billing_country()?; + + let currency = + req.request + .currency + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "currency", + })?; + + let endpoint = match (country, currency) { + (api_models::enums::CountryAlpha2::FI, api_models::enums::Currency::EUR) => { + "/personal/v5/payments/sepa-credit-transfers" + } + (api_models::enums::CountryAlpha2::DK, api_models::enums::Currency::DKK) => { + "/personal/v5/payments/domestic-credit-transfers" + } + ( + api_models::enums::CountryAlpha2::FI + | api_models::enums::CountryAlpha2::DK + | api_models::enums::CountryAlpha2::SE + | api_models::enums::CountryAlpha2::NO, + _, + ) => "/personal/v5/payments/cross-border-credit-transfers", + _ => { + return Err(errors::ConnectorError::NotSupported { + message: format!("Country {country:?} is not supported by Nordea"), + connector: "Nordea", + } + .into()) + } + }; + + Ok(format!("{}{}", self.base_url(connectors), endpoint)) } fn get_request_body( &self, - _req: &PaymentsCaptureRouterData, + req: &PaymentsPreProcessingRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) + let minor_amount = + req.request + .minor_amount + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "minor_amount", + })?; + let currency = + req.request + .currency + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "currency", + })?; + + let amount = utils::convert_amount(self.amount_converter, minor_amount, currency)?; + let connector_router_data = NordeaRouterData::from((amount, req)); + let connector_req = NordeaPaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, - req: &PaymentsCaptureRouterData, + req: &PaymentsPreProcessingRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) - .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) + .url(&types::PaymentsPreProcessingType::get_url( + self, req, connectors, + )?) .attach_default_headers() - .headers(types::PaymentsCaptureType::get_headers( + .headers(types::PaymentsPreProcessingType::get_headers( self, req, connectors, )?) - .set_body(types::PaymentsCaptureType::get_request_body( + .set_body(types::PaymentsPreProcessingType::get_request_body( self, req, connectors, )?) .build(), @@ -362,16 +843,18 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo fn handle_response( &self, - data: &PaymentsCaptureRouterData, + data: &PaymentsPreProcessingRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { - let response: nordea::NordeaPaymentsResponse = res + ) -> CustomResult<PaymentsPreProcessingRouterData, errors::ConnectorError> { + let response: NordeaPaymentsInitiateResponse = res .response - .parse_struct("Nordea PaymentsCaptureResponse") + .parse_struct("NordeaPaymentsInitiateResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { response, data: data.clone(), @@ -388,12 +871,10 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo } } -impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Nordea {} - -impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Nordea { +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Nordea { fn get_headers( &self, - req: &RefundsRouterData<Execute>, + req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) @@ -403,61 +884,74 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Nordea self.common_get_content_type() } + fn get_http_method(&self) -> Method { + Method::Put + } + fn get_url( &self, - _req: &RefundsRouterData<Execute>, + _req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + Ok(format!( + "{}{}", + self.base_url(_connectors), + "/personal/v5/payments" + )) } fn get_request_body( &self, - req: &RefundsRouterData<Execute>, + req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let refund_amount = utils::convert_amount( + let amount = utils::convert_amount( self.amount_converter, - req.request.minor_refund_amount, + req.request.minor_amount, req.request.currency, )?; - let connector_router_data = nordea::NordeaRouterData::from((refund_amount, req)); - let connector_req = nordea::NordeaRefundRequest::try_from(&connector_router_data)?; + let connector_router_data = NordeaRouterData::from((amount, req)); + let connector_req = NordeaPaymentsConfirmRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, - req: &RefundsRouterData<Execute>, + req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { - let request = RequestBuilder::new() - .method(Method::Post) - .url(&types::RefundExecuteType::get_url(self, req, connectors)?) - .attach_default_headers() - .headers(types::RefundExecuteType::get_headers( - self, req, connectors, - )?) - .set_body(types::RefundExecuteType::get_request_body( - self, req, connectors, - )?) - .build(); - Ok(Some(request)) + Ok(Some( + RequestBuilder::new() + .method(types::PaymentsAuthorizeType::get_http_method(self)) + .url(&types::PaymentsAuthorizeType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsAuthorizeType::get_request_body( + self, req, connectors, + )?) + .build(), + )) } fn handle_response( &self, - data: &RefundsRouterData<Execute>, + data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { - let response: nordea::RefundResponse = - res.response - .parse_struct("nordea RefundResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { + let response: NordeaPaymentsConfirmResponse = res + .response + .parse_struct("NordeaPaymentsConfirmResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { response, data: data.clone(), @@ -474,10 +968,10 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Nordea } } -impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Nordea { +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Nordea { fn get_headers( &self, - req: &RefundSyncRouterData, + req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) @@ -487,41 +981,52 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Nordea { self.common_get_content_type() } + fn get_http_method(&self) -> Method { + Method::Get + } + fn get_url( &self, - _req: &RefundSyncRouterData, + req: &PaymentsSyncRouterData, _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + let id = req.request.connector_transaction_id.clone(); + let connector_transaction_id = id + .get_connector_transaction_id() + .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; + + Ok(format!( + "{}{}{}", + self.base_url(_connectors), + "/personal/v5/payments/", + connector_transaction_id + )) } fn build_request( &self, - req: &RefundSyncRouterData, + req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() - .method(Method::Get) - .url(&types::RefundSyncType::get_url(self, req, connectors)?) + .method(types::PaymentsSyncType::get_http_method(self)) + .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::RefundSyncType::get_headers(self, req, connectors)?) - .set_body(types::RefundSyncType::get_request_body( - self, req, connectors, - )?) + .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, - data: &RefundSyncRouterData, + data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { - let response: nordea::RefundResponse = res + ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { + let response: NordeaPaymentsInitiateResponse = res .response - .parse_struct("nordea RefundSyncResponse") + .parse_struct("NordeaPaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -541,6 +1046,52 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Nordea { } } +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Nordea { + fn build_request( + &self, + _req: &RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Err(errors::ConnectorError::FlowNotSupported { + flow: "Capture".to_string(), + connector: "Nordea".to_string(), + } + .into()) + } +} + +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Nordea { + fn build_request( + &self, + _req: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Err(errors::ConnectorError::FlowNotSupported { + flow: "Payments Cancel".to_string(), + connector: "Nordea".to_string(), + } + .into()) + } +} + +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Nordea { + fn build_request( + &self, + _req: &RefundsRouterData<Execute>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Err(errors::ConnectorError::FlowNotSupported { + flow: "Personal API Refunds".to_string(), + connector: "Nordea".to_string(), + } + .into()) + } +} + +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Nordea { + // Default impl gets executed +} + #[async_trait::async_trait] impl webhooks::IncomingWebhook for Nordea { fn get_webhook_object_reference_id( @@ -565,4 +1116,54 @@ impl webhooks::IncomingWebhook for Nordea { } } -impl ConnectorSpecifications for Nordea {} +lazy_static! { + static ref NORDEA_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: + "Nordea", + description: + "Nordea is one of the leading financial services group in the Nordics and the preferred choice for millions across the region.", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, + }; + static ref NORDEA_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = { + let nordea_supported_capture_methods = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::SequentialAutomatic, + ]; + + let mut nordea_supported_payment_methods = SupportedPaymentMethods::new(); + + nordea_supported_payment_methods.add( + enums::PaymentMethod::BankDebit, + enums::PaymentMethodType::Sepa, + PaymentMethodDetails { + mandates: common_enums::FeatureStatus::NotSupported, + // Supported only in corporate API (corporate accounts) + refunds: common_enums::FeatureStatus::NotSupported, + supported_capture_methods: nordea_supported_capture_methods.clone(), + specific_features: None, + }, + ); + + nordea_supported_payment_methods + }; + static ref NORDEA_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new(); +} + +impl ConnectorSpecifications for Nordea { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&*NORDEA_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*NORDEA_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&*NORDEA_SUPPORTED_WEBHOOK_FLOWS) + } + + fn authentication_token_for_token_creation(&self) -> bool { + // Nordea requires authentication token for access token creation + true + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/nordea/requests.rs b/crates/hyperswitch_connectors/src/connectors/nordea/requests.rs new file mode 100644 index 00000000000..a30a12ce407 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/nordea/requests.rs @@ -0,0 +1,381 @@ +use common_utils::types::StringMajorUnit; +use masking::Secret; +use serde::{Deserialize, Serialize}; + +pub struct NordeaRouterData<T> { + pub amount: StringMajorUnit, + pub router_data: T, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct NordeaOAuthRequest { + /// Country is a mandatory parameter with possible values FI, DK, NO or SE + pub country: api_models::enums::CountryAlpha2, + /// Duration of access authorization in minutes. range: 1 to 259200 minutes (180 days). + /// Duration should be left empty if the request includes PAYMENTS_SINGLE_SCA scope. + #[serde(skip_serializing_if = "Option::is_none")] + pub duration: Option<i32>, + /// Maximum transaction history in months. Optional if ACCOUNTS_TRANSACTIONS scope is requested. Default=2 months. range: 1 to 18 months + #[serde(rename = "max_tx_history")] + #[serde(skip_serializing_if = "Option::is_none")] + pub maximum_transaction_history: Option<i32>, + /// Redirect URI you used when this application was registered with Nordea. + pub redirect_uri: String, + pub scope: Vec<AccessScope>, + /// The OAuth2 state parameter. This is a nonce and should be used to prevent CSRF attacks. + pub state: Secret<String>, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "snake_case")] +pub enum GrantType { + AuthorizationCode, + RefreshToken, +} + +// To be passed in query parameters for OAuth scopes +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum AccessScope { + AccountsBasic, + AccountsBalances, + AccountsDetails, + AccountsTransactions, + PaymentsMultiple, + PaymentsSingleSca, + CardsInformation, + CardsTransactions, +} + +#[derive(Debug, Clone, Serialize)] +pub struct NordeaOAuthExchangeRequest { + /// authorization_code flow + #[serde(skip_serializing_if = "Option::is_none")] + pub code: Option<Secret<String>>, + pub grant_type: GrantType, + #[serde(skip_serializing_if = "Option::is_none")] + pub redirect_uri: Option<String>, + /// refresh_token flow + #[serde(skip_serializing_if = "Option::is_none")] + pub refresh_token: Option<Secret<String>>, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum AccountType { + /// International bank account number + Iban, + /// National bank account number of Sweden + BbanSe, + /// National bank account number of Denmark + BbanDk, + /// National bank account number of Norway + BbanNo, + /// Bankgiro number + Bgnr, + /// Plusgiro number + Pgnr, + /// Creditor number (Giro) Denmark + GiroDk, + /// Any bank account number without any check-digit validations + BbanOther, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +pub struct AccountNumber { + /// Type of account number + #[serde(rename = "_type")] + pub account_type: AccountType, + /// Currency of the account (Mandatory for debtor, Optional for creditor) + #[serde(skip_serializing_if = "Option::is_none")] + pub currency: Option<api_models::enums::Currency>, + /// Actual account number + pub value: Secret<String>, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +pub struct CreditorAccountReference { + /// RF or Invoice for FI Sepa payments, OCR for NO Kid payments and 01, 04, 15, 71, 73 or 75 for Danish Transfer Form payments. + #[serde(rename = "_type")] + pub creditor_reference_type: String, + /// Actual reference number + #[serde(skip_serializing_if = "Option::is_none")] + pub value: Option<String>, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +pub struct NordeaAddress { + /// First line of the address. e.g. Street address + pub line1: Option<Secret<String>>, + /// Second line of the address (optional). e.g. Postal address + pub line2: Option<Secret<String>>, + /// Third line of the address (optional). e.g. Country + pub line3: Option<Secret<String>>, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +pub struct CreditorBank { + /// Address + pub address: Option<NordeaAddress>, + /// Bank code + pub bank_code: Option<String>, + /// Business identifier code (BIC) of the creditor bank. + /// This information is required, if the creditor account number is not in IBAN format. + #[serde(rename = "bic")] + pub business_identifier_code: Option<Secret<String>>, + /// Country of the creditor bank. Only ISO 3166 alpha-2 codes are used. + pub country: api_models::enums::CountryAlpha2, + /// Name of the creditor bank. + #[serde(rename = "name")] + pub bank_name: Option<String>, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +pub struct CreditorAccount { + /// Account number + pub account: AccountNumber, + /// Creditor bank information. + pub bank: Option<CreditorBank>, + /// Country of the creditor + pub country: Option<api_models::enums::CountryAlpha2>, + /// Address + pub creditor_address: Option<NordeaAddress>, + /// Message for the creditor to appear on their transaction. + /// Max length: FI SEPA:140; SE:12; PGNR:25; BGNR:150; DK: 40 (Instant/Express: 140); NO: 140 + #[serde(skip_serializing_if = "Option::is_none")] + pub message: Option<String>, + /// Name of the creditor. + /// Max length: FI SEPA: 30; SE: 35; DK: Not use (Mandatory for Instant/Express payments: 70); + /// NO: 30 (mandatory for Straksbetaling/Express payments). + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option<Secret<String>>, + /// Creditor reference number. + /// Either Reference or Message has to be passed in the Request + pub reference: Option<CreditorAccountReference>, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +pub struct DebitorAccount { + /// Account number + pub account: AccountNumber, + /// Own message to be on the debtor's transaction. + /// Max length 20. NB: This field is not supported for SEPA and Norwegian payments and will be ignored. + #[serde(skip_serializing_if = "Option::is_none")] + pub message: Option<String>, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +pub struct InstructedAmount { + /// Monetary amount of the payment. Max (digits+decimals): FI SEPA: (9+2); SE:(11+2); DK:(7+2); NO:(7+2) + pub amount: StringMajorUnit, + /// Currency code according to ISO 4217. + /// NB: Possible value depends on the type of the payment. + /// For domestic payment it should be same as debtor local currency, + /// for SEPA it must be EUR, + /// for cross border it can be Currency code according to ISO 4217. + pub currency: api_models::enums::Currency, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum RecurrenceType { + Daily, + Weekly, + Biweekly, + MonthlySameDay, + MonthlyEom, + QuartelySameDay, + QuartelyEom, + SemiAnnuallySameDay, + SemiAnnuallyEom, + TriAnnuallySameDay, + YearlySameDay, + YearlyEom, + EveryMinuteSandboxOnly, +} + +#[derive(Debug, Serialize, PartialEq)] +#[serde(rename_all = "snake_case")] +#[allow(dead_code)] // This is an optional field and not having it is fine +pub enum FundsAvailabilityRequest { + True, + False, +} + +#[derive(Debug, Serialize, PartialEq, Clone)] +pub enum PaymentsUrgency { + Standard, + Express, + Sameday, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +pub struct RecurringInformation { + /// Number of occurrences. Not applicable for NO (use end_date instead). Format: int32. + #[serde(skip_serializing_if = "Option::is_none")] + pub count: Option<i32>, + /// Date on which the recurrence will end. Format: YYYY-MM-DD. Applicable only for Norway. Format: date + #[serde(skip_serializing_if = "Option::is_none")] + pub end_date: Option<String>, + /// Repeats every interval + #[serde(skip_serializing_if = "Option::is_none")] + pub recurrence_type: Option<RecurrenceType>, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum TppCategory { + Error, + Warning, + Info, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum TppCode { + Ds0a, + Narr, + Am21, + Am04, + Tm01, + Am12, + Rc06, + Rc07, + Rc04, + Ag06, + Bg06, + Be22, + Be20, + Ff06, + Be19, + Am03, + Am11, + Ch04, + Dt01, + Ch03, + Ff08, + Ac10, + Ac02, + Ag08, + Rr09, + Rc11, + Ff10, + Rr10, + Ff05, + Ch15, + Ff04, + Ac11, + Ac03, + Ac13, + Ac14, + Ac05, + Ac06, + Rr07, + Dt03, + Am13, + Ds24, + Fr01, + Am02, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +pub struct ThirdPartyMessages { + /// Category of the TPP message, INFO is further information, WARNING is something can be fixed, ERROR possibly non fixable issue + #[serde(skip_serializing_if = "Option::is_none")] + pub category: Option<TppCategory>, + /// Additional code that is combined with the text + #[serde(skip_serializing_if = "Option::is_none")] + pub code: Option<TppCode>, + /// Additional explaining text to the TPP + #[serde(skip_serializing_if = "Option::is_none")] + pub text: Option<String>, +} + +#[derive(Debug, Serialize, PartialEq)] +pub struct NordeaPaymentsRequest { + /// Creditor of the payment + #[serde(rename = "creditor")] + pub creditor_account: CreditorAccount, + /// Debtor of the payment + #[serde(rename = "debtor")] + pub debitor_account: DebitorAccount, + /// Free text reference that can be provided by the PSU. + /// This identification is passed on throughout the entire end-to-end chain. + /// Only in scope for Nordea Business DK. + #[serde(skip_serializing_if = "Option::is_none")] + pub end_to_end_identification: Option<String>, + /// Unique identification as assigned by a partner to identify the payment. + #[serde(skip_serializing_if = "Option::is_none")] + pub external_id: Option<String>, + /// Monetary amount + pub instructed_amount: InstructedAmount, + /// Recurring information + #[serde(skip_serializing_if = "Option::is_none")] + pub recurring: Option<RecurringInformation>, + /// Use as an indicator that the supplied payment (amount, currency and debtor account) + /// should be used to check whether the funds are available for further processing - at this moment. + #[serde(skip_serializing_if = "Option::is_none")] + pub request_availability_of_funds: Option<FundsAvailabilityRequest>, + /// Choose a preferred execution date (or leave blank for today's date). + /// This should be a valid bank day, and depending on the country the date will either be + /// pushed to the next valid bank day, or return an error if a non-banking day date was + /// supplied (all dates accepted in sandbox). SEPA: max +5 years from yesterday, + /// Domestic: max. +1 year from yesterday. NB: Not supported for Own transfer Non-Recurring Norway. + /// Format:date. + #[serde(skip_serializing_if = "Option::is_none")] + pub requested_execution_date: Option<String>, + /// Additional messages for third parties + #[serde(rename = "tpp_messages")] + #[serde(skip_serializing_if = "Option::is_none")] + pub tpp_messages: Option<Vec<ThirdPartyMessages>>, + /// Urgency of the payment. NB: This field is supported for + /// DK Domestic ('standard' and 'express') + /// NO Domestic bank transfer payments ('standard'). Use 'express' for Straksbetaling (Instant payment). + /// FI Sepa ('standard' and 'express') All other payment types ignore this input. + /// For further details on urgencies and cut-offs, refer to the Nordea website. Value 'sameday' is marked as deprecated and will be removed in the future. + #[serde(skip_serializing_if = "Option::is_none")] + pub urgency: Option<PaymentsUrgency>, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum NordeaAuthenticationMethod { + Mta, + #[serde(rename = "CCALC (Deprecated)")] + Ccalc, + Qrt, + CardRdr, + BankidSe, + QrtSe, + BankidNo, + BankidmNo, + MtaNo, + #[serde(rename = "NEMID_2F")] + Nemid2f, + Mitid, + MtaDk, + QrtDk, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] +#[serde(rename_all = "snake_case")] +pub enum NordeaConfirmLanguage { + Fi, + Da, + Sv, + En, + No, +} + +#[derive(Debug, Serialize, PartialEq)] +pub struct NordeaPaymentsConfirmRequest { + /// Authentication method to use for the signing of payment. + #[serde(skip_serializing_if = "Option::is_none")] + pub authentication_method: Option<NordeaAuthenticationMethod>, + /// Language of the signing page that will be displayed to client, ISO639-1 and 639-2, default=en + #[serde(skip_serializing_if = "Option::is_none")] + pub language: Option<NordeaConfirmLanguage>, + pub payments_ids: Vec<String>, + pub redirect_url: Option<String>, + pub state: Option<String>, +} diff --git a/crates/hyperswitch_connectors/src/connectors/nordea/responses.rs b/crates/hyperswitch_connectors/src/connectors/nordea/responses.rs new file mode 100644 index 00000000000..10693c9b43a --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/nordea/responses.rs @@ -0,0 +1,261 @@ +use common_enums::CountryAlpha2; +use common_utils::types::StringMajorUnit; +use masking::Secret; +use serde::{Deserialize, Serialize}; + +use super::requests::{ + CreditorAccount, DebitorAccount, InstructedAmount, PaymentsUrgency, RecurringInformation, + ThirdPartyMessages, +}; + +// OAuth token response structure +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct NordeaOAuthExchangeResponse { + pub access_token: Option<Secret<String>>, + pub expires_in: Option<i64>, + pub refresh_token: Option<Secret<String>>, + pub token_type: Option<String>, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "PascalCase")] +pub enum NordeaPaymentStatus { + #[default] + PendingConfirmation, + PendingSecondConfirmation, + PendingUserApproval, + OnHold, + Confirmed, + Rejected, + Paid, + InsufficientFunds, + LimitExceeded, + UserApprovalFailed, + UserApprovalTimeout, + UserApprovalCancelled, + Unknown, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +pub struct NordeaGroupHeader { + /// Response creation time. Format: date-time. + pub creation_date_time: Option<String>, + /// HTTP code for response. Format: int32. + pub http_code: Option<i32>, + /// Original request id for correlation purposes + pub message_identification: Option<String>, + /// Details of paginated response + pub message_pagination: Option<MessagePagination>, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +pub struct NordeaResponseLinks { + /// Describes the nature of the link, e.g. 'details' for a link to the detailed information of a listed resource. + pub rel: Option<String>, + /// Relative path to the linked resource + pub href: Option<String>, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum FeesType { + Additional, + Standard, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +pub struct TransactionFee { + /// Monetary amount + pub amount: InstructedAmount, + pub description: Option<String>, + pub excluded_from_total_fee: Option<bool>, + pub percentage: Option<bool>, + #[serde(rename = "type")] + pub fees_type: Option<FeesType>, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +pub struct BankFee { + /// Example 'domestic_transaction' only for DK domestic payments + #[serde(rename = "_type")] + pub bank_fee_type: Option<String>, + /// Country code according to ISO Alpha-2 + pub country_code: Option<CountryAlpha2>, + /// Currency code according to ISO 4217 + pub currency_code: Option<api_models::enums::Currency>, + /// Value of the fee. + pub value: Option<StringMajorUnit>, + pub fees: Option<Vec<TransactionFee>>, + /// Monetary amount + pub total_fee_amount: InstructedAmount, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum ChargeBearer { + Shar, + Debt, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +pub struct ExchangeRate { + pub base_currency: Option<api_models::enums::Currency>, + pub exchange_currency: Option<api_models::enums::Currency>, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +pub struct MessagePagination { + /// Resource listing may return a continuationKey if there's more results available. + /// Request may be retried with the continuationKey, but otherwise same parameters, in order to get more results. + pub continuation_key: Option<String>, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +pub struct NordeaPaymentsInitiateResponseData { + /// Unique payment identifier assigned for new payment + #[serde(rename = "_id")] + pub payment_id: String, + /// HATEOAS inspired links: 'rel' and 'href'. Context specific link (only GET supported) + #[serde(rename = "_links")] + pub links: Option<Vec<NordeaResponseLinks>>, + /// Marked as required field in the docs, but connector does not send amount in payment_response.amount + pub amount: Option<StringMajorUnit>, + /// Bearer of charges. shar = The Debtor (sender of the payment) will pay all fees charged by the sending bank. + /// The Creditor (recipient of the payment) will pay all fees charged by the receiving bank. + /// debt = The Debtor (sender of the payment) will bear all of the payment transaction fees. + /// The creditor (beneficiary) will receive the full amount of the payment. + pub charge_bearer: Option<ChargeBearer>, + /// Creditor of the payment + #[serde(rename = "creditor")] + pub creditor_account: CreditorAccount, + pub currency: Option<api_models::enums::Currency>, + /// Debtor of the payment + #[serde(rename = "debtor")] + pub debitor_account: Option<DebitorAccount>, + /// Timestamp of payment creation. ISO 8601 format yyyy-mm-ddThh:mm:ss.fffZ. Format:date-time. + pub entry_date_time: Option<String>, + /// Unique identification as assigned by a partner to identify the payment. + pub external_id: Option<String>, + /// An amount the bank will charge for executing the payment + pub fee: Option<BankFee>, + pub indicative_exchange_rate: Option<ExchangeRate>, + /// It is mentioned as `number`. It can be an integer or a decimal number. + pub rate: Option<f32>, + /// Monetary amount + pub instructed_amount: Option<InstructedAmount>, + /// Indication of cross border payment to own account + pub is_own_account_transfer: Option<bool>, + /// OTP Challenge + pub otp_challenge: Option<String>, + /// Status of the payment + pub payment_status: NordeaPaymentStatus, + /// Planned execution date will indicate the day the payment will be finalized. If the payment has been pushed due to cut-off, it will be indicated in planned execution date. Format:date. + pub planned_execution_date: Option<String>, + /// Recurring information + pub recurring: Option<RecurringInformation>, + /// Choose a preferred execution date (or leave blank for today's date). + /// This should be a valid bank day, and depending on the country the date will either be pushed to the next valid bank day, + /// or return an error if a non-banking day date was supplied (all dates accepted in sandbox). + /// SEPA: max +5 years from yesterday, Domestic: max. +1 year from yesterday. NB: Not supported for Own transfer Non-Recurring Norway. + /// Format:date. + pub requested_execution_date: Option<String>, + /// Timestamp of payment creation. ISO 8601 format yyyy-mm-ddThh:mm:ss.fffZ Format:date-time. + pub timestamp: Option<String>, + /// Additional messages for third parties + pub tpp_messages: Option<Vec<ThirdPartyMessages>>, + pub transaction_fee: Option<Vec<BankFee>>, + /// Currency that the cross border payment will be transferred in. + /// This field is only supported for cross border payments for DK. + /// If this field is not supplied then the payment will use the currency specified for the currency field of instructed_amount. + pub transfer_currency: Option<api_models::enums::Currency>, + /// Urgency of the payment. NB: This field is supported for DK Domestic ('standard' and 'express') and NO Domestic bank transfer payments ('standard' and 'express'). + /// Use 'express' for Straksbetaling (Instant payment). + /// All other payment types ignore this input. + /// For further details on urgencies and cut-offs, refer to the Nordea website. + /// Value 'sameday' is marked as deprecated and will be removed in the future. + pub urgency: Option<PaymentsUrgency>, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +pub struct NordeaPaymentsInitiateResponse { + /// Payment information + #[serde(rename = "response")] + pub payments_response: Option<NordeaPaymentsInitiateResponseData>, + /// External response header + pub group_header: Option<NordeaGroupHeader>, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +pub struct NordeaPaymentsConfirmErrorObject { + /// Error message + pub error: Option<String>, + /// Description of the error + pub error_description: Option<String>, + /// Payment id of the payment, the error is associated with + pub payment_id: Option<String>, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +pub struct NordeaPaymentsResponseWrapper { + pub payments: Vec<NordeaPaymentsInitiateResponseData>, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +pub struct NordeaPaymentsConfirmResponse { + /// HATEOAS inspired links: 'rel' and 'href' + #[serde(rename = "_links")] + pub links: Option<Vec<NordeaResponseLinks>>, + /// Error description + pub errors: Option<Vec<NordeaPaymentsConfirmErrorObject>>, + /// External response header + pub group_header: Option<NordeaGroupHeader>, + /// OTP Challenge + pub otp_challenge: Option<String>, + #[serde(rename = "response")] + pub nordea_payments_response: Option<NordeaPaymentsResponseWrapper>, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +pub struct NordeaOriginalRequest { + /// Original request url + #[serde(rename = "url")] + pub nordea_url: Option<String>, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +pub struct NordeaFailures { + /// Failure code + pub code: Option<String>, + /// Failure description + pub description: Option<String>, + /// JSON path of the failing element if applicable + pub path: Option<String>, + /// Type of the validation error, e.g. NotNull + #[serde(rename = "type")] + pub failure_type: Option<String>, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +pub struct NordeaErrorBody { + // Serde JSON because connector returns an `(item)` object in failures array object + /// More details on the occurred error: Validation error + #[serde(rename = "failures")] + pub nordea_failures: Option<Vec<NordeaFailures>>, + /// Original request information + #[serde(rename = "request")] + pub nordea_request: Option<NordeaOriginalRequest>, +} + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +pub struct NordeaErrorResponse { + /// Error response body + pub error: Option<NordeaErrorBody>, + /// External response header + pub group_header: Option<NordeaGroupHeader>, + #[serde(rename = "httpCode")] + pub http_code: Option<String>, + #[serde(rename = "moreInformation")] + pub more_information: Option<String>, +} + +// Nordea does not support refunds in Private APIs. Only Corporate APIs support Refunds diff --git a/crates/hyperswitch_connectors/src/connectors/nordea/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nordea/transformers.rs index bea06d53e39..6e781e7de9a 100644 --- a/crates/hyperswitch_connectors/src/connectors/nordea/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nordea/transformers.rs @@ -1,31 +1,43 @@ -use common_enums::enums; -use common_utils::types::StringMinorUnit; +use std::collections::HashMap; + +use common_utils::{pii, request::Method, types::StringMajorUnit}; +use error_stack::ResultExt; use hyperswitch_domain_models::{ - payment_method_data::PaymentMethodData, - router_data::{ConnectorAuthType, RouterData}, - router_flow_types::refunds::{Execute, RSync}, - router_request_types::ResponseId, - router_response_types::{PaymentsResponseData, RefundsResponseData}, - types::{PaymentsAuthorizeRouterData, RefundsRouterData}, + payment_method_data::{BankDebitData, PaymentMethodData}, + router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, + router_flow_types::{Authorize, PreProcessing}, + router_request_types::{PaymentsAuthorizeData, PaymentsPreProcessingData, ResponseId}, + router_response_types::{PaymentsResponseData, RedirectForm}, + types::{ + self, AccessTokenAuthenticationRouterData, PaymentsAuthorizeRouterData, + PaymentsPreProcessingRouterData, PaymentsSyncRouterData, + }, }; use hyperswitch_interfaces::errors; use masking::Secret; -use serde::{Deserialize, Serialize}; +use rand::distributions::DistString; +use serde::{Deserialize, Deserializer, Serialize}; use crate::{ - types::{RefundsResponseRouterData, ResponseRouterData}, - utils::PaymentsAuthorizeRequestData, + connectors::nordea::{ + requests::{ + AccessScope, AccountNumber, AccountType, CreditorAccount, CreditorBank, DebitorAccount, + GrantType, NordeaOAuthExchangeRequest, NordeaOAuthRequest, + NordeaPaymentsConfirmRequest, NordeaPaymentsRequest, NordeaRouterData, PaymentsUrgency, + }, + responses::{ + NordeaErrorBody, NordeaFailures, NordeaOAuthExchangeResponse, NordeaPaymentStatus, + NordeaPaymentsConfirmResponse, NordeaPaymentsInitiateResponse, + }, + }, + types::{PaymentsSyncResponseRouterData, ResponseRouterData}, + utils::{self, get_unimplemented_payment_method_error_message, RouterData as _}, }; -//TODO: Fill the struct with respective fields -pub struct NordeaRouterData<T> { - pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. - pub router_data: T, -} +type Error = error_stack::Report<errors::ConnectorError>; -impl<T> From<(StringMinorUnit, T)> for NordeaRouterData<T> { - fn from((amount, item): (StringMinorUnit, T)) -> Self { - //Todo : use utils to convert the amount to the type of amount that a connector accepts +impl<T> From<(StringMajorUnit, T)> for NordeaRouterData<T> { + fn from((amount, item): (StringMajorUnit, T)) -> Self { Self { amount, router_data: item, @@ -33,196 +45,528 @@ impl<T> From<(StringMinorUnit, T)> for NordeaRouterData<T> { } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Serialize, PartialEq)] -pub struct NordeaPaymentsRequest { - amount: StringMinorUnit, - card: NordeaCard, -} - -#[derive(Default, Debug, Serialize, Eq, PartialEq)] -pub struct NordeaCard { - number: cards::CardNumber, - expiry_month: Secret<String>, - expiry_year: Secret<String>, - cvc: Secret<String>, - complete: bool, -} - -impl TryFrom<&NordeaRouterData<&PaymentsAuthorizeRouterData>> for NordeaPaymentsRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - item: &NordeaRouterData<&PaymentsAuthorizeRouterData>, - ) -> Result<Self, Self::Error> { - match item.router_data.request.payment_method_data.clone() { - PaymentMethodData::Card(req_card) => { - let card = NordeaCard { - number: req_card.card_number, - expiry_month: req_card.card_exp_month, - expiry_year: req_card.card_exp_year, - cvc: req_card.card_cvc, - complete: item.router_data.request.is_auto_capture()?, - }; - Ok(Self { - amount: item.amount.clone(), - card, - }) - } - _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), - } - } -} - -//TODO: Fill the struct with respective fields // Auth Struct +#[derive(Debug)] pub struct NordeaAuthType { - pub(super) api_key: Secret<String>, + pub(super) client_id: Secret<String>, + pub(super) client_secret: Secret<String>, + /// PEM format private key for eIDAS signing + /// Should be base64 encoded + pub(super) eidas_private_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for NordeaAuthType { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = Error; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { - ConnectorAuthType::HeaderKey { api_key } => Ok(Self { - api_key: api_key.to_owned(), + ConnectorAuthType::SignatureKey { + api_key, + key1, + api_secret, + } => Ok(Self { + client_id: key1.to_owned(), + client_secret: api_key.to_owned(), + eidas_private_key: api_secret.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } -// PaymentsResponse -//TODO: Append the remaining status flags -#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] -#[serde(rename_all = "lowercase")] -pub enum NordeaPaymentStatus { - Succeeded, - Failed, - #[default] - Processing, + +#[derive(Debug, Default, Serialize, Deserialize)] +pub struct NordeaConnectorMetadataObject { + pub creditor_account_value: Secret<String>, + pub creditor_account_type: String, + pub creditor_beneficiary_name: Secret<String>, } -impl From<NordeaPaymentStatus> for common_enums::AttemptStatus { - fn from(item: NordeaPaymentStatus) -> Self { - match item { - NordeaPaymentStatus::Succeeded => Self::Charged, - NordeaPaymentStatus::Failed => Self::Failure, - NordeaPaymentStatus::Processing => Self::Authorizing, - } +impl TryFrom<&Option<pii::SecretSerdeValue>> for NordeaConnectorMetadataObject { + type Error = Error; + fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> { + let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone()) + .change_context(errors::ConnectorError::InvalidConnectorConfig { + config: "merchant_connector_account.metadata", + })?; + Ok(metadata) } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct NordeaPaymentsResponse { - status: NordeaPaymentStatus, - id: String, +impl TryFrom<&AccessTokenAuthenticationRouterData> for NordeaOAuthRequest { + type Error = Error; + fn try_from(item: &AccessTokenAuthenticationRouterData) -> Result<Self, Self::Error> { + let country = item.get_billing_country()?; + + // Set refresh_token maximum expiry duration to 180 days (259200 / 60 = 180) + // Minimum is 1 minute + let duration = Some(259200); + let maximum_transaction_history = Some(18); + let redirect_uri = "https://hyperswitch.io".to_string(); + let scope = [ + AccessScope::AccountsBasic, + AccessScope::AccountsDetails, + AccessScope::AccountsBalances, + AccessScope::AccountsTransactions, + AccessScope::PaymentsMultiple, + ] + .to_vec(); + let state = rand::distributions::Alphanumeric.sample_string(&mut rand::thread_rng(), 15); + + Ok(Self { + country, + duration, + maximum_transaction_history, + redirect_uri, + scope, + state: state.into(), + }) + } +} + +impl TryFrom<&types::RefreshTokenRouterData> for NordeaOAuthExchangeRequest { + type Error = Error; + fn try_from(item: &types::RefreshTokenRouterData) -> Result<Self, Self::Error> { + let code = item + .request + .authentication_token + .as_ref() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "authorization_code", + })? + .code + .clone(); + let grant_type = GrantType::AuthorizationCode; + let redirect_uri = Some("https://hyperswitch.io".to_string()); + + Ok(Self { + code: Some(code), + grant_type, + redirect_uri, + refresh_token: None, // We're not using refresh_token to generate new access_token + }) + } } -impl<F, T> TryFrom<ResponseRouterData<F, NordeaPaymentsResponse, T, PaymentsResponseData>> - for RouterData<F, T, PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, NordeaOAuthExchangeResponse, T, AccessToken>> + for RouterData<F, T, AccessToken> { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = Error; fn try_from( - item: ResponseRouterData<F, NordeaPaymentsResponse, T, PaymentsResponseData>, + item: ResponseRouterData<F, NordeaOAuthExchangeResponse, T, AccessToken>, ) -> Result<Self, Self::Error> { + let access_token = + item.response + .access_token + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "access_token", + })?; + + let expires_in = item.response.expires_in.unwrap_or(3600); // Default to 1 hour if not provided + Ok(Self { - status: common_enums::AttemptStatus::from(item.response.status), - response: Ok(PaymentsResponseData::TransactionResponse { - resource_id: ResponseId::ConnectorTransactionId(item.response.id), - redirection_data: Box::new(None), - mandate_reference: Box::new(None), - connector_metadata: None, - network_txn_id: None, - connector_response_reference_id: None, - incremental_authorization_allowed: None, - charges: None, + status: common_enums::AttemptStatus::AuthenticationSuccessful, + response: Ok(AccessToken { + token: access_token.clone(), + expires: expires_in, }), ..item.data }) } } -//TODO: Fill the struct with respective fields -// REFUND : -// Type definition for RefundRequest -#[derive(Default, Debug, Serialize)] -pub struct NordeaRefundRequest { - pub amount: StringMinorUnit, +impl TryFrom<&str> for AccountType { + type Error = Error; + + fn try_from(value: &str) -> Result<Self, Self::Error> { + match value.to_uppercase().as_str() { + "IBAN" => Ok(Self::Iban), + "BBAN_SE" => Ok(Self::BbanSe), + "BBAN_DK" => Ok(Self::BbanDk), + "BBAN_NO" => Ok(Self::BbanNo), + "BGNR" => Ok(Self::Bgnr), + "PGNR" => Ok(Self::Pgnr), + "GIRO_DK" => Ok(Self::GiroDk), + "BBAN_OTHER" => Ok(Self::BbanOther), + _ => Err(errors::ConnectorError::InvalidConnectorConfig { + config: "account_type", + } + .into()), + } + } } -impl<F> TryFrom<&NordeaRouterData<&RefundsRouterData<F>>> for NordeaRefundRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &NordeaRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { - Ok(Self { - amount: item.amount.to_owned(), - }) +impl<'de> Deserialize<'de> for PaymentsUrgency { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: Deserializer<'de>, + { + let s = String::deserialize(deserializer)?.to_lowercase(); + match s.as_str() { + "standard" => Ok(Self::Standard), + "express" => Ok(Self::Express), + "sameday" => Ok(Self::Sameday), + _ => Err(serde::de::Error::unknown_variant( + &s, + &["standard", "express", "sameday"], + )), + } + } +} + +fn get_creditor_account_from_metadata( + router_data: &PaymentsPreProcessingRouterData, +) -> Result<CreditorAccount, Error> { + let metadata: NordeaConnectorMetadataObject = + utils::to_connector_meta_from_secret(router_data.connector_meta_data.clone()) + .change_context(errors::ConnectorError::InvalidConnectorConfig { + config: "merchant_connector_account.metadata", + })?; + let creditor_account = CreditorAccount { + account: AccountNumber { + account_type: AccountType::try_from(metadata.creditor_account_type.as_str()) + .unwrap_or(AccountType::Iban), + currency: router_data.request.currency, + value: metadata.creditor_account_value, + }, + country: router_data.get_optional_billing_country(), + // Merchant is the beneficiary in this case + name: Some(metadata.creditor_beneficiary_name), + message: router_data + .description + .as_ref() + .map(|desc| desc.chars().take(20).collect::<String>()), + bank: Some(CreditorBank { + address: None, + bank_code: None, + bank_name: None, + business_identifier_code: None, + country: router_data.get_billing_country()?, + }), + creditor_address: None, + // Either Reference or Message must be supplied in the request + reference: None, + }; + Ok(creditor_account) +} + +impl TryFrom<&NordeaRouterData<&PaymentsPreProcessingRouterData>> for NordeaPaymentsRequest { + type Error = Error; + fn try_from( + item: &NordeaRouterData<&PaymentsPreProcessingRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + Some(PaymentMethodData::BankDebit(bank_debit_data)) => match bank_debit_data { + BankDebitData::SepaBankDebit { iban, .. } => { + let creditor_account = get_creditor_account_from_metadata(item.router_data)?; + let debitor_account = DebitorAccount { + account: AccountNumber { + account_type: AccountType::Iban, + currency: item.router_data.request.currency, + value: iban, + }, + message: item + .router_data + .description + .as_ref() + .map(|desc| desc.chars().take(20).collect::<String>()), + }; + + let instructed_amount = super::requests::InstructedAmount { + amount: item.amount.clone(), + currency: item.router_data.request.currency.ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "amount", + }, + )?, + }; + + Ok(Self { + creditor_account, + debitor_account, + end_to_end_identification: None, + external_id: Some(item.router_data.connector_request_reference_id.clone()), + instructed_amount, + recurring: None, + request_availability_of_funds: None, + requested_execution_date: None, + tpp_messages: None, + urgency: None, + }) + } + BankDebitData::AchBankDebit { .. } + | BankDebitData::BacsBankDebit { .. } + | BankDebitData::BecsBankDebit { .. } => { + Err(errors::ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("Nordea"), + ) + .into()) + } + }, + Some(PaymentMethodData::CardRedirect(_)) + | Some(PaymentMethodData::CardDetailsForNetworkTransactionId(_)) + | Some(PaymentMethodData::Wallet(_)) + | Some(PaymentMethodData::PayLater(_)) + | Some(PaymentMethodData::BankRedirect(_)) + | Some(PaymentMethodData::BankTransfer(_)) + | Some(PaymentMethodData::Crypto(_)) + | Some(PaymentMethodData::MandatePayment) + | Some(PaymentMethodData::Reward) + | Some(PaymentMethodData::RealTimePayment(_)) + | Some(PaymentMethodData::MobilePayment(_)) + | Some(PaymentMethodData::Upi(_)) + | Some(PaymentMethodData::Voucher(_)) + | Some(PaymentMethodData::GiftCard(_)) + | Some(PaymentMethodData::OpenBanking(_)) + | Some(PaymentMethodData::CardToken(_)) + | Some(PaymentMethodData::NetworkToken(_)) + | Some(PaymentMethodData::Card(_)) + | None => { + Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()) + } + } } } -// Type definition for Refund Response +impl TryFrom<&NordeaRouterData<&PaymentsAuthorizeRouterData>> for NordeaPaymentsConfirmRequest { + type Error = Error; + fn try_from( + item: &NordeaRouterData<&PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + let payment_ids = match &item.router_data.response { + Ok(response_data) => response_data + .get_connector_transaction_id() + .map_err(|_| errors::ConnectorError::MissingConnectorTransactionID)?, + Err(_) => return Err(errors::ConnectorError::ResponseDeserializationFailed.into()), + }; -#[allow(dead_code)] -#[derive(Debug, Serialize, Default, Deserialize, Clone)] -pub enum RefundStatus { - Succeeded, - Failed, - #[default] - Processing, + Ok(Self { + authentication_method: None, + language: None, + payments_ids: vec![payment_ids], + redirect_url: None, + state: None, + }) + } } -impl From<RefundStatus> for enums::RefundStatus { - fn from(item: RefundStatus) -> Self { +impl From<NordeaPaymentStatus> for common_enums::AttemptStatus { + fn from(item: NordeaPaymentStatus) -> Self { match item { - RefundStatus::Succeeded => Self::Success, - RefundStatus::Failed => Self::Failure, - RefundStatus::Processing => Self::Pending, - //TODO: Review mapping + NordeaPaymentStatus::Confirmed | NordeaPaymentStatus::Paid => Self::Charged, + + NordeaPaymentStatus::PendingConfirmation + | NordeaPaymentStatus::PendingSecondConfirmation => Self::ConfirmationAwaited, + NordeaPaymentStatus::PendingUserApproval => Self::AuthenticationPending, + + NordeaPaymentStatus::OnHold | NordeaPaymentStatus::Unknown => Self::Pending, + + NordeaPaymentStatus::Rejected + | NordeaPaymentStatus::InsufficientFunds + | NordeaPaymentStatus::LimitExceeded + | NordeaPaymentStatus::UserApprovalFailed + | NordeaPaymentStatus::UserApprovalTimeout + | NordeaPaymentStatus::UserApprovalCancelled => Self::Failure, } } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Clone, Serialize, Deserialize)] -pub struct RefundResponse { - id: String, - status: RefundStatus, +pub fn get_error_data(error_response: Option<&NordeaErrorBody>) -> Option<&NordeaFailures> { + error_response + .and_then(|error| error.nordea_failures.as_ref()) + .and_then(|failures| failures.first()) +} + +// Helper function to convert NordeaPaymentsInitiateResponse to common response data +fn convert_nordea_payment_response( + response: &NordeaPaymentsInitiateResponse, +) -> Result<(PaymentsResponseData, common_enums::AttemptStatus), Error> { + let payment_response = response + .payments_response + .as_ref() + .ok_or(errors::ConnectorError::ResponseHandlingFailed)?; + + let resource_id = ResponseId::ConnectorTransactionId(payment_response.payment_id.clone()); + + let response_data = PaymentsResponseData::TransactionResponse { + resource_id, + redirection_data: Box::new(None), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: payment_response.external_id.clone(), + incremental_authorization_allowed: None, + charges: None, + }; + + let status = common_enums::AttemptStatus::from(payment_response.payment_status.clone()); + + Ok((response_data, status)) } -impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { - type Error = error_stack::Report<errors::ConnectorError>; +impl + TryFrom< + ResponseRouterData< + PreProcessing, + NordeaPaymentsInitiateResponse, + PaymentsPreProcessingData, + PaymentsResponseData, + >, + > for RouterData<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData> +{ + type Error = Error; fn try_from( - item: RefundsResponseRouterData<Execute, RefundResponse>, + item: ResponseRouterData< + PreProcessing, + NordeaPaymentsInitiateResponse, + PaymentsPreProcessingData, + PaymentsResponseData, + >, ) -> Result<Self, Self::Error> { + let (response, status) = convert_nordea_payment_response(&item.response)?; Ok(Self { - response: Ok(RefundsResponseData { - connector_refund_id: item.response.id.to_string(), - refund_status: enums::RefundStatus::from(item.response.status), - }), + status, + response: Ok(response), ..item.data }) } } -impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { - type Error = error_stack::Report<errors::ConnectorError>; +impl + TryFrom< + ResponseRouterData< + Authorize, + NordeaPaymentsConfirmResponse, + PaymentsAuthorizeData, + PaymentsResponseData, + >, + > for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData> +{ + type Error = Error; fn try_from( - item: RefundsResponseRouterData<RSync, RefundResponse>, + item: ResponseRouterData< + Authorize, + NordeaPaymentsConfirmResponse, + PaymentsAuthorizeData, + PaymentsResponseData, + >, ) -> Result<Self, Self::Error> { + // First check if there are any errors in the response + if let Some(errors) = &item.response.errors { + if !errors.is_empty() { + // Get the first error for the error response + let first_error = errors + .first() + .ok_or(errors::ConnectorError::ResponseHandlingFailed)?; + + return Ok(Self { + status: common_enums::AttemptStatus::Failure, + response: Err(ErrorResponse { + code: first_error + .error + .clone() + .unwrap_or_else(|| "UNKNOWN_ERROR".to_string()), + message: first_error + .error_description + .clone() + .unwrap_or_else(|| "Payment confirmation failed".to_string()), + reason: first_error.error_description.clone(), + status_code: item.http_code, + attempt_status: Some(common_enums::AttemptStatus::Failure), + connector_transaction_id: first_error.payment_id.clone(), + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + }), + ..item.data + }); + } + } + + // If no errors, proceed with normal response handling + // Check if there's a redirect link at the top level only + let redirection_data = item + .response + .links + .as_ref() + .and_then(|links| { + links.iter().find(|link| { + link.rel + .as_ref() + .map(|rel| rel == "signing") + .unwrap_or(false) + }) + }) + .and_then(|link| link.href.clone()) + .map(|redirect_url| RedirectForm::Form { + endpoint: redirect_url, + method: Method::Get, + form_fields: HashMap::new(), + }); + + let (response, status) = match &item.response.nordea_payments_response { + Some(payment_response_wrapper) => { + // Get the first payment from the payments array + let payment = payment_response_wrapper + .payments + .first() + .ok_or(errors::ConnectorError::ResponseHandlingFailed)?; + + let resource_id = ResponseId::ConnectorTransactionId(payment.payment_id.clone()); + + let response = Ok(PaymentsResponseData::TransactionResponse { + resource_id, + redirection_data: Box::new(redirection_data), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: payment.external_id.clone(), + incremental_authorization_allowed: None, + charges: None, + }); + + let status = common_enums::AttemptStatus::from(payment.payment_status.clone()); + + (response, status) + } + None => { + // No payment response, but we might still have a redirect link + if let Some(redirect) = redirection_data { + let response = Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::NoResponseId, + redirection_data: Box::new(Some(redirect)), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: None, + incremental_authorization_allowed: None, + charges: None, + }); + (response, common_enums::AttemptStatus::AuthenticationPending) + } else { + return Err(errors::ConnectorError::ResponseHandlingFailed.into()); + } + } + }; + Ok(Self { - response: Ok(RefundsResponseData { - connector_refund_id: item.response.id.to_string(), - refund_status: enums::RefundStatus::from(item.response.status), - }), + status, + response, ..item.data }) } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] -pub struct NordeaErrorResponse { - pub status_code: u16, - pub code: String, - pub message: String, - pub reason: Option<String>, +impl TryFrom<PaymentsSyncResponseRouterData<NordeaPaymentsInitiateResponse>> + for PaymentsSyncRouterData +{ + type Error = Error; + fn try_from( + item: PaymentsSyncResponseRouterData<NordeaPaymentsInitiateResponse>, + ) -> Result<Self, Self::Error> { + let (response, status) = convert_nordea_payment_response(&item.response)?; + Ok(Self { + status, + response: Ok(response), + ..item.data + }) + } } diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 7df691d95ab..484f20cf8df 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -24,25 +24,8 @@ use hyperswitch_domain_models::router_response_types::revenue_recovery::{ BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse, RevenueRecoveryRecordBackResponse, }; -#[cfg(feature = "frm")] -use hyperswitch_domain_models::{ - router_flow_types::fraud_check::{Checkout, Fulfillment, RecordReturn, Sale, Transaction}, - router_request_types::fraud_check::{ - FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData, - FraudCheckSaleData, FraudCheckTransactionData, - }, - router_response_types::fraud_check::FraudCheckResponseData, -}; -#[cfg(feature = "payouts")] -use hyperswitch_domain_models::{ - router_flow_types::payouts::{ - PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, - PoSync, - }, - router_request_types::PayoutsData, - router_response_types::PayoutsResponseData, -}; use hyperswitch_domain_models::{ + router_data::AccessTokenAuthenticationResponse, router_flow_types::{ authentication::{ Authentication, PostAuthentication, PreAuthentication, PreAuthenticationVersionCall, @@ -57,8 +40,9 @@ use hyperswitch_domain_models::{ UpdateMetadata, }, webhooks::VerifyWebhookSource, - Authenticate, AuthenticationConfirmation, ExternalVaultCreateFlow, ExternalVaultDeleteFlow, - ExternalVaultInsertFlow, ExternalVaultRetrieveFlow, PostAuthenticate, PreAuthenticate, + AccessTokenAuthentication, Authenticate, AuthenticationConfirmation, + ExternalVaultCreateFlow, ExternalVaultDeleteFlow, ExternalVaultInsertFlow, + ExternalVaultRetrieveFlow, PostAuthenticate, PreAuthenticate, }, router_request_types::{ authentication, @@ -67,14 +51,15 @@ use hyperswitch_domain_models::{ UasConfirmationRequestData, UasPostAuthenticationRequestData, UasPreAuthenticationRequestData, }, - AcceptDisputeRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData, - ConnectorCustomerData, CreateOrderRequestData, DefendDisputeRequestData, DisputeSyncData, - FetchDisputesRequestData, MandateRevokeRequestData, PaymentsApproveData, - PaymentsCancelPostCaptureData, PaymentsIncrementalAuthorizationData, - PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreProcessingData, - PaymentsRejectData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, - RetrieveFileRequestData, SdkPaymentsSessionUpdateData, SubmitEvidenceRequestData, - UploadFileRequestData, VaultRequestData, VerifyWebhookSourceRequestData, + AcceptDisputeRequestData, AccessTokenAuthenticationRequestData, AuthorizeSessionTokenData, + CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData, + DefendDisputeRequestData, DisputeSyncData, FetchDisputesRequestData, + MandateRevokeRequestData, PaymentsApproveData, PaymentsCancelPostCaptureData, + PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData, + PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsRejectData, + PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RetrieveFileRequestData, + SdkPaymentsSessionUpdateData, SubmitEvidenceRequestData, UploadFileRequestData, + VaultRequestData, VerifyWebhookSourceRequestData, }, router_response_types::{ AcceptDisputeResponse, AuthenticationResponseData, DefendDisputeResponse, @@ -85,6 +70,24 @@ use hyperswitch_domain_models::{ }, }; #[cfg(feature = "frm")] +use hyperswitch_domain_models::{ + router_flow_types::fraud_check::{Checkout, Fulfillment, RecordReturn, Sale, Transaction}, + router_request_types::fraud_check::{ + FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData, + FraudCheckSaleData, FraudCheckTransactionData, + }, + router_response_types::fraud_check::FraudCheckResponseData, +}; +#[cfg(feature = "payouts")] +use hyperswitch_domain_models::{ + router_flow_types::payouts::{ + PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, + PoSync, + }, + router_request_types::PayoutsData, + router_response_types::PayoutsResponseData, +}; +#[cfg(feature = "frm")] use hyperswitch_interfaces::api::fraud_check::{ FraudCheck, FraudCheckCheckout, FraudCheckFulfillment, FraudCheckRecordReturn, FraudCheckSale, FraudCheckTransaction, @@ -124,9 +127,10 @@ use hyperswitch_interfaces::{ ExternalVault, ExternalVaultCreate, ExternalVaultDelete, ExternalVaultInsert, ExternalVaultRetrieve, }, - ConnectorIntegration, ConnectorMandateRevoke, ConnectorRedirectResponse, - ConnectorTransactionId, UasAuthentication, UasAuthenticationConfirmation, - UasPostAuthentication, UasPreAuthentication, UnifiedAuthenticationService, + ConnectorAuthenticationToken, ConnectorIntegration, ConnectorMandateRevoke, + ConnectorRedirectResponse, ConnectorTransactionId, UasAuthentication, + UasAuthenticationConfirmation, UasPostAuthentication, UasPreAuthentication, + UnifiedAuthenticationService, }, errors::ConnectorError, }; @@ -1703,7 +1707,6 @@ default_imp_for_pre_processing_steps!( connectors::Netcetera, connectors::Nomupay, connectors::Noon, - connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Opayo, @@ -7499,6 +7502,146 @@ default_imp_for_external_vault_create!( connectors::Zsl ); +macro_rules! default_imp_for_connector_authentication_token { + ($($path:ident::$connector:ident),*) => { + $( + impl ConnectorAuthenticationToken for $path::$connector {} + impl + ConnectorIntegration< + AccessTokenAuthentication, + AccessTokenAuthenticationRequestData, + AccessTokenAuthenticationResponse, + > for $path::$connector + {} + )* + }; +} + +default_imp_for_connector_authentication_token!( + connectors::Aci, + connectors::Adyen, + connectors::Adyenplatform, + connectors::Affirm, + connectors::Airwallex, + connectors::Amazonpay, + connectors::Archipel, + connectors::Authipay, + connectors::Authorizedotnet, + connectors::Barclaycard, + connectors::Bambora, + connectors::Bamboraapac, + connectors::Bankofamerica, + connectors::Billwerk, + connectors::Bitpay, + connectors::Bluecode, + connectors::Bluesnap, + connectors::Blackhawknetwork, + connectors::Boku, + connectors::Braintree, + connectors::Breadpay, + connectors::Cashtocode, + connectors::Celero, + connectors::Chargebee, + connectors::Checkbook, + connectors::Checkout, + connectors::Coinbase, + connectors::Coingate, + connectors::Cryptopay, + connectors::CtpMastercard, + connectors::Custombilling, + connectors::Cybersource, + connectors::Datatrans, + connectors::Deutschebank, + connectors::Digitalvirgo, + connectors::Dlocal, + connectors::Dwolla, + connectors::Ebanx, + connectors::Elavon, + connectors::Facilitapay, + connectors::Fiserv, + connectors::Fiservemea, + connectors::Fiuu, + connectors::Flexiti, + connectors::Forte, + connectors::Getnet, + connectors::Globalpay, + connectors::Globepay, + connectors::Gocardless, + connectors::Gpayments, + connectors::Helcim, + connectors::Hipay, + connectors::HyperswitchVault, + connectors::Iatapay, + connectors::Inespay, + connectors::Itaubank, + connectors::Juspaythreedsserver, + connectors::Jpmorgan, + connectors::Katapult, + connectors::Klarna, + connectors::Mpgs, + connectors::Netcetera, + connectors::Nomupay, + connectors::Nmi, + connectors::Noon, + connectors::Novalnet, + connectors::Nexinets, + connectors::Nexixpay, + connectors::Nuvei, + connectors::Opayo, + connectors::Opennode, + connectors::Payeezy, + connectors::Payload, + connectors::Paystack, + connectors::Paytm, + connectors::Payu, + connectors::Phonepe, + connectors::Paypal, + connectors::Plaid, + connectors::Powertranz, + connectors::Prophetpay, + connectors::Mifinity, + connectors::Mollie, + connectors::Moneris, + connectors::Multisafepay, + connectors::Paybox, + connectors::Payme, + connectors::Payone, + connectors::Placetopay, + connectors::Rapyd, + connectors::Razorpay, + connectors::Recurly, + connectors::Redsys, + connectors::Riskified, + connectors::Santander, + connectors::Sift, + connectors::Signifyd, + connectors::Shift4, + connectors::Silverflow, + connectors::Stax, + connectors::Stripe, + connectors::Stripebilling, + connectors::Square, + connectors::Taxjar, + connectors::Threedsecureio, + connectors::Thunes, + connectors::Tokenio, + connectors::Trustpay, + connectors::Trustpayments, + connectors::Tsys, + connectors::UnifiedAuthenticationService, + connectors::Wise, + connectors::Worldline, + connectors::Worldpay, + connectors::Worldpayvantiv, + connectors::Worldpayxml, + connectors::Wellsfargo, + connectors::Vgs, + connectors::Volt, + connectors::Xendit, + connectors::Zen, + connectors::Zsl +); + #[cfg(feature = "dummy_connector")] impl<const T: u8> PaymentsCompleteAuthorize for connectors::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] @@ -8026,3 +8169,15 @@ impl<const T: u8> ConnectorIntegration<ExternalVaultCreateFlow, VaultRequestData for connectors::DummyConnector<T> { } + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> ConnectorAuthenticationToken for connectors::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + ConnectorIntegration< + AccessTokenAuthentication, + AccessTokenAuthenticationRequestData, + AccessTokenAuthenticationResponse, + > for connectors::DummyConnector<T> +{ +} diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index 69166f3e01f..046aba87b0a 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -1,12 +1,13 @@ use hyperswitch_domain_models::{ - router_data::AccessToken, + router_data::{AccessToken, AccessTokenAuthenticationResponse}, router_data_v2::{ flow_common_types::{ BillingConnectorInvoiceSyncFlowData, BillingConnectorPaymentsSyncFlowData, DisputesFlowData, MandateRevokeFlowData, PaymentFlowData, RefundFlowData, RevenueRecoveryRecordBackData, WebhookSourceVerifyData, }, - AccessTokenFlowData, ExternalAuthenticationFlowData, FilesFlowData, VaultConnectorFlowData, + AccessTokenFlowData, AuthenticationTokenFlowData, ExternalAuthenticationFlowData, + FilesFlowData, VaultConnectorFlowData, }, router_flow_types::{ authentication::{ @@ -26,8 +27,8 @@ use hyperswitch_domain_models::{ BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, RecoveryRecordBack, }, webhooks::VerifyWebhookSource, - AccessTokenAuth, ExternalVaultCreateFlow, ExternalVaultDeleteFlow, ExternalVaultInsertFlow, - ExternalVaultRetrieveFlow, + AccessTokenAuth, AccessTokenAuthentication, ExternalVaultCreateFlow, + ExternalVaultDeleteFlow, ExternalVaultInsertFlow, ExternalVaultRetrieveFlow, }, router_request_types::{ authentication, @@ -35,14 +36,14 @@ use hyperswitch_domain_models::{ BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest, RevenueRecoveryRecordBackRequest, }, - AcceptDisputeRequestData, AccessTokenRequestData, AuthorizeSessionTokenData, - CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData, - DefendDisputeRequestData, DisputeSyncData, FetchDisputesRequestData, - MandateRevokeRequestData, PaymentMethodTokenizationData, PaymentsApproveData, - PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData, - PaymentsCaptureData, PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData, - PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsRejectData, - PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, + AcceptDisputeRequestData, AccessTokenAuthenticationRequestData, AccessTokenRequestData, + AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, + CreateOrderRequestData, DefendDisputeRequestData, DisputeSyncData, + FetchDisputesRequestData, MandateRevokeRequestData, PaymentMethodTokenizationData, + PaymentsApproveData, PaymentsAuthorizeData, PaymentsCancelData, + PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData, + PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreProcessingData, + PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RefundsData, RetrieveFileRequestData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, SubmitEvidenceRequestData, UploadFileRequestData, VaultRequestData, VerifyWebhookSourceRequestData, @@ -118,7 +119,8 @@ use hyperswitch_interfaces::{ ExternalVaultCreateV2, ExternalVaultDeleteV2, ExternalVaultInsertV2, ExternalVaultRetrieveV2, ExternalVaultV2, }, - ConnectorAccessTokenV2, ConnectorMandateRevokeV2, ConnectorVerifyWebhookSourceV2, + ConnectorAccessTokenV2, ConnectorAuthenticationTokenV2, ConnectorMandateRevokeV2, + ConnectorVerifyWebhookSourceV2, }, connector_integration_v2::ConnectorIntegrationV2, }; @@ -524,6 +526,136 @@ default_imp_for_new_connector_integration_refund!( connectors::Zsl ); +macro_rules! default_imp_for_new_connector_integration_connector_authentication_token { + ($($path:ident::$connector:ident),*) => { + $( + impl ConnectorAuthenticationTokenV2 for $path::$connector{} + impl + ConnectorIntegrationV2<AccessTokenAuthentication, AuthenticationTokenFlowData, AccessTokenAuthenticationRequestData, AccessTokenAuthenticationResponse,> + for $path::$connector{} + )* + }; +} + +default_imp_for_new_connector_integration_connector_authentication_token!( + connectors::Vgs, + connectors::Aci, + connectors::Adyen, + connectors::Adyenplatform, + connectors::Affirm, + connectors::Airwallex, + connectors::Amazonpay, + connectors::Authipay, + connectors::Authorizedotnet, + connectors::Bambora, + connectors::Bamboraapac, + connectors::Bankofamerica, + connectors::Barclaycard, + connectors::Billwerk, + connectors::Bitpay, + connectors::Blackhawknetwork, + connectors::Bluesnap, + connectors::Boku, + connectors::Braintree, + connectors::Breadpay, + connectors::Cashtocode, + connectors::Celero, + connectors::Chargebee, + connectors::Checkbook, + connectors::Checkout, + connectors::Coinbase, + connectors::Coingate, + connectors::Cryptopay, + connectors::CtpMastercard, + connectors::Custombilling, + connectors::Cybersource, + connectors::Datatrans, + connectors::Deutschebank, + connectors::Digitalvirgo, + connectors::Dlocal, + connectors::Dwolla, + connectors::Ebanx, + connectors::Elavon, + connectors::Facilitapay, + connectors::Fiserv, + connectors::Fiservemea, + connectors::Fiuu, + connectors::Forte, + connectors::Getnet, + connectors::Globalpay, + connectors::Globepay, + connectors::Gocardless, + connectors::Gpayments, + connectors::Hipay, + connectors::Helcim, + connectors::HyperswitchVault, + connectors::Iatapay, + connectors::Inespay, + connectors::Itaubank, + connectors::Jpmorgan, + connectors::Juspaythreedsserver, + connectors::Klarna, + connectors::Nomupay, + connectors::Noon, + connectors::Nordea, + connectors::Novalnet, + connectors::Netcetera, + connectors::Nexinets, + connectors::Nexixpay, + connectors::Nmi, + connectors::Payone, + connectors::Opayo, + connectors::Opennode, + connectors::Nuvei, + connectors::Paybox, + connectors::Payeezy, + connectors::Payload, + connectors::Payme, + connectors::Paypal, + connectors::Paystack, + connectors::Payu, + connectors::Placetopay, + connectors::Plaid, + connectors::Powertranz, + connectors::Prophetpay, + connectors::Mifinity, + connectors::Mollie, + connectors::Moneris, + connectors::Multisafepay, + connectors::Rapyd, + connectors::Razorpay, + connectors::Recurly, + connectors::Redsys, + connectors::Riskified, + connectors::Santander, + connectors::Shift4, + connectors::Sift, + connectors::Silverflow, + connectors::Signifyd, + connectors::Stax, + connectors::Stripe, + connectors::Square, + connectors::Stripebilling, + connectors::Taxjar, + connectors::Threedsecureio, + connectors::Thunes, + connectors::Tokenio, + connectors::Trustpay, + connectors::Tsys, + connectors::UnifiedAuthenticationService, + connectors::Wise, + connectors::Worldline, + connectors::Volt, + connectors::Worldpay, + connectors::Worldpayvantiv, + connectors::Worldpayxml, + connectors::Wellsfargo, + connectors::Wellsfargopayout, + connectors::Xendit, + connectors::Zen, + connectors::Zsl +); + macro_rules! default_imp_for_new_connector_integration_connector_access_token { ($($path:ident::$connector:ident),*) => { $( diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index 13998ed6612..743c04aad72 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -1696,6 +1696,7 @@ pub trait PaymentsAuthorizeRequestData { fn get_connector_mandate_id(&self) -> Result<String, Error>; fn get_complete_authorize_url(&self) -> Result<String, Error>; fn get_ip_address_as_optional(&self) -> Option<Secret<String, IpAddress>>; + fn get_ip_address(&self) -> Result<Secret<String, IpAddress>, Error>; fn get_optional_user_agent(&self) -> Option<String>; fn get_original_amount(&self) -> i64; fn get_surcharge_amount(&self) -> Option<i64>; @@ -1818,6 +1819,16 @@ impl PaymentsAuthorizeRequestData for PaymentsAuthorizeData { .map(|ip| Secret::new(ip.to_string())) }) } + fn get_ip_address(&self) -> Result<Secret<String, IpAddress>, Error> { + let ip_address = self + .browser_info + .clone() + .and_then(|browser_info| browser_info.ip_address); + + let val = ip_address.ok_or_else(missing_field_err("browser_info.ip_address"))?; + + Ok(Secret::new(val.to_string())) + } fn get_optional_user_agent(&self) -> Option<String> { self.browser_info .clone() diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs index f8613275034..d3b6883571e 100644 --- a/crates/hyperswitch_domain_models/src/router_data.rs +++ b/crates/hyperswitch_domain_models/src/router_data.rs @@ -258,6 +258,12 @@ impl ConnectorAuthType { } } +#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)] +pub struct AccessTokenAuthenticationResponse { + pub code: Secret<String>, + pub expires: i64, +} + #[derive(serde::Deserialize, serde::Serialize, Debug, Clone)] pub struct AccessToken { pub token: Secret<String>, diff --git a/crates/hyperswitch_domain_models/src/router_data_v2.rs b/crates/hyperswitch_domain_models/src/router_data_v2.rs index d6498c962ef..60b6070da0d 100644 --- a/crates/hyperswitch_domain_models/src/router_data_v2.rs +++ b/crates/hyperswitch_domain_models/src/router_data_v2.rs @@ -8,9 +8,9 @@ pub use flow_common_types::FrmFlowData; #[cfg(feature = "payouts")] pub use flow_common_types::PayoutFlowData; pub use flow_common_types::{ - AccessTokenFlowData, DisputesFlowData, ExternalAuthenticationFlowData, FilesFlowData, - MandateRevokeFlowData, PaymentFlowData, RefundFlowData, UasFlowData, VaultConnectorFlowData, - WebhookSourceVerifyData, + AccessTokenFlowData, AuthenticationTokenFlowData, DisputesFlowData, + ExternalAuthenticationFlowData, FilesFlowData, MandateRevokeFlowData, PaymentFlowData, + RefundFlowData, UasFlowData, VaultConnectorFlowData, WebhookSourceVerifyData, }; use crate::router_data::{ConnectorAuthType, ErrorResponse}; diff --git a/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs b/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs index 5bc18dc8af2..3fe6e85bdab 100644 --- a/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs +++ b/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs @@ -132,6 +132,9 @@ pub struct WebhookSourceVerifyData { pub merchant_id: common_utils::id_type::MerchantId, } +#[derive(Debug, Clone)] +pub struct AuthenticationTokenFlowData {} + #[derive(Debug, Clone)] pub struct AccessTokenFlowData {} diff --git a/crates/hyperswitch_domain_models/src/router_flow_types/access_token_auth.rs b/crates/hyperswitch_domain_models/src/router_flow_types/access_token_auth.rs index dd45ca9ca37..66c940e5ec2 100644 --- a/crates/hyperswitch_domain_models/src/router_flow_types/access_token_auth.rs +++ b/crates/hyperswitch_domain_models/src/router_flow_types/access_token_auth.rs @@ -1,2 +1,5 @@ +#[derive(Clone, Debug)] +pub struct AccessTokenAuthentication; + #[derive(Clone, Debug)] pub struct AccessTokenAuth; diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index 8d1bf9ffaa5..142d2633fcc 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -16,7 +16,7 @@ use crate::{ address, errors::api_error_response::ApiErrorResponse, mandates, payments, - router_data::{self, RouterData}, + router_data::{self, AccessTokenAuthenticationResponse, RouterData}, router_flow_types as flows, router_response_types as response_types, vault::PaymentMethodVaultingData, }; @@ -813,13 +813,29 @@ pub struct DestinationChargeRefund { pub revert_transfer: bool, } +#[derive(Debug, Clone)] +pub struct AccessTokenAuthenticationRequestData { + pub auth_creds: router_data::ConnectorAuthType, +} + +impl TryFrom<router_data::ConnectorAuthType> for AccessTokenAuthenticationRequestData { + type Error = ApiErrorResponse; + fn try_from(connector_auth: router_data::ConnectorAuthType) -> Result<Self, Self::Error> { + Ok(Self { + auth_creds: connector_auth, + }) + } +} + #[derive(Debug, Clone)] pub struct AccessTokenRequestData { pub app_id: Secret<String>, pub id: Option<Secret<String>>, + pub authentication_token: Option<AccessTokenAuthenticationResponse>, // Add more keys if required } +// This is for backward compatibility impl TryFrom<router_data::ConnectorAuthType> for AccessTokenRequestData { type Error = ApiErrorResponse; fn try_from(connector_auth: router_data::ConnectorAuthType) -> Result<Self, Self::Error> { @@ -827,18 +843,22 @@ impl TryFrom<router_data::ConnectorAuthType> for AccessTokenRequestData { router_data::ConnectorAuthType::HeaderKey { api_key } => Ok(Self { app_id: api_key, id: None, + authentication_token: None, }), router_data::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { app_id: api_key, id: Some(key1), + authentication_token: None, }), router_data::ConnectorAuthType::SignatureKey { api_key, key1, .. } => Ok(Self { app_id: api_key, id: Some(key1), + authentication_token: None, }), router_data::ConnectorAuthType::MultiAuthKey { api_key, key1, .. } => Ok(Self { app_id: api_key, id: Some(key1), + authentication_token: None, }), _ => Err(ApiErrorResponse::InvalidDataValue { @@ -848,6 +868,25 @@ impl TryFrom<router_data::ConnectorAuthType> for AccessTokenRequestData { } } +impl + TryFrom<( + router_data::ConnectorAuthType, + Option<AccessTokenAuthenticationResponse>, + )> for AccessTokenRequestData +{ + type Error = ApiErrorResponse; + fn try_from( + (connector_auth, authentication_token): ( + router_data::ConnectorAuthType, + Option<AccessTokenAuthenticationResponse>, + ), + ) -> Result<Self, Self::Error> { + let mut access_token_request_data = Self::try_from(connector_auth)?; + access_token_request_data.authentication_token = authentication_token; + Ok(access_token_request_data) + } +} + #[derive(Default, Debug, Clone)] pub struct AcceptDisputeRequestData { pub dispute_id: String, diff --git a/crates/hyperswitch_domain_models/src/types.rs b/crates/hyperswitch_domain_models/src/types.rs index 2dc507cf200..6036bdcca58 100644 --- a/crates/hyperswitch_domain_models/src/types.rs +++ b/crates/hyperswitch_domain_models/src/types.rs @@ -1,16 +1,16 @@ pub use diesel_models::types::OrderDetailsWithAmount; use crate::{ - router_data::{AccessToken, RouterData}, + router_data::{AccessToken, AccessTokenAuthenticationResponse, RouterData}, router_data_v2::{self, RouterDataV2}, router_flow_types::{ mandate_revoke::MandateRevoke, revenue_recovery::RecoveryRecordBack, AccessTokenAuth, - Authenticate, AuthenticationConfirmation, Authorize, AuthorizeSessionToken, - BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, CalculateTax, Capture, - CompleteAuthorize, CreateConnectorCustomer, CreateOrder, Execute, IncrementalAuthorization, - PSync, PaymentMethodToken, PostAuthenticate, PostCaptureVoid, PostSessionTokens, - PreAuthenticate, PreProcessing, RSync, SdkSessionUpdate, Session, SetupMandate, - UpdateMetadata, VerifyWebhookSource, Void, + AccessTokenAuthentication, Authenticate, AuthenticationConfirmation, Authorize, + AuthorizeSessionToken, BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, + CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, CreateOrder, Execute, + IncrementalAuthorization, PSync, PaymentMethodToken, PostAuthenticate, PostCaptureVoid, + PostSessionTokens, PreAuthenticate, PreProcessing, RSync, SdkSessionUpdate, Session, + SetupMandate, UpdateMetadata, VerifyWebhookSource, Void, }, router_request_types::{ revenue_recovery::{ @@ -22,12 +22,13 @@ use crate::{ UasConfirmationRequestData, UasPostAuthenticationRequestData, UasPreAuthenticationRequestData, }, - AccessTokenRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData, - ConnectorCustomerData, CreateOrderRequestData, MandateRevokeRequestData, - PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, - PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData, - PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsSessionData, - PaymentsSyncData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RefundsData, + AccessTokenAuthenticationRequestData, AccessTokenRequestData, AuthorizeSessionTokenData, + CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData, + MandateRevokeRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData, + PaymentsIncrementalAuthorizationData, PaymentsPostSessionTokensData, + PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, + PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RefundsData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, VaultRequestData, VerifyWebhookSourceRequestData, }, @@ -67,6 +68,11 @@ pub type PaymentsCompleteAuthorizeRouterData = RouterData<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>; pub type PaymentsTaxCalculationRouterData = RouterData<CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData>; +pub type AccessTokenAuthenticationRouterData = RouterData< + AccessTokenAuthentication, + AccessTokenAuthenticationRequestData, + AccessTokenAuthenticationResponse, +>; pub type RefreshTokenRouterData = RouterData<AccessTokenAuth, AccessTokenRequestData, AccessToken>; pub type PaymentsPostSessionTokensRouterData = RouterData<PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData>; diff --git a/crates/hyperswitch_interfaces/src/api.rs b/crates/hyperswitch_interfaces/src/api.rs index 70d1bc2c1b6..6efc23c3c3d 100644 --- a/crates/hyperswitch_interfaces/src/api.rs +++ b/crates/hyperswitch_interfaces/src/api.rs @@ -40,14 +40,17 @@ use hyperswitch_domain_models::{ connector_endpoints::Connectors, errors::api_error_response::ApiErrorResponse, payment_method_data::PaymentMethodData, - router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, + router_data::{ + AccessToken, AccessTokenAuthenticationResponse, ConnectorAuthType, ErrorResponse, + RouterData, + }, router_data_v2::{ - flow_common_types::WebhookSourceVerifyData, AccessTokenFlowData, MandateRevokeFlowData, - UasFlowData, + flow_common_types::{AuthenticationTokenFlowData, WebhookSourceVerifyData}, + AccessTokenFlowData, MandateRevokeFlowData, UasFlowData, }, router_flow_types::{ - mandate_revoke::MandateRevoke, AccessTokenAuth, Authenticate, AuthenticationConfirmation, - PostAuthenticate, PreAuthenticate, VerifyWebhookSource, + mandate_revoke::MandateRevoke, AccessTokenAuth, AccessTokenAuthentication, Authenticate, + AuthenticationConfirmation, PostAuthenticate, PreAuthenticate, VerifyWebhookSource, }, router_request_types::{ unified_authentication_service::{ @@ -55,7 +58,8 @@ use hyperswitch_domain_models::{ UasConfirmationRequestData, UasPostAuthenticationRequestData, UasPreAuthenticationRequestData, }, - AccessTokenRequestData, MandateRevokeRequestData, VerifyWebhookSourceRequestData, + AccessTokenAuthenticationRequestData, AccessTokenRequestData, MandateRevokeRequestData, + VerifyWebhookSourceRequestData, }, router_response_types::{ ConnectorInfo, MandateRevokeResponseData, PaymentMethodDetails, SupportedPaymentMethods, @@ -87,6 +91,7 @@ pub trait Connector: + ConnectorRedirectResponse + webhooks::IncomingWebhook + ConnectorAccessToken + + ConnectorAuthenticationToken + disputes::Dispute + files::FileUpload + ConnectorTransactionId @@ -109,6 +114,7 @@ impl< + Send + webhooks::IncomingWebhook + ConnectorAccessToken + + ConnectorAuthenticationToken + disputes::Dispute + files::FileUpload + ConnectorTransactionId @@ -383,6 +389,12 @@ pub trait ConnectorSpecifications { None } + /// Check if connector should make another request to create an access token + /// Connectors should override this method if they require an authentication token to create a new access token + fn authentication_token_for_token_creation(&self) -> bool { + false + } + #[cfg(not(feature = "v2"))] /// Generate connector request reference ID fn generate_connector_request_reference_id( @@ -445,6 +457,27 @@ pub trait ConnectorMandateRevokeV2: { } +/// trait ConnectorAuthenticationToken +pub trait ConnectorAuthenticationToken: + ConnectorIntegration< + AccessTokenAuthentication, + AccessTokenAuthenticationRequestData, + AccessTokenAuthenticationResponse, +> +{ +} + +/// trait ConnectorAuthenticationTokenV2 +pub trait ConnectorAuthenticationTokenV2: + ConnectorIntegrationV2< + AccessTokenAuthentication, + AuthenticationTokenFlowData, + AccessTokenAuthenticationRequestData, + AccessTokenAuthenticationResponse, +> +{ +} + /// trait ConnectorAccessToken pub trait ConnectorAccessToken: ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> diff --git a/crates/hyperswitch_interfaces/src/connector_integration_interface.rs b/crates/hyperswitch_interfaces/src/connector_integration_interface.rs index c40c65ac5f7..66a1e291756 100644 --- a/crates/hyperswitch_interfaces/src/connector_integration_interface.rs +++ b/crates/hyperswitch_interfaces/src/connector_integration_interface.rs @@ -519,6 +519,14 @@ impl ConnectorSpecifications for ConnectorEnum { } } + /// Check if connector supports authentication token + fn authentication_token_for_token_creation(&self) -> bool { + match self { + Self::Old(connector) => connector.authentication_token_for_token_creation(), + Self::New(connector) => connector.authentication_token_for_token_creation(), + } + } + #[cfg(feature = "v1")] fn generate_connector_request_reference_id( &self, diff --git a/crates/hyperswitch_interfaces/src/connector_integration_v2.rs b/crates/hyperswitch_interfaces/src/connector_integration_v2.rs index d51320ebbff..999770b65cb 100644 --- a/crates/hyperswitch_interfaces/src/connector_integration_v2.rs +++ b/crates/hyperswitch_interfaces/src/connector_integration_v2.rs @@ -22,6 +22,7 @@ pub trait ConnectorV2: + api::payments_v2::PaymentV2 + api::ConnectorRedirectResponse + webhooks::IncomingWebhook + + api::ConnectorAuthenticationTokenV2 + api::ConnectorAccessTokenV2 + api::disputes_v2::DisputeV2 + api::files_v2::FileUploadV2 @@ -42,6 +43,7 @@ impl< + api::ConnectorRedirectResponse + Send + webhooks::IncomingWebhook + + api::ConnectorAuthenticationTokenV2 + api::ConnectorAccessTokenV2 + api::disputes_v2::DisputeV2 + api::files_v2::FileUploadV2 diff --git a/crates/hyperswitch_interfaces/src/conversion_impls.rs b/crates/hyperswitch_interfaces/src/conversion_impls.rs index 633a7172be2..d70b8e882af 100644 --- a/crates/hyperswitch_interfaces/src/conversion_impls.rs +++ b/crates/hyperswitch_interfaces/src/conversion_impls.rs @@ -9,7 +9,7 @@ use hyperswitch_domain_models::{ router_data::{self, RouterData}, router_data_v2::{ flow_common_types::{ - AccessTokenFlowData, BillingConnectorInvoiceSyncFlowData, + AccessTokenFlowData, AuthenticationTokenFlowData, BillingConnectorInvoiceSyncFlowData, BillingConnectorPaymentsSyncFlowData, DisputesFlowData, ExternalAuthenticationFlowData, FilesFlowData, MandateRevokeFlowData, PaymentFlowData, RefundFlowData, RevenueRecoveryRecordBackData, UasFlowData, VaultConnectorFlowData, @@ -91,6 +91,45 @@ fn get_default_router_data<F, Req, Resp>( } } +impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> + for AuthenticationTokenFlowData +{ + fn from_old_router_data( + old_router_data: &RouterData<T, Req, Resp>, + ) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError> + where + Self: Sized, + { + let resource_common_data = Self {}; + Ok(RouterDataV2 { + flow: std::marker::PhantomData, + tenant_id: old_router_data.tenant_id.clone(), + resource_common_data, + connector_auth_type: old_router_data.connector_auth_type.clone(), + request: old_router_data.request.clone(), + response: old_router_data.response.clone(), + }) + } + + fn to_old_router_data( + new_router_data: RouterDataV2<T, Self, Req, Resp>, + ) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError> + where + Self: Sized, + { + let Self {} = new_router_data.resource_common_data; + let request = new_router_data.request.clone(); + let response = new_router_data.response.clone(); + let router_data = get_default_router_data( + new_router_data.tenant_id.clone(), + "authentication token", + request, + response, + ); + Ok(router_data) + } +} + impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for AccessTokenFlowData { fn from_old_router_data( old_router_data: &RouterData<T, Req, Resp>, diff --git a/crates/hyperswitch_interfaces/src/types.rs b/crates/hyperswitch_interfaces/src/types.rs index 04053546c93..eed89fe00ba 100644 --- a/crates/hyperswitch_interfaces/src/types.rs +++ b/crates/hyperswitch_interfaces/src/types.rs @@ -1,7 +1,7 @@ //! Types interface use hyperswitch_domain_models::{ - router_data::AccessToken, + router_data::{AccessToken, AccessTokenAuthenticationResponse}, router_data_v2::flow_common_types, router_flow_types::{ access_token_auth::AccessTokenAuth, @@ -24,7 +24,7 @@ use hyperswitch_domain_models::{ ExternalVaultRetrieveFlow, }, webhooks::VerifyWebhookSource, - BillingConnectorInvoiceSync, + AccessTokenAuthentication, BillingConnectorInvoiceSync, }, router_request_types::{ revenue_recovery::{ @@ -36,12 +36,12 @@ use hyperswitch_domain_models::{ UasConfirmationRequestData, UasPostAuthenticationRequestData, UasPreAuthenticationRequestData, }, - AcceptDisputeRequestData, AccessTokenRequestData, AuthorizeSessionTokenData, - CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData, - DefendDisputeRequestData, DisputeSyncData, FetchDisputesRequestData, - MandateRevokeRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, - PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData, - PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData, + AcceptDisputeRequestData, AccessTokenAuthenticationRequestData, AccessTokenRequestData, + AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, + CreateOrderRequestData, DefendDisputeRequestData, DisputeSyncData, + FetchDisputesRequestData, MandateRevokeRequestData, PaymentMethodTokenizationData, + PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData, + PaymentsCaptureData, PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RefundsData, RetrieveFileRequestData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, @@ -193,6 +193,12 @@ pub type PayoutQuoteType = dyn ConnectorIntegration<PoQuote, PayoutsData, Payout /// Type alias for `ConnectorIntegration<PoSync, PayoutsData, PayoutsResponseData>` #[cfg(feature = "payouts")] pub type PayoutSyncType = dyn ConnectorIntegration<PoSync, PayoutsData, PayoutsResponseData>; +/// Type alias for `ConnectorIntegration<AccessTokenAuthentication, AccessTokenAuthenticationRequestData, AccessTokenAuthenticationResponse>` +pub type AuthenticationTokenType = dyn ConnectorIntegration< + AccessTokenAuthentication, + AccessTokenAuthenticationRequestData, + AccessTokenAuthenticationResponse, +>; /// Type alias for `ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>` pub type RefreshTokenType = dyn ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>; diff --git a/crates/payment_methods/src/configs/payment_connector_required_fields.rs b/crates/payment_methods/src/configs/payment_connector_required_fields.rs index 8e67724d68d..57b6e94cbba 100644 --- a/crates/payment_methods/src/configs/payment_connector_required_fields.rs +++ b/crates/payment_methods/src/configs/payment_connector_required_fields.rs @@ -3210,6 +3210,19 @@ fn get_bank_debit_required_fields() -> HashMap<enums::PaymentMethodType, Connect Connector::Inespay, fields(vec![], vec![], vec![RequiredField::SepaBankDebitIban]), ), + ( + Connector::Nordea, + RequiredFieldFinal { + mandate: HashMap::new(), + + non_mandate: HashMap::new(), + + common: HashMap::from([ + RequiredField::BillingAddressCountries(vec!["DK,FI,NO,SE"]).to_tuple(), + RequiredField::SepaBankDebitIban.to_tuple(), + ]), + }, + ), ]), ), ( diff --git a/crates/router/src/core/connector_validation.rs b/crates/router/src/core/connector_validation.rs index b9019d9cf3d..874f778017b 100644 --- a/crates/router/src/core/connector_validation.rs +++ b/crates/router/src/core/connector_validation.rs @@ -349,10 +349,10 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> { noon::transformers::NoonAuthType::try_from(self.auth_type)?; Ok(()) } - // api_enums::Connector::Nordea => { - // nordea::transformers::NordeaAuthType::try_from(self.auth_type)?; - // Ok(()) - // } + api_enums::Connector::Nordea => { + nordea::transformers::NordeaAuthType::try_from(self.auth_type)?; + Ok(()) + } api_enums::Connector::Novalnet => { novalnet::transformers::NovalnetAuthType::try_from(self.auth_type)?; Ok(()) diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index ee7aa40496b..e5604e5afbc 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -6113,7 +6113,9 @@ where } } Some(domain::PaymentMethodData::BankDebit(_)) => { - if connector.connector_name == router_types::Connector::Gocardless { + if connector.connector_name == router_types::Connector::Gocardless + || connector.connector_name == router_types::Connector::Nordea + { router_data = router_data.preprocessing_steps(state, connector).await?; let is_error_in_response = router_data.response.is_err(); // If is_error_in_response is true, should_continue_payment should be false, we should throw the error diff --git a/crates/router/src/core/payments/access_token.rs b/crates/router/src/core/payments/access_token.rs index f2f75964914..cf49d65b138 100644 --- a/crates/router/src/core/payments/access_token.rs +++ b/crates/router/src/core/payments/access_token.rs @@ -2,6 +2,7 @@ use std::fmt::Debug; use common_utils::ext_traits::AsyncExt; use error_stack::ResultExt; +use hyperswitch_interfaces::api::ConnectorSpecifications; use crate::{ consts, @@ -112,10 +113,15 @@ pub async fn add_access_token< )), ); + let authentication_token = + execute_authentication_token(state, connector, router_data).await?; + let cloned_router_data = router_data.clone(); - let refresh_token_request_data = types::AccessTokenRequestData::try_from( + + let refresh_token_request_data = types::AccessTokenRequestData::try_from(( router_data.connector_auth_type.clone(), - ) + authentication_token, + )) .attach_printable( "Could not create access token request, invalid connector account credentials", )?; @@ -254,3 +260,93 @@ pub async fn refresh_connector_auth( ); Ok(access_token_router_data) } + +pub async fn execute_authentication_token< + F: Clone + 'static, + Req: Debug + Clone + 'static, + Res: Debug + Clone + 'static, +>( + state: &SessionState, + connector: &api_types::ConnectorData, + router_data: &types::RouterData<F, Req, Res>, +) -> RouterResult<Option<types::AccessTokenAuthenticationResponse>> { + let should_create_authentication_token = connector + .connector + .authentication_token_for_token_creation(); + + if !should_create_authentication_token { + return Ok(None); + } + + let authentication_token_request_data = types::AccessTokenAuthenticationRequestData::try_from( + router_data.connector_auth_type.clone(), + ) + .attach_printable( + "Could not create authentication token request, invalid connector account credentials", + )?; + + let authentication_token_response_data: Result< + types::AccessTokenAuthenticationResponse, + types::ErrorResponse, + > = Err(types::ErrorResponse::default()); + + let auth_token_router_data = payments::helpers::router_data_type_conversion::< + _, + api_types::AccessTokenAuthentication, + _, + _, + _, + _, + >( + router_data.clone(), + authentication_token_request_data, + authentication_token_response_data, + ); + + let connector_integration: services::BoxedAuthenticationTokenConnectorIntegrationInterface< + api_types::AccessTokenAuthentication, + types::AccessTokenAuthenticationRequestData, + types::AccessTokenAuthenticationResponse, + > = connector.connector.get_connector_integration(); + + let auth_token_router_data_result = services::execute_connector_processing_step( + state, + connector_integration, + &auth_token_router_data, + payments::CallConnectorAction::Trigger, + None, + None, + ) + .await; + + let auth_token_result = match auth_token_router_data_result { + Ok(router_data) => router_data.response, + Err(connector_error) => { + // Handle timeout errors + if connector_error.current_context().is_connector_timeout() { + let error_response = types::ErrorResponse { + code: consts::REQUEST_TIMEOUT_ERROR_CODE.to_string(), + message: consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string(), + reason: Some(consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string()), + status_code: 504, + attempt_status: None, + connector_transaction_id: None, + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + }; + Err(error_response) + } else { + return Err(connector_error + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Could not get authentication token")); + } + } + }; + + let authentication_token = auth_token_result + .map_err(|_error| errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get authentication token")?; + + Ok(Some(authentication_token)) +} diff --git a/crates/router/src/core/payments/flows/approve_flow.rs b/crates/router/src/core/payments/flows/approve_flow.rs index 296b081db6a..4008e0debe5 100644 --- a/crates/router/src/core/payments/flows/approve_flow.rs +++ b/crates/router/src/core/payments/flows/approve_flow.rs @@ -85,8 +85,14 @@ impl Feature<api::Approve, types::PaymentsApproveData> merchant_context: &domain::MerchantContext, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> { - access_token::add_access_token(state, connector, merchant_context, self, creds_identifier) - .await + Box::pin(access_token::add_access_token( + state, + connector, + merchant_context, + self, + creds_identifier, + )) + .await } async fn build_flow_specific_connector_request( diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 2aa69e6a36b..a51912e5662 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -248,8 +248,14 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu merchant_context: &domain::MerchantContext, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> { - access_token::add_access_token(state, connector, merchant_context, self, creds_identifier) - .await + Box::pin(access_token::add_access_token( + state, + connector, + merchant_context, + self, + creds_identifier, + )) + .await } async fn add_session_token<'a>( diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rs index 7f025f81c85..a452a165c7d 100644 --- a/crates/router/src/core/payments/flows/cancel_flow.rs +++ b/crates/router/src/core/payments/flows/cancel_flow.rs @@ -103,8 +103,14 @@ impl Feature<api::Void, types::PaymentsCancelData> merchant_context: &domain::MerchantContext, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> { - access_token::add_access_token(state, connector, merchant_context, self, creds_identifier) - .await + Box::pin(access_token::add_access_token( + state, + connector, + merchant_context, + self, + creds_identifier, + )) + .await } async fn build_flow_specific_connector_request( diff --git a/crates/router/src/core/payments/flows/cancel_post_capture_flow.rs b/crates/router/src/core/payments/flows/cancel_post_capture_flow.rs index 67ccd612a9d..5b4625c8478 100644 --- a/crates/router/src/core/payments/flows/cancel_post_capture_flow.rs +++ b/crates/router/src/core/payments/flows/cancel_post_capture_flow.rs @@ -111,8 +111,14 @@ impl Feature<api::PostCaptureVoid, types::PaymentsCancelPostCaptureData> merchant_context: &domain::MerchantContext, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> { - access_token::add_access_token(state, connector, merchant_context, self, creds_identifier) - .await + Box::pin(access_token::add_access_token( + state, + connector, + merchant_context, + self, + creds_identifier, + )) + .await } async fn build_flow_specific_connector_request( diff --git a/crates/router/src/core/payments/flows/capture_flow.rs b/crates/router/src/core/payments/flows/capture_flow.rs index 3f2dafc0cb7..61f54eb3d50 100644 --- a/crates/router/src/core/payments/flows/capture_flow.rs +++ b/crates/router/src/core/payments/flows/capture_flow.rs @@ -124,8 +124,14 @@ impl Feature<api::Capture, types::PaymentsCaptureData> merchant_context: &domain::MerchantContext, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> { - access_token::add_access_token(state, connector, merchant_context, self, creds_identifier) - .await + Box::pin(access_token::add_access_token( + state, + connector, + merchant_context, + self, + creds_identifier, + )) + .await } async fn build_flow_specific_connector_request( diff --git a/crates/router/src/core/payments/flows/complete_authorize_flow.rs b/crates/router/src/core/payments/flows/complete_authorize_flow.rs index 1d7a7772fbe..30ed3477150 100644 --- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs +++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs @@ -142,8 +142,14 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData> merchant_context: &domain::MerchantContext, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> { - access_token::add_access_token(state, connector, merchant_context, self, creds_identifier) - .await + Box::pin(access_token::add_access_token( + state, + connector, + merchant_context, + self, + creds_identifier, + )) + .await } async fn add_payment_method_token<'a>( diff --git a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs b/crates/router/src/core/payments/flows/incremental_authorization_flow.rs index ef04b0354da..23a4c788e8a 100644 --- a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs +++ b/crates/router/src/core/payments/flows/incremental_authorization_flow.rs @@ -106,8 +106,14 @@ impl Feature<api::IncrementalAuthorization, types::PaymentsIncrementalAuthorizat merchant_context: &domain::MerchantContext, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> { - access_token::add_access_token(state, connector, merchant_context, self, creds_identifier) - .await + Box::pin(access_token::add_access_token( + state, + connector, + merchant_context, + self, + creds_identifier, + )) + .await } async fn build_flow_specific_connector_request( diff --git a/crates/router/src/core/payments/flows/post_session_tokens_flow.rs b/crates/router/src/core/payments/flows/post_session_tokens_flow.rs index b356b695131..68ecc97e8a0 100644 --- a/crates/router/src/core/payments/flows/post_session_tokens_flow.rs +++ b/crates/router/src/core/payments/flows/post_session_tokens_flow.rs @@ -105,8 +105,14 @@ impl Feature<api::PostSessionTokens, types::PaymentsPostSessionTokensData> merchant_context: &domain::MerchantContext, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> { - access_token::add_access_token(state, connector, merchant_context, self, creds_identifier) - .await + Box::pin(access_token::add_access_token( + state, + connector, + merchant_context, + self, + creds_identifier, + )) + .await } async fn build_flow_specific_connector_request( diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs index 641af1d397e..93a2c1ecd48 100644 --- a/crates/router/src/core/payments/flows/psync_flow.rs +++ b/crates/router/src/core/payments/flows/psync_flow.rs @@ -168,8 +168,14 @@ impl Feature<api::PSync, types::PaymentsSyncData> merchant_context: &domain::MerchantContext, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> { - access_token::add_access_token(state, connector, merchant_context, self, creds_identifier) - .await + Box::pin(access_token::add_access_token( + state, + connector, + merchant_context, + self, + creds_identifier, + )) + .await } async fn build_flow_specific_connector_request( diff --git a/crates/router/src/core/payments/flows/reject_flow.rs b/crates/router/src/core/payments/flows/reject_flow.rs index 2c7a9878ed2..0bf9f091f33 100644 --- a/crates/router/src/core/payments/flows/reject_flow.rs +++ b/crates/router/src/core/payments/flows/reject_flow.rs @@ -84,8 +84,14 @@ impl Feature<api::Reject, types::PaymentsRejectData> merchant_context: &domain::MerchantContext, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> { - access_token::add_access_token(state, connector, merchant_context, self, creds_identifier) - .await + Box::pin(access_token::add_access_token( + state, + connector, + merchant_context, + self, + creds_identifier, + )) + .await } async fn build_flow_specific_connector_request( diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 06441f24662..1f67fd4c003 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -125,8 +125,14 @@ impl Feature<api::Session, types::PaymentsSessionData> for types::PaymentsSessio merchant_context: &domain::MerchantContext, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> { - access_token::add_access_token(state, connector, merchant_context, self, creds_identifier) - .await + Box::pin(access_token::add_access_token( + state, + connector, + merchant_context, + self, + creds_identifier, + )) + .await } async fn create_connector_customer<'a>( diff --git a/crates/router/src/core/payments/flows/session_update_flow.rs b/crates/router/src/core/payments/flows/session_update_flow.rs index 24b51ce1ca1..a52eef0b1d0 100644 --- a/crates/router/src/core/payments/flows/session_update_flow.rs +++ b/crates/router/src/core/payments/flows/session_update_flow.rs @@ -105,8 +105,14 @@ impl Feature<api::SdkSessionUpdate, types::SdkPaymentsSessionUpdateData> merchant_context: &domain::MerchantContext, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> { - access_token::add_access_token(state, connector, merchant_context, self, creds_identifier) - .await + Box::pin(access_token::add_access_token( + state, + connector, + merchant_context, + self, + creds_identifier, + )) + .await } async fn build_flow_specific_connector_request( diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs index c89f04aa69a..4c1b1a445df 100644 --- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs +++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs @@ -145,8 +145,14 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup merchant_context: &domain::MerchantContext, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> { - access_token::add_access_token(state, connector, merchant_context, self, creds_identifier) - .await + Box::pin(access_token::add_access_token( + state, + connector, + merchant_context, + self, + creds_identifier, + )) + .await } async fn add_payment_method_token<'a>( diff --git a/crates/router/src/core/payments/flows/update_metadata_flow.rs b/crates/router/src/core/payments/flows/update_metadata_flow.rs index a57b6acb751..538ed55d11f 100644 --- a/crates/router/src/core/payments/flows/update_metadata_flow.rs +++ b/crates/router/src/core/payments/flows/update_metadata_flow.rs @@ -104,8 +104,14 @@ impl Feature<api::UpdateMetadata, types::PaymentsUpdateMetadataData> merchant_context: &domain::MerchantContext, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> { - access_token::add_access_token(state, connector, merchant_context, self, creds_identifier) - .await + Box::pin(access_token::add_access_token( + state, + connector, + merchant_context, + self, + creds_identifier, + )) + .await } async fn build_flow_specific_connector_request( diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 0894297b747..ed44f61b4da 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -183,13 +183,13 @@ pub async fn trigger_refund_to_gateway( ) .await?; - let add_access_token_result = access_token::add_access_token( + let add_access_token_result = Box::pin(access_token::add_access_token( state, &connector, merchant_context, &router_data, creds_identifier.as_deref(), - ) + )) .await?; logger::debug!(refund_router_data=?router_data); @@ -617,13 +617,13 @@ pub async fn sync_refund_with_gateway( ) .await?; - let add_access_token_result = access_token::add_access_token( + let add_access_token_result = Box::pin(access_token::add_access_token( state, &connector, merchant_context, &router_data, creds_identifier.as_deref(), - ) + )) .await?; logger::debug!(refund_retrieve_router_data=?router_data); diff --git a/crates/router/src/core/refunds_v2.rs b/crates/router/src/core/refunds_v2.rs index ceab569885d..bb4f2535ee7 100644 --- a/crates/router/src/core/refunds_v2.rs +++ b/crates/router/src/core/refunds_v2.rs @@ -169,9 +169,14 @@ pub async fn trigger_refund_to_gateway( ) .await?; - let add_access_token_result = - access_token::add_access_token(state, &connector, merchant_context, &router_data, None) - .await?; + let add_access_token_result = Box::pin(access_token::add_access_token( + state, + &connector, + merchant_context, + &router_data, + None, + )) + .await?; logger::debug!(refund_router_data=?router_data); @@ -271,9 +276,14 @@ pub async fn internal_trigger_refund_to_gateway( ) .await?; - let add_access_token_result = - access_token::add_access_token(state, &connector, merchant_context, &router_data, None) - .await?; + let add_access_token_result = Box::pin(access_token::add_access_token( + state, + &connector, + merchant_context, + &router_data, + None, + )) + .await?; access_token::update_router_data_with_access_token_result( &add_access_token_result, @@ -805,9 +815,14 @@ pub async fn sync_refund_with_gateway( ) .await?; - let add_access_token_result = - access_token::add_access_token(state, &connector, merchant_context, &router_data, None) - .await?; + let add_access_token_result = Box::pin(access_token::add_access_token( + state, + &connector, + merchant_context, + &router_data, + None, + )) + .await?; logger::debug!(refund_retrieve_router_data=?router_data); @@ -886,9 +901,14 @@ pub async fn internal_sync_refund_with_gateway( ) .await?; - let add_access_token_result = - access_token::add_access_token(state, &connector, merchant_context, &router_data, None) - .await?; + let add_access_token_result = Box::pin(access_token::add_access_token( + state, + &connector, + merchant_context, + &router_data, + None, + )) + .await?; access_token::update_router_data_with_access_token_result( &add_access_token_result, diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index d36cacd1a5c..005f41f91c8 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -98,6 +98,8 @@ pub type BoxedWebhookSourceVerificationConnectorIntegrationInterface<T, Req, Res BoxedConnectorIntegrationInterface<T, common_types::WebhookSourceVerifyData, Req, Resp>; pub type BoxedExternalAuthenticationConnectorIntegrationInterface<T, Req, Resp> = BoxedConnectorIntegrationInterface<T, common_types::ExternalAuthenticationFlowData, Req, Resp>; +pub type BoxedAuthenticationTokenConnectorIntegrationInterface<T, Req, Resp> = + BoxedConnectorIntegrationInterface<T, common_types::AuthenticationTokenFlowData, Req, Resp>; pub type BoxedAccessTokenConnectorIntegrationInterface<T, Req, Resp> = BoxedConnectorIntegrationInterface<T, common_types::AccessTokenFlowData, Req, Resp>; pub type BoxedFilesConnectorIntegrationInterface<T, Req, Resp> = diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 41254507c23..f735c0e5863 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -47,15 +47,15 @@ use hyperswitch_domain_models::router_flow_types::{ pub use hyperswitch_domain_models::{ payment_address::PaymentAddress, router_data::{ - AccessToken, AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, - ConnectorResponseData, ErrorResponse, GooglePayPaymentMethodDetails, + AccessToken, AccessTokenAuthenticationResponse, AdditionalPaymentMethodConnectorResponse, + ConnectorAuthType, ConnectorResponseData, ErrorResponse, GooglePayPaymentMethodDetails, GooglePayPredecryptDataInternal, L2L3Data, PaymentMethodBalance, PaymentMethodToken, RecurringMandatePaymentData, RouterData, }, router_data_v2::{ - AccessTokenFlowData, DisputesFlowData, ExternalAuthenticationFlowData, FilesFlowData, - MandateRevokeFlowData, PaymentFlowData, RefundFlowData, RouterDataV2, UasFlowData, - WebhookSourceVerifyData, + AccessTokenFlowData, AuthenticationTokenFlowData, DisputesFlowData, + ExternalAuthenticationFlowData, FilesFlowData, MandateRevokeFlowData, PaymentFlowData, + RefundFlowData, RouterDataV2, UasFlowData, WebhookSourceVerifyData, }, router_request_types::{ revenue_recovery::{ @@ -67,14 +67,14 @@ pub use hyperswitch_domain_models::{ UasConfirmationRequestData, UasPostAuthenticationRequestData, UasPreAuthenticationRequestData, }, - AcceptDisputeRequestData, AccessTokenRequestData, AuthorizeSessionTokenData, - BrowserInformation, ChargeRefunds, ChargeRefundsOptions, CompleteAuthorizeData, - CompleteAuthorizeRedirectResponse, ConnectorCustomerData, CreateOrderRequestData, - DefendDisputeRequestData, DestinationChargeRefund, DirectChargeRefund, DisputeSyncData, - FetchDisputesRequestData, MandateRevokeRequestData, MultipleCaptureRequestData, - PaymentMethodTokenizationData, PaymentsApproveData, PaymentsAuthorizeData, - PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData, - PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData, + AcceptDisputeRequestData, AccessTokenAuthenticationRequestData, AccessTokenRequestData, + AuthorizeSessionTokenData, BrowserInformation, ChargeRefunds, ChargeRefundsOptions, + CompleteAuthorizeData, CompleteAuthorizeRedirectResponse, ConnectorCustomerData, + CreateOrderRequestData, DefendDisputeRequestData, DestinationChargeRefund, + DirectChargeRefund, DisputeSyncData, FetchDisputesRequestData, MandateRevokeRequestData, + MultipleCaptureRequestData, PaymentMethodTokenizationData, PaymentsApproveData, + PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData, + PaymentsCaptureData, PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RefundsData, ResponseId, RetrieveFileRequestData, @@ -118,15 +118,14 @@ pub use hyperswitch_interfaces::{ }, }; +#[cfg(feature = "v2")] +use crate::core::errors; pub use crate::core::payments::CustomerDetails; #[cfg(feature = "payouts")] use crate::core::utils::IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_PAYOUTS_FLOW; use crate::{ consts, - core::{ - errors::{self}, - payments::{OperationSessionGetters, PaymentData}, - }, + core::payments::{OperationSessionGetters, PaymentData}, services, types::transformers::{ForeignFrom, ForeignTryFrom}, }; @@ -1133,34 +1132,6 @@ pub struct ConnectorsList { pub connectors: Vec<String>, } -impl ForeignTryFrom<ConnectorAuthType> for AccessTokenRequestData { - type Error = errors::ApiErrorResponse; - fn foreign_try_from(connector_auth: ConnectorAuthType) -> Result<Self, Self::Error> { - match connector_auth { - ConnectorAuthType::HeaderKey { api_key } => Ok(Self { - app_id: api_key, - id: None, - }), - ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { - app_id: api_key, - id: Some(key1), - }), - ConnectorAuthType::SignatureKey { api_key, key1, .. } => Ok(Self { - app_id: api_key, - id: Some(key1), - }), - ConnectorAuthType::MultiAuthKey { api_key, key1, .. } => Ok(Self { - app_id: api_key, - id: Some(key1), - }), - - _ => Err(errors::ApiErrorResponse::InvalidDataValue { - field_name: "connector_account_details", - }), - } - } -} - impl ForeignFrom<&PaymentsAuthorizeRouterData> for AuthorizeSessionTokenData { fn foreign_from(data: &PaymentsAuthorizeRouterData) -> Self { Self { diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 156bb21d0b8..01f872e6f3a 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -43,7 +43,8 @@ use api_models::routing::{self as api_routing, RoutableConnectorChoice}; use common_enums::RoutableConnectors; use error_stack::ResultExt; pub use hyperswitch_domain_models::router_flow_types::{ - access_token_auth::AccessTokenAuth, mandate_revoke::MandateRevoke, + access_token_auth::{AccessTokenAuth, AccessTokenAuthentication}, + mandate_revoke::MandateRevoke, webhooks::VerifyWebhookSource, }; pub use hyperswitch_interfaces::{ @@ -62,7 +63,8 @@ pub use hyperswitch_interfaces::{ RevenueRecovery, RevenueRecoveryRecordBack, }, revenue_recovery_v2::RevenueRecoveryV2, - BoxedConnector, Connector, ConnectorAccessToken, ConnectorAccessTokenV2, ConnectorCommon, + BoxedConnector, Connector, ConnectorAccessToken, ConnectorAccessTokenV2, + ConnectorAuthenticationToken, ConnectorAuthenticationTokenV2, ConnectorCommon, ConnectorCommonExt, ConnectorMandateRevoke, ConnectorMandateRevokeV2, ConnectorTransactionId, ConnectorVerifyWebhookSource, ConnectorVerifyWebhookSourceV2, CurrencyUnit, diff --git a/crates/router/src/types/api/connector_mapping.rs b/crates/router/src/types/api/connector_mapping.rs index 2bd3bf33141..580ac62062c 100644 --- a/crates/router/src/types/api/connector_mapping.rs +++ b/crates/router/src/types/api/connector_mapping.rs @@ -312,7 +312,9 @@ impl ConnectorData { Ok(ConnectorEnum::Old(Box::new(connector::Nomupay::new()))) } enums::Connector::Noon => Ok(ConnectorEnum::Old(Box::new(connector::Noon::new()))), - // enums::Connector::Nordea => Ok(ConnectorEnum::Old(Box::new(connector::Nordea::new()))), + enums::Connector::Nordea => { + Ok(ConnectorEnum::Old(Box::new(connector::Nordea::new()))) + } enums::Connector::Novalnet => { Ok(ConnectorEnum::Old(Box::new(connector::Novalnet::new()))) } diff --git a/crates/router/src/types/connector_transformers.rs b/crates/router/src/types/connector_transformers.rs index ddb8fc333ca..4cf4bad8086 100644 --- a/crates/router/src/types/connector_transformers.rs +++ b/crates/router/src/types/connector_transformers.rs @@ -99,7 +99,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { api_enums::Connector::Nmi => Self::Nmi, api_enums::Connector::Nomupay => Self::Nomupay, api_enums::Connector::Noon => Self::Noon, - // api_enums::Connector::Nordea => Self::Nordea, + api_enums::Connector::Nordea => Self::Nordea, api_enums::Connector::Novalnet => Self::Novalnet, api_enums::Connector::Nuvei => Self::Nuvei, api_enums::Connector::Opennode => Self::Opennode, diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index 625cdb50176..00784b49c15 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -289,6 +289,7 @@ api_key = "API Key" [nordea] api_key = "Client Secret" key1 = "Client ID" +api_secret = "eIDAS Private Key" [novalnet] api_key="API Key" diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index 3829fc17eba..22a44919f83 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -81,7 +81,7 @@ pub struct ConnectorAuthentication { pub nexixpay: Option<HeaderKey>, pub nomupay: Option<BodyKey>, pub noon: Option<SignatureKey>, - pub nordea: Option<BodyKey>, + pub nordea: Option<SignatureKey>, pub novalnet: Option<HeaderKey>, pub nmi: Option<HeaderKey>, pub nuvei: Option<SignatureKey>, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index adb2d4a2491..41954a9f8b8 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -591,6 +591,9 @@ paypal = { currency = "AUD,BRL,CAD,CHF,CNY,CZK,DKK,EUR,GBP,HKD,HUF,ILS,JPY,MXN,M credit = { country = "US, CA", currency = "CAD,USD" } debit = { country = "US, CA", currency = "CAD,USD" } +[pm_filters.nordea] +sepa = { country = "DK,FI,NO,SE", currency = "DKK,EUR,NOK,SEK" } + [pm_filters.fiuu] duit_now = { country = "MY", currency = "MYR" } apple_pay = { country = "MY", currency = "MYR" }
2025-05-25T16:18:23Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [x] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> ### Summary This PR introduces Nordea as a new payment connector with support for SEPA bank debit payments. It also implements a new **Authentication Token Flow** mechanism that enables two-step OAuth authentication, which is required by certain connectors like Nordea. ### Problem Statement Some payment connectors require a more complex authentication process that involves: 1. **Step 1**: Obtaining an authentication token (authorization code) using client credentials 2. **Step 2**: Exchanging that authentication token for an access token using OAuth 2.0 flow The existing access token flow in Hyperswitch only supported direct access token generation, making it incompatible with connectors that require this two-step OAuth authentication process. ### Solution This PR introduces: 1. **Authentication Token Flow**: A new connector flow that handles the two-step OAuth authentication process 2. **Nordea Connector Integration**: The first connector to utilize this new authentication flow 3. **SEPA Bank Debit Support**: Implementation of SEPA payment method through Nordea ### Implementation Details #### Authentication Token Flow Architecture The new authentication flow works as follows: ```mermaid flowchart TD A[Payment Flow Initiated] --> B{Connector Supports<br/>Access Token?} B -->|No| Z[Continue with Payment<br/>No Access Token] B -->|Yes| C[Check Access Token Cache] C --> D{Access Token<br/>in Cache?} D -->|Yes| E[Use Cached Access Token] D -->|No| F{Connector Needs<br/>Authentication Token?} F -->|No| G[Create AccessTokenRequestData<br/>with ConnectorAuthType only] F -->|Yes| H[Authentication Token Flow] H --> I[Create AccessTokenAuthenticationRequestData<br/>from ConnectorAuthType] I --> J[Call execute_authentication_token] J --> K[POST /oauth/authorize<br/>with client credentials] K --> L{Authentication<br/>Successful?} L -->|No| M[Return Error] L -->|Yes| N[Receive AccessTokenAuthenticationResponse<br/>authorization code] N --> O[Create AccessTokenRequestData<br/>with ConnectorAuthType + AuthenticationToken] O --> P[Access Token Flow] G --> P P --> Q[Call refresh_connector_auth] Q --> R[POST /oauth/token<br/>exchange auth code for access token] R --> S{Access Token<br/>Successful?} S -->|No| T[Return Error] S -->|Yes| U[Receive AccessToken<br/>bearer token + expiry] U --> V[Cache Access Token<br/>with reduced expiry] V --> W[Return Access Token] E --> W W --> X[Use Access Token<br/>for Payment Requests] M --> Y[Payment Flow Fails] T --> Y X --> AA[Payment Flow Continues] Z --> AA style H fill:#e1f5fe style P fill:#f3e5f5 style I fill:#e8f5e8 style O fill:#e8f5e8 style K fill:#fff3e0 style R fill:#fff3e0 style V fill:#e8eaf6 ``` #### Key Components - __AccessTokenAuthenticationRequestData__: Contains connector auth credentials for the first OAuth step - __AccessTokenAuthenticationResponse__: Contains the authorization code received from the authentication endpoint - __Enhanced AccessTokenRequestData__: Now supports both direct access token creation and token exchange flows - __Automatic Flow Detection__: The system automatically detects if a connector needs authentication tokens via `authentication_token_for_token_creation()` #### Nordea Connector Integration - __Authentication__: Implements OAuth 2.0 with eIDAS signature validation - __Payment Methods__: SEPA Credit Transfers (bank debit) - __Supported Operations__: - Payment authorization (automatic capture only) - Payment synchronization (PSync) - Two-step OAuth authentication flow - __Not Supported__: - Manual capture - Refunds (only available in Corporate APIs) - Void/cancellation #### Technical Implementation - __Signature Generation__: Implements eIDAS signature generation using RSA-SHA256 for API request signing - __Auth Configuration__: Uses `SignatureKey` auth type with: - `api_key`: Client Secret - `key1`: Client ID - `api_secret`: eIDAS Private Key (base64 encoded) - __Request Signing__: All requests include: - X-Nordea-Originating-Host - X-Nordea-Originating-Date - Signature header (following HTTP Signature spec) - Digest header for POST/PUT requests - __Payment Flow__: 1. Authentication token creation (authorization) 2. Access token exchange 3. Payment initiation (PreProcessing) 4. Payment confirmation (Authorize) ### Changes Made 1. __Core Authentication Infrastructure__: - Added `AccessTokenAuthenticationRequestData` struct for auth token requests - Added `AccessTokenAuthenticationResponse` struct for auth token responses - Enhanced `AccessTokenRequestData` to support both direct and exchange flows - Added `execute_authentication_token` function for OAuth step 1 - Modified access token flow to check for authentication token support - Added backward-compatible authentication token detection 2. __Connector Implementation__: - Added Nordea connector module with request/response structures - Implemented eIDAS signature generation - Added SEPA payment method support - Implemented OAuth 2.0 authentication flow 3. __Configuration__: - Added Nordea to connector configs (development, sandbox, production) - Added payment method required fields configuration - Updated WASM bindings for frontend integration ### Testing - Tested SEPA bank debit payments through complete flow - Verified eIDAS signature generation - Confirmed OAuth authentication flow works correctly - Validated payment status synchronization - Tested backward compatibility with existing connectors ### Unsupported features by Nordea - Webhooks - Manual Capture - Refunds (only supported through Corporate API and is behind a paywall) ### Breaking Changes None - The authentication token flow is backward compatible and only activates for connectors that explicitly support it through the `authentication_token_for_token_creation()` method. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [x] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> New connector Nordea SEPA integration. Closes #8134. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> <details> <summary>MCA</summary> ```curl curl --location 'http://localhost:8080/account/postman_merchant_GHAction_1752842696/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_DL49cxo4k5VbOYIabte7WgRsu9xTmB6in77WVBxdN8nPRWMqzFb5ISd3mGocJC0I' \ --data '{ "connector_type": "payment_processor", "connector_name": "nordea", "business_country": "US", "business_label": "default", "connector_account_details": { "auth_type": "SignatureKey", "api_key": "client_secret", "key1": "client_id", "api_secret": "decrypted_certificate" }, "test_mode": false, "disabled": false, "metadata": { "creditor_account_type": "IBAN", "creditor_account_value": "{{creditor_account_number}}", "creditor_beneficiary_name": "Test Merchant" }, "payment_methods_enabled": [ { "payment_method": "bank_debit", "payment_method_types": [ { "payment_method_type": "sepa", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ] }' ``` ```json { "connector_type": "payment_processor", "connector_name": "nordea", "connector_label": "nordea_US_default", "merchant_connector_id": "mca_UWrnV7EnGkfVapwuHOAM", "profile_id": "pro_892QTRQ3W6mWykBeSXDQ", "connector_account_details": { "auth_type": "SignatureKey", "api_key": "client_secret", "key1": "client_id", "api_secret": "decrypted_certificate" }, "payment_methods_enabled": [ { "payment_method": "bank_debit", "payment_method_types": [ { "payment_method_type": "sepa", "payment_experience": null, "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "connector_webhook_details": null, "metadata": { "creditor_account_type": "IBAN", "creditor_account_value": "FI7473834510057469", "creditor_beneficiary_name": "Test Merchant" }, "test_mode": false, "disabled": false, "frm_configs": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "applepay_verified_domains": null, "pm_auth_config": null, "status": "active", "additional_merchant_data": null, "connector_wallets_details": null } ``` </details> <details> <summary>Payment Create</summary> ```curl curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Accept-Language: ja' \ --header 'api-key: dev_DL49cxo4k5VbOYIabte7WgRsu9xTmB6in77WVBxdN8nPRWMqzFb5ISd3mGocJC0I' \ --data-raw '{ "amount": 10400, "currency": "EUR", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 10400, "customer_id": "customer", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://duck.com", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "FI" , "first_name": "PiX" , "last_name": "THE" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "FI", "first_name": "PiX" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "browser_info": { "color_depth": 24, "java_enabled": true, "java_script_enabled": true, "language": "en-GB", "screen_height": 720, "screen_width": 1280, "time_zone": -330, "ip_address": "208.127.127.193", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0" } }' ``` ```json { "payment_id": "pay_GJDKAKdDxM4bQ8xX0anw", "merchant_id": "postman_merchant_GHAction_1752842696", "status": "requires_payment_method", "amount": 10400, "net_amount": 10400, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_GJDKAKdDxM4bQ8xX0anw_secret_TL3I7uzVd7IA4uvwkPqh", "created": "2025-07-18T12:45:03.009Z", "currency": "EUR", "customer_id": "customer", "customer": { "id": "customer", "name": null, "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "FI", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "FI", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": "THE" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": null, "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "customer", "created_at": 1752842702, "expires": 1752846302, "secret": "epk_d55a0599354449ebafda40a1f4989778" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_892QTRQ3W6mWykBeSXDQ", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-07-18T13:00:03.008Z", "fingerprint": null, "browser_info": { "language": "en-GB", "time_zone": -330, "ip_address": "208.127.127.193", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0", "color_depth": 24, "java_enabled": true, "screen_width": 1280, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 720, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-07-18T12:45:03.075Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` </details> <details> <summary>Payment Confirm</summary> ```curl curl --location 'http://localhost:8080/payments/pay_GJDKAKdDxM4bQ8xX0anw/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_b6513b5899694eaeb7d76adfe1d29708' \ --data '{ "payment_method": "bank_debit", "payment_method_type": "sepa", "payment_method_data": { "bank_debit": { "sepa_bank_debit": { "iban": "FI6593857450293470" } } }, "client_secret": "pay_GJDKAKdDxM4bQ8xX0anw_secret_TL3I7uzVd7IA4uvwkPqh" }' ``` ```json { "payment_id": "pay_GJDKAKdDxM4bQ8xX0anw", "merchant_id": "postman_merchant_GHAction_1752842696", "status": "requires_customer_action", "amount": 10400, "net_amount": 10400, "shipping_cost": null, "amount_capturable": 10400, "amount_received": null, "connector": "nordea", "client_secret": "pay_GJDKAKdDxM4bQ8xX0anw_secret_TL3I7uzVd7IA4uvwkPqh", "created": "2025-07-18T12:45:03.009Z", "currency": "EUR", "customer_id": "customer", "customer": { "id": "customer", "name": null, "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "bank_debit", "payment_method_data": { "bank_debit": { "sepa": { "iban": "FI659********93470", "bank_account_holder_name": null } }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "FI", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "FI", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": "THE" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": null, "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_GJDKAKdDxM4bQ8xX0anw/postman_merchant_GHAction_1752842696/pay_GJDKAKdDxM4bQ8xX0anw_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "sepa", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "c14b226e-dfc1-4458-a477-a7b3ee4387fd", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_GJDKAKdDxM4bQ8xX0anw_1", "payment_link": null, "profile_id": "pro_892QTRQ3W6mWykBeSXDQ", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_UWrnV7EnGkfVapwuHOAM", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-07-18T13:00:03.008Z", "fingerprint": null, "browser_info": { "os_type": null, "language": null, "time_zone": null, "ip_address": "::1", "os_version": null, "user_agent": null, "color_depth": null, "device_model": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "accept_language": "en", "java_script_enabled": null }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-07-18T12:45:06.878Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` </details> <details> <summary>Redirection</summary> <img width="249" height="120" alt="image" src="https://github.com/user-attachments/assets/c66f3ea7-e779-4702-8190-1d7925bfa7fc" /> </details> <details> <summary>Retrieve</summary> ```curl curl --location 'http://localhost:8080/payments/pay_GJDKAKdDxM4bQ8xX0anw?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_DL49cxo4k5VbOYIabte7WgRsu9xTmB6in77WVBxdN8nPRWMqzFb5ISd3mGocJC0I' ``` ```json { "payment_id": "pay_GJDKAKdDxM4bQ8xX0anw", "merchant_id": "postman_merchant_GHAction_1752842696", "status": "succeeded", "amount": 10400, "net_amount": 10400, "shipping_cost": null, "amount_capturable": 0, "amount_received": 10400, "connector": "nordea", "client_secret": "pay_GJDKAKdDxM4bQ8xX0anw_secret_TL3I7uzVd7IA4uvwkPqh", "created": "2025-07-18T12:45:03.009Z", "currency": "EUR", "customer_id": "customer", "customer": { "id": "customer", "name": null, "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "bank_debit", "payment_method_data": { "bank_debit": { "sepa": { "iban": "FI659********93470", "bank_account_holder_name": null } }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "FI", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "FI", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": "THE" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": null, "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "sepa", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "c14b226e-dfc1-4458-a477-a7b3ee4387fd", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_GJDKAKdDxM4bQ8xX0anw_1", "payment_link": null, "profile_id": "pro_892QTRQ3W6mWykBeSXDQ", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_UWrnV7EnGkfVapwuHOAM", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-07-18T13:00:03.008Z", "fingerprint": null, "browser_info": { "os_type": null, "language": null, "time_zone": null, "ip_address": "::1", "os_version": null, "user_agent": null, "color_depth": null, "device_model": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "accept_language": "en", "java_script_enabled": null }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-07-18T12:45:16.869Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` </details> <details> <summary>Cypress</summary> WILL INTRODUCE IN NEXT PR. </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `just clippy && just clippy_v2` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible <!-- @coderabbitai ignore -->
v1.115.0
06dc66c62e33c1c56c42aab18a7959e1648d6fae
06dc66c62e33c1c56c42aab18a7959e1648d6fae
juspay/hyperswitch
juspay__hyperswitch-8115
Bug: feat: list for dynamic routing ### Context **The dashboard required changes** - get api for dynamic routing is inplace - list active Dynamic routing - Refactor volume split response
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 956d6d6697c..5933e3d0538 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -8375,6 +8375,54 @@ }, "additionalProperties": false }, + "ContractBasedRoutingConfig": { + "type": "object", + "properties": { + "config": { + "allOf": [ + { + "$ref": "#/components/schemas/ContractBasedRoutingConfigBody" + } + ], + "nullable": true + }, + "label_info": { + "type": "array", + "items": { + "$ref": "#/components/schemas/LabelInformation" + }, + "nullable": true + } + } + }, + "ContractBasedRoutingConfigBody": { + "type": "object", + "properties": { + "constants": { + "type": "array", + "items": { + "type": "number", + "format": "double" + }, + "nullable": true + }, + "time_scale": { + "allOf": [ + { + "$ref": "#/components/schemas/ContractBasedTimeScale" + } + ], + "nullable": true + } + } + }, + "ContractBasedTimeScale": { + "type": "string", + "enum": [ + "day", + "month" + ] + }, "CountryAlpha2": { "type": "string", "enum": [ @@ -9197,6 +9245,23 @@ "ZWL" ] }, + "CurrentBlockThreshold": { + "type": "object", + "properties": { + "duration_in_mins": { + "type": "integer", + "format": "int64", + "nullable": true, + "minimum": 0 + }, + "max_total_count": { + "type": "integer", + "format": "int64", + "nullable": true, + "minimum": 0 + } + } + }, "CustomerAcceptance": { "type": "object", "description": "This \"CustomerAcceptance\" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client.", @@ -9704,6 +9769,123 @@ }, "additionalProperties": false }, + "DecisionEngineEliminationData": { + "type": "object", + "required": [ + "threshold" + ], + "properties": { + "threshold": { + "type": "number", + "format": "double" + } + } + }, + "DecisionEngineGatewayWiseExtraScore": { + "type": "object", + "required": [ + "gatewayName", + "gatewaySigmaFactor" + ], + "properties": { + "gatewayName": { + "type": "string" + }, + "gatewaySigmaFactor": { + "type": "number", + "format": "double" + } + } + }, + "DecisionEngineSRSubLevelInputConfig": { + "type": "object", + "properties": { + "paymentMethodType": { + "type": "string", + "nullable": true + }, + "paymentMethod": { + "type": "string", + "nullable": true + }, + "latencyThreshold": { + "type": "number", + "format": "double", + "nullable": true + }, + "bucketSize": { + "type": "integer", + "format": "int32", + "nullable": true + }, + "hedgingPercent": { + "type": "number", + "format": "double", + "nullable": true + }, + "lowerResetFactor": { + "type": "number", + "format": "double", + "nullable": true + }, + "upperResetFactor": { + "type": "number", + "format": "double", + "nullable": true + }, + "gatewayExtraScore": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DecisionEngineGatewayWiseExtraScore" + }, + "nullable": true + } + } + }, + "DecisionEngineSuccessRateData": { + "type": "object", + "properties": { + "defaultLatencyThreshold": { + "type": "number", + "format": "double", + "nullable": true + }, + "defaultBucketSize": { + "type": "integer", + "format": "int32", + "nullable": true + }, + "defaultHedgingPercent": { + "type": "number", + "format": "double", + "nullable": true + }, + "defaultLowerResetFactor": { + "type": "number", + "format": "double", + "nullable": true + }, + "defaultUpperResetFactor": { + "type": "number", + "format": "double", + "nullable": true + }, + "defaultGatewayExtraScore": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DecisionEngineGatewayWiseExtraScore" + }, + "nullable": true + }, + "subLevelInputConfig": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DecisionEngineSRSubLevelInputConfig" + }, + "nullable": true + } + } + }, "DecoupledAuthenticationType": { "type": "string", "enum": [ @@ -9969,6 +10151,31 @@ } } }, + "DynamicRoutingAlgorithm": { + "oneOf": [ + { + "$ref": "#/components/schemas/EliminationRoutingConfig" + }, + { + "$ref": "#/components/schemas/SuccessBasedRoutingConfig" + }, + { + "$ref": "#/components/schemas/ContractBasedRoutingConfig" + } + ] + }, + "DynamicRoutingConfigParams": { + "type": "string", + "enum": [ + "PaymentMethod", + "PaymentMethodType", + "AuthenticationType", + "Currency", + "Country", + "CardNetwork", + "CardBin" + ] + }, "ElementPosition": { "type": "string", "enum": [ @@ -10024,6 +10231,51 @@ } ] }, + "EliminationAnalyserConfig": { + "type": "object", + "properties": { + "bucket_size": { + "type": "integer", + "format": "int64", + "nullable": true, + "minimum": 0 + }, + "bucket_leak_interval_in_secs": { + "type": "integer", + "format": "int64", + "nullable": true, + "minimum": 0 + } + }, + "additionalProperties": false + }, + "EliminationRoutingConfig": { + "type": "object", + "required": [ + "decision_engine_configs" + ], + "properties": { + "params": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DynamicRoutingConfigParams" + }, + "nullable": true + }, + "elimination_analyser_config": { + "allOf": [ + { + "$ref": "#/components/schemas/EliminationAnalyserConfig" + } + ], + "nullable": true + }, + "decision_engine_configs": { + "$ref": "#/components/schemas/DecisionEngineEliminationData" + } + }, + "additionalProperties": false + }, "EnablePaymentLinkRequest": { "type": "string", "description": "Whether payment link is requested to be enabled or not for this transaction", @@ -12054,6 +12306,33 @@ } } }, + "LabelInformation": { + "type": "object", + "required": [ + "label", + "target_count", + "target_time", + "mca_id" + ], + "properties": { + "label": { + "type": "string" + }, + "target_count": { + "type": "integer", + "format": "int64", + "minimum": 0 + }, + "target_time": { + "type": "integer", + "format": "int64", + "minimum": 0 + }, + "mca_id": { + "type": "string" + } + } + }, "LinkedRoutingConfigRetrieveResponse": { "oneOf": [ { @@ -13237,7 +13516,7 @@ "type": "string" }, "algorithm": { - "$ref": "#/components/schemas/RoutingAlgorithm" + "$ref": "#/components/schemas/RoutingAlgorithmWrapper" }, "created_at": { "type": "integer", @@ -18787,7 +19066,7 @@ "routing": { "allOf": [ { - "$ref": "#/components/schemas/RoutingAlgorithm" + "$ref": "#/components/schemas/StaticRoutingAlgorithm" } ], "nullable": true @@ -21669,92 +21948,6 @@ "zsl" ] }, - "RoutingAlgorithm": { - "oneOf": [ - { - "type": "object", - "required": [ - "type", - "data" - ], - "properties": { - "type": { - "type": "string", - "enum": [ - "single" - ] - }, - "data": { - "$ref": "#/components/schemas/RoutableConnectorChoice" - } - } - }, - { - "type": "object", - "required": [ - "type", - "data" - ], - "properties": { - "type": { - "type": "string", - "enum": [ - "priority" - ] - }, - "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/RoutableConnectorChoice" - } - } - } - }, - { - "type": "object", - "required": [ - "type", - "data" - ], - "properties": { - "type": { - "type": "string", - "enum": [ - "volume_split" - ] - }, - "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ConnectorVolumeSplit" - } - } - } - }, - { - "type": "object", - "required": [ - "type", - "data" - ], - "properties": { - "type": { - "type": "string", - "enum": [ - "advanced" - ] - }, - "data": { - "$ref": "#/components/schemas/ProgramConnectorSelection" - } - } - } - ], - "description": "Routing Algorithm kind", - "discriminator": { - "propertyName": "type" - } - }, "RoutingAlgorithmId": { "type": "object", "required": [ @@ -21776,6 +21969,16 @@ "dynamic" ] }, + "RoutingAlgorithmWrapper": { + "oneOf": [ + { + "$ref": "#/components/schemas/StaticRoutingAlgorithm" + }, + { + "$ref": "#/components/schemas/DynamicRoutingAlgorithm" + } + ] + }, "RoutingConfigRequest": { "type": "object", "required": [ @@ -21792,7 +21995,7 @@ "type": "string" }, "algorithm": { - "$ref": "#/components/schemas/RoutingAlgorithm" + "$ref": "#/components/schemas/StaticRoutingAlgorithm" }, "profile_id": { "type": "string" @@ -22749,6 +22952,91 @@ ], "description": "Charge specific fields for controlling the revert of funds from either platform or connected account. Check sub-fields for more details." }, + "StaticRoutingAlgorithm": { + "oneOf": [ + { + "type": "object", + "required": [ + "type", + "data" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "single" + ] + }, + "data": { + "$ref": "#/components/schemas/RoutableConnectorChoice" + } + } + }, + { + "type": "object", + "required": [ + "type", + "data" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "priority" + ] + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RoutableConnectorChoice" + } + } + } + }, + { + "type": "object", + "required": [ + "type", + "data" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "volume_split" + ] + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ConnectorVolumeSplit" + } + } + } + }, + { + "type": "object", + "required": [ + "type", + "data" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "advanced" + ] + }, + "data": { + "$ref": "#/components/schemas/ProgramConnectorSelection" + } + } + } + ], + "discriminator": { + "propertyName": "type" + } + }, "StraightThroughAlgorithm": { "oneOf": [ { @@ -22898,6 +23186,74 @@ }, "additionalProperties": false }, + "SuccessBasedRoutingConfig": { + "type": "object", + "required": [ + "decision_engine_configs" + ], + "properties": { + "params": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DynamicRoutingConfigParams" + }, + "nullable": true + }, + "config": { + "allOf": [ + { + "$ref": "#/components/schemas/SuccessBasedRoutingConfigBody" + } + ], + "nullable": true + }, + "decision_engine_configs": { + "$ref": "#/components/schemas/DecisionEngineSuccessRateData" + } + }, + "additionalProperties": false + }, + "SuccessBasedRoutingConfigBody": { + "type": "object", + "properties": { + "min_aggregates_size": { + "type": "integer", + "format": "int32", + "nullable": true, + "minimum": 0 + }, + "default_success_rate": { + "type": "number", + "format": "double", + "nullable": true + }, + "max_aggregates_size": { + "type": "integer", + "format": "int32", + "nullable": true, + "minimum": 0 + }, + "current_block_threshold": { + "allOf": [ + { + "$ref": "#/components/schemas/CurrentBlockThreshold" + } + ], + "nullable": true + }, + "specificity_level": { + "$ref": "#/components/schemas/SuccessRateSpecificityLevel" + } + }, + "additionalProperties": false + }, + "SuccessRateSpecificityLevel": { + "type": "string", + "enum": [ + "merchant", + "global" + ] + }, "SupportedPaymentMethod": { "allOf": [ { diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 3e94666e40a..a4de89860ba 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -12106,6 +12106,19 @@ } } }, + "DynamicRoutingAlgorithm": { + "oneOf": [ + { + "$ref": "#/components/schemas/EliminationRoutingConfig" + }, + { + "$ref": "#/components/schemas/SuccessBasedRoutingConfig" + }, + { + "$ref": "#/components/schemas/ContractBasedRoutingConfig" + } + ] + }, "DynamicRoutingConfigParams": { "type": "string", "enum": [ @@ -12181,6 +12194,51 @@ } ] }, + "EliminationAnalyserConfig": { + "type": "object", + "properties": { + "bucket_size": { + "type": "integer", + "format": "int64", + "nullable": true, + "minimum": 0 + }, + "bucket_leak_interval_in_secs": { + "type": "integer", + "format": "int64", + "nullable": true, + "minimum": 0 + } + }, + "additionalProperties": false + }, + "EliminationRoutingConfig": { + "type": "object", + "required": [ + "decision_engine_configs" + ], + "properties": { + "params": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DynamicRoutingConfigParams" + }, + "nullable": true + }, + "elimination_analyser_config": { + "allOf": [ + { + "$ref": "#/components/schemas/EliminationAnalyserConfig" + } + ], + "nullable": true + }, + "decision_engine_configs": { + "$ref": "#/components/schemas/DecisionEngineEliminationData" + } + }, + "additionalProperties": false + }, "EnabledPaymentMethod": { "type": "object", "description": "Object for EnabledPaymentMethod", @@ -14619,7 +14677,7 @@ "payout_routing_algorithm": { "allOf": [ { - "$ref": "#/components/schemas/RoutingAlgorithm" + "$ref": "#/components/schemas/StaticRoutingAlgorithm" } ], "nullable": true @@ -14865,7 +14923,7 @@ "payout_routing_algorithm": { "allOf": [ { - "$ref": "#/components/schemas/RoutingAlgorithm" + "$ref": "#/components/schemas/StaticRoutingAlgorithm" } ], "nullable": true @@ -14911,7 +14969,7 @@ "frm_routing_algorithm": { "allOf": [ { - "$ref": "#/components/schemas/RoutingAlgorithm" + "$ref": "#/components/schemas/StaticRoutingAlgorithm" } ], "nullable": true @@ -14998,7 +15056,7 @@ "payout_routing_algorithm": { "allOf": [ { - "$ref": "#/components/schemas/RoutingAlgorithm" + "$ref": "#/components/schemas/StaticRoutingAlgorithm" } ], "nullable": true @@ -15939,7 +15997,7 @@ "type": "string" }, "algorithm": { - "$ref": "#/components/schemas/RoutingAlgorithm" + "$ref": "#/components/schemas/RoutingAlgorithmWrapper" }, "created_at": { "type": "integer", @@ -22620,7 +22678,7 @@ "routing": { "allOf": [ { - "$ref": "#/components/schemas/RoutingAlgorithm" + "$ref": "#/components/schemas/StaticRoutingAlgorithm" } ], "nullable": true @@ -23566,7 +23624,7 @@ "routing": { "allOf": [ { - "$ref": "#/components/schemas/RoutingAlgorithm" + "$ref": "#/components/schemas/StaticRoutingAlgorithm" } ], "nullable": true @@ -23789,7 +23847,7 @@ "routing": { "allOf": [ { - "$ref": "#/components/schemas/RoutingAlgorithm" + "$ref": "#/components/schemas/StaticRoutingAlgorithm" } ], "nullable": true @@ -24369,7 +24427,7 @@ "payout_routing_algorithm": { "allOf": [ { - "$ref": "#/components/schemas/RoutingAlgorithm" + "$ref": "#/components/schemas/StaticRoutingAlgorithm" } ], "nullable": true @@ -24649,7 +24707,7 @@ "payout_routing_algorithm": { "allOf": [ { - "$ref": "#/components/schemas/RoutingAlgorithm" + "$ref": "#/components/schemas/StaticRoutingAlgorithm" } ], "nullable": true @@ -26049,92 +26107,6 @@ "zsl" ] }, - "RoutingAlgorithm": { - "oneOf": [ - { - "type": "object", - "required": [ - "type", - "data" - ], - "properties": { - "type": { - "type": "string", - "enum": [ - "single" - ] - }, - "data": { - "$ref": "#/components/schemas/RoutableConnectorChoice" - } - } - }, - { - "type": "object", - "required": [ - "type", - "data" - ], - "properties": { - "type": { - "type": "string", - "enum": [ - "priority" - ] - }, - "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/RoutableConnectorChoice" - } - } - } - }, - { - "type": "object", - "required": [ - "type", - "data" - ], - "properties": { - "type": { - "type": "string", - "enum": [ - "volume_split" - ] - }, - "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ConnectorVolumeSplit" - } - } - } - }, - { - "type": "object", - "required": [ - "type", - "data" - ], - "properties": { - "type": { - "type": "string", - "enum": [ - "advanced" - ] - }, - "data": { - "$ref": "#/components/schemas/ProgramConnectorSelection" - } - } - } - ], - "description": "Routing Algorithm kind", - "discriminator": { - "propertyName": "type" - } - }, "RoutingAlgorithmKind": { "type": "string", "enum": [ @@ -26145,6 +26117,16 @@ "dynamic" ] }, + "RoutingAlgorithmWrapper": { + "oneOf": [ + { + "$ref": "#/components/schemas/StaticRoutingAlgorithm" + }, + { + "$ref": "#/components/schemas/DynamicRoutingAlgorithm" + } + ] + }, "RoutingConfigRequest": { "type": "object", "properties": { @@ -26159,7 +26141,7 @@ "algorithm": { "allOf": [ { - "$ref": "#/components/schemas/RoutingAlgorithm" + "$ref": "#/components/schemas/StaticRoutingAlgorithm" } ], "nullable": true @@ -27106,6 +27088,91 @@ ], "description": "Charge specific fields for controlling the revert of funds from either platform or connected account. Check sub-fields for more details." }, + "StaticRoutingAlgorithm": { + "oneOf": [ + { + "type": "object", + "required": [ + "type", + "data" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "single" + ] + }, + "data": { + "$ref": "#/components/schemas/RoutableConnectorChoice" + } + } + }, + { + "type": "object", + "required": [ + "type", + "data" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "priority" + ] + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RoutableConnectorChoice" + } + } + } + }, + { + "type": "object", + "required": [ + "type", + "data" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "volume_split" + ] + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ConnectorVolumeSplit" + } + } + } + }, + { + "type": "object", + "required": [ + "type", + "data" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "advanced" + ] + }, + "data": { + "$ref": "#/components/schemas/ProgramConnectorSelection" + } + } + } + ], + "discriminator": { + "propertyName": "type" + } + }, "StraightThroughAlgorithm": { "oneOf": [ { @@ -27279,7 +27346,8 @@ "decision_engine_configs": { "$ref": "#/components/schemas/DecisionEngineSuccessRateData" } - } + }, + "additionalProperties": false }, "SuccessBasedRoutingConfigBody": { "type": "object", @@ -27312,7 +27380,8 @@ "specificity_level": { "$ref": "#/components/schemas/SuccessRateSpecificityLevel" } - } + }, + "additionalProperties": false }, "SuccessRateSpecificityLevel": { "type": "string", diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 60eca62b618..1d026a68548 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -58,7 +58,7 @@ pub struct MerchantAccountCreate { /// The routing algorithm to be used for routing payouts to desired connectors #[cfg(feature = "payouts")] - #[schema(value_type = Option<RoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] + #[schema(value_type = Option<StaticRoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] pub payout_routing_algorithm: Option<serde_json::Value>, /// A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false. @@ -165,8 +165,9 @@ impl MerchantAccountCreate { pub fn parse_routing_algorithm(&self) -> CustomResult<(), errors::ParsingError> { match self.routing_algorithm { Some(ref routing_algorithm) => { - let _: routing::RoutingAlgorithm = - routing_algorithm.clone().parse_value("RoutingAlgorithm")?; + let _: routing::StaticRoutingAlgorithm = routing_algorithm + .clone() + .parse_value("StaticRoutingAlgorithm")?; Ok(()) } None => Ok(()), @@ -325,7 +326,7 @@ pub struct MerchantAccountUpdate { /// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom' #[cfg(feature = "payouts")] - #[schema(value_type = Option<RoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] + #[schema(value_type = Option<StaticRoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] pub payout_routing_algorithm: Option<serde_json::Value>, /// A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false. @@ -425,8 +426,9 @@ impl MerchantAccountUpdate { pub fn parse_routing_algorithm(&self) -> CustomResult<(), errors::ParsingError> { match self.routing_algorithm { Some(ref routing_algorithm) => { - let _: routing::RoutingAlgorithm = - routing_algorithm.clone().parse_value("RoutingAlgorithm")?; + let _: routing::StaticRoutingAlgorithm = routing_algorithm + .clone() + .parse_value("StaticRoutingAlgorithm")?; Ok(()) } None => Ok(()), @@ -517,7 +519,7 @@ pub struct MerchantAccountResponse { /// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom' #[cfg(feature = "payouts")] - #[schema(value_type = Option<RoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] + #[schema(value_type = Option<StaticRoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] pub payout_routing_algorithm: Option<serde_json::Value>, /// A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false. @@ -545,7 +547,7 @@ pub struct MerchantAccountResponse { pub primary_business_details: Vec<PrimaryBusinessDetails>, /// The frm routing algorithm to be used to process the incoming request from merchant to outgoing payment FRM. - #[schema(value_type = Option<RoutingAlgorithm>, max_length = 255, example = r#"{"type": "single", "data": "stripe" }"#)] + #[schema(value_type = Option<StaticRoutingAlgorithm>, max_length = 255, example = r#"{"type": "single", "data": "stripe" }"#)] pub frm_routing_algorithm: Option<serde_json::Value>, /// The organization id merchant is associated with @@ -1897,7 +1899,7 @@ pub struct ProfileCreate { /// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom' #[cfg(feature = "payouts")] - #[schema(value_type = Option<RoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] + #[schema(value_type = Option<StaticRoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] pub payout_routing_algorithm: Option<serde_json::Value>, /// Verified Apple Pay domains for a particular profile @@ -2199,7 +2201,7 @@ pub struct ProfileResponse { /// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom' #[cfg(feature = "payouts")] - #[schema(value_type = Option<RoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] + #[schema(value_type = Option<StaticRoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] pub payout_routing_algorithm: Option<serde_json::Value>, /// Verified Apple Pay domains for a particular profile @@ -2504,7 +2506,7 @@ pub struct ProfileUpdate { /// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom' #[cfg(feature = "payouts")] - #[schema(value_type = Option<RoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] + #[schema(value_type = Option<StaticRoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] pub payout_routing_algorithm: Option<serde_json::Value>, /// Verified Apple Pay domains for a particular profile diff --git a/crates/api_models/src/events/routing.rs b/crates/api_models/src/events/routing.rs index c9fa118f596..750bfde2710 100644 --- a/crates/api_models/src/events/routing.rs +++ b/crates/api_models/src/events/routing.rs @@ -6,9 +6,9 @@ use crate::routing::{ LinkedRoutingConfigRetrieveResponse, MerchantRoutingAlgorithm, ProfileDefaultRoutingConfig, RoutingAlgorithmId, RoutingConfigRequest, RoutingDictionaryRecord, RoutingKind, RoutingLinkWrapper, RoutingPayloadWrapper, RoutingRetrieveLinkQuery, - RoutingRetrieveLinkQueryWrapper, RoutingRetrieveQuery, RoutingVolumeSplitWrapper, - SuccessBasedRoutingConfig, SuccessBasedRoutingPayloadWrapper, ToggleDynamicRoutingQuery, - ToggleDynamicRoutingWrapper, + RoutingRetrieveLinkQueryWrapper, RoutingRetrieveQuery, RoutingVolumeSplit, + RoutingVolumeSplitWrapper, SuccessBasedRoutingConfig, SuccessBasedRoutingPayloadWrapper, + ToggleDynamicRoutingQuery, ToggleDynamicRoutingWrapper, }; impl ApiEventMetric for RoutingKind { @@ -134,3 +134,9 @@ impl ApiEventMetric for RoutingVolumeSplitWrapper { Some(ApiEventsType::Routing) } } + +impl ApiEventMetric for RoutingVolumeSplit { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Routing) + } +} diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rs index 4c8a73b75a8..cf07fd9e109 100644 --- a/crates/api_models/src/payouts.rs +++ b/crates/api_models/src/payouts.rs @@ -58,7 +58,7 @@ pub struct PayoutCreateRequest { pub currency: Option<api_enums::Currency>, /// Specifies routing algorithm for selecting a connector - #[schema(value_type = Option<RoutingAlgorithm>, example = json!({ + #[schema(value_type = Option<StaticRoutingAlgorithm>, example = json!({ "type": "single", "data": "adyen" }))] diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index 12075935cd4..a15b135ac1f 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -49,7 +49,7 @@ impl ConnectorSelection { pub struct RoutingConfigRequest { pub name: String, pub description: String, - pub algorithm: RoutingAlgorithm, + pub algorithm: StaticRoutingAlgorithm, #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, } @@ -59,7 +59,7 @@ pub struct RoutingConfigRequest { pub struct RoutingConfigRequest { pub name: Option<String>, pub description: Option<String>, - pub algorithm: Option<RoutingAlgorithm>, + pub algorithm: Option<StaticRoutingAlgorithm>, #[schema(value_type = Option<String>)] pub profile_id: Option<common_utils::id_type::ProfileId>, } @@ -96,7 +96,7 @@ pub struct RoutingRetrieveResponse { #[derive(Debug, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum LinkedRoutingConfigRetrieveResponse { - MerchantAccountBased(RoutingRetrieveResponse), + MerchantAccountBased(Box<RoutingRetrieveResponse>), ProfileBased(Vec<RoutingDictionaryRecord>), } @@ -109,7 +109,7 @@ pub struct MerchantRoutingAlgorithm { pub profile_id: common_utils::id_type::ProfileId, pub name: String, pub description: String, - pub algorithm: RoutingAlgorithm, + pub algorithm: RoutingAlgorithmWrapper, pub created_at: i64, pub modified_at: i64, pub algorithm_for: TransactionType, @@ -301,6 +301,20 @@ pub struct RoutingPayloadWrapper { pub updated_config: Vec<RoutableConnectorChoice>, pub profile_id: common_utils::id_type::ProfileId, } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] +#[serde(untagged)] +pub enum RoutingAlgorithmWrapper { + Static(StaticRoutingAlgorithm), + Dynamic(DynamicRoutingAlgorithm), +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] +#[serde(untagged)] +pub enum DynamicRoutingAlgorithm { + EliminationBasedAlgorithm(EliminationRoutingConfig), + SuccessBasedAlgorithm(SuccessBasedRoutingConfig), + ContractBasedAlgorithm(ContractBasedRoutingConfig), +} #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde( @@ -309,8 +323,7 @@ pub struct RoutingPayloadWrapper { rename_all = "snake_case", try_from = "RoutingAlgorithmSerde" )] -/// Routing Algorithm kind -pub enum RoutingAlgorithm { +pub enum StaticRoutingAlgorithm { Single(Box<RoutableConnectorChoice>), Priority(Vec<RoutableConnectorChoice>), VolumeSplit(Vec<ConnectorVolumeSplit>), @@ -318,7 +331,7 @@ pub enum RoutingAlgorithm { Advanced(ast::Program<ConnectorSelection>), } -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] pub enum RoutingAlgorithmSerde { Single(Box<RoutableConnectorChoice>), @@ -327,7 +340,7 @@ pub enum RoutingAlgorithmSerde { Advanced(ast::Program<ConnectorSelection>), } -impl TryFrom<RoutingAlgorithmSerde> for RoutingAlgorithm { +impl TryFrom<RoutingAlgorithmSerde> for StaticRoutingAlgorithm { type Error = error_stack::Report<ParsingError>; fn try_from(value: RoutingAlgorithmSerde) -> Result<Self, Self::Error> { @@ -434,7 +447,7 @@ impl From<StraightThroughAlgorithm> for StraightThroughAlgorithmSerde { } } -impl From<StraightThroughAlgorithm> for RoutingAlgorithm { +impl From<StraightThroughAlgorithm> for StaticRoutingAlgorithm { fn from(value: StraightThroughAlgorithm) -> Self { match value { StraightThroughAlgorithm::Single(conn) => Self::Single(conn), @@ -444,7 +457,7 @@ impl From<StraightThroughAlgorithm> for RoutingAlgorithm { } } -impl RoutingAlgorithm { +impl StaticRoutingAlgorithm { pub fn get_kind(&self) -> RoutingAlgorithmKind { match self { Self::Single(_) => RoutingAlgorithmKind::Single, @@ -845,6 +858,7 @@ pub struct ToggleDynamicRoutingPath { } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] +#[serde(deny_unknown_fields)] pub struct EliminationRoutingConfig { pub params: Option<Vec<DynamicRoutingConfigParams>>, pub elimination_analyser_config: Option<EliminationAnalyserConfig>, @@ -853,6 +867,7 @@ pub struct EliminationRoutingConfig { } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy, ToSchema)] +#[serde(deny_unknown_fields)] pub struct EliminationAnalyserConfig { pub bucket_size: Option<u64>, pub bucket_leak_interval_in_secs: Option<u64>, @@ -924,6 +939,7 @@ impl EliminationRoutingConfig { } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] +#[serde(deny_unknown_fields)] pub struct SuccessBasedRoutingConfig { pub params: Option<Vec<DynamicRoutingConfigParams>>, pub config: Option<SuccessBasedRoutingConfigBody>, @@ -950,7 +966,9 @@ impl Default for SuccessBasedRoutingConfig { } } -#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema, strum::Display)] +#[derive( + serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema, PartialEq, strum::Display, +)] pub enum DynamicRoutingConfigParams { PaymentMethod, PaymentMethodType, @@ -962,6 +980,7 @@ pub enum DynamicRoutingConfigParams { } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] +#[serde(deny_unknown_fields)] pub struct SuccessBasedRoutingConfigBody { pub min_aggregates_size: Option<u32>, pub default_success_rate: Option<f64>, diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index b042d2bdbd6..ffba56ac6bc 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -658,7 +658,12 @@ Never share your secret api keys. Keep them guarded and secure. api_models::routing::MerchantRoutingAlgorithm, api_models::routing::RoutingAlgorithmKind, api_models::routing::RoutingDictionary, - api_models::routing::RoutingAlgorithm, + api_models::routing::RoutingAlgorithmWrapper, + api_models::routing::EliminationRoutingConfig, + api_models::open_router::DecisionEngineEliminationData, + api_models::routing::EliminationAnalyserConfig, + api_models::routing::DynamicRoutingAlgorithm, + api_models::routing::StaticRoutingAlgorithm, api_models::routing::StraightThroughAlgorithm, api_models::routing::ConnectorVolumeSplit, api_models::routing::ConnectorSelection, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 9b8387389fe..f5632e9c3c9 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -644,7 +644,25 @@ Never share your secret api keys. Keep them guarded and secure. api_models::routing::MerchantRoutingAlgorithm, api_models::routing::RoutingAlgorithmKind, api_models::routing::RoutingDictionary, - api_models::routing::RoutingAlgorithm, + api_models::routing::DynamicRoutingConfigParams, + api_models::routing::SuccessBasedRoutingConfig, + api_models::routing::SuccessRateSpecificityLevel, + api_models::routing::CurrentBlockThreshold, + api_models::open_router::DecisionEngineSuccessRateData, + api_models::routing::ContractBasedTimeScale, + api_models::routing::LabelInformation, + api_models::routing::ContractBasedRoutingConfig, + api_models::routing::ContractBasedRoutingConfigBody, + api_models::open_router::DecisionEngineGatewayWiseExtraScore, + api_models::open_router::DecisionEngineSRSubLevelInputConfig, + api_models::open_router::DecisionEngineEliminationData, + api_models::routing::SuccessBasedRoutingConfigBody, + api_models::routing::RoutingAlgorithmWrapper, + api_models::routing::EliminationRoutingConfig, + api_models::open_router::DecisionEngineEliminationData, + api_models::routing::EliminationAnalyserConfig, + api_models::routing::DynamicRoutingAlgorithm, + api_models::routing::StaticRoutingAlgorithm, api_models::routing::StraightThroughAlgorithm, api_models::routing::ConnectorVolumeSplit, api_models::routing::ConnectorSelection, diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index ee5fb184257..c153c88e0ec 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -287,7 +287,7 @@ impl TryFrom<StripePaymentIntentRequest> for payments::PaymentsRequest { let routing = routable_connector .map(|connector| { - api_models::routing::RoutingAlgorithm::Single(Box::new( + api_models::routing::StaticRoutingAlgorithm::Single(Box::new( api_models::routing::RoutableConnectorChoice { choice_kind: api_models::routing::RoutableChoiceKind::FullStruct, connector, diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs index 77db75e2188..90098f1c308 100644 --- a/crates/router/src/compatibility/stripe/setup_intents/types.rs +++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs @@ -183,7 +183,7 @@ impl TryFrom<StripeSetupIntentRequest> for payments::PaymentsRequest { let routing = routable_connector .map(|connector| { - api_models::routing::RoutingAlgorithm::Single(Box::new( + api_models::routing::StaticRoutingAlgorithm::Single(Box::new( api_models::routing::RoutableConnectorChoice { choice_kind: api_models::routing::RoutableChoiceKind::FullStruct, connector, diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 14f2e439f50..c8f53cd07a6 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -3801,7 +3801,7 @@ impl ProfileCreateBridge for api::ProfileCreate { } if let Some(ref routing_algorithm) = self.routing_algorithm { - let _: api_models::routing::RoutingAlgorithm = routing_algorithm + let _: api_models::routing::StaticRoutingAlgorithm = routing_algorithm .clone() .parse_value("RoutingAlgorithm") .change_context(errors::ApiErrorResponse::InvalidDataValue { @@ -4300,7 +4300,7 @@ impl ProfileUpdateBridge for api::ProfileUpdate { let webhook_details = self.webhook_details.map(ForeignInto::foreign_into); if let Some(ref routing_algorithm) = self.routing_algorithm { - let _: api_models::routing::RoutingAlgorithm = routing_algorithm + let _: api_models::routing::StaticRoutingAlgorithm = routing_algorithm .clone() .parse_value("RoutingAlgorithm") .change_context(errors::ApiErrorResponse::InvalidDataValue { diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 4c3894d5d37..7a3727aa563 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -6240,7 +6240,7 @@ where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { - let _: api_models::routing::RoutingAlgorithm = request_straight_through + let _: api_models::routing::StaticRoutingAlgorithm = request_straight_through .clone() .parse_value("RoutingAlgorithm") .attach_printable("Invalid straight through routing rules format")?; diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 2b851c192b0..b4ac7d4421d 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -577,15 +577,15 @@ fn execute_dsl_and_get_connector_v1( backend_input: dsl_inputs::BackendInput, interpreter: &backend::VirInterpreterBackend<ConnectorSelection>, ) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> { - let routing_output: routing_types::RoutingAlgorithm = interpreter + let routing_output: routing_types::StaticRoutingAlgorithm = interpreter .execute(backend_input) .map(|out| out.connector_selection.foreign_into()) .change_context(errors::RoutingError::DslExecutionError)?; Ok(match routing_output { - routing_types::RoutingAlgorithm::Priority(plist) => plist, + routing_types::StaticRoutingAlgorithm::Priority(plist) => plist, - routing_types::RoutingAlgorithm::VolumeSplit(splits) => perform_volume_split(splits) + routing_types::StaticRoutingAlgorithm::VolumeSplit(splits) => perform_volume_split(splits) .change_context(errors::RoutingError::DslFinalConnectorSelectionFailed)?, _ => Err(errors::RoutingError::DslIncorrectSelectionAlgorithm) @@ -605,7 +605,7 @@ pub async fn refresh_routing_cache_v1( .find_routing_algorithm_by_profile_id_algorithm_id(profile_id, algorithm_id) .await .change_context(errors::RoutingError::DslMissingInDb)?; - let algorithm: routing_types::RoutingAlgorithm = algorithm + let algorithm: routing_types::StaticRoutingAlgorithm = algorithm .algorithm_data .parse_value("RoutingAlgorithm") .change_context(errors::RoutingError::DslParsingError)?; @@ -613,12 +613,12 @@ pub async fn refresh_routing_cache_v1( }; let cached_algorithm = match algorithm { - routing_types::RoutingAlgorithm::Single(conn) => CachedAlgorithm::Single(conn), - routing_types::RoutingAlgorithm::Priority(plist) => CachedAlgorithm::Priority(plist), - routing_types::RoutingAlgorithm::VolumeSplit(splits) => { + routing_types::StaticRoutingAlgorithm::Single(conn) => CachedAlgorithm::Single(conn), + routing_types::StaticRoutingAlgorithm::Priority(plist) => CachedAlgorithm::Priority(plist), + routing_types::StaticRoutingAlgorithm::VolumeSplit(splits) => { CachedAlgorithm::VolumeSplit(splits) } - routing_types::RoutingAlgorithm::Advanced(program) => { + routing_types::StaticRoutingAlgorithm::Advanced(program) => { let interpreter = backend::VirInterpreterBackend::with_program(program) .change_context(errors::RoutingError::DslBackendInitError) .attach_printable("Error initializing DSL interpreter backend")?; diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs index 893c66af24c..df6189ea424 100644 --- a/crates/router/src/core/routing.rs +++ b/crates/router/src/core/routing.rs @@ -275,7 +275,7 @@ pub async fn create_routing_algorithm_under_profile( request: routing_types::RoutingConfigRequest, transaction_type: enums::TransactionType, ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { - use api_models::routing::RoutingAlgorithm as EuclidAlgorithm; + use api_models::routing::StaticRoutingAlgorithm as EuclidAlgorithm; use crate::services::logger; @@ -1174,16 +1174,20 @@ pub async fn retrieve_linked_routing_config( transaction_type: &enums::TransactionType, ) -> RouterResponse<routing_types::LinkedRoutingConfigRetrieveResponse> { metrics::ROUTING_RETRIEVE_LINK_CONFIG.add(1, &[]); + let db = state.store.as_ref(); let key_manager_state = &(&state).into(); + let merchant_key_store = merchant_context.get_merchant_key_store(); + let merchant_id = merchant_context.get_merchant_account().get_id(); + // Get business profiles let business_profiles = if let Some(profile_id) = query_params.profile_id { core_utils::validate_and_get_business_profile( db, key_manager_state, - merchant_context.get_merchant_key_store(), + merchant_key_store, Some(&profile_id), - merchant_context.get_merchant_account().get_id(), + merchant_id, ) .await? .map(|profile| vec![profile]) @@ -1193,28 +1197,25 @@ pub async fn retrieve_linked_routing_config( })? } else { let business_profile = db - .list_profile_by_merchant_id( - key_manager_state, - merchant_context.get_merchant_key_store(), - merchant_context.get_merchant_account().get_id(), - ) + .list_profile_by_merchant_id(key_manager_state, merchant_key_store, merchant_id) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; core_utils::filter_objects_based_on_profile_id_list( authentication_profile_id.map(|profile_id| vec![profile_id]), - business_profile.clone(), + business_profile, ) }; let mut active_algorithms = Vec::new(); for business_profile in business_profiles { - let profile_id = business_profile.get_id().to_owned(); + let profile_id = business_profile.get_id(); + // Handle static routing algorithm let routing_ref: routing_types::RoutingAlgorithmRef = match transaction_type { - enums::TransactionType::Payment => business_profile.routing_algorithm, + enums::TransactionType::Payment => &business_profile.routing_algorithm, #[cfg(feature = "payouts")] - enums::TransactionType::Payout => business_profile.payout_routing_algorithm, + enums::TransactionType::Payout => &business_profile.payout_routing_algorithm, } .clone() .map(|val| val.parse_value("RoutingAlgorithmRef")) @@ -1227,11 +1228,53 @@ pub async fn retrieve_linked_routing_config( let record = db .find_routing_algorithm_metadata_by_algorithm_id_profile_id( &algorithm_id, - &profile_id, + profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; + active_algorithms.push(record.foreign_into()); + } + + // Handle dynamic routing algorithms + let dynamic_routing_ref: routing_types::DynamicRoutingAlgorithmRef = business_profile + .dynamic_routing_algorithm + .clone() + .map(|val| val.parse_value("DynamicRoutingAlgorithmRef")) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "unable to deserialize dynamic routing algorithm ref from business profile", + )? + .unwrap_or_default(); + // Collect all dynamic algorithm IDs + let mut dynamic_algorithm_ids = Vec::new(); + + if let Some(sba) = &dynamic_routing_ref.success_based_algorithm { + if let Some(id) = &sba.algorithm_id_with_timestamp.algorithm_id { + dynamic_algorithm_ids.push(id.clone()); + } + } + if let Some(era) = &dynamic_routing_ref.elimination_routing_algorithm { + if let Some(id) = &era.algorithm_id_with_timestamp.algorithm_id { + dynamic_algorithm_ids.push(id.clone()); + } + } + if let Some(cbr) = &dynamic_routing_ref.contract_based_routing { + if let Some(id) = &cbr.algorithm_id_with_timestamp.algorithm_id { + dynamic_algorithm_ids.push(id.clone()); + } + } + + // Fetch all dynamic algorithms + for algorithm_id in dynamic_algorithm_ids { + let record = db + .find_routing_algorithm_metadata_by_algorithm_id_profile_id( + &algorithm_id, + profile_id, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; active_algorithms.push(record.foreign_into()); } } @@ -1456,7 +1499,7 @@ pub async fn configure_dynamic_routing_volume_split( merchant_context: domain::MerchantContext, profile_id: common_utils::id_type::ProfileId, routing_info: routing::RoutingVolumeSplit, -) -> RouterResponse<()> { +) -> RouterResponse<routing::RoutingVolumeSplit> { metrics::ROUTING_CREATE_REQUEST_RECEIVED.add( 1, router_env::metric_attributes!(("profile_id", profile_id.clone())), @@ -1508,7 +1551,7 @@ pub async fn configure_dynamic_routing_volume_split( ) .await?; - Ok(service_api::ApplicationResponse::StatusOk) + Ok(service_api::ApplicationResponse::Json(routing_info)) } #[cfg(all(feature = "v1", feature = "dynamic_routing"))] diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 89d0cb7bfe3..a29f25331ec 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -312,7 +312,7 @@ pub async fn update_business_profile_active_dynamic_algorithm_ref( pub struct RoutingAlgorithmHelpers<'h> { pub name_mca_id_set: ConnectNameAndMCAIdForProfile<'h>, pub name_set: ConnectNameForProfile<'h>, - pub routing_algorithm: &'h routing_types::RoutingAlgorithm, + pub routing_algorithm: &'h routing_types::StaticRoutingAlgorithm, } #[cfg(feature = "v1")] @@ -410,23 +410,23 @@ impl RoutingAlgorithmHelpers<'_> { pub fn validate_connectors_in_routing_config(&self) -> RouterResult<()> { match self.routing_algorithm { - routing_types::RoutingAlgorithm::Single(choice) => { + routing_types::StaticRoutingAlgorithm::Single(choice) => { self.connector_choice(choice)?; } - routing_types::RoutingAlgorithm::Priority(list) => { + routing_types::StaticRoutingAlgorithm::Priority(list) => { for choice in list { self.connector_choice(choice)?; } } - routing_types::RoutingAlgorithm::VolumeSplit(splits) => { + routing_types::StaticRoutingAlgorithm::VolumeSplit(splits) => { for split in splits { self.connector_choice(&split.connector)?; } } - routing_types::RoutingAlgorithm::Advanced(program) => { + routing_types::StaticRoutingAlgorithm::Advanced(program) => { let check_connector_selection = |selection: &routing_types::ConnectorSelection| -> RouterResult<()> { match selection { @@ -464,7 +464,7 @@ pub async fn validate_connectors_in_routing_config( key_store: &domain::MerchantKeyStore, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, - routing_algorithm: &routing_types::RoutingAlgorithm, + routing_algorithm: &routing_types::StaticRoutingAlgorithm, ) -> RouterResult<()> { let all_mcas = state .store @@ -518,23 +518,23 @@ pub async fn validate_connectors_in_routing_config( }; match routing_algorithm { - routing_types::RoutingAlgorithm::Single(choice) => { + routing_types::StaticRoutingAlgorithm::Single(choice) => { connector_choice(choice)?; } - routing_types::RoutingAlgorithm::Priority(list) => { + routing_types::StaticRoutingAlgorithm::Priority(list) => { for choice in list { connector_choice(choice)?; } } - routing_types::RoutingAlgorithm::VolumeSplit(splits) => { + routing_types::StaticRoutingAlgorithm::VolumeSplit(splits) => { for split in splits { connector_choice(&split.connector)?; } } - routing_types::RoutingAlgorithm::Advanced(program) => { + routing_types::StaticRoutingAlgorithm::Advanced(program) => { let check_connector_selection = |selection: &routing_types::ConnectorSelection| -> RouterResult<()> { match selection { diff --git a/crates/router/src/core/routing/transformers.rs b/crates/router/src/core/routing/transformers.rs index ebf521c4604..4face887995 100644 --- a/crates/router/src/core/routing/transformers.rs +++ b/crates/router/src/core/routing/transformers.rs @@ -1,6 +1,6 @@ use api_models::routing::{ - MerchantRoutingAlgorithm, RoutingAlgorithm as Algorithm, RoutingAlgorithmKind, - RoutingDictionaryRecord, + DynamicRoutingAlgorithm, MerchantRoutingAlgorithm, RoutingAlgorithmKind, + RoutingAlgorithmWrapper, RoutingDictionaryRecord, }; #[cfg(feature = "v1")] use api_models::{ @@ -59,15 +59,23 @@ impl ForeignTryFrom<RoutingAlgorithm> for MerchantRoutingAlgorithm { type Error = error_stack::Report<errors::ParsingError>; fn foreign_try_from(value: RoutingAlgorithm) -> Result<Self, Self::Error> { + let algorithm: RoutingAlgorithmWrapper = match value.kind { + diesel_models::enums::RoutingAlgorithmKind::Dynamic => value + .algorithm_data + .parse_value::<DynamicRoutingAlgorithm>("RoutingAlgorithmDynamic") + .map(RoutingAlgorithmWrapper::Dynamic)?, + _ => value + .algorithm_data + .parse_value::<api_models::routing::StaticRoutingAlgorithm>("RoutingAlgorithm") + .map(RoutingAlgorithmWrapper::Static)?, + }; + Ok(Self { id: value.algorithm_id, name: value.name, - profile_id: value.profile_id, description: value.description.unwrap_or_default(), - algorithm: value - .algorithm_data - .parse_value::<Algorithm>("RoutingAlgorithm")?, + algorithm, created_at: value.created_at.assume_utc().unix_timestamp(), modified_at: value.modified_at.assume_utc().unix_timestamp(), algorithm_for: value.algorithm_for, diff --git a/crates/router/src/types/api/routing.rs b/crates/router/src/types/api/routing.rs index d201f57eb92..ac7337d923b 100644 --- a/crates/router/src/types/api/routing.rs +++ b/crates/router/src/types/api/routing.rs @@ -1,9 +1,9 @@ pub use api_models::{ enums as api_enums, routing::{ - ConnectorVolumeSplit, RoutableChoiceKind, RoutableConnectorChoice, RoutingAlgorithm, - RoutingAlgorithmKind, RoutingAlgorithmRef, RoutingConfigRequest, RoutingDictionary, - RoutingDictionaryRecord, StraightThroughAlgorithm, + ConnectorVolumeSplit, RoutableChoiceKind, RoutableConnectorChoice, RoutingAlgorithmKind, + RoutingAlgorithmRef, RoutingConfigRequest, RoutingDictionary, RoutingDictionaryRecord, + StaticRoutingAlgorithm, StraightThroughAlgorithm, }, }; diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 911cacf604e..ea4c98c31f1 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -1820,7 +1820,7 @@ impl From<domain::Address> for payments::AddressDetails { } } -impl ForeignFrom<ConnectorSelection> for routing_types::RoutingAlgorithm { +impl ForeignFrom<ConnectorSelection> for routing_types::StaticRoutingAlgorithm { fn foreign_from(value: ConnectorSelection) -> Self { match value { ConnectorSelection::Priority(connectors) => Self::Priority(connectors),
2025-05-22T11:13:41Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR introduces support for listing both static and dynamic routing algorithms under a unified API interface. To accomplish this, it refactors how routing algorithms are represented and parsed, introducing clear separation between `StaticRoutingAlgorithm` and `DynamicRoutingAlgorithm`. The new enum `RoutingAlgorithmWrapper` is used to encapsulate both types. Dynamic routing strategies like `EliminationBasedAlgorithm`, `SuccessBasedAlgorithm`, and `ContractBasedAlgorithm` are now modeled and tracked similarly to static rules, allowing for consistent listing and configuration. ## Outcomes - Enables unified listing of static and dynamic routing algorithms linked to a business profile. - Enhances the routing engine’s flexibility to support multiple dynamic strategies (e.g., success-based, elimination-based). - Provides type-safe and structured handling of dynamic routing configurations. - Prepares the system for future expansion (e.g., integration of new algorithm types). - Improves API and database alignment by enabling dynamic routing references per profile. ## Diff Hunk Explanation ### `api_models/src/routing.rs` - Added `StaticRoutingAlgorithm`, `DynamicRoutingAlgorithm`, and `RoutingAlgorithmWrapper` enums to distinguish algorithm types. - Updated various structs to use `StaticRoutingAlgorithm` instead of the generic `RoutingAlgorithm`. - Introduced serde wrappers with `#[serde(untagged)]` for backward-compatible JSON parsing. ### `api_models/src/events/routing.rs` - Registered new types like `RoutingVolumeSplit` for event logging via `ApiEventMetric`. ### `router/src/core/routing.rs` - In `retrieve_linked_routing_config`, extended logic to resolve dynamic routing references and list their metadata. - Dynamic algorithms from the profile are resolved and listed alongside static algorithms. ### `router/src/core/routing/helpers.rs` - Updated connector validation to work with `StaticRoutingAlgorithm`. - Added support to validate connectors within dynamic strategies indirectly via wrapper types. ### `router/src/core/payments/routing.rs` - Adjusted runtime routing execution to handle `StaticRoutingAlgorithm`. - Ensured routing output from interpreters is correctly matched and handled. ### `transformers.rs`, `admin.rs`, `payments.rs`, and `stripe/types.rs` - Refactored references and conversions to use the newly introduced `StaticRoutingAlgorithm`. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ### Curls for testing the flows: 1. Create a static rule: ``` curl --location 'http://127.0.0.1:8080/routing' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_IpYFqCd4DHf7x4ER1GBQrW0mHOZzam3pYyuP2tSRb6q7qvTw7jvEjF7UzjwFPXWu' \ --data ' { "name": "Priority rule with fallback", "description": "It is my ADVANCED config", "profile_id": "pro_INSNcGnV7dSldWXpW1GE", "algorithm": { "type": "advanced", "data": { "defaultSelection": { "type": "priority", "data": [ { "connector": "stripe", "merchant_connector_id": "mca_gtMC3BG1m6YTX0j8hwUU" } ] }, "rules": [ { "name": "cybersource first", "connectorSelection": { "type": "priority", "data": [ { "connector": "stripe", "merchant_connector_id": "mca_gtMC3BG1m6YTX0j8hwUU" } ] }, "statements": [ { "condition": [ { "lhs": "billing_country", "comparison": "equal", "value": { "type": "enum_variant", "value": "Netherlands" }, "metadata": {} }, { "lhs": "amount", "comparison": "greater_than", "value": { "type": "number", "value": 1000 }, "metadata": {} } ], "nested": null } ] } ], "metadata": {} } } } ' ``` 2. Retrive the rule using id ``` curl --location 'http://127.0.0.1:8080/routing/routing_v2x2BWS0Rf3QKsyc8GUU' \ --header 'api-key: dev_IpYFqCd4DHf7x4ER1GBQrW0mHOZzam3pYyuP2tSRb6q7qvTw7jvEjF7UzjwFPXWu' ``` Response ``` { "id": "routing_v2x2BWS0Rf3QKsyc8GUU", "profile_id": "pro_INSNcGnV7dSldWXpW1GE", "name": "Priority rule with fallback", "description": "It is my ADVANCED config", "algorithm": { "type": "advanced", "data": { "defaultSelection": { "type": "priority", "data": [ { "connector": "stripe", "merchant_connector_id": "mca_gtMC3BG1m6YTX0j8hwUU" } ] }, "rules": [ { "name": "cybersource first", "connectorSelection": { "type": "priority", "data": [ { "connector": "stripe", "merchant_connector_id": "mca_gtMC3BG1m6YTX0j8hwUU" } ] }, "statements": [ { "condition": [ { "lhs": "billing_country", "comparison": "equal", "value": { "type": "enum_variant", "value": "Netherlands" }, "metadata": {} }, { "lhs": "amount", "comparison": "greater_than", "value": { "type": "number", "value": 1000 }, "metadata": {} } ], "nested": null } ] } ], "metadata": {} } }, "created_at": 1747996597, "modified_at": 1747996597, "algorithm_for": "payment" } ``` 3. Toggle SR routing ``` curl --location --request POST 'http://localhost:8080/account/merchant_1747967454/business_profile/pro_INSNcGnV7dSldWXpW1GE/dynamic_routing/success_based/toggle?enable=dynamic_connector_selection' \ --header 'api-key: dev_IpYFqCd4DHf7x4ER1GBQrW0mHOZzam3pYyuP2tSRb6q7qvTw7jvEjF7UzjwFPXWu' ``` 4. Retrieve it using the routing id: ``` curl --location 'http://127.0.0.1:8080/routing/routing_XP894HcdwYPJqCQjQqJV' \ --header 'api-key: dev_IpYFqCd4DHf7x4ER1GBQrW0mHOZzam3pYyuP2tSRb6q7qvTw7jvEjF7UzjwFPXWu' ``` Response: ``` { "id": "routing_XP894HcdwYPJqCQjQqJV", "profile_id": "pro_INSNcGnV7dSldWXpW1GE", "name": "Success rate based dynamic routing algorithm", "description": "", "algorithm": { "params": [ "PaymentMethod" ], "config": { "min_aggregates_size": 2, "default_success_rate": 100.0, "max_aggregates_size": 3, "current_block_threshold": { "duration_in_mins": 5, "max_total_count": 2 }, "specificity_level": "merchant" } }, "created_at": 1747967494, "modified_at": 1747967494, "algorithm_for": "payment" } ``` 5. Toggle elimination routing ``` curl --location --request POST 'http://localhost:8080/account/merchant_1747967454/business_profile/pro_INSNcGnV7dSldWXpW1GE/dynamic_routing/elimination/toggle?enable=dynamic_connector_selection' \ --header 'api-key: dev_IpYFqCd4DHf7x4ER1GBQrW0mHOZzam3pYyuP2tSRb6q7qvTw7jvEjF7UzjwFPXWu' ``` 6. Retrieve it using the routing id: ``` curl --location 'http://127.0.0.1:8080/routing/routing_XP894HcdwYPJqCQjQqJV' \ --header 'api-key: dev_IpYFqCd4DHf7x4ER1GBQrW0mHOZzam3pYyuP2tSRb6q7qvTw7jvEjF7UzjwFPXWu' ``` Response: ``` { "id": "routing_ZlQZoyVildA7HusIfehn", "profile_id": "pro_INSNcGnV7dSldWXpW1GE", "name": "Elimination based dynamic routing algorithm", "description": "", "algorithm": { "params": [ "PaymentMethod" ], "elimination_analyser_config": { "bucket_size": 5, "bucket_leak_interval_in_secs": 60 } }, "created_at": 1747968281, "modified_at": 1747968281, "algorithm_for": "payment" } ``` 5. Toggle contract based routing ``` curl --location 'http://localhost:8080/account/merchant_1747967454/business_profile/pro_INSNcGnV7dSldWXpW1GE/dynamic_routing/contracts/toggle?enable=dynamic_connector_selection' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_IpYFqCd4DHf7x4ER1GBQrW0mHOZzam3pYyuP2tSRb6q7qvTw7jvEjF7UzjwFPXWu' \ --data ' { "config": null, "label_info": null }' ``` 6. Retrieve it using the routing id: ``` curl --location 'http://127.0.0.1:8080/routing/routing_XP894HcdwYPJqCQjQqJV' \ --header 'api-key: dev_IpYFqCd4DHf7x4ER1GBQrW0mHOZzam3pYyuP2tSRb6q7qvTw7jvEjF7UzjwFPXWu' ``` Response: ``` { "id": "routing_C13lGF4NR613rAyuUsuZ", "profile_id": "pro_INSNcGnV7dSldWXpW1GE", "name": "Contract based dynamic routing algorithm", "description": "", "algorithm": { "config": null, "label_info": null }, "created_at": 1747998023, "modified_at": 1747998023, "algorithm_for": "payment" } ``` 7. Volume between routing types ``` curl --location --request POST 'http://localhost:8080/account/merchant_1747967454/business_profile/pro_INSNcGnV7dSldWXpW1GE/dynamic_routing/set_volume_split?split=100' \ --header 'api-key: dev_IpYFqCd4DHf7x4ER1GBQrW0mHOZzam3pYyuP2tSRb6q7qvTw7jvEjF7UzjwFPXWu' ``` Response ``` { "routing_type": "dynamic", "split": 100 } ``` 8. List active configs toggle SR, toggle ER create a static rule and activate it ``` curl --location 'http://localhost:8080/routing/active' \ --header 'api-key: dev_IpYFqCd4DHf7x4ER1GBQrW0mHOZzam3pYyuP2tSRb6q7qvTw7jvEjF7UzjwFPXWu' ``` Response 3 values should come ``` [ { "id": "routing_j9omIKybJb6jw2PIwFhQ", "profile_id": "pro_INSNcGnV7dSldWXpW1GE", "name": "Priority rule with fallback", "kind": "advanced", "description": "It is my ADVANCED config", "created_at": 1748005058, "modified_at": 1748005058, "algorithm_for": "payment", "decision_engine_routing_id": null }, { "id": "routing_ZlQZoyVildA7HusIfehn", "profile_id": "pro_INSNcGnV7dSldWXpW1GE", "name": "Elimination based dynamic routing algorithm", "kind": "dynamic", "description": "", "created_at": 1747968281, "modified_at": 1747968281, "algorithm_for": "payment", "decision_engine_routing_id": null }, { "id": "routing_4E6HvDyeOUJKs3ncGDk7", "profile_id": "pro_INSNcGnV7dSldWXpW1GE", "name": "Contract based dynamic routing algorithm", "kind": "dynamic", "description": "", "created_at": 1748005049, "modified_at": 1748005049, "algorithm_for": "payment", "decision_engine_routing_id": null } ] ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
e272e7ab23845b664857ee729bb0eb7d05faac36
e272e7ab23845b664857ee729bb0eb7d05faac36
juspay/hyperswitch
juspay__hyperswitch-8122
Bug: [BUG] Fiuu connector does not return error_code and error_message for failed FPX transactions ### Bug Description Currently, Fiuu connector is not returning error_code and error_message for failed FPX transactions. This is returned during redirection back to HS but not during PSync. However, this is being not being respected. ### Expected Behavior In case error_code and error_message is present, it should be populated in the API and webhooks response. ### Actual Behavior The error code and message returned during redirection back to HS is not being respected. ### Steps To Reproduce 1. Create fpx transaction 2. Proceed with failure 3. Retrieve payments in HS - should see empty error_code and error_message in the payments API response ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs index 367f800a1d4..d05654265fd 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs @@ -1282,6 +1282,65 @@ impl TryFrom<&PaymentsSyncRouterData> for FiuuPaymentSyncRequest { } } +struct ErrorInputs { + encoded_data: Option<String>, + response_error_code: Option<String>, + response_error_desc: Option<String>, +} + +struct ErrorDetails { + pub code: String, + pub message: String, + pub reason: Option<String>, +} + +impl TryFrom<ErrorInputs> for ErrorDetails { + type Error = Report<errors::ConnectorError>; + fn try_from(value: ErrorInputs) -> Result<Self, Self::Error> { + let query_params = value + .encoded_data + .as_ref() + .map(|encoded_data| { + serde_urlencoded::from_str::<FiuuPaymentRedirectResponse>(encoded_data) + }) + .transpose() + .change_context(errors::ConnectorError::ResponseDeserializationFailed) + .attach_printable("Failed to deserialize FiuuPaymentRedirectResponse")?; + let error_message = value + .response_error_desc + .as_ref() + .filter(|s| !s.is_empty()) + .cloned() + .or_else(|| { + query_params + .as_ref() + .and_then(|qp| qp.error_desc.as_ref()) + .filter(|s| !s.is_empty()) + .cloned() + }); + let error_code = value + .response_error_code + .as_ref() + .filter(|s| !s.is_empty()) + .cloned() + .or_else(|| { + query_params + .as_ref() + .and_then(|qp| qp.error_code.as_ref()) + .filter(|s| !s.is_empty()) + .cloned() + }) + .unwrap_or_else(|| consts::NO_ERROR_CODE.to_owned()); + Ok(Self { + code: error_code, + message: error_message + .clone() + .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_owned()), + reason: error_message, + }) + } +} + impl TryFrom<PaymentsSyncResponseRouterData<FiuuPaymentResponse>> for PaymentsSyncRouterData { type Error = Report<errors::ConnectorError>; fn try_from( @@ -1297,16 +1356,16 @@ impl TryFrom<PaymentsSyncResponseRouterData<FiuuPaymentResponse>> for PaymentsSy stat_code, })?; let error_response = if status == enums::AttemptStatus::Failure { + let error_details = ErrorDetails::try_from(ErrorInputs { + encoded_data: item.data.request.encoded_data.clone(), + response_error_code: response.error_code.clone(), + response_error_desc: response.error_desc.clone(), + })?; Some(ErrorResponse { status_code: item.http_code, - code: response - .error_code - .unwrap_or(consts::NO_ERROR_CODE.to_owned()), - message: response - .error_desc - .clone() - .unwrap_or(consts::NO_ERROR_MESSAGE.to_owned()), - reason: response.error_desc, + code: error_details.code, + message: error_details.message, + reason: error_details.reason, attempt_status: Some(enums::AttemptStatus::Failure), connector_transaction_id: Some(txn_id.clone()), network_advice_code: None, @@ -1364,17 +1423,16 @@ impl TryFrom<PaymentsSyncResponseRouterData<FiuuPaymentResponse>> for PaymentsSy } }); let error_response = if status == enums::AttemptStatus::Failure { + let error_details = ErrorDetails::try_from(ErrorInputs { + encoded_data: item.data.request.encoded_data.clone(), + response_error_code: response.error_code.clone(), + response_error_desc: response.error_desc.clone(), + })?; Some(ErrorResponse { status_code: item.http_code, - code: response - .error_code - .clone() - .unwrap_or(consts::NO_ERROR_CODE.to_owned()), - message: response - .error_desc - .clone() - .unwrap_or(consts::NO_ERROR_MESSAGE.to_owned()), - reason: response.error_desc.clone(), + code: error_details.code, + message: error_details.message, + reason: error_details.reason, attempt_status: Some(enums::AttemptStatus::Failure), connector_transaction_id: Some(txn_id.clone()), network_advice_code: None, @@ -1861,6 +1919,17 @@ pub struct FiuuWebhooksPaymentResponse { pub extra_parameters: Option<Secret<String>>, } +#[derive(Debug, Deserialize, Serialize, Clone)] +pub struct FiuuPaymentRedirectResponse { + pub skey: Secret<String>, + #[serde(rename = "tranID")] + pub tran_id: String, + pub status: FiuuPaymentWebhookStatus, + pub appcode: Option<String>, + pub error_code: Option<String>, + pub error_desc: Option<String>, +} + #[derive(Debug, Deserialize, Serialize, Clone)] #[serde(rename_all = "PascalCase")] pub struct FiuuWebhooksRefundResponse {
2025-05-23T10:47:15Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Fixed Fiuu connector to properly handle and return `error_code` and `error_message` for failed FPX transactions. The connector was previously receiving error information during redirection back to Hyperswitch but was not populating these fields in API responses after redirection back to Hyperswitch during Payment Sync (PSync) operations. **Changes made:** - Updated Fiuu connector's FPX transaction handling to capture and store error_code and error_message from redirection responses - Modified PSync logic to properly propagate error information to payment API response ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> This change addresses a critical gap in error handling for FPX transactions through the Fiuu connector. Currently, when FPX transactions fail, the error details provided during redirection are not being captured and made available through the Hyperswitch API or webhooks. This makes it difficult for merchants to understand why transactions failed and provide appropriate feedback to their customers. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Steps for testing - <details> <summary>1. Add Fiuu connector and enable FPX</summary> cURL curl --location --request POST 'http://localhost:8080/account/merchant_1747931797/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-feature: integ-custom' \ --header 'api-key: dev_8GkaY93JFWEP8zYOBlUmFePPfckcnGW5qdoLLXxb3jSqYOwt0ZhTNTpIFoLVLfo4' \ --data '{"connector_type":"payment_processor","connector_name":"fiuu","connector_label":"fiuu_payments","connector_account_details":{"auth_type":"SignatureKey","api_key":"A","key1":"B","api_secret":"C"},"test_mode":true,"disabled":false,"payment_methods_enabled":[{"payment_method":"card","payment_method_types":[{"payment_method_type":"debit","payment_experience":null,"card_networks":["Visa"],"accepted_currencies":null,"accepted_countries":null,"minimum_amount":1,"maximum_amount":68607706,"recurring_enabled":true,"installment_payment_enabled":true},{"payment_method_type":"credit","payment_experience":null,"card_networks":["Visa"],"accepted_currencies":null,"accepted_countries":null,"minimum_amount":1,"maximum_amount":68607706,"recurring_enabled":true,"installment_payment_enabled":true}]},{"payment_method":"bank_redirect","payment_method_types":[{"payment_method_type":"online_banking_fpx","payment_experience":null,"card_networks":null,"accepted_currencies":null,"accepted_countries":null,"minimum_amount":1,"maximum_amount":68607706,"recurring_enabled":true,"installment_payment_enabled":true}]}]}' </details> <details> <summary>2. Create a payment link with MYR currency</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_8GkaY93JFWEP8zYOBlUmFePPfckcnGW5qdoLLXxb3jSqYOwt0ZhTNTpIFoLVLfo4' \ --data-raw '{"authentication_type":"three_ds","customer_id":"cus_Wz8ND2QMGUTQCZBgO4Jx","profile_id":"pro_POJq22KThTEaouJM0sv7","customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"amount":1000,"currency":"MYR","confirm":false,"payment_link":true,"setup_future_usage":"off_session","billing":{"address":{},"email":"[email protected]"},"return_url":"https://www.example.com","payment_link_config":{"background_image":{"url":"https://img.freepik.com/free-photo/abstract-blue-geometric-shapes-background_24972-1841.jpg","position":"bottom","size":"cover"}}}' Response {"payment_id":"pay_yPdYbjvEUbc7FFYKG2QF","merchant_id":"merchant_1747931797","status":"requires_payment_method","amount":1000,"net_amount":1000,"shipping_cost":null,"amount_capturable":0,"amount_received":null,"connector":null,"client_secret":"pay_yPdYbjvEUbc7FFYKG2QF_secret_VHqHmGCJjjQpSeyewAxN","created":"2025-05-23T10:36:41.060Z","currency":"MYR","customer_id":"cus_Wz8ND2QMGUTQCZBgO4Jx","customer":{"id":"cus_Wz8ND2QMGUTQCZBgO4Jx","name":null,"email":null,"phone":null,"phone_country_code":null},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":null,"payment_method":null,"payment_method_data":null,"payment_token":null,"shipping":null,"billing":{"address":null,"phone":null,"email":"[email protected]"},"order_details":null,"email":null,"name":null,"phone":null,"return_url":"https://www.example.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":null,"connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_Wz8ND2QMGUTQCZBgO4Jx","created_at":1747996601,"expires":1748000201,"secret":"epk_a10b3bda47314b72ab41296146b73e6a"},"manual_retry_allowed":null,"connector_transaction_id":null,"frm_message":null,"metadata":null,"connector_metadata":null,"feature_metadata":null,"reference_id":null,"payment_link":{"link":"http://localhost:8080/payment_link/merchant_1747931797/pay_yPdYbjvEUbc7FFYKG2QF?locale=es-ES","secure_link":null,"payment_link_id":"plink_ACAHjaujoqHWhJQrulhC"},"profile_id":"pro_POJq22KThTEaouJM0sv7","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":null,"incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-05-23T10:51:41.055Z","fingerprint":null,"browser_info":null,"payment_method_id":null,"payment_method_status":null,"updated":"2025-05-23T10:36:41.080Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":null,"force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null,"is_iframe_redirection_enabled":null,"whole_connector_response":null} </details> 3. Proceed with the FPX payment and mark it as a failure <details> <summary>4. Retrieve the payment - Response to have `error_code` and `error_message`</summary> cURL curl --location --request GET 'http://localhost:8080/payments/pay_yPdYbjvEUbc7FFYKG2QF?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_8GkaY93JFWEP8zYOBlUmFePPfckcnGW5qdoLLXxb3jSqYOwt0ZhTNTpIFoLVLfo4' Response {"payment_id":"pay_yPdYbjvEUbc7FFYKG2QF","merchant_id":"merchant_1747931797","status":"failed","amount":1000,"net_amount":1000,"shipping_cost":null,"amount_capturable":0,"amount_received":null,"connector":"fiuu","client_secret":"pay_yPdYbjvEUbc7FFYKG2QF_secret_VHqHmGCJjjQpSeyewAxN","created":"2025-05-23T10:36:41.060Z","currency":"MYR","customer_id":"cus_Wz8ND2QMGUTQCZBgO4Jx","customer":{"id":"cus_Wz8ND2QMGUTQCZBgO4Jx","name":null,"email":null,"phone":null,"phone_country_code":null},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"on_session","off_session":null,"capture_on":null,"capture_method":null,"payment_method":"bank_redirect","payment_method_data":{"bank_redirect":{"type":"BankRedirectResponse","bank_name":"affin_bank"},"billing":null},"payment_token":null,"shipping":null,"billing":{"address":null,"phone":null,"email":"[email protected]"},"order_details":null,"email":null,"name":null,"phone":null,"return_url":"https://www.example.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":"FPX_1B","error_message":"Buyer Failed To Provide The Necessary Info To Login IB Login Page","unified_code":"UE_9000","unified_message":"Something went wrong","payment_experience":null,"payment_method_type":"online_banking_fpx","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":null,"manual_retry_allowed":true,"connector_transaction_id":"30994873","frm_message":null,"metadata":null,"connector_metadata":null,"feature_metadata":null,"reference_id":null,"payment_link":{"link":"http://localhost:8080/payment_link/merchant_1747931797/pay_yPdYbjvEUbc7FFYKG2QF?locale=es-ES","secure_link":null,"payment_link_id":"plink_ACAHjaujoqHWhJQrulhC"},"profile_id":"pro_POJq22KThTEaouJM0sv7","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_D52A4XabkFvmpjJMgiUd","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-05-23T10:51:41.055Z","fingerprint":null,"browser_info":{"os_type":"macOS","language":"en-US","time_zone":-330,"ip_address":"::1","os_version":"10.15.7","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.4 Safari/605.1.15","color_depth":24,"device_model":"Macintosh","java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"accept_language":"en-US,en;q=0.9","java_script_enabled":true},"payment_method_id":"pm_RhSibHsj5rRz9sav6phs","payment_method_status":"inactive","updated":"2025-05-23T10:46:22.127Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":null,"force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null,"is_iframe_redirection_enabled":null,"whole_connector_response":null} </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
caa07235029a012af4f7106515f64025cf68d12d
caa07235029a012af4f7106515f64025cf68d12d
juspay/hyperswitch
juspay__hyperswitch-8129
Bug: chore: address Rust 1.87.0 clippy lints Address the clippy lints occurring due to new rust version 1.87.0 See https://github.com/juspay/hyperswitch/issues/3391 for more information.
diff --git a/crates/external_services/src/email/ses.rs b/crates/external_services/src/email/ses.rs index f8e941b57b5..bc813b7d644 100644 --- a/crates/external_services/src/email/ses.rs +++ b/crates/external_services/src/email/ses.rs @@ -54,7 +54,7 @@ impl SESConfig { pub enum AwsSesError { /// An error occurred in the SDK while sending email. #[error("Failed to Send Email {0:?}")] - SendingFailure(aws_sdk_sesv2::error::SdkError<SendEmailError>), + SendingFailure(Box<aws_sdk_sesv2::error::SdkError<SendEmailError>>), /// Configuration variable is missing to construct the email client #[error("Missing configuration variable {0}")] @@ -245,7 +245,7 @@ impl EmailClient for AwsSes { ) .send() .await - .map_err(AwsSesError::SendingFailure) + .map_err(|e| AwsSesError::SendingFailure(Box::new(e))) .change_context(EmailError::EmailSendingFailure)?; Ok(()) diff --git a/crates/kgraph_utils/src/error.rs b/crates/kgraph_utils/src/error.rs index 017b53ec0c0..2363e08c492 100644 --- a/crates/kgraph_utils/src/error.rs +++ b/crates/kgraph_utils/src/error.rs @@ -14,7 +14,7 @@ pub enum KgraphError { #[error("There was an error constructing the graph: {0}")] GraphConstructionError(hyperswitch_constraint_graph::GraphError<dir::DirValue>), #[error("There was an error constructing the context")] - ContextConstructionError(AnalysisErrorType), + ContextConstructionError(Box<AnalysisErrorType>), #[error("there was an unprecedented indexing error")] IndexingError, } diff --git a/crates/kgraph_utils/src/transformers.rs b/crates/kgraph_utils/src/transformers.rs index 1b5d3392aa2..d9e16773a2c 100644 --- a/crates/kgraph_utils/src/transformers.rs +++ b/crates/kgraph_utils/src/transformers.rs @@ -167,7 +167,7 @@ impl IntoDirValue for (api_enums::PaymentMethodType, api_enums::PaymentMethod) { | api_enums::PaymentMethod::Voucher | api_enums::PaymentMethod::OpenBanking | api_enums::PaymentMethod::GiftCard => Err(KgraphError::ContextConstructionError( - AnalysisErrorType::NotSupported, + Box::new(AnalysisErrorType::NotSupported), )), }, api_enums::PaymentMethodType::Bacs => match self.1 { @@ -186,7 +186,7 @@ impl IntoDirValue for (api_enums::PaymentMethodType, api_enums::PaymentMethod) { | api_enums::PaymentMethod::Voucher | api_enums::PaymentMethod::OpenBanking | api_enums::PaymentMethod::GiftCard => Err(KgraphError::ContextConstructionError( - AnalysisErrorType::NotSupported, + Box::new(AnalysisErrorType::NotSupported), )), }, api_enums::PaymentMethodType::Becs => Ok(dirval!(BankDebitType = Becs)), diff --git a/crates/masking/src/serde.rs b/crates/masking/src/serde.rs index 48514df8c6c..ecb92086a63 100644 --- a/crates/masking/src/serde.rs +++ b/crates/masking/src/serde.rs @@ -15,7 +15,6 @@ use crate::{Secret, Strategy, StrongSecret, ZeroizableSecret}; /// /// This is done deliberately to prevent accidental exfiltration of secrets /// via `serde` serialization. - #[cfg_attr(docsrs, cfg(feature = "serde"))] pub trait SerializableSecret: Serialize {} // #[cfg_attr(docsrs, doc(cfg(feature = "serde")))] diff --git a/crates/router/src/bin/router.rs b/crates/router/src/bin/router.rs index 212a1257425..0fb415bdd4a 100644 --- a/crates/router/src/bin/router.rs +++ b/crates/router/src/bin/router.rs @@ -45,6 +45,6 @@ async fn main() -> ApplicationResult<()> { let _ = server.await; Err(error_stack::Report::from(ApplicationError::from( - std::io::Error::new(std::io::ErrorKind::Other, "Server shut down"), + std::io::Error::other("Server shut down"), ))) } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index c3c6352152b..220a48cd1e1 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -2008,9 +2008,11 @@ pub fn decide_payment_method_retrieval_action( ) }; - should_retry_with_pan - .then_some(VaultFetchAction::FetchCardDetailsFromLocker) - .unwrap_or_else(standard_flow) + if should_retry_with_pan { + VaultFetchAction::FetchCardDetailsFromLocker + } else { + standard_flow() + } } pub fn determine_standard_vault_action(
2025-05-23T19:28:56Z
## Type of Change - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR addresses the clippy lints occurring due to new rust version 1.87.0 https://rust-lang.github.io/rust-clippy/master/index.html ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> CI checks should pass as this PR addresses clippy lints. 1. ran `rustc --version` <img width="381" alt="Screenshot 2025-05-24 at 5 18 56 AM" src="https://github.com/user-attachments/assets/dfb59d28-3085-4e96-b3b9-2bd635086356" /> 3. ran `just clippy` with new rust version (1.87.0) <img width="1004" alt="Screenshot 2025-04-07 at 5 46 05 PM" src="https://github.com/user-attachments/assets/5951c74e-8f3d-44e2-8172-e376c01c2e9d" /> 4. ran `just clippy_v2` with new rust version (1.87.0) <img width="948" alt="Screenshot 2025-05-24 at 5 19 50 AM" src="https://github.com/user-attachments/assets/a04d74c4-a1e0-48b1-8f93-09b70cde32c2" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
e272e7ab23845b664857ee729bb0eb7d05faac36
e272e7ab23845b664857ee729bb0eb7d05faac36
juspay/hyperswitch
juspay__hyperswitch-8118
Bug: [FEATURE]: Enable client_secret auth for payments - Get Intent [v2] Required for SDK
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 36c8b727b5a..2df62a36e17 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -232,10 +232,16 @@ pub async fn payments_get_intent( header_payload.clone(), ) }, - &auth::V2ApiKeyAuth { - is_connected_allowed: false, - is_platform_allowed: false, - }, + auth::api_or_client_auth( + &auth::V2ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: false, + }, + &auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment( + global_payment_id.clone(), + )), + req.headers(), + ), api_locking::LockAction::NotApplicable, )) .await
2025-05-23T08:40:35Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Added support for `client_secret` authentication in `Payments - Get Intent` ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #8118 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - Request: ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_0196fc47794a7a81b64346c96b71be4d/get-intent' \ --header 'x-profile-id: pro_pbRrpRVsI1yMUsyNhmrC' \ --header 'Authorization: publishable-key=pk_dev_41285e1d1b2a4998b1d9192874583289,client-secret=cs_0196fc4779ac7fe2826efc5ea6a2be24' \ --data '' ``` - Response: ```json { "id": "12345_pay_0196fc47794a7a81b64346c96b71be4d", "status": "requires_payment_method", "amount_details": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null }, "client_secret": null, "profile_id": "pro_pbRrpRVsI1yMUsyNhmrC", "merchant_reference_id": null, "routing_algorithm_id": null, "capture_method": "manual", "authentication_type": "no_three_ds", "billing": { "address": { "city": null, "country": null, "line1": null, "line2": null, "line3": null, "zip": null, "state": null, "first_name": "John", "last_name": "Dough" }, "phone": null, "email": "[email protected]" }, "shipping": { "address": { "city": "Karwar", "country": null, "line1": null, "line2": null, "line3": null, "zip": "581301", "state": "Karnataka", "first_name": "John", "last_name": "Dough" }, "phone": null, "email": "[email protected]" }, "customer_id": "12345_cus_0196fb8c515f79c3bda13a5e8bd62de0", "customer_present": "present", "description": null, "return_url": null, "setup_future_usage": "on_session", "apply_mit_exemption": "Skip", "statement_descriptor": null, "order_details": null, "allowed_payment_method_types": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "payment_link_enabled": "Skip", "payment_link_config": null, "request_incremental_authorization": "default", "expires_on": "2025-05-23T08:49:24.798Z", "frm_metadata": null, "request_external_three_ds_authentication": "Skip" } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
9f9fef492b775e22b2d489c3eb89ba3409fbd4ce
9f9fef492b775e22b2d489c3eb89ba3409fbd4ce
juspay/hyperswitch
juspay__hyperswitch-8097
Bug: refactor(success_rate): update the default configs update the default settings of success based
diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index c929bb3ea5d..e1802ab56f5 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -889,12 +889,12 @@ impl Default for SuccessBasedRoutingConfig { Self { params: Some(vec![DynamicRoutingConfigParams::PaymentMethod]), config: Some(SuccessBasedRoutingConfigBody { - min_aggregates_size: Some(2), + min_aggregates_size: Some(5), default_success_rate: Some(100.0), - max_aggregates_size: Some(3), + max_aggregates_size: Some(8), current_block_threshold: Some(CurrentBlockThreshold { - duration_in_mins: Some(5), - max_total_count: Some(2), + duration_in_mins: None, + max_total_count: Some(5), }), specificity_level: SuccessRateSpecificityLevel::default(), }), diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index b485cd9d987..83d3abef44e 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -1779,11 +1779,11 @@ pub async fn perform_decide_gateway_call_with_open_router( ); routable_connectors.sort_by(|connector_choice_a, connector_choice_b| { let connector_choice_a_score = gateway_priority_map - .get(&connector_choice_a.connector.to_string()) + .get(&connector_choice_a.to_string()) .copied() .unwrap_or(0.0); let connector_choice_b_score = gateway_priority_map - .get(&connector_choice_b.connector.to_string()) + .get(&connector_choice_b.to_string()) .copied() .unwrap_or(0.0); connector_choice_b_score
2025-05-21T12:02:57Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This pull request modifies the default configuration for `SuccessBasedRoutingConfig` in the `crates/api_models/src/routing.rs` file. The changes adjust the values for aggregate sizes, success rate thresholds, and block duration to better align with updated routing requirements. Key changes to default routing configuration: * Updated `min_aggregates_size` from `2` to `5` and `max_aggregates_size` from `3` to `8` to allow for larger aggregate sizes. * Changed `current_block_threshold` to set `duration_in_mins` to `None` (previously `5`) and increased `max_total_count` from `2` to `5`, providing more flexibility in block thresholds. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Toggle success based routing for a profile, Check the business profile table in DB, get the routing_algorithm_id active for that profile and check in routing_algorithm table. it should have default config as above numbers ``` curl --location --request POST 'http://localhost:8080/account/merchant_1747851996/business_profile/pro_Rbh3PEV8EITILLoKDC6N/dynamic_routing/success_based/toggle?enable=dynamic_connector_selection' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: xyz' \ --data '' ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
5f5998fb07dfd72c8360c97919dfa56ba25de205
5f5998fb07dfd72c8360c97919dfa56ba25de205
juspay/hyperswitch
juspay__hyperswitch-8113
Bug: feat(dynamic_routing): add get api for dynamic routing volume split
diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 70c8ed1e8c7..99d172f7b35 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -26254,6 +26254,19 @@ } } }, + "RoutingVolumeSplitResponse": { + "type": "object", + "required": [ + "split" + ], + "properties": { + "split": { + "type": "integer", + "format": "int32", + "minimum": 0 + } + } + }, "RuleConnectorSelection": { "type": "object", "description": "Represents a rule\n\n```text\nrule_name: [stripe, adyen, checkout]\n{\npayment.method = card {\npayment.method.cardtype = (credit, debit) {\npayment.method.network = (amex, rupay, diners)\n}\n\npayment.method.cardtype = credit\n}\n}\n```", diff --git a/crates/api_models/src/events/routing.rs b/crates/api_models/src/events/routing.rs index 750bfde2710..f1ba35bd9f3 100644 --- a/crates/api_models/src/events/routing.rs +++ b/crates/api_models/src/events/routing.rs @@ -7,8 +7,9 @@ use crate::routing::{ RoutingAlgorithmId, RoutingConfigRequest, RoutingDictionaryRecord, RoutingKind, RoutingLinkWrapper, RoutingPayloadWrapper, RoutingRetrieveLinkQuery, RoutingRetrieveLinkQueryWrapper, RoutingRetrieveQuery, RoutingVolumeSplit, - RoutingVolumeSplitWrapper, SuccessBasedRoutingConfig, SuccessBasedRoutingPayloadWrapper, - ToggleDynamicRoutingQuery, ToggleDynamicRoutingWrapper, + RoutingVolumeSplitResponse, RoutingVolumeSplitWrapper, SuccessBasedRoutingConfig, + SuccessBasedRoutingPayloadWrapper, ToggleDynamicRoutingPath, ToggleDynamicRoutingQuery, + ToggleDynamicRoutingWrapper, }; impl ApiEventMetric for RoutingKind { @@ -135,6 +136,18 @@ impl ApiEventMetric for RoutingVolumeSplitWrapper { } } +impl ApiEventMetric for ToggleDynamicRoutingPath { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Routing) + } +} + +impl ApiEventMetric for RoutingVolumeSplitResponse { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Routing) + } +} + impl ApiEventMetric for RoutingVolumeSplit { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index a15b135ac1f..527e8353b8c 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -857,6 +857,11 @@ pub struct ToggleDynamicRoutingPath { pub profile_id: common_utils::id_type::ProfileId, } +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] +pub struct RoutingVolumeSplitResponse { + pub split: u8, +} + #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct EliminationRoutingConfig { diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 8612dd080bd..4de9b85cd7c 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -671,6 +671,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::routing::SuccessRateSpecificityLevel, api_models::routing::ToggleDynamicRoutingQuery, api_models::routing::ToggleDynamicRoutingPath, + api_models::routing::RoutingVolumeSplitResponse, api_models::routing::ast::RoutableChoiceKind, api_models::enums::RoutableConnectors, api_models::routing::ast::ProgramConnectorSelection, diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs index df6189ea424..1811f43d51e 100644 --- a/crates/router/src/core/routing.rs +++ b/crates/router/src/core/routing.rs @@ -1554,6 +1554,48 @@ pub async fn configure_dynamic_routing_volume_split( Ok(service_api::ApplicationResponse::Json(routing_info)) } +#[cfg(feature = "v1")] +pub async fn retrieve_dynamic_routing_volume_split( + state: SessionState, + merchant_context: domain::MerchantContext, + profile_id: common_utils::id_type::ProfileId, +) -> RouterResponse<routing_types::RoutingVolumeSplitResponse> { + let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); + + let business_profile: domain::Profile = core_utils::validate_and_get_business_profile( + db, + key_manager_state, + merchant_context.get_merchant_key_store(), + Some(&profile_id), + merchant_context.get_merchant_account().get_id(), + ) + .await? + .get_required_value("Profile") + .change_context(errors::ApiErrorResponse::ProfileNotFound { + id: profile_id.get_string_repr().to_owned(), + })?; + + let dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef = business_profile + .dynamic_routing_algorithm + .clone() + .map(|val| val.parse_value("DynamicRoutingAlgorithmRef")) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "unable to deserialize dynamic routing algorithm ref from business profile", + )? + .unwrap_or_default(); + + let resp = routing_types::RoutingVolumeSplitResponse { + split: dynamic_routing_algo_ref + .dynamic_routing_volume_split + .unwrap_or_default(), + }; + + Ok(service_api::ApplicationResponse::Json(resp)) +} + #[cfg(all(feature = "v1", feature = "dynamic_routing"))] pub async fn success_based_routing_update_configs( state: SessionState, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 6071a9ee0b0..7e082296e7f 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -2082,6 +2082,10 @@ impl Profile { web::resource("/set_volume_split") .route(web::post().to(routing::set_dynamic_routing_volume_split)), ) + .service( + web::resource("/get_volume_split") + .route(web::get().to(routing::get_dynamic_routing_volume_split)), + ) .service( web::scope("/elimination") .service( diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs index ba041cbe5ac..ff8ad06e91c 100644 --- a/crates/router/src/routes/routing.rs +++ b/crates/router/src/routes/routing.rs @@ -1502,3 +1502,44 @@ pub async fn set_dynamic_routing_volume_split( )) .await } + +#[cfg(all(feature = "olap", feature = "v1"))] +#[instrument(skip_all)] +pub async fn get_dynamic_routing_volume_split( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<routing_types::ToggleDynamicRoutingPath>, +) -> impl Responder { + let flow = Flow::VolumeSplitOnRoutingType; + + let payload = path.into_inner(); + Box::pin(oss_api::server_wrap( + flow, + state, + &req, + payload.clone(), + |state, auth: auth::AuthenticationData, payload, _| { + let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( + domain::Context(auth.merchant_account, auth.key_store), + )); + routing::retrieve_dynamic_routing_volume_split( + state, + merchant_context, + payload.profile_id, + ) + }, + auth::auth_type( + &auth::HeaderAuth(auth::ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: false, + }), + &auth::JWTAuthProfileFromRoute { + profile_id: payload.profile_id, + required_permission: Permission::ProfileRoutingRead, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +}
2025-05-22T16:54:51Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This pull request introduces a new feature for retrieving dynamic routing volume split configurations and includes related updates across multiple files. The changes primarily focus on adding a new API endpoint, defining associated data structures, and integrating the functionality into the existing routing system. ### New Feature: Retrieve Dynamic Routing Volume Split #### API Enhancements: * Added a new endpoint `/get_volume_split` to retrieve dynamic routing volume split configurations. This endpoint is defined in `crates/router/src/routes/app.rs` and implemented in `crates/router/src/routes/routing.rs`. [[1]](diffhunk://#diff-a6e49b399ffdee83dd322b3cb8bee170c65fb9c6e2e52c14222ec310f6927c54R2055-R2058) [[2]](diffhunk://#diff-bdc480582fe22076ee5ec5bc2452ff57bf86b1b746607bdad4b4ed248c44c45fR1505-R1545) #### Data Structures: * Introduced a new struct `RoutingVolumeSplitResponse` in `crates/api_models/src/routing.rs` to encapsulate the volume split value (`split: u8`). * Updated the `ApiEventMetric` trait implementation to include `RoutingVolumeSplitResponse` and `ToggleDynamicRoutingPath`. #### Backend Logic: * Added a new function `retrieve_dynamic_routing_volume_split` in `crates/router/src/core/routing.rs` to handle the business logic for fetching the volume split value from the database and returning it as a response. #### Dependency Updates: * Updated imports in `crates/api_models/src/events/routing.rs` and `crates/openapi/src/openapi.rs` to include the new `RoutingVolumeSplitResponse` type. [[1]](diffhunk://#diff-040f264f6e1e25cf7598bf4fafabb91f2d54d7d848ed356a9cf5ec356d5be087L9-R11) [[2]](diffhunk://#diff-449ddbba20051c3e750e25f17452d490a28f78cfe4bcda279865a0365c6b29d8R668) ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create merchant account and api_key 2. Using the default profile created during merchant account creation, hit below api to set volume split ``` curl --location --request POST 'http://localhost:8080/account/merchant_1747932999/business_profile/pro_kXrizzzc7yklUW8sfxXz/dynamic_routing/set_volume_split?split=50' \ --header 'api-key: xyz' ``` 3. Hit get api which is added in this PR to get the volume split set in above api ``` curl --location 'http://localhost:8080/account/merchant_1747932999/business_profile/pro_kXrizzzc7yklUW8sfxXz/dynamic_routing/get_volume_split' \ --header 'api-key: xyz' ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
e637b214e348216d30c9af59cce85a1264badebf
e637b214e348216d30c9af59cce85a1264badebf
juspay/hyperswitch
juspay__hyperswitch-8091
Bug: Pre-configuring an account in the local setup using docker Pre-configuring an account in the local setup using docker
diff --git a/README.md b/README.md index fd211f33552..05764933882 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,9 @@ Single API to access the payments ecosystem and its features <a href="https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2jqxmpsbm-WXUENx022HjNEy~Ark7Orw"> <img src="https://img.shields.io/badge/chat-on_slack-blue?logo=slack&labelColor=grey&color=%233f0e40"/> </a> + <a href="https://deepwiki.com/juspay/hyperswitch"> + <img src="https://deepwiki.com/badge.svg" alt="Ask DeepWiki"> + </a> </p> <hr> diff --git a/scripts/setup.sh b/scripts/setup.sh index 79aa5097317..f1d69b7b288 100755 --- a/scripts/setup.sh +++ b/scripts/setup.sh @@ -1,4 +1,4 @@ -#! /usr/bin/env bash +#!/usr/bin/env bash set -euo pipefail # ANSI color codes for pretty output @@ -9,49 +9,60 @@ BLUE='\033[0;34m' BOLD='\033[1m' NC='\033[0m' # No Color -# Alias for docker to use podman -alias docker=podman +# Global cleanup function to handle error conditions and graceful exit +cleanup() { + # Restore strict error checking + set -e + # Remove any temporary files if needed + # Add any necessary cleanup operations here + + # The exit status passed to the function + exit $1 +} + +# Set up trap to call cleanup function on script exit or interruptions +trap 'cleanup $?' EXIT +trap 'cleanup 1' INT TERM # Function to print colorful messages echo_info() { - echo -e "${BLUE}[INFO]${NC} $1" + printf "${BLUE}[INFO]${NC} %s\n" "$1" } echo_success() { - echo -e "${GREEN}[SUCCESS]${NC} $1" + printf "${GREEN}[SUCCESS]${NC} %s\n" "$1" } echo_warning() { - echo -e "${YELLOW}[WARNING]${NC} $1" + printf "${YELLOW}[WARNING]${NC} %s\n" "$1" } echo_error() { - echo -e "${RED}[ERROR]${NC} $1" + printf "${RED}[ERROR]${NC} %s\n" "$1" } show_banner() { - echo -e "${BLUE}${BOLD}" - echo "" - echo " # " - echo " # # # #### ##### ## # # " - echo " # # # # # # # # # # " - echo " # # # #### # # # # # " - echo " # # # # # ##### ###### # " - echo " # # # # # # # # # # " - echo " ##### #### #### # # # # " - echo "" - echo "" - echo " # # # # ##### ###### ##### #### # # # ##### #### # # " - echo " # # # # # # # # # # # # # # # # # # " - echo " # # # # # ##### # # #### # # # # # ###### " - echo " ####### # ##### # ##### # # ## # # # # # # " - echo " # # # # # # # # # ## ## # # # # # # " - echo " # # # # ###### # # #### # # # # #### # # " - echo "" + printf "${BLUE}${BOLD}\n" + printf "\n" + printf " # \n" + printf " # # # #### ##### ## # # \n" + printf " # # # # # # # # # # \n" + printf " # # # #### # # # # # \n" + printf " # # # # # ##### ###### # \n" + printf " # # # # # # # # # # \n" + printf " ##### #### #### # # # # \n" + printf "\n" + printf "\n" + printf " # # # # ##### ###### ##### #### # # # ##### #### # # \n" + printf " # # # # # # # # # # # # # # # # # # \n" + printf " # # # # # ##### # # #### # # # # # ###### \n" + printf " ####### # ##### # ##### # # ## # # # # # # \n" + printf " # # # # # # # # # ## ## # # # # # # \n" + printf " # # # # ###### # # #### # # # # #### # # \n" + printf "\n" sleep 1 - echo -e "${NC}" - echo -e "🚀 ${BLUE}One-Click Docker Setup${NC} 🚀" - echo + printf "${NC}\n" + printf "🚀 ${BLUE}One-Click Docker Setup${NC} 🚀\n" } # Detect Docker Compose version @@ -135,7 +146,6 @@ check_prerequisites() { exit 1 fi else - echo_success "All required ports are available." echo "" fi } @@ -148,16 +158,16 @@ setup_config() { } select_profile() { - echo "" - echo "Select a setup option:" - echo -e "1) ${YELLOW}Standard Setup${NC}: ${BLUE}[Recommended]${NC} Ideal for quick trial." - echo -e " Services included: ${BLUE}App Server, Control Center, Unified Checkout, PostgreSQL and Redis${NC}" - echo "" - echo -e "2) ${YELLOW}Full Stack Setup${NC}: Ideal for comprehensive end-to-end payment testing." - echo -e " Services included: ${BLUE}Everything in Standard, Monitoring and Scheduler${NC}" - echo "" - echo -e "3) ${YELLOW}Standalone App Server${NC}: Ideal for API-first integration testing." - echo -e " Services included: ${BLUE}App server, PostgreSQL and Redis)${NC}" + printf "\n" + printf "Select a setup option:\n" + printf "1) ${YELLOW}Standard Setup${NC}: ${BLUE}[Recommended]${NC} Ideal for quick trial.\n" + printf " Services included: ${BLUE}App Server, Control Center, PostgreSQL and Redis${NC}\n" + printf "\n" + printf "2) ${YELLOW}Full Stack Setup${NC}: Ideal for comprehensive end-to-end payment testing.\n" + printf " Services included: ${BLUE}Everything in Standard, Monitoring and Scheduler${NC}\n" + printf "\n" + printf "3) ${YELLOW}Standalone App Server${NC}: Ideal for API-first integration testing.\n" + printf " Services included: ${BLUE}App Server, PostgreSQL and Redis)${NC}\n" echo "" local profile_selected=false while [ "$profile_selected" = false ]; do @@ -209,60 +219,272 @@ check_services_health() { RETRIES=0 while [ $RETRIES -lt $MAX_RETRIES ]; do - if curl --silent --head --request GET 'http://localhost:8080/health' | grep "200 OK" > /dev/null; then - print_access_info # Call print_access_info only when the server is healthy + response=$(curl -s -w "\\nStatus_Code:%{http_code}" http://localhost:8080/health) + status_code=$(echo "$response" | grep "Status_Code:" | cut -d':' -f2) + response_body=$(echo "$response" | head -n1) + + if [ "$status_code" = "200" ] && [ "$response_body" = "health is good" ]; then + print_access_info return fi RETRIES=$((RETRIES+1)) if [ $RETRIES -eq $MAX_RETRIES ]; then - echo "" + printf "\n" echo_error "${RED}${BOLD}Hyperswitch server did not become healthy in the expected time." - echo -e "Check logs with: $DOCKER_COMPOSE logs hyperswitch-server, Or reach out to us on slack(https://hyperswitch-io.slack.com/) for help." - echo -e "The setup process will continue, but some services might not work correctly.${NC}" - echo "" + printf "Check logs with: $DOCKER_COMPOSE logs hyperswitch-server, Or reach out to us on slack(https://hyperswitch-io.slack.com/) for help.\n" + printf "\n" else - echo "Waiting for server to become healthy... ($RETRIES/$MAX_RETRIES)" + printf "Waiting for server to become healthy... (%d/%d)\n" $RETRIES $MAX_RETRIES sleep $RETRY_INTERVAL fi done } -print_access_info() { - echo "" - echo -e "${GREEN}${BOLD}Setup complete! You can access Hyperswitch services at:${NC}" - echo "" +configure_account() { + # Temporarily disable strict error checking to prevent premature exit + set +e + local show_credentials_flag=false - if [ "$PROFILE" != "standalone" ]; then - echo -e " • ${GREEN}${BOLD}Control Center${NC}: ${BLUE}${BOLD}http://localhost:9000${NC}" + BASE_URL="http://localhost:8080" + EMAIL="[email protected]" + PASSWORD="Hyperswitch@123" + # Initialize merchant_id and profile_id to empty strings + merchant_id="" + profile_id="" + + # Function to make API calls with proper headers + make_api_call() { + local method=$1 + local endpoint=$2 + local data=$3 + local auth_header=${4:-} + + # Ensure endpoint starts with /user if it doesn't already + if [[ ! $endpoint =~ ^/user && ! $endpoint =~ ^/health && ! $endpoint =~ ^/accounts && ! $endpoint =~ ^/account ]]; then + endpoint="/user$endpoint" + fi + + local headers=(-H "Content-Type: application/json" -H "api-key: hyperswitch" -H "User-Agent: HyperSwitch-Shell-Client/1.0" -H "Referer: http://localhost:9000/") + + if [ -n "$auth_header" ]; then + headers+=(-H "authorization: Bearer $auth_header") + fi + + if [ -n "$merchant_id" ]; then + headers+=(-H "X-Merchant-Id: $merchant_id") + fi + + if [ -n "$profile_id" ]; then + headers+=(-H "X-Profile-Id: $profile_id") + fi + + local curl_cmd + if [ "$method" = "GET" ]; then + curl_cmd=(curl -s -X "$method" "${headers[@]}" "$BASE_URL$endpoint") + else + curl_cmd=(curl -s -X "$method" "${headers[@]}" -d "$data" "$BASE_URL$endpoint") + fi + + local retries=3 + local i=0 + while [ $i -lt $retries ]; do + response=$("${curl_cmd[@]}") + local response_code=$("${curl_cmd[@]}" -o /dev/null -s -w "%{http_code}") + + if [ $response_code -lt 400 ]; then + echo "$response" + return 0 + fi + + i=$((i+1)) + done + return 1 + } + + # Test the health endpoint first to ensure the API is responsive + health_response=$(curl -s -w "\\nStatus_Code:%{http_code}" "$BASE_URL/health") + health_status_code=$(echo "$health_response" | grep "Status_Code:" | cut -d':' -f2) + health_response_body=$(echo "$health_response" | head -n1) + + # Try signin first + signin_payload="{\"email\":\"$EMAIL\",\"password\":\"$PASSWORD\"}" + signin_response=$(make_api_call "POST" "/signin" "$signin_payload") + status_code=$? + + # Check if user needs to be created + if [[ $status_code -ne 0 || $(echo "$signin_response" | grep -q "error"; echo $?) -eq 0 ]]; then + # User doesn't exist or login failed, create new account + signup_payload="{\"email\":\"$EMAIL\",\"password\":\"$PASSWORD\",\"country\":\"IN\"}" + + # Only try signing up once - using exact headers from browser + # For making signup request without verbose logging + signup_cmd="curl -s -X POST '$BASE_URL/user/signup' \ + -H 'Accept: */*' \ + -H 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' \ + -H 'Content-Type: application/json' \ + -H 'Origin: http://localhost:9000' \ + -H 'Referer: http://localhost:9000/' \ + -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36' \ + -H 'api-key: hyperswitch' \ + -d '$signup_payload'" + + signup_response=$(eval "$signup_cmd") + + # Extract token from signup response + token=$(echo "$signup_response" | grep -o '"token":"[^"]*"' | cut -d'"' -f4) + token_type=$(echo "$signup_response" | grep -o '"token_type":"[^"]*"' | cut -d'"' -f4) + + if [ -n "$token" ]; then + show_credentials_flag=true + fi + is_new_user=true + else + auth_response="$signin_response" + token=$(echo "$auth_response" | grep -o '"token":"[^"]*"' | cut -d'"' -f4) + token_type=$(echo "$auth_response" | grep -o '"token_type":"[^"]*"' | cut -d'"' -f4) + if [ -n "$token" ]; then + show_credentials_flag=true + fi + is_new_user=false fi + + # Handle 2FA if needed + if [ "$token_type" = "totp" ]; then + MAX_RETRIES=3 + for i in $(seq 1 $MAX_RETRIES); do + terminate_response=$(curl -s -X GET -H "Content-Type: application/json" -H "api-key: hyperswitch" -H "authorization: Bearer $token" "$BASE_URL/user/2fa/terminate?skip_two_factor_auth=true") + + new_token=$(echo "$terminate_response" | grep -o '"token":"[^"]*"' | cut -d'"' -f4) + if [ -n "$new_token" ]; then + token="$new_token" + break + else + if [ $i -lt $MAX_RETRIES ]; then + sleep 1 + fi + fi + done + fi + + # Get user info + if [ -n "$token" ]; then + user_info_cmd="curl -s -X GET -H 'Content-Type: application/json' -H 'api-key: hyperswitch' -H 'authorization: Bearer $token' '$BASE_URL/user'" + user_info=$(eval "$user_info_cmd") + else + user_info="{}" + fi + + merchant_id=$(echo "$user_info" | grep -o '"merchant_id":"[^"]*"' | cut -d'"' -f4 || echo "") + profile_id=$(echo "$user_info" | grep -o '"profile_id":"[^"]*"' | cut -d'"' -f4 || echo "") - echo -e " • ${GREEN}${BOLD}App Server${NC}: ${BLUE}${BOLD}http://localhost:8080${NC}" + # Configure account for new users + if [ "$is_new_user" = true ] && [ -n "$merchant_id" ] && [ -n "$token" ]; then + # Create merchant account + merchant_payload="{\"merchant_id\":\"$merchant_id\",\"merchant_name\":\"Test\"}" + merchant_response=$(curl -s -X POST -H "Content-Type: application/json" -H "api-key: hyperswitch" -H "authorization: Bearer $token" -d "$merchant_payload" "$BASE_URL/accounts/$merchant_id") + + # Configure connector + connector_payload=$(cat <<EOF +{ + "connector_type": "payment_processor", + "profile_id": "$profile_id", + "connector_name": "paypal_test", + "connector_label": "paypal_test_default", + "disabled": false, + "test_mode": true, + "payment_methods_enabled": [ + { + "payment_method": "card", + "payment_method_types": [ + { + "payment_method_type": "debit", + "card_networks": [ + "Mastercard" + ], + "minimum_amount": 0, + "maximum_amount": 68607706, + "recurring_enabled": true, + "installment_payment_enabled": false + }, + { + "payment_method_type": "credit", + "card_networks": [ + "Visa" + ], + "minimum_amount": 0, + "maximum_amount": 68607706, + "recurring_enabled": true, + "installment_payment_enabled": false + } + ] + } + ], + "metadata": {}, + "connector_account_details": { + "api_key": "test_key", + "auth_type": "HeaderKey" + }, + "status": "active" +} +EOF +) + connector_response=$(curl -s -X POST -H "Content-Type: application/json" -H "api-key: hyperswitch" -H "authorization: Bearer $token" -d "$connector_payload" "$BASE_URL/account/$merchant_id/connectors") + + # Silently check if configuration was successful without printing messages + if [ -z "$(echo "$merchant_response" | grep -o 'merchant_id')" ] || [ -z "$(echo "$connector_response" | grep -o 'connector_id')" ]; then + # Only log to debug log if we want to troubleshoot later + : # No-op command + fi + fi + + # Provide helpful information to the user regardless of success/failure + if [ "$show_credentials_flag" = true ]; then + printf " Use the following credentials:\n" + printf " Email: $EMAIL\n" + printf " Password: $PASSWORD\n" + fi + + # Restore strict error checking + set -e +} + +print_access_info() { + printf "${BLUE}" + printf "╔════════════════════════════════════════════════════════════════╗\n" + printf "║ Welcome to Juspay Hyperswitch! ║\n" + printf "╚════════════════════════════════════════════════════════════════╝\n" + printf "${NC}\n" + + printf "${GREEN}${BOLD}Setup complete! You can now access Hyperswitch services at:${NC}\n" if [ "$PROFILE" != "standalone" ]; then - echo -e " • ${GREEN}${BOLD}Unified Checkout${NC}: ${BLUE}${BOLD}http://localhost:9060${NC}" + printf " • ${GREEN}${BOLD}Control Center${NC}: ${BLUE}${BOLD}http://localhost:9000${NC}\n" + configure_account || true fi + printf " • ${GREEN}${BOLD}App Server${NC}: ${BLUE}${BOLD}http://localhost:8080${NC}\n" + if [ "$PROFILE" = "full" ]; then - echo -e " • ${GREEN}${BOLD}Monitoring (Grafana)${NC}: ${BLUE}${BOLD}http://localhost:3000${NC}" + printf " • ${GREEN}${BOLD}Monitoring (Grafana)${NC}: ${BLUE}${BOLD}http://localhost:3000${NC}\n" fi - echo "" + printf "\n" # Provide the stop command based on the selected profile echo_info "To stop all services, run the following command:" case $PROFILE in standalone) - echo -e "${BLUE}$DOCKER_COMPOSE down${NC}" + printf "${BLUE}$DOCKER_COMPOSE down${NC}\n" ;; standard) - echo -e "${BLUE}$DOCKER_COMPOSE down${NC}" + printf "${BLUE}$DOCKER_COMPOSE down${NC}\n" ;; full) - echo -e "${BLUE}$DOCKER_COMPOSE --profile scheduler --profile monitoring --profile olap --profile full_setup down${NC}" + printf "${BLUE}$DOCKER_COMPOSE --profile scheduler --profile monitoring --profile olap --profile full_setup down${NC}\n" ;; esac - echo "" - echo -e "Reach out to us on ${BLUE}https://hyperswitch-io.slack.com${NC} in case you face any issues." + printf "\n" + printf "Reach out to us on ${BLUE}https://hyperswitch-io.slack.com${NC} in case you face any issues.\n" } # Main execution flow
2025-05-21T06:46:32Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Enhanced the script to pre-configure a user and a dummy connector in the control center for the local setup. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> closes #8091 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> <img width="1306" alt="Screenshot 2025-05-21 at 2 17 17 PM" src="https://github.com/user-attachments/assets/1ab1766c-c124-4a52-afb6-1e3aae48a6c1" /> <img width="606" alt="Screenshot 2025-05-21 at 2 17 30 PM" src="https://github.com/user-attachments/assets/03e03b28-71b3-4ebf-b8b7-642d6db1d1a7" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
7c1d893c91d22d7402504513d79fc94e0315dd10
7c1d893c91d22d7402504513d79fc94e0315dd10
juspay/hyperswitch
juspay__hyperswitch-8105
Bug: make `is_debit_routing_enabled` optional in profile general update is_debit_routing_enabled field is a business profile field introduced in this [pr](https://github.com/juspay/hyperswitch/pull/7470). It is made a mandatory field in the business profile update and is being set as false in case of RoutingAlgorithmUpdate. This field needs to be made a optional in the business profile update call and set to None in the other business profile updates
diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs index 4cb36d5685c..0bc52b33189 100644 --- a/crates/diesel_models/src/business_profile.rs +++ b/crates/diesel_models/src/business_profile.rs @@ -178,7 +178,7 @@ pub struct ProfileUpdateInternal { pub card_testing_secret_key: Option<Encryption>, pub is_clear_pan_retries_enabled: Option<bool>, pub force_3ds_challenge: Option<bool>, - pub is_debit_routing_enabled: bool, + pub is_debit_routing_enabled: Option<bool>, pub merchant_business_country: Option<common_enums::CountryAlpha2>, pub is_iframe_redirection_enabled: Option<bool>, pub is_pre_network_tokenization_enabled: Option<bool>, @@ -306,7 +306,8 @@ impl ProfileUpdateInternal { .unwrap_or(source.is_clear_pan_retries_enabled), force_3ds_challenge, id: source.id, - is_debit_routing_enabled, + is_debit_routing_enabled: is_debit_routing_enabled + .unwrap_or(source.is_debit_routing_enabled), merchant_business_country: merchant_business_country .or(source.merchant_business_country), is_iframe_redirection_enabled: is_iframe_redirection_enabled @@ -502,7 +503,7 @@ pub struct ProfileUpdateInternal { pub card_testing_guard_config: Option<CardTestingGuardConfig>, pub card_testing_secret_key: Option<Encryption>, pub is_clear_pan_retries_enabled: Option<bool>, - pub is_debit_routing_enabled: bool, + pub is_debit_routing_enabled: Option<bool>, pub merchant_business_country: Option<common_enums::CountryAlpha2>, pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub order_fulfillment_time: Option<i64>, @@ -649,7 +650,8 @@ impl ProfileUpdateInternal { is_clear_pan_retries_enabled: is_clear_pan_retries_enabled .unwrap_or(source.is_clear_pan_retries_enabled), force_3ds_challenge: None, - is_debit_routing_enabled, + is_debit_routing_enabled: is_debit_routing_enabled + .unwrap_or(source.is_debit_routing_enabled), merchant_business_country: merchant_business_country .or(source.merchant_business_country), revenue_recovery_retry_algorithm_type: revenue_recovery_retry_algorithm_type diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs index f7dd3f9539d..8e5de204fba 100644 --- a/crates/hyperswitch_domain_models/src/business_profile.rs +++ b/crates/hyperswitch_domain_models/src/business_profile.rs @@ -244,7 +244,7 @@ pub struct ProfileGeneralUpdate { pub card_testing_secret_key: OptionalEncryptableName, pub is_clear_pan_retries_enabled: Option<bool>, pub force_3ds_challenge: Option<bool>, - pub is_debit_routing_enabled: bool, + pub is_debit_routing_enabled: Option<bool>, pub merchant_business_country: Option<api_enums::CountryAlpha2>, pub is_iframe_redirection_enabled: Option<bool>, pub is_pre_network_tokenization_enabled: Option<bool>, @@ -420,7 +420,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { card_testing_secret_key: None, is_clear_pan_retries_enabled: None, force_3ds_challenge: None, - is_debit_routing_enabled: false, + is_debit_routing_enabled: None, merchant_business_country: None, is_iframe_redirection_enabled: None, is_pre_network_tokenization_enabled: None, @@ -469,7 +469,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { card_testing_secret_key: None, is_clear_pan_retries_enabled: None, force_3ds_challenge: None, - is_debit_routing_enabled: false, + is_debit_routing_enabled: None, merchant_business_country: None, is_iframe_redirection_enabled: None, is_pre_network_tokenization_enabled: None, @@ -518,7 +518,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { card_testing_secret_key: None, is_clear_pan_retries_enabled: None, force_3ds_challenge: None, - is_debit_routing_enabled: false, + is_debit_routing_enabled: None, merchant_business_country: None, is_iframe_redirection_enabled: None, is_pre_network_tokenization_enabled: None, @@ -567,7 +567,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { card_testing_secret_key: None, is_clear_pan_retries_enabled: None, force_3ds_challenge: None, - is_debit_routing_enabled: false, + is_debit_routing_enabled: None, merchant_business_country: None, is_iframe_redirection_enabled: None, is_pre_network_tokenization_enabled: None, @@ -616,7 +616,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { card_testing_secret_key: None, is_clear_pan_retries_enabled: None, force_3ds_challenge: None, - is_debit_routing_enabled: false, + is_debit_routing_enabled: None, merchant_business_country: None, is_iframe_redirection_enabled: None, is_pre_network_tokenization_enabled: None, @@ -665,7 +665,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { card_testing_secret_key: card_testing_secret_key.map(Encryption::from), is_clear_pan_retries_enabled: None, force_3ds_challenge: None, - is_debit_routing_enabled: false, + is_debit_routing_enabled: None, merchant_business_country: None, is_iframe_redirection_enabled: None, is_pre_network_tokenization_enabled: None, @@ -1140,7 +1140,7 @@ pub struct ProfileGeneralUpdate { pub three_ds_decision_manager_config: Option<common_types::payments::DecisionManagerRecord>, pub card_testing_guard_config: Option<CardTestingGuardConfig>, pub card_testing_secret_key: OptionalEncryptableName, - pub is_debit_routing_enabled: bool, + pub is_debit_routing_enabled: Option<bool>, pub merchant_business_country: Option<api_enums::CountryAlpha2>, pub is_iframe_redirection_enabled: Option<bool>, pub is_external_vault_enabled: Option<bool>, @@ -1321,7 +1321,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { card_testing_guard_config: None, card_testing_secret_key: None, is_clear_pan_retries_enabled: None, - is_debit_routing_enabled: false, + is_debit_routing_enabled: None, merchant_business_country: None, revenue_recovery_retry_algorithm_type: None, revenue_recovery_retry_algorithm_data: None, @@ -1373,7 +1373,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { card_testing_guard_config: None, card_testing_secret_key: None, is_clear_pan_retries_enabled: None, - is_debit_routing_enabled: false, + is_debit_routing_enabled: None, merchant_business_country: None, revenue_recovery_retry_algorithm_type: None, revenue_recovery_retry_algorithm_data: None, @@ -1425,7 +1425,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { card_testing_guard_config: None, card_testing_secret_key: None, is_clear_pan_retries_enabled: None, - is_debit_routing_enabled: false, + is_debit_routing_enabled: None, merchant_business_country: None, revenue_recovery_retry_algorithm_type: None, revenue_recovery_retry_algorithm_data: None, @@ -1477,7 +1477,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { card_testing_guard_config: None, card_testing_secret_key: None, is_clear_pan_retries_enabled: None, - is_debit_routing_enabled: false, + is_debit_routing_enabled: None, merchant_business_country: None, revenue_recovery_retry_algorithm_type: None, revenue_recovery_retry_algorithm_data: None, @@ -1529,7 +1529,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { card_testing_guard_config: None, card_testing_secret_key: None, is_clear_pan_retries_enabled: None, - is_debit_routing_enabled: false, + is_debit_routing_enabled: None, merchant_business_country: None, revenue_recovery_retry_algorithm_type: None, revenue_recovery_retry_algorithm_data: None, @@ -1581,7 +1581,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { card_testing_guard_config: None, card_testing_secret_key: None, is_clear_pan_retries_enabled: None, - is_debit_routing_enabled: false, + is_debit_routing_enabled: None, merchant_business_country: None, revenue_recovery_retry_algorithm_type: None, revenue_recovery_retry_algorithm_data: None, @@ -1633,7 +1633,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { card_testing_guard_config: None, card_testing_secret_key: None, is_clear_pan_retries_enabled: None, - is_debit_routing_enabled: false, + is_debit_routing_enabled: None, merchant_business_country: None, revenue_recovery_retry_algorithm_type: None, revenue_recovery_retry_algorithm_data: None, @@ -1685,7 +1685,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { card_testing_guard_config: None, card_testing_secret_key: card_testing_secret_key.map(Encryption::from), is_clear_pan_retries_enabled: None, - is_debit_routing_enabled: false, + is_debit_routing_enabled: None, merchant_business_country: None, revenue_recovery_retry_algorithm_type: None, revenue_recovery_retry_algorithm_data: None, @@ -1738,7 +1738,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { card_testing_guard_config: None, card_testing_secret_key: None, is_clear_pan_retries_enabled: None, - is_debit_routing_enabled: false, + is_debit_routing_enabled: None, merchant_business_country: None, revenue_recovery_retry_algorithm_type: Some(revenue_recovery_retry_algorithm_type), revenue_recovery_retry_algorithm_data, diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 860d82ab487..68e91511d36 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -4426,7 +4426,7 @@ impl ProfileUpdateBridge for api::ProfileUpdate { card_testing_secret_key, is_clear_pan_retries_enabled: self.is_clear_pan_retries_enabled, force_3ds_challenge: self.force_3ds_challenge, // - is_debit_routing_enabled: self.is_debit_routing_enabled.unwrap_or_default(), + is_debit_routing_enabled: self.is_debit_routing_enabled, merchant_business_country: self.merchant_business_country, is_iframe_redirection_enabled: self.is_iframe_redirection_enabled, is_pre_network_tokenization_enabled: self.is_pre_network_tokenization_enabled, @@ -4562,7 +4562,7 @@ impl ProfileUpdateBridge for api::ProfileUpdate { .card_testing_guard_config .map(ForeignInto::foreign_into), card_testing_secret_key, - is_debit_routing_enabled: self.is_debit_routing_enabled.unwrap_or_default(), + is_debit_routing_enabled: self.is_debit_routing_enabled, merchant_business_country: self.merchant_business_country, is_iframe_redirection_enabled: None, is_external_vault_enabled: self.is_external_vault_enabled,
2025-05-21T17:27:53Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> is_debit_routing_enabled field is a business profile field introduced in this [pr](https://github.com/juspay/hyperswitch/pull/7470). It is made a mandatory field in the business profile update and is being set as false in case of RoutingAlgorithmUpdate. This field needs to be made a optional in the business profile update call and set to None in the other business profile updates ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create a business profile and set `is_debit_routing_enabled` to true ``` curl --location 'http://localhost:8080/account/merchant_1747852121/business_profile/pro_dJ37X4BXujuveLBLSZAV' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: <api-key>' \ --data '{ "is_debit_routing_enabled": true }' ``` ``` { "merchant_id": "merchant_1747852121", "profile_id": "pro_dJ37X4BXujuveLBLSZAV", "profile_name": "US_default", "return_url": "https://google.com/success", "enable_payment_response_hash": true, "payment_response_hash_key": "tyNDlBZHJ4iiykQMSG5HWQrp9E6kP7QZKoi8fILj6REqeHA96RbASElSSAjS1jZU", "redirect_to_merchant_with_http_post": false, "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "webhook_url": null, "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "metadata": null, "routing_algorithm": null, "intent_fulfillment_time": 900, "frm_routing_algorithm": null, "payout_routing_algorithm": null, "applepay_verified_domains": null, "session_expiry": 900, "payment_link_config": null, "authentication_connector_details": null, "use_billing_as_payment_method_billing": true, "extended_card_info_config": null, "collect_shipping_details_from_wallet_connector": false, "collect_billing_details_from_wallet_connector": false, "always_collect_shipping_details_from_wallet_connector": false, "always_collect_billing_details_from_wallet_connector": false, "is_connector_agnostic_mit_enabled": false, "payout_link_config": null, "outgoing_webhook_custom_http_headers": null, "tax_connector_id": null, "is_tax_connector_enabled": false, "is_network_tokenization_enabled": false, "is_auto_retries_enabled": false, "max_auto_retries_enabled": null, "always_request_extended_authorization": null, "is_click_to_pay_enabled": false, "authentication_product_ids": null, "card_testing_guard_config": { "card_ip_blocking_status": "disabled", "card_ip_blocking_threshold": 3, "guest_user_card_blocking_status": "disabled", "guest_user_card_blocking_threshold": 10, "customer_id_blocking_status": "disabled", "customer_id_blocking_threshold": 5, "card_testing_guard_expiry": 3600 }, "is_clear_pan_retries_enabled": false, "force_3ds_challenge": false, "is_debit_routing_enabled": true, "merchant_business_country": null, "is_pre_network_tokenization_enabled": false } ``` 2. update business profile by enabling feature other than debit routing. After this debit routing should still be true ``` curl --location 'http://localhost:8080/account/merchant_1747852121/business_profile/pro_dJ37X4BXujuveLBLSZAV' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: <api-key>' \ --data '{ "is_connector_agnostic_mit_enabled": false }' ``` ``` { "merchant_id": "merchant_1747852121", "profile_id": "pro_dJ37X4BXujuveLBLSZAV", "profile_name": "US_default", "return_url": "https://google.com/success", "enable_payment_response_hash": true, "payment_response_hash_key": "tyNDlBZHJ4iiykQMSG5HWQrp9E6kP7QZKoi8fILj6REqeHA96RbASElSSAjS1jZU", "redirect_to_merchant_with_http_post": false, "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "webhook_url": null, "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "metadata": null, "routing_algorithm": null, "intent_fulfillment_time": 900, "frm_routing_algorithm": null, "payout_routing_algorithm": null, "applepay_verified_domains": null, "session_expiry": 900, "payment_link_config": null, "authentication_connector_details": null, "use_billing_as_payment_method_billing": true, "extended_card_info_config": null, "collect_shipping_details_from_wallet_connector": false, "collect_billing_details_from_wallet_connector": false, "always_collect_shipping_details_from_wallet_connector": false, "always_collect_billing_details_from_wallet_connector": false, "is_connector_agnostic_mit_enabled": false, "payout_link_config": null, "outgoing_webhook_custom_http_headers": null, "tax_connector_id": null, "is_tax_connector_enabled": false, "is_network_tokenization_enabled": false, "is_auto_retries_enabled": false, "max_auto_retries_enabled": null, "always_request_extended_authorization": null, "is_click_to_pay_enabled": false, "authentication_product_ids": null, "card_testing_guard_config": { "card_ip_blocking_status": "disabled", "card_ip_blocking_threshold": 3, "guest_user_card_blocking_status": "disabled", "guest_user_card_blocking_threshold": 10, "customer_id_blocking_status": "disabled", "customer_id_blocking_threshold": 5, "card_testing_guard_expiry": 3600 }, "is_clear_pan_retries_enabled": false, "force_3ds_challenge": false, "is_debit_routing_enabled": true, "merchant_business_country": null, "is_pre_network_tokenization_enabled": false } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
6fc50b67295a5682b9433b17399c09a57be664f2
6fc50b67295a5682b9433b17399c09a57be664f2
juspay/hyperswitch
juspay__hyperswitch-8089
Bug: [FEATURE]: Save Payment Method on Payments Confirm (V2) Add functionality to save a payment method after a successful payment
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index e3b41ce3899..b0a60046574 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -3043,7 +3043,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PaymentMethodListResponse" + "$ref": "#/components/schemas/PaymentMethodListResponseForSession" } } } @@ -9471,18 +9471,19 @@ } } }, - "CustomerPaymentMethod": { + "CustomerPaymentMethodResponseItem": { "type": "object", "required": [ "id", + "payment_token", "customer_id", "payment_method_type", "payment_method_subtype", "recurring_enabled", "created", "requires_cvv", - "is_default", - "psp_tokenization_enabled" + "last_used_at", + "is_default" ], "properties": { "id": { @@ -9490,6 +9491,11 @@ "description": "The unique identifier of the payment method.", "example": "12345_pm_01926c58bc6e77c09e809964e72af8c8" }, + "payment_token": { + "type": "string", + "description": "Temporary Token for payment method in vault which gets refreshed for every payment", + "example": "7ebf443f-a050-4067-84e5-e6f6d4800aef" + }, "customer_id": { "type": "string", "description": "The unique identifier of the customer.", @@ -9553,18 +9559,6 @@ } ], "nullable": true - }, - "network_tokenization": { - "allOf": [ - { - "$ref": "#/components/schemas/NetworkTokenResponse" - } - ], - "nullable": true - }, - "psp_tokenization_enabled": { - "type": "boolean", - "description": "Whether psp_tokenization is enabled for the payment_method, this will be true when at least\none multi-use token with status `Active` is available for the payment method" } } }, @@ -9577,7 +9571,7 @@ "customer_payment_methods": { "type": "array", "items": { - "$ref": "#/components/schemas/CustomerPaymentMethod" + "$ref": "#/components/schemas/PaymentMethodResponseItem" }, "description": "List of payment methods for customer" } @@ -16751,49 +16745,49 @@ }, "additionalProperties": false }, - "PaymentMethodListResponse": { + "PaymentMethodListResponseForPayments": { "type": "object", "required": [ - "payment_methods_enabled", - "customer_payment_methods" + "payment_methods_enabled" ], "properties": { "payment_methods_enabled": { "type": "array", "items": { - "$ref": "#/components/schemas/ResponsePaymentMethodTypes" + "$ref": "#/components/schemas/ResponsePaymentMethodTypesForPayments" }, "description": "The list of payment methods that are enabled for the business profile" }, "customer_payment_methods": { "type": "array", "items": { - "$ref": "#/components/schemas/CustomerPaymentMethod" + "$ref": "#/components/schemas/CustomerPaymentMethodResponseItem" }, - "description": "The list of saved payment methods of the customer" + "description": "The list of payment methods that are saved by the given customer\nThis field is only returned if the customer_id is provided in the request", + "nullable": true } } }, - "PaymentMethodListResponseForPayments": { + "PaymentMethodListResponseForSession": { "type": "object", "required": [ - "payment_methods_enabled" + "payment_methods_enabled", + "customer_payment_methods" ], "properties": { "payment_methods_enabled": { "type": "array", "items": { - "$ref": "#/components/schemas/ResponsePaymentMethodTypesForPayments" + "$ref": "#/components/schemas/ResponsePaymentMethodTypes" }, "description": "The list of payment methods that are enabled for the business profile" }, "customer_payment_methods": { "type": "array", "items": { - "$ref": "#/components/schemas/CustomerPaymentMethod" + "$ref": "#/components/schemas/CustomerPaymentMethodResponseItem" }, - "description": "The list of payment methods that are saved by the given customer\nThis field is only returned if the customer_id is provided in the request", - "nullable": true + "description": "The list of saved payment methods of the customer" } } }, @@ -16895,6 +16889,103 @@ } ] }, + "PaymentMethodResponseItem": { + "type": "object", + "required": [ + "id", + "customer_id", + "payment_method_type", + "payment_method_subtype", + "recurring_enabled", + "created", + "requires_cvv", + "is_default", + "psp_tokenization_enabled" + ], + "properties": { + "id": { + "type": "string", + "description": "The unique identifier of the payment method.", + "example": "12345_pm_01926c58bc6e77c09e809964e72af8c8" + }, + "customer_id": { + "type": "string", + "description": "The unique identifier of the customer.", + "example": "12345_cus_01926c58bc6e77c09e809964e72af8c8", + "maxLength": 64, + "minLength": 32 + }, + "payment_method_type": { + "$ref": "#/components/schemas/PaymentMethod" + }, + "payment_method_subtype": { + "$ref": "#/components/schemas/PaymentMethodType" + }, + "recurring_enabled": { + "type": "boolean", + "description": "Indicates whether the payment method is eligible for recurring payments", + "example": true + }, + "payment_method_data": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentMethodListData" + } + ], + "nullable": true + }, + "bank": { + "allOf": [ + { + "$ref": "#/components/schemas/MaskedBankDetails" + } + ], + "nullable": true + }, + "created": { + "type": "string", + "format": "date-time", + "description": "A timestamp (ISO 8601 code) that determines when the payment method was created", + "example": "2023-01-18T11:04:09.922Z" + }, + "requires_cvv": { + "type": "boolean", + "description": "Whether this payment method requires CVV to be collected", + "example": true + }, + "last_used_at": { + "type": "string", + "format": "date-time", + "description": "A timestamp (ISO 8601 code) that determines when the payment method was last used", + "example": "2024-02-24T11:04:09.922Z" + }, + "is_default": { + "type": "boolean", + "description": "Indicates if the payment method has been set to default or not", + "example": true + }, + "billing": { + "allOf": [ + { + "$ref": "#/components/schemas/Address" + } + ], + "nullable": true + }, + "network_tokenization": { + "allOf": [ + { + "$ref": "#/components/schemas/NetworkTokenResponse" + } + ], + "nullable": true + }, + "psp_tokenization_enabled": { + "type": "boolean", + "description": "Whether psp_tokenization is enabled for the payment_method, this will be true when at least\none multi-use token with status `Active` is available for the payment method" + } + } + }, "PaymentMethodSessionConfirmRequest": { "type": "object", "required": [ @@ -17617,6 +17708,12 @@ "type": "string", "description": "The payment_method_id to be associated with the payment", "nullable": true + }, + "payment_token": { + "type": "string", + "description": "Provide a reference to a stored payment method", + "example": "187282ab-40ef-47a9-9206-5099ba31e432", + "nullable": true } }, "additionalProperties": false diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs index 76d1201c2e7..851e2500f7e 100644 --- a/crates/api_models/src/events/payment.rs +++ b/crates/api_models/src/events/payment.rs @@ -5,23 +5,29 @@ use super::{ PaymentStartRedirectionRequest, PaymentsCreateIntentRequest, PaymentsGetIntentRequest, PaymentsIntentResponse, PaymentsRequest, }; +#[cfg(feature = "v2")] +use crate::payment_methods::PaymentMethodListResponseForSession; #[cfg(feature = "v1")] -use crate::payments::{ - ExtendedCardInfoResponse, PaymentIdType, PaymentListFilterConstraints, PaymentListResponseV2, - PaymentsApproveRequest, PaymentsCancelRequest, PaymentsCaptureRequest, - PaymentsCompleteAuthorizeRequest, PaymentsDynamicTaxCalculationRequest, - PaymentsDynamicTaxCalculationResponse, PaymentsExternalAuthenticationRequest, - PaymentsExternalAuthenticationResponse, PaymentsIncrementalAuthorizationRequest, - PaymentsManualUpdateRequest, PaymentsManualUpdateResponse, PaymentsPostSessionTokensRequest, - PaymentsPostSessionTokensResponse, PaymentsRejectRequest, PaymentsRetrieveRequest, - PaymentsStartRequest, PaymentsUpdateMetadataRequest, PaymentsUpdateMetadataResponse, +use crate::{ + payment_methods::PaymentMethodListResponse, + payments::{ + ExtendedCardInfoResponse, PaymentIdType, PaymentListFilterConstraints, + PaymentListResponseV2, PaymentsApproveRequest, PaymentsCancelRequest, + PaymentsCaptureRequest, PaymentsCompleteAuthorizeRequest, + PaymentsDynamicTaxCalculationRequest, PaymentsDynamicTaxCalculationResponse, + PaymentsExternalAuthenticationRequest, PaymentsExternalAuthenticationResponse, + PaymentsIncrementalAuthorizationRequest, PaymentsManualUpdateRequest, + PaymentsManualUpdateResponse, PaymentsPostSessionTokensRequest, + PaymentsPostSessionTokensResponse, PaymentsRejectRequest, PaymentsRetrieveRequest, + PaymentsStartRequest, PaymentsUpdateMetadataRequest, PaymentsUpdateMetadataResponse, + }, }; use crate::{ payment_methods::{ self, ListCountriesCurrenciesRequest, ListCountriesCurrenciesResponse, PaymentMethodCollectLinkRenderRequest, PaymentMethodCollectLinkRequest, - PaymentMethodCollectLinkResponse, PaymentMethodListRequest, PaymentMethodListResponse, - PaymentMethodMigrateResponse, PaymentMethodResponse, PaymentMethodUpdate, + PaymentMethodCollectLinkResponse, PaymentMethodListRequest, PaymentMethodMigrateResponse, + PaymentMethodResponse, PaymentMethodUpdate, }, payments::{ self, PaymentListConstraints, PaymentListFilters, PaymentListFiltersV2, @@ -304,6 +310,8 @@ impl ApiEventMetric for PaymentMethodListRequest { impl ApiEventMetric for ListCountriesCurrenciesRequest {} impl ApiEventMetric for ListCountriesCurrenciesResponse {} + +#[cfg(feature = "v1")] impl ApiEventMetric for PaymentMethodListResponse {} #[cfg(feature = "v1")] @@ -454,6 +462,9 @@ impl ApiEventMetric for payments::PaymentMethodListResponseForPayments { } } +#[cfg(feature = "v2")] +impl ApiEventMetric for PaymentMethodListResponseForSession {} + #[cfg(feature = "v2")] impl ApiEventMetric for payments::PaymentsCaptureResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 92761192d1c..2153bda7320 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -1225,12 +1225,12 @@ impl From<CardDetailFromLocker> for payments::AdditionalCardInfo { #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] -pub struct PaymentMethodListResponse { +pub struct PaymentMethodListResponseForSession { /// The list of payment methods that are enabled for the business profile pub payment_methods_enabled: Vec<ResponsePaymentMethodTypes>, /// The list of saved payment methods of the customer - pub customer_payment_methods: Vec<CustomerPaymentMethod>, + pub customer_payment_methods: Vec<CustomerPaymentMethodResponseItem>, } #[cfg(all( @@ -1930,11 +1930,12 @@ pub struct CustomerPaymentMethodsListResponse { pub is_guest_customer: Option<bool>, } +// OLAP PML Response #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Serialize, ToSchema)] pub struct CustomerPaymentMethodsListResponse { /// List of payment methods for customer - pub customer_payment_methods: Vec<CustomerPaymentMethod>, + pub customer_payment_methods: Vec<PaymentMethodResponseItem>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] @@ -2073,7 +2074,7 @@ pub struct CustomerDefaultPaymentMethodResponse { #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, Clone, serde::Serialize, ToSchema)] -pub struct CustomerPaymentMethod { +pub struct PaymentMethodResponseItem { /// The unique identifier of the payment method. #[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub id: id_type::GlobalPaymentMethodId, @@ -2136,6 +2137,68 @@ pub struct CustomerPaymentMethod { pub psp_tokenization_enabled: bool, } +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[derive(Debug, Clone, serde::Serialize, ToSchema)] +pub struct CustomerPaymentMethodResponseItem { + /// The unique identifier of the payment method. + #[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] + pub id: id_type::GlobalPaymentMethodId, + + /// Temporary Token for payment method in vault which gets refreshed for every payment + #[schema(example = "7ebf443f-a050-4067-84e5-e6f6d4800aef")] + pub payment_token: String, + + /// The unique identifier of the customer. + #[schema( + min_length = 32, + max_length = 64, + example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", + value_type = String + )] + pub customer_id: id_type::GlobalCustomerId, + + /// The type of payment method use for the payment. + #[schema(value_type = PaymentMethod,example = "card")] + pub payment_method_type: api_enums::PaymentMethod, + + /// This is a sub-category of payment method. + #[schema(value_type = PaymentMethodType,example = "credit")] + pub payment_method_subtype: api_enums::PaymentMethodType, + + /// Indicates whether the payment method is eligible for recurring payments + #[schema(example = true)] + pub recurring_enabled: bool, + + /// PaymentMethod Data from locker + pub payment_method_data: Option<PaymentMethodListData>, + + /// Masked bank details from PM auth services + #[schema(example = json!({"mask": "0000"}))] + pub bank: Option<MaskedBankDetails>, + + /// A timestamp (ISO 8601 code) that determines when the payment method was created + #[schema(value_type = PrimitiveDateTime, example = "2023-01-18T11:04:09.922Z")] + #[serde(with = "common_utils::custom_serde::iso8601")] + pub created: time::PrimitiveDateTime, + + /// Whether this payment method requires CVV to be collected + #[schema(example = true)] + pub requires_cvv: bool, + + /// A timestamp (ISO 8601 code) that determines when the payment method was last used + #[schema(value_type = PrimitiveDateTime,example = "2024-02-24T11:04:09.922Z")] + #[serde(with = "common_utils::custom_serde::iso8601")] + pub last_used_at: time::PrimitiveDateTime, + + /// Indicates if the payment method has been set to default or not + #[schema(example = true)] + pub is_default: bool, + + /// The billing details of the payment method + #[schema(value_type = Option<Address>)] + pub billing: Option<payments::Address>, +} + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, Clone, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 7ab8bc19361..33d489716c6 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -5328,6 +5328,10 @@ pub struct PaymentsConfirmIntentRequest { /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, + + /// Provide a reference to a stored payment method + #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] + pub payment_token: Option<String>, } #[cfg(feature = "v2")] @@ -5550,6 +5554,7 @@ impl From<&PaymentsRequest> for PaymentsConfirmIntentRequest { customer_acceptance: request.customer_acceptance.clone(), browser_info: request.browser_info.clone(), payment_method_id: request.payment_method_id.clone(), + payment_token: None, } } } @@ -7590,8 +7595,8 @@ pub struct PaymentMethodListResponseForPayments { /// The list of payment methods that are saved by the given customer /// This field is only returned if the customer_id is provided in the request - #[schema(value_type = Option<Vec<CustomerPaymentMethod>>)] - pub customer_payment_methods: Option<Vec<payment_methods::CustomerPaymentMethod>>, + #[schema(value_type = Option<Vec<CustomerPaymentMethodResponseItem>>)] + pub customer_payment_methods: Option<Vec<payment_methods::CustomerPaymentMethodResponseItem>>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index f351c884a05..a694f3fc0ca 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -833,7 +833,7 @@ pub struct PaymentAttemptUpdateInternal { pub authentication_type: Option<storage_enums::AuthenticationType>, pub error_message: Option<String>, pub connector_payment_id: Option<String>, - // payment_method_id: Option<String>, + pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, // cancellation_reason: Option<String>, pub modified_at: PrimitiveDateTime, pub browser_info: Option<serde_json::Value>, diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 2240df7241f..6b93394d134 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -843,6 +843,56 @@ impl } } +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +impl + From<( + payment_methods::CardDetail, + Secret<String>, + Option<Secret<String>>, + )> for Card +{ + fn from( + (card_detail, card_cvc, card_holder_name): ( + payment_methods::CardDetail, + Secret<String>, + Option<Secret<String>>, + ), + ) -> Self { + Self { + card_number: card_detail.card_number, + card_exp_month: card_detail.card_exp_month, + card_exp_year: card_detail.card_exp_year, + card_cvc, + card_issuer: card_detail.card_issuer, + card_network: card_detail.card_network, + card_type: card_detail.card_type.map(|val| val.to_string()), + card_issuing_country: card_detail.card_issuing_country.map(|val| val.to_string()), + bank_code: None, + nick_name: card_detail.nick_name, + card_holder_name: card_holder_name.or(card_detail.card_holder_name), + co_badged_card_data: None, + } + } +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +impl From<Card> for payment_methods::CardDetail { + fn from(card: Card) -> Self { + Self { + card_number: card.card_number, + card_exp_month: card.card_exp_month, + card_exp_year: card.card_exp_year, + card_holder_name: card.card_holder_name, + nick_name: card.nick_name, + card_issuing_country: None, + card_network: card.card_network, + card_issuer: card.card_issuer, + card_type: None, + card_cvc: Some(card.card_cvc), + } + } +} + impl From<api_models::payments::CardRedirectData> for CardRedirectData { fn from(value: api_models::payments::CardRedirectData) -> Self { match value { diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index 42d1ef1a426..6adc7f2a394 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -43,7 +43,7 @@ use self::payment_attempt::PaymentAttempt; use crate::{ address::Address, business_profile, customer, errors, merchant_account, merchant_connector_account, merchant_context, payment_address, payment_method_data, - revenue_recovery, routing, ApiModelToDieselModelConvertor, + payment_methods, revenue_recovery, routing, ApiModelToDieselModelConvertor, }; #[cfg(feature = "v1")] use crate::{payment_method_data, RemoteStorageObject}; @@ -853,6 +853,7 @@ where pub payment_method_data: Option<payment_method_data::PaymentMethodData>, pub payment_address: payment_address::PaymentAddress, pub mandate_data: Option<api_models::payments::MandateIds>, + pub payment_method: Option<payment_methods::PaymentMethod>, } #[cfg(feature = "v2")] @@ -871,6 +872,22 @@ impl<F: Clone> PaymentConfirmData<F> { .get_connector_customer_id_from_feature_metadata(), } } + + pub fn update_payment_method_data( + &mut self, + payment_method_data: payment_method_data::PaymentMethodData, + ) { + self.payment_method_data = Some(payment_method_data); + } + + pub fn update_payment_method_and_pm_id( + &mut self, + payment_method_id: id_type::GlobalPaymentMethodId, + payment_method: payment_methods::PaymentMethod, + ) { + self.payment_attempt.payment_method_id = Some(payment_method_id); + self.payment_method = Some(payment_method); + } } #[cfg(feature = "v2")] diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index c7342590e35..fb655280fe9 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -6,7 +6,9 @@ use common_types::primitive_wrappers::{ }; #[cfg(feature = "v2")] use common_utils::{ - crypto::Encryptable, encryption::Encryption, ext_traits::ValueExt, + crypto::Encryptable, + encryption::Encryption, + ext_traits::{Encode, ValueExt}, types::keymanager::ToEncryptable, }; use common_utils::{ @@ -562,7 +564,7 @@ impl PaymentAttempt { last_synced: None, cancellation_reason: None, browser_info: request.browser_info.clone(), - payment_token: None, + payment_token: request.payment_token.clone(), connector_metadata: None, payment_experience: None, payment_method_data: None, @@ -581,7 +583,14 @@ impl PaymentAttempt { charges: None, client_source: None, client_version: None, - customer_acceptance: None, + customer_acceptance: request + .customer_acceptance + .as_ref() + .map(Encode::encode_to_value) + .transpose() + .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encode customer_acceptance")? + .map(Secret::new), profile_id: payment_intent.profile_id.clone(), organization_id: payment_intent.organization_id.clone(), payment_method_type: request.payment_method_type, @@ -1747,6 +1756,15 @@ pub enum PaymentAttemptUpdate { merchant_connector_id: id_type::MerchantConnectorAccountId, authentication_type: storage_enums::AuthenticationType, }, + /// Update the payment attempt on confirming the intent, before calling the connector, when payment_method_id is present + ConfirmIntentTokenized { + status: storage_enums::AttemptStatus, + updated_by: String, + connector: String, + merchant_connector_id: id_type::MerchantConnectorAccountId, + authentication_type: storage_enums::AuthenticationType, + payment_method_id: id_type::GlobalPaymentMethodId, + }, /// Update the payment attempt on confirming the intent, after calling the connector on success response ConfirmIntentResponse(Box<ConfirmIntentResponseUpdate>), /// Update the payment attempt after force syncing with the connector @@ -2523,6 +2541,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal authentication_type, } => Self { status: Some(status), + payment_method_id: None, error_message: None, modified_at: common_utils::date_time::now(), browser_info: None, @@ -2553,6 +2572,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal updated_by, } => Self { status: Some(status), + payment_method_id: None, error_message: Some(error.message), error_code: Some(error.code), modified_at: common_utils::date_time::now(), @@ -2587,6 +2607,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal } = *confirm_intent_response_update; Self { status: Some(status), + payment_method_id: None, amount_capturable, error_message: None, error_code: None, @@ -2617,6 +2638,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal updated_by, } => Self { status: Some(status), + payment_method_id: None, amount_capturable, error_message: None, error_code: None, @@ -2645,6 +2667,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal updated_by, } => Self { status: Some(status), + payment_method_id: None, amount_capturable, amount_to_capture: None, error_message: None, @@ -2672,6 +2695,7 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal updated_by, } => Self { amount_to_capture, + payment_method_id: None, error_message: None, modified_at: common_utils::date_time::now(), browser_info: None, @@ -2694,6 +2718,38 @@ impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal network_decline_code: None, network_error_message: None, }, + PaymentAttemptUpdate::ConfirmIntentTokenized { + status, + updated_by, + connector, + merchant_connector_id, + authentication_type, + payment_method_id, + } => Self { + status: Some(status), + payment_method_id: Some(payment_method_id), + error_message: None, + modified_at: common_utils::date_time::now(), + browser_info: None, + error_code: None, + error_reason: None, + updated_by, + merchant_connector_id: Some(merchant_connector_id), + unified_code: None, + unified_message: None, + connector_payment_id: None, + connector: Some(connector), + redirection_data: None, + connector_metadata: None, + amount_capturable: None, + amount_to_capture: None, + connector_token_details: None, + authentication_type: Some(authentication_type), + feature_metadata: None, + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + }, } } } diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index f43712782f6..7191d9fda26 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -232,9 +232,11 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payment_methods::AuthenticationDetails, api_models::payment_methods::PaymentMethodResponse, api_models::payment_methods::PaymentMethodResponseData, - api_models::payment_methods::CustomerPaymentMethod, + api_models::payment_methods::CustomerPaymentMethodResponseItem, + api_models::payment_methods::PaymentMethodResponseItem, api_models::payment_methods::PaymentMethodListRequest, - api_models::payment_methods::PaymentMethodListResponse, + api_models::payment_methods::PaymentMethodListResponseForSession, + api_models::payment_methods::CustomerPaymentMethodsListResponse, api_models::payment_methods::ResponsePaymentMethodsEnabled, api_models::payment_methods::PaymentMethodSubtypeSpecificData, api_models::payment_methods::ResponsePaymentMethodTypes, @@ -242,7 +244,6 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payment_methods::CardNetworkTypes, api_models::payment_methods::BankDebitTypes, api_models::payment_methods::BankTransferTypes, - api_models::payment_methods::CustomerPaymentMethodsListResponse, api_models::payment_methods::PaymentMethodDeleteResponse, api_models::payment_methods::PaymentMethodUpdate, api_models::payment_methods::PaymentMethodUpdateData, diff --git a/crates/openapi/src/routes/payment_method.rs b/crates/openapi/src/routes/payment_method.rs index fd16b2ee2b2..2e991063644 100644 --- a/crates/openapi/src/routes/payment_method.rs +++ b/crates/openapi/src/routes/payment_method.rs @@ -401,7 +401,7 @@ pub fn payment_method_session_retrieve() {} ("id" = String, Path, description = "The unique identifier for the Payment Method Session"), ), responses( - (status = 200, description = "The payment method session is retrieved successfully", body = PaymentMethodListResponse), + (status = 200, description = "The payment method session is retrieved successfully", body = PaymentMethodListResponseForSession), (status = 404, description = "The request is invalid") ), tag = "Payment Method Session", diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 96ac030f57f..0350a507aeb 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -37,6 +37,8 @@ use diesel_models::{ enums, GenericLinkNew, PaymentMethodCollectLink, PaymentMethodCollectLinkData, }; use error_stack::{report, ResultExt}; +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +use futures::TryStreamExt; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use hyperswitch_domain_models::api::{GenericLinks, GenericLinksData}; #[cfg(all( @@ -899,7 +901,8 @@ pub async fn create_payment_method( merchant_context: &domain::MerchantContext, profile: &domain::Profile, ) -> RouterResponse<api::PaymentMethodResponse> { - let response = + // payment_method is for internal use, can never be populated in response + let (response, _payment_method) = create_payment_method_core(state, request_state, req, merchant_context, profile).await?; Ok(services::ApplicationResponse::Json(response)) @@ -913,7 +916,7 @@ pub async fn create_payment_method_core( req: api::PaymentMethodCreate, merchant_context: &domain::MerchantContext, profile: &domain::Profile, -) -> RouterResult<api::PaymentMethodResponse> { +) -> RouterResult<(api::PaymentMethodResponse, domain::PaymentMethod)> { use common_utils::ext_traits::ValueExt; req.validate()?; @@ -1055,7 +1058,7 @@ pub async fn create_payment_method_core( } }?; - Ok(response) + Ok((response, payment_method)) } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] @@ -1345,7 +1348,7 @@ pub async fn list_payment_methods_for_session( merchant_context: domain::MerchantContext, profile: domain::Profile, payment_method_session_id: id_type::GlobalPaymentMethodSessionId, -) -> RouterResponse<api::PaymentMethodListResponse> { +) -> RouterResponse<api::PaymentMethodListResponseForSession> { let key_manager_state = &(&state).into(); let db = &*state.store; @@ -1371,7 +1374,7 @@ pub async fn list_payment_methods_for_session( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error when fetching merchant connector accounts")?; - let customer_payment_methods = list_customer_payment_method_core( + let customer_payment_methods = list_customer_payment_methods_core( &state, &merchant_context, &payment_method_session.customer_id, @@ -1382,7 +1385,7 @@ pub async fn list_payment_methods_for_session( hyperswitch_domain_models::merchant_connector_account::FlattenedPaymentMethodsEnabled::from_payment_connectors_list(payment_connector_accounts) .perform_filtering() .get_required_fields(RequiredFieldsInput::new(state.conf.required_fields.clone())) - .generate_response(customer_payment_methods.customer_payment_methods); + .generate_response_for_session(customer_payment_methods); Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( response, @@ -1395,9 +1398,9 @@ pub async fn list_saved_payment_methods_for_customer( state: SessionState, merchant_context: domain::MerchantContext, customer_id: id_type::GlobalCustomerId, -) -> RouterResponse<api::CustomerPaymentMethodsListResponse> { +) -> RouterResponse<payment_methods::CustomerPaymentMethodsListResponse> { let customer_payment_methods = - list_customer_payment_method_core(&state, &merchant_context, &customer_id).await?; + list_payment_methods_core(&state, &merchant_context, &customer_id).await?; Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( customer_payment_methods, @@ -1628,10 +1631,10 @@ struct RequiredFieldsForEnabledPaymentMethodTypes(Vec<RequiredFieldsForEnabledPa #[cfg(feature = "v2")] impl RequiredFieldsForEnabledPaymentMethodTypes { - fn generate_response( + fn generate_response_for_session( self, - customer_payment_methods: Vec<payment_methods::CustomerPaymentMethod>, - ) -> payment_methods::PaymentMethodListResponse { + customer_payment_methods: Vec<payment_methods::CustomerPaymentMethodResponseItem>, + ) -> payment_methods::PaymentMethodListResponseForSession { let response_payment_methods = self .0 .into_iter() @@ -1645,7 +1648,7 @@ impl RequiredFieldsForEnabledPaymentMethodTypes { ) .collect(); - payment_methods::PaymentMethodListResponse { + payment_methods::PaymentMethodListResponseForSession { payment_methods_enabled: response_payment_methods, customer_payment_methods, } @@ -1798,7 +1801,9 @@ pub async fn create_pm_additional_data_update( .map(From::from); let pm_update = storage::PaymentMethodUpdate::GenericUpdate { - status: Some(enums::PaymentMethodStatus::Active), + // A new payment method is created with inactive state + // It will be marked active after payment succeeds + status: Some(enums::PaymentMethodStatus::Inactive), locker_id: vault_id, payment_method_type_v2: payment_method_type, payment_method_subtype, @@ -2006,8 +2011,6 @@ pub async fn vault_payment_method( } } -// TODO: check if this function will be used for listing the customer payment methods for payments -#[allow(unused)] #[cfg(all( feature = "v2", feature = "payment_methods_v2", @@ -2029,7 +2032,7 @@ fn get_pm_list_context( card_details: api::CardDetailFromLocker::from(card), token_data: is_payment_associated.then_some( storage::PaymentTokenData::permanent_card( - Some(payment_method.get_id().clone()), + payment_method.get_id().clone(), payment_method .locker_id .as_ref() @@ -2095,12 +2098,38 @@ fn get_pm_list_context( Ok(payment_method_retrieval_context) } +#[cfg(all( + feature = "v2", + feature = "payment_methods_v2", + feature = "customer_v2" +))] +fn get_pm_list_token_data( + payment_method_type: enums::PaymentMethod, + payment_method: &domain::PaymentMethod, +) -> Result<Option<storage::PaymentTokenData>, error_stack::Report<errors::ApiErrorResponse>> { + let pm_list_context = get_pm_list_context(payment_method_type, payment_method, true)? + .get_required_value("PaymentMethodListContext")?; + + match pm_list_context { + PaymentMethodListContext::Card { + card_details: _, + token_data, + } => Ok(token_data), + PaymentMethodListContext::Bank { token_data } => Ok(token_data), + PaymentMethodListContext::BankTransfer { + bank_transfer_details: _, + token_data, + } => Ok(token_data), + PaymentMethodListContext::TemporaryToken { token_data } => Ok(token_data), + } +} + #[cfg(all(feature = "v2", feature = "olap"))] -pub async fn list_customer_payment_method_core( +pub async fn list_payment_methods_core( state: &SessionState, merchant_context: &domain::MerchantContext, customer_id: &id_type::GlobalCustomerId, -) -> RouterResult<api::CustomerPaymentMethodsListResponse> { +) -> RouterResult<payment_methods::CustomerPaymentMethodsListResponse> { let db = &*state.store; let key_manager_state = &(state).into(); @@ -2120,16 +2149,84 @@ pub async fn list_customer_payment_method_core( let customer_payment_methods = saved_payment_methods .into_iter() .map(ForeignTryFrom::foreign_try_from) - .collect::<Result<Vec<api::CustomerPaymentMethod>, _>>() + .collect::<Result<Vec<payment_methods::PaymentMethodResponseItem>, _>>() .change_context(errors::ApiErrorResponse::InternalServerError)?; - let response = api::CustomerPaymentMethodsListResponse { + let response = payment_methods::CustomerPaymentMethodsListResponse { customer_payment_methods, }; Ok(response) } +#[cfg(all(feature = "v2", feature = "oltp"))] +pub async fn list_customer_payment_methods_core( + state: &SessionState, + merchant_context: &domain::MerchantContext, + customer_id: &id_type::GlobalCustomerId, +) -> RouterResult<Vec<payment_methods::CustomerPaymentMethodResponseItem>> { + let db = &*state.store; + let key_manager_state = &(state).into(); + + let saved_payment_methods = db + .find_payment_method_by_global_customer_id_merchant_id_status( + key_manager_state, + merchant_context.get_merchant_key_store(), + customer_id, + merchant_context.get_merchant_account().get_id(), + common_enums::PaymentMethodStatus::Active, + None, + merchant_context.get_merchant_account().storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; + + let mut customer_payment_methods = Vec::new(); + + let payment_method_results: Result<Vec<_>, error_stack::Report<errors::ApiErrorResponse>> = + saved_payment_methods + .into_iter() + .map(|pm| async move { + let parent_payment_method_token = generate_id(consts::ID_LENGTH, "token"); + + // For payment methods that are active we should always have the payment method type + let payment_method_type = pm + .payment_method_type + .get_required_value("payment_method_type")?; + + let intent_fulfillment_time = common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME; + + let token_data = get_pm_list_token_data(payment_method_type, &pm)?; + + if let Some(token_data) = token_data { + pm_routes::ParentPaymentMethodToken::create_key_for_token(( + &parent_payment_method_token, + payment_method_type, + )) + .insert(intent_fulfillment_time, token_data, state) + .await?; + + let final_pm = api::CustomerPaymentMethodResponseItem::foreign_try_from(( + pm, + parent_payment_method_token, + )) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to convert payment method to response format")?; + + Ok(Some(final_pm)) + } else { + Ok(None) + } + }) + .collect::<futures::stream::FuturesUnordered<_>>() + .try_collect::<Vec<_>>() + .await; + + customer_payment_methods.extend(payment_method_results?.into_iter().flatten()); + + Ok(customer_payment_methods) +} + #[cfg(all(feature = "v2", feature = "olap"))] pub async fn get_total_payment_method_count_core( state: &SessionState, @@ -2184,6 +2281,48 @@ pub async fn retrieve_payment_method( .map(services::ApplicationResponse::Json) } +// TODO: When we separate out microservices, this function will be an endpoint in payment_methods +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[instrument(skip_all)] +pub async fn update_payment_method_status_internal( + state: &SessionState, + key_store: &domain::MerchantKeyStore, + storage_scheme: enums::MerchantStorageScheme, + status: enums::PaymentMethodStatus, + payment_method_id: &id_type::GlobalPaymentMethodId, +) -> RouterResult<domain::PaymentMethod> { + let db = &*state.store; + let key_manager_state = &state.into(); + + let payment_method = db + .find_payment_method( + &((state).into()), + key_store, + payment_method_id, + storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; + + let pm_update = storage::PaymentMethodUpdate::StatusUpdate { + status: Some(status), + }; + + let updated_pm = db + .update_payment_method( + key_manager_state, + key_store, + payment_method.clone(), + pm_update, + storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to update payment method in db")?; + + Ok(updated_pm) +} + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[instrument(skip_all)] pub async fn update_payment_method( @@ -2896,7 +3035,7 @@ pub async fn payment_methods_session_confirm( ) .attach_printable("Failed to create payment method request")?; - let payment_method = create_payment_method_core( + let (payment_method_response, _payment_method) = create_payment_method_core( &state, &req_state, create_payment_method_request.clone(), @@ -2913,7 +3052,7 @@ pub async fn payment_methods_session_confirm( let zero_auth_request = construct_zero_auth_payments_request( &request, &payment_method_session, - &payment_method, + &payment_method_response, )?; let payments_response = Box::pin(create_zero_auth_payment( state.clone(), @@ -2936,7 +3075,7 @@ pub async fn payment_methods_session_confirm( merchant_context.clone(), profile.clone(), &create_payment_method_request.clone(), - &payment_method, + &payment_method_response, &payment_method_session, )) .await?; @@ -3013,7 +3152,7 @@ impl pm_types::SavedPMLPaymentsInfo { &self, state: &SessionState, parent_payment_method_token: Option<String>, - pma: &api::CustomerPaymentMethod, + pma: &api::CustomerPaymentMethodResponseItem, pm_list_context: PaymentMethodListContext, ) -> RouterResult<()> { let token = parent_payment_method_token diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 47d74d29deb..539298ac534 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -4591,7 +4591,7 @@ pub async fn perform_surcharge_ops( _state: &routes::SessionState, _merchant_context: &domain::MerchantContext, _business_profile: Option<Profile>, - _response: &mut api::CustomerPaymentMethodsListResponse, + _response: &mut api_models::payment_methods::CustomerPaymentMethodsListResponse, ) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> { todo!() } diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index fd36f6d0ab7..3e64e846153 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -1,4 +1,6 @@ pub use ::payment_methods::controller::{DataDuplicationCheck, DeleteCardResp}; +#[cfg(feature = "v2")] +use api_models::payment_methods::PaymentMethodResponseItem; use api_models::{enums as api_enums, payment_methods::Card}; use common_utils::{ ext_traits::{Encode, StringExt}, @@ -930,7 +932,73 @@ pub fn mk_card_value2( } #[cfg(feature = "v2")] -impl transformers::ForeignTryFrom<domain::PaymentMethod> for api::CustomerPaymentMethod { +impl transformers::ForeignTryFrom<(domain::PaymentMethod, String)> + for api::CustomerPaymentMethodResponseItem +{ + type Error = error_stack::Report<errors::ValidationError>; + + fn foreign_try_from( + (item, payment_token): (domain::PaymentMethod, String), + ) -> Result<Self, Self::Error> { + // For payment methods that are active we should always have the payment method subtype + let payment_method_subtype = + item.payment_method_subtype + .ok_or(errors::ValidationError::MissingRequiredField { + field_name: "payment_method_subtype".to_string(), + })?; + + // For payment methods that are active we should always have the payment method type + let payment_method_type = + item.payment_method_type + .ok_or(errors::ValidationError::MissingRequiredField { + field_name: "payment_method_type".to_string(), + })?; + + let payment_method_data = item + .payment_method_data + .map(|payment_method_data| payment_method_data.into_inner()) + .map(|payment_method_data| match payment_method_data { + api_models::payment_methods::PaymentMethodsData::Card( + card_details_payment_method, + ) => { + let card_details = api::CardDetailFromLocker::from(card_details_payment_method); + api_models::payment_methods::PaymentMethodListData::Card(card_details) + } + api_models::payment_methods::PaymentMethodsData::BankDetails(..) => todo!(), + api_models::payment_methods::PaymentMethodsData::WalletDetails(..) => { + todo!() + } + }); + + let payment_method_billing = item + .payment_method_billing_address + .clone() + .map(|billing| billing.into_inner()) + .map(From::from); + + // TODO: check how we can get this field + let recurring_enabled = true; + + Ok(Self { + id: item.id, + customer_id: item.customer_id, + payment_method_type, + payment_method_subtype, + created: item.created_at, + last_used_at: item.last_used_at, + recurring_enabled, + payment_method_data, + bank: None, + requires_cvv: true, + is_default: false, + billing: payment_method_billing, + payment_token, + }) + } +} + +#[cfg(feature = "v2")] +impl transformers::ForeignTryFrom<domain::PaymentMethod> for PaymentMethodResponseItem { type Error = error_stack::Report<errors::ValidationError>; fn foreign_try_from(item: domain::PaymentMethod) -> Result<Self, Self::Error> { diff --git a/crates/router/src/core/payment_methods/utils.rs b/crates/router/src/core/payment_methods/utils.rs index 5885b830e7a..512c40fc8d2 100644 --- a/crates/router/src/core/payment_methods/utils.rs +++ b/crates/router/src/core/payment_methods/utils.rs @@ -6,6 +6,10 @@ use api_models::{ payment_methods::RequestPaymentMethodTypes, }; use common_enums::enums; +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +use common_utils::ext_traits::{OptionExt, StringExt}; +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +use error_stack::ResultExt; use euclid::frontend::dir; use hyperswitch_constraint_graph as cgraph; use kgraph_utils::{error::KgraphError, transformers::IntoDirValue}; @@ -13,6 +17,14 @@ use masking::ExposeInterface; use storage_impl::redis::cache::{CacheKey, PM_FILTERS_CGRAPH_CACHE}; use crate::{configs::settings, routes::SessionState}; +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +use crate::{ + db::{ + errors, + storage::{self, enums as storage_enums}, + }, + services::logger, +}; pub fn make_pm_graph( builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>, @@ -798,3 +810,63 @@ fn compile_accepted_currency_for_mca( .map_err(KgraphError::GraphConstructionError)?, )) } + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +pub(super) async fn retrieve_payment_token_data( + state: &SessionState, + token: String, + payment_method: Option<&storage_enums::PaymentMethod>, +) -> errors::RouterResult<storage::PaymentTokenData> { + let redis_conn = state + .store + .get_redis_conn() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get redis connection")?; + + let key = format!( + "pm_token_{}_{}_hyperswitch", + token, + payment_method + .get_required_value("payment_method") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Payment method is required")? + ); + + let token_data_string = redis_conn + .get_key::<Option<String>>(&key.into()) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to fetch the token from redis")? + .ok_or(error_stack::Report::new( + errors::ApiErrorResponse::UnprocessableEntity { + message: "Token is invalid or expired".to_owned(), + }, + ))?; + + token_data_string + .clone() + .parse_struct("PaymentTokenData") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to deserialize hyperswitch token data") +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +pub(super) async fn delete_payment_token_data( + state: &SessionState, + key_for_token: &str, +) -> errors::RouterResult<()> { + let redis_conn = state + .store + .get_redis_conn() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get redis connection")?; + match redis_conn.delete_key(&key_for_token.into()).await { + Ok(_) => Ok(()), + Err(err) => { + { + logger::error!("Error while deleting redis key: {:?}", err) + }; + Ok(()) + } + } +} diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index 9a2c096d66a..fbdff25107c 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -23,8 +23,8 @@ use crate::types::api::payouts; use crate::{ consts, core::errors::{self, CustomResult, RouterResult}, - db, logger, routes, - routes::metrics, + db, logger, + routes::{self, metrics}, types::{ api, domain, storage::{self, enums}, @@ -35,7 +35,8 @@ use crate::{ use crate::{ core::{ errors::ConnectorErrorExt, - payment_methods::transformers as pm_transforms, + errors::StorageErrorExt, + payment_methods::{transformers as pm_transforms, utils}, payments::{self as payments_core, helpers as payment_helpers}, utils as core_utils, }, @@ -45,6 +46,7 @@ use crate::{ types::{self, payment_methods as pm_types}, utils::{ext_traits::OptionExt, ConnectorResponseExt}, }; + const VAULT_SERVICE_NAME: &str = "CARD"; pub struct SupplementaryVaultData { @@ -1463,6 +1465,87 @@ pub fn get_vault_response_for_retrieve_payment_method_data<F>( } } +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[instrument(skip_all)] +pub async fn retrieve_payment_method_from_vault_using_payment_token( + state: &routes::SessionState, + merchant_context: &domain::MerchantContext, + profile: &domain::Profile, + payment_token: &String, + payment_method_type: &common_enums::PaymentMethod, +) -> RouterResult<(domain::PaymentMethod, domain::PaymentMethodVaultingData)> { + let pm_token_data = utils::retrieve_payment_token_data( + state, + payment_token.to_string(), + Some(payment_method_type), + ) + .await?; + + let payment_method_id = match pm_token_data { + storage::PaymentTokenData::PermanentCard(card_token_data) => { + card_token_data.payment_method_id + } + storage::PaymentTokenData::TemporaryGeneric(_) => { + Err(errors::ApiErrorResponse::NotImplemented { + message: errors::NotImplementedMessage::Reason( + "TemporaryGeneric Token not implemented".to_string(), + ), + })? + } + storage::PaymentTokenData::AuthBankDebit(_) => { + Err(errors::ApiErrorResponse::NotImplemented { + message: errors::NotImplementedMessage::Reason( + "AuthBankDebit Token not implemented".to_string(), + ), + })? + } + }; + let db = &*state.store; + let key_manager_state = &state.into(); + + let storage_scheme = merchant_context.get_merchant_account().storage_scheme; + + let payment_method = db + .find_payment_method( + key_manager_state, + merchant_context.get_merchant_key_store(), + &payment_method_id, + storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + + let vault_data = + retrieve_payment_method_from_vault(state, merchant_context, profile, &payment_method) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to retrieve payment method from vault")? + .data; + + Ok((payment_method, vault_data)) +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[instrument(skip_all)] +pub async fn delete_payment_token( + state: &routes::SessionState, + key_for_token: &str, + intent_status: enums::IntentStatus, +) -> RouterResult<()> { + if ![ + enums::IntentStatus::RequiresCustomerAction, + enums::IntentStatus::RequiresMerchantAction, + ] + .contains(&intent_status) + { + utils::delete_payment_token_data(state, key_for_token) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to delete payment_token")?; + } + Ok(()) +} + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[instrument(skip_all)] pub async fn retrieve_payment_method_from_vault( diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 2cd9f507893..6372caa0225 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -92,6 +92,8 @@ use super::{ use crate::core::debit_routing; #[cfg(feature = "frm")] use crate::core::fraud_check as frm_core; +#[cfg(feature = "v2")] +use crate::core::payment_methods::vault; #[cfg(feature = "v1")] use crate::core::routing::helpers as routing_helpers; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] @@ -169,6 +171,11 @@ where // Get the trackers related to track the state of the payment let operations::GetTrackerResponse { mut payment_data } = get_tracker_response; + operation + .to_domain()? + .create_or_fetch_payment_method(state, &merchant_context, profile, &mut payment_data) + .await?; + let (_operation, customer) = operation .to_domain()? .get_customer_details( @@ -294,6 +301,22 @@ where ConnectorCallType::Skip => payment_data, }; + let payment_intent_status = payment_data.get_payment_intent().status; + + // Delete the tokens after payment + payment_data + .get_payment_attempt() + .payment_token + .as_ref() + .zip(Some(payment_data.get_payment_attempt().payment_method_type)) + .map(ParentPaymentMethodToken::return_key_for_token) + .async_map(|key_for_token| async move { + let _ = vault::delete_payment_token(state, &key_for_token, payment_intent_status) + .await + .inspect_err(|err| logger::error!("Failed to delete payment_token: {:?}", err)); + }) + .await; + Ok((payment_data, req, customer, None, None)) } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index a166c54139d..a94d7322e4d 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -2482,6 +2482,10 @@ pub async fn retrieve_payment_method_from_db_with_token_data( } } +#[cfg(all( + any(feature = "v2", feature = "v1"), + not(feature = "payment_methods_v2") +))] pub async fn retrieve_payment_token_data( state: &SessionState, token: String, diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs index ebbece06850..ff873b13779 100644 --- a/crates/router/src/core/payments/operations.rs +++ b/crates/router/src/core/payments/operations.rs @@ -373,6 +373,17 @@ pub trait Domain<F: Clone, R, D>: Send + Sync { Ok(()) } + #[cfg(feature = "v2")] + async fn create_or_fetch_payment_method<'a>( + &'a self, + state: &SessionState, + merchant_context: &domain::MerchantContext, + business_profile: &domain::Profile, + payment_data: &mut D, + ) -> CustomResult<(), errors::ApiErrorResponse> { + Ok(()) + } + // #[cfg(feature = "v2")] // async fn call_connector<'a, RouterDataReq>( // &'a self, diff --git a/crates/router/src/core/payments/operations/payment_confirm_intent.rs b/crates/router/src/core/payments/operations/payment_confirm_intent.rs index 7084fc14bb8..8805710c077 100644 --- a/crates/router/src/core/payments/operations/payment_confirm_intent.rs +++ b/crates/router/src/core/payments/operations/payment_confirm_intent.rs @@ -1,9 +1,9 @@ use api_models::{enums::FrmSuggestion, payments::PaymentsConfirmIntentRequest}; use async_trait::async_trait; -use common_utils::{ext_traits::Encode, types::keymanager::ToEncryptable}; +use common_utils::{ext_traits::Encode, fp_utils::when, types::keymanager::ToEncryptable}; use error_stack::ResultExt; use hyperswitch_domain_models::payments::PaymentConfirmData; -use masking::PeekInterface; +use masking::{ExposeOptionInterface, PeekInterface}; use router_env::{instrument, tracing}; use super::{Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; @@ -11,6 +11,7 @@ use crate::{ core::{ admin, errors::{self, CustomResult, RouterResult, StorageErrorExt}, + payment_methods, payments::{ self, call_decision_manager, helpers, operations::{self, ValidateStatusForOperation}, @@ -225,6 +226,23 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentConfirmData<F>, PaymentsConfir .clone() .map(hyperswitch_domain_models::payment_method_data::PaymentMethodData::from); + if request.payment_token.is_some() { + when( + !matches!( + payment_method_data, + Some(domain::payment_method_data::PaymentMethodData::CardToken(_)) + ), + || { + Err(errors::ApiErrorResponse::InvalidDataValue { + field_name: "payment_method_data", + }) + .attach_printable( + "payment_method_data should be card_token when a token is passed", + ) + }, + )?; + }; + let payment_address = hyperswitch_domain_models::payment_address::PaymentAddress::new( payment_intent .shipping_address @@ -248,6 +266,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentConfirmData<F>, PaymentsConfir payment_method_data, payment_address, mandate_data: None, + payment_method: None, }; let get_trackers_response = operations::GetTrackerResponse { payment_data }; @@ -347,6 +366,125 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsConfirmIntentRequest, PaymentConf ) .await } + + #[cfg(feature = "v2")] + async fn create_or_fetch_payment_method<'a>( + &'a self, + state: &SessionState, + merchant_context: &domain::MerchantContext, + business_profile: &domain::Profile, + payment_data: &mut PaymentConfirmData<F>, + ) -> CustomResult<(), errors::ApiErrorResponse> { + let (payment_method, payment_method_data) = match ( + &payment_data.payment_attempt.payment_token, + &payment_data.payment_method_data, + &payment_data.payment_attempt.customer_acceptance, + ) { + ( + Some(payment_token), + Some(domain::payment_method_data::PaymentMethodData::CardToken(card_token)), + None, + ) => { + let (card_cvc, card_holder_name) = { + ( + card_token + .card_cvc + .clone() + .ok_or(errors::ApiErrorResponse::InvalidDataValue { + field_name: "card_cvc", + }) + .attach_printable("card_cvc not provided")?, + card_token.card_holder_name.clone(), + ) + }; + + let (payment_method, vault_data) = + payment_methods::vault::retrieve_payment_method_from_vault_using_payment_token( + state, + merchant_context, + business_profile, + payment_token, + &payment_data.payment_attempt.payment_method_type, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to retrieve payment method from vault")?; + + match vault_data { + domain::vault::PaymentMethodVaultingData::Card(card_detail) => { + let pm_data_from_vault = + domain::payment_method_data::PaymentMethodData::Card( + domain::payment_method_data::Card::from(( + card_detail, + card_cvc, + card_holder_name, + )), + ); + + (Some(payment_method), Some(pm_data_from_vault)) + } + _ => Err(errors::ApiErrorResponse::NotImplemented { + message: errors::NotImplementedMessage::Reason( + "Non-card Tokenization not implemented".to_string(), + ), + })?, + } + } + + (Some(_payment_token), _, _) => Err(errors::ApiErrorResponse::InvalidDataValue { + field_name: "payment_method_data", + }) + .attach_printable("payment_method_data should be card_token when a token is passed")?, + + (None, Some(domain::PaymentMethodData::Card(card)), Some(_customer_acceptance)) => { + let customer_id = match &payment_data.payment_intent.customer_id { + Some(customer_id) => customer_id.clone(), + None => { + return Err(errors::ApiErrorResponse::InvalidDataValue { + field_name: "customer_id", + }) + .attach_printable("customer_id not provided"); + } + }; + + let pm_create_data = + api::PaymentMethodCreateData::Card(api::CardDetail::from(card.clone())); + + let req = api::PaymentMethodCreate { + payment_method_type: payment_data.payment_attempt.payment_method_type, + payment_method_subtype: payment_data.payment_attempt.payment_method_subtype, + metadata: None, + customer_id, + payment_method_data: pm_create_data, + billing: None, + psp_tokenization: None, + network_tokenization: None, + }; + + let (_pm_response, payment_method) = payment_methods::create_payment_method_core( + state, + &state.get_req_state(), + req, + merchant_context, + business_profile, + ) + .await?; + + // Don't modify payment_method_data in this case, only the payment_method and payment_method_id + (Some(payment_method), None) + } + _ => (None, None), // Pass payment_data unmodified for any other case + }; + + if let Some(pm_data) = payment_method_data { + payment_data.update_payment_method_data(pm_data); + } + if let Some(pm) = payment_method { + payment_data.update_payment_method_and_pm_id(pm.get_id().clone(), pm); + } + + Ok(()) + } } #[async_trait] @@ -400,12 +538,26 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentConfirmData<F>, PaymentsConfirmInt let authentication_type = payment_data.payment_attempt.authentication_type; - let payment_attempt_update = hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptUpdate::ConfirmIntent { - status: attempt_status, - updated_by: storage_scheme.to_string(), - connector, - merchant_connector_id, - authentication_type, + let payment_attempt_update = match &payment_data.payment_method { + Some(payment_method) => { + hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptUpdate::ConfirmIntentTokenized { + status: attempt_status, + updated_by: storage_scheme.to_string(), + connector, + merchant_connector_id, + authentication_type, + payment_method_id : payment_method.get_id().clone() + } + } + None => { + hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptUpdate::ConfirmIntent { + status: attempt_status, + updated_by: storage_scheme.to_string(), + connector, + merchant_connector_id, + authentication_type, + } + } }; let updated_payment_intent = db diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 40285ee5ce4..41d494989b9 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -2541,9 +2541,55 @@ impl<F: Clone> PostUpdateTracker<F, PaymentConfirmData<F>, types::PaymentsAuthor .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to update payment attempt")?; + let attempt_status = updated_payment_attempt.status; + payment_data.payment_intent = updated_payment_intent; payment_data.payment_attempt = updated_payment_attempt; + if let Some(payment_method) = &payment_data.payment_method { + match attempt_status { + common_enums::AttemptStatus::AuthenticationFailed + | common_enums::AttemptStatus::RouterDeclined + | common_enums::AttemptStatus::AuthorizationFailed + | common_enums::AttemptStatus::Voided + | common_enums::AttemptStatus::VoidInitiated + | common_enums::AttemptStatus::CaptureFailed + | common_enums::AttemptStatus::VoidFailed + | common_enums::AttemptStatus::AutoRefunded + | common_enums::AttemptStatus::Unresolved + | common_enums::AttemptStatus::Pending + | common_enums::AttemptStatus::Failure => (), + + common_enums::AttemptStatus::Started + | common_enums::AttemptStatus::AuthenticationPending + | common_enums::AttemptStatus::AuthenticationSuccessful + | common_enums::AttemptStatus::Authorized + | common_enums::AttemptStatus::Charged + | common_enums::AttemptStatus::Authorizing + | common_enums::AttemptStatus::CodInitiated + | common_enums::AttemptStatus::PartialCharged + | common_enums::AttemptStatus::PartialChargedAndChargeable + | common_enums::AttemptStatus::CaptureInitiated + | common_enums::AttemptStatus::PaymentMethodAwaited + | common_enums::AttemptStatus::ConfirmationAwaited + | common_enums::AttemptStatus::DeviceDataCollectionPending => { + let pm_update_status = enums::PaymentMethodStatus::Active; + + // payment_methods microservice call + payment_methods::update_payment_method_status_internal( + state, + key_store, + storage_scheme, + pm_update_status, + payment_method.get_id(), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to update payment method status")?; + } + } + } + Ok(payment_data) } } diff --git a/crates/router/src/core/payments/operations/proxy_payments_intent.rs b/crates/router/src/core/payments/operations/proxy_payments_intent.rs index 1d7fb108b30..9829c109440 100644 --- a/crates/router/src/core/payments/operations/proxy_payments_intent.rs +++ b/crates/router/src/core/payments/operations/proxy_payments_intent.rs @@ -260,6 +260,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentConfirmData<F>, ProxyPaymentsR payment_method_data: Some(PaymentMethodData::MandatePayment), payment_address, mandate_data: Some(mandate_data_input), + payment_method: None, }; let get_trackers_response = operations::GetTrackerResponse { payment_data }; diff --git a/crates/router/src/core/payments/payment_methods.rs b/crates/router/src/core/payments/payment_methods.rs index 887bd078914..46c88e76a06 100644 --- a/crates/router/src/core/payments/payment_methods.rs +++ b/crates/router/src/core/payments/payment_methods.rs @@ -5,7 +5,7 @@ use common_utils::{ext_traits::OptionExt, id_type}; use error_stack::ResultExt; use super::errors; -use crate::{db::errors::StorageErrorExt, routes, types::domain}; +use crate::{core::payment_methods, db::errors::StorageErrorExt, routes, types::domain}; #[cfg(all( feature = "v2", @@ -46,12 +46,24 @@ pub async fn list_payment_methods( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error when fetching merchant connector accounts")?; + let customer_payment_methods = match &payment_intent.customer_id { + Some(customer_id) => Some( + payment_methods::list_customer_payment_methods_core( + &state, + &merchant_context, + customer_id, + ) + .await?, + ), + None => None, + }; + let response = hyperswitch_domain_models::merchant_connector_account::FlattenedPaymentMethodsEnabled::from_payment_connectors_list(payment_connector_accounts) .perform_filtering() .get_required_fields(RequiredFieldsInput::new()) .perform_surcharge_calculation() - .generate_response(); + .generate_response(customer_payment_methods); Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( response, @@ -119,7 +131,12 @@ struct RequiredFieldsAndSurchargeForEnabledPaymentMethodTypes( ); impl RequiredFieldsAndSurchargeForEnabledPaymentMethodTypes { - fn generate_response(self) -> api_models::payments::PaymentMethodListResponseForPayments { + fn generate_response( + self, + customer_payment_methods: Option< + Vec<api_models::payment_methods::CustomerPaymentMethodResponseItem>, + >, + ) -> api_models::payments::PaymentMethodListResponseForPayments { let response_payment_methods = self .0 .into_iter() @@ -136,7 +153,7 @@ impl RequiredFieldsAndSurchargeForEnabledPaymentMethodTypes { api_models::payments::PaymentMethodListResponseForPayments { payment_methods_enabled: response_payment_methods, - customer_payment_methods: None, + customer_payment_methods, } } } diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 0efbd655772..1e8969d3727 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -1044,6 +1044,17 @@ impl ParentPaymentMethodToken { ), } } + + #[cfg(feature = "v2")] + pub fn return_key_for_token( + (parent_pm_token, payment_method): (&String, api_models::enums::PaymentMethod), + ) -> String { + format!( + "pm_token_{}_{}_hyperswitch", + parent_pm_token, payment_method + ) + } + pub async fn insert( &self, fulfillment_time: i64, diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs index 09dd783e483..ecc3ec35edf 100644 --- a/crates/router/src/types/api/payment_methods.rs +++ b/crates/router/src/types/api/payment_methods.rs @@ -1,19 +1,18 @@ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub use api_models::payment_methods::{ CardDetail, CardDetailFromLocker, CardDetailsPaymentMethod, CardNetworkTokenizeRequest, - CardNetworkTokenizeResponse, CardType, CustomerPaymentMethod, - CustomerPaymentMethodsListResponse, DeleteTokenizeByTokenRequest, GetTokenizePayloadRequest, - GetTokenizePayloadResponse, ListCountriesCurrenciesRequest, MigrateCardDetail, - NetworkTokenDetailsPaymentMethod, NetworkTokenDetailsResponse, NetworkTokenResponse, - PaymentMethodCollectLinkRenderRequest, PaymentMethodCollectLinkRequest, PaymentMethodCreate, - PaymentMethodCreateData, PaymentMethodDeleteResponse, PaymentMethodId, - PaymentMethodIntentConfirm, PaymentMethodIntentCreate, PaymentMethodListData, - PaymentMethodListRequest, PaymentMethodListResponse, PaymentMethodMigrate, - PaymentMethodMigrateResponse, PaymentMethodResponse, PaymentMethodResponseData, - PaymentMethodUpdate, PaymentMethodUpdateData, PaymentMethodsData, TokenDataResponse, - TokenDetailsResponse, TokenizePayloadEncrypted, TokenizePayloadRequest, TokenizedCardValue1, - TokenizedCardValue2, TokenizedWalletValue1, TokenizedWalletValue2, - TotalPaymentMethodCountResponse, + CardNetworkTokenizeResponse, CardType, CustomerPaymentMethodResponseItem, + DeleteTokenizeByTokenRequest, GetTokenizePayloadRequest, GetTokenizePayloadResponse, + ListCountriesCurrenciesRequest, MigrateCardDetail, NetworkTokenDetailsPaymentMethod, + NetworkTokenDetailsResponse, NetworkTokenResponse, PaymentMethodCollectLinkRenderRequest, + PaymentMethodCollectLinkRequest, PaymentMethodCreate, PaymentMethodCreateData, + PaymentMethodDeleteResponse, PaymentMethodId, PaymentMethodIntentConfirm, + PaymentMethodIntentCreate, PaymentMethodListData, PaymentMethodListRequest, + PaymentMethodListResponseForSession, PaymentMethodMigrate, PaymentMethodMigrateResponse, + PaymentMethodResponse, PaymentMethodResponseData, PaymentMethodUpdate, PaymentMethodUpdateData, + PaymentMethodsData, TokenDataResponse, TokenDetailsResponse, TokenizePayloadEncrypted, + TokenizePayloadRequest, TokenizedCardValue1, TokenizedCardValue2, TokenizedWalletValue1, + TokenizedWalletValue2, TotalPaymentMethodCountResponse, }; #[cfg(all( any(feature = "v2", feature = "v1"), diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs index 21c15c23b3c..ff12d890df4 100644 --- a/crates/router/src/types/storage/payment_method.rs +++ b/crates/router/src/types/storage/payment_method.rs @@ -29,7 +29,7 @@ pub struct CardTokenData { #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct CardTokenData { - pub payment_method_id: Option<common_utils::id_type::GlobalPaymentMethodId>, + pub payment_method_id: common_utils::id_type::GlobalPaymentMethodId, pub locker_id: Option<String>, pub token: String, } @@ -53,6 +53,7 @@ pub struct WalletTokenData { #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(tag = "kind", rename_all = "snake_case")] +#[cfg(feature = "v1")] pub enum PaymentTokenData { // The variants 'Temporary' and 'Permanent' are added for backwards compatibility // with any tokenized data present in Redis at the time of deployment of this change @@ -64,6 +65,15 @@ pub enum PaymentTokenData { WalletToken(WalletTokenData), } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +pub enum PaymentTokenData { + TemporaryGeneric(GenericTokenData), + PermanentCard(CardTokenData), + AuthBankDebit(payment_methods::BankAccountTokenData), +} + impl PaymentTokenData { #[cfg(all( any(feature = "v1", feature = "v2"), @@ -85,7 +95,7 @@ impl PaymentTokenData { #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub fn permanent_card( - payment_method_id: Option<common_utils::id_type::GlobalPaymentMethodId>, + payment_method_id: common_utils::id_type::GlobalPaymentMethodId, locker_id: Option<String>, token: String, ) -> Self { @@ -100,13 +110,20 @@ impl PaymentTokenData { Self::TemporaryGeneric(GenericTokenData { token }) } + #[cfg(feature = "v1")] pub fn wallet_token(payment_method_id: String) -> Self { Self::WalletToken(WalletTokenData { payment_method_id }) } + #[cfg(feature = "v1")] pub fn is_permanent_card(&self) -> bool { matches!(self, Self::PermanentCard(_) | Self::Permanent(_)) } + + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] + pub fn is_permanent_card(&self) -> bool { + matches!(self, Self::PermanentCard(_)) + } } #[cfg(all( @@ -126,6 +143,7 @@ pub struct PaymentMethodListContext { pub enum PaymentMethodListContext { Card { card_details: api::CardDetailFromLocker, + // TODO: Why can't these fields be mandatory? token_data: Option<PaymentTokenData>, }, Bank { diff --git a/crates/router/src/workflows/revenue_recovery.rs b/crates/router/src/workflows/revenue_recovery.rs index af27d6f45d1..792251de496 100644 --- a/crates/router/src/workflows/revenue_recovery.rs +++ b/crates/router/src/workflows/revenue_recovery.rs @@ -85,13 +85,13 @@ impl ProcessTrackerWorkflow<SessionState> for ExecutePcrWorkflow { match process.name.as_deref() { Some("EXECUTE_WORKFLOW") => { - pcr::perform_execute_payment( + Box::pin(pcr::perform_execute_payment( state, &process, &tracking_data, &revenue_recovery_payment_data, &payment_data.payment_intent, - ) + )) .await } Some("PSYNC_WORKFLOW") => {
2025-05-21T05:40:55Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - Added a field `payment_token` to customer PML response - During `/confirm-intent`, in case of card, an inactive payment method method is created before `call_conector_service` - After the payment has completed, depending on its status the payment method is marked active - Added support for confirming a payment using `payment_token` and `card_cvc` ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #8089 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Confirm Intent Request: ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_01971c02c9f176a3b60be16df712bfc3/confirm-intent' \ --header 'x-client-secret: cs_01971c02ca147f11baea8a2521618052' \ --header 'x-profile-id: pro_W5FEDaNZ8OqqVDgFXgfg' \ --header 'Authorization: publishable-key=pk_dev_08e48a189e584123be3657ad34e1fb74,client-secret=cs_01971c02ca147f11baea8a2521618052' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_08e48a189e584123be3657ad34e1fb74' \ --data '{ "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "John Doe", "card_cvc": "100" } }, "customer_acceptance": { "acceptance_type": "online", "accepted_at": "2025-05-10T10:11:12Z", "online": null }, "payment_method_type": "card", "payment_method_subtype": "card" }' ``` 2. Confirm Intent Response: ```json { "id": "12345_pay_01971677d7ea7c80a137ddcb47221e17", "status": "succeeded", "amount": { "order_amount": 100, "currency": "USD", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 100, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": 100 }, "customer_id": "12345_cus_01971677c68c79d1be4297b6565164fb", "connector": "stripe", "created": "2025-05-28T10:37:22.297Z", "payment_method_data": { "billing": null }, "payment_method_type": "card", "payment_method_subtype": "card", "connector_transaction_id": "pi_3RThMRD5R7gDAGff03fgp3sK", "connector_reference_id": null, "merchant_connector_id": "mca_zi4k2xVeD6hTCWqHxDeX", "browser_info": null, "error": null, "shipping": null, "billing": null, "attempts": null, "connector_token_details": { "token": "pm_1RThMRD5R7gDAGffyr5YF1e5", "connector_token_request_reference_id": "rmuFSW2YVDX2PHEnpU" }, "payment_method_id": "12345_pm_01971677e50c7aa29a4ec01584df07dc", "next_action": null, "return_url": "https://google.com/success", "authentication_type": "no_three_ds", "authentication_type_applied": "no_three_ds", "is_iframe_redirection_enabled": null } ``` 3. Customer PML Request: ``` curl --location 'http://localhost:8080/v2/customers/12345_cus_01971677c68c79d1be4297b6565164fb/saved-payment-methods' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_hvfcgBE4PqzQ25QRg2Y1' \ --header 'Authorization: api-key=dev_huT4fMR6cwCZL7j8pGpORZqKUGfTmWOD6ahQ6IOkmOMgJdJkVbJfYCHxpuapjpuM' \ --header 'api-key: dev_huT4fMR6cwCZL7j8pGpORZqKUGfTmWOD6ahQ6IOkmOMgJdJkVbJfYCHxpuapjpuM' ``` 4. Customer PML Response: ```json { "customer_payment_methods": [ { "id": "12345_pm_01971677e50c7aa29a4ec01584df07dc", "payment_token": "token_mb4HgBeUiiDtw4p9fmsh", "customer_id": "12345_cus_01971677c68c79d1be4297b6565164fb", "payment_method_type": "card", "payment_method_subtype": "card", "recurring_enabled": true, "payment_method_data": { "card": { "issuer_country": null, "last4_digits": "4242", "expiry_month": "10", "expiry_year": "25", "card_holder_name": "John Doe", "card_fingerprint": null, "nick_name": null, "card_network": null, "card_isin": null, "card_issuer": null, "card_type": null, "saved_to_locker": true } }, "bank": null, "created": "2025-05-28T10:37:25.645Z", "requires_cvv": true, "last_used_at": "2025-05-28T10:37:25.645Z", "is_default": false, "billing": null, "network_tokenization": null, "psp_tokenization_enabled": false } ] } ``` 5. Payments Confirm using token request: ``` curl --location 'http://localhost:8080/v2/payments/12345_pay_01971ae0cd847b20984cf9b465bd84ba/confirm-intent' \ --header 'x-profile-id: pro_pE7MrT231b4IhEVnTycu' \ --header 'x-client-secret: cs_01971ae0cd9170b1a05d40f837a86c8f' \ --header 'Authorization: publishable-key=pk_dev_841e89133d1246d3b53a3468ea92dd6a,client-secret=cs_01971ae0cd9170b1a05d40f837a86c8f' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_841e89133d1246d3b53a3468ea92dd6a' \ --data '{ "payment_method_data": { "card_token": { "card_holder_name": "John Doe", "card_cvc": "123" } }, "payment_method_type": "card", "payment_method_subtype": "card", "payment_token": "token_14edM60EPMfyyPvp80Ex" }' ``` 6. Payments Confirm using token response: ```json { "id": "12345_pay_01971ae0cd847b20984cf9b465bd84ba", "status": "succeeded", "amount": { "order_amount": 100, "currency": "GBP", "shipping_cost": null, "order_tax_amount": null, "external_tax_calculation": "skip", "surcharge_calculation": "skip", "surcharge_amount": null, "tax_on_surcharge": null, "net_amount": 100, "amount_to_capture": null, "amount_capturable": 0, "amount_captured": 100 }, "customer_id": "12345_cus_01971adcfc007813b7bc2367e2a399b5", "connector": "stripe", "created": "2025-05-29T07:10:29.774Z", "payment_method_data": { "billing": null }, "payment_method_type": "card", "payment_method_subtype": "card", "connector_transaction_id": "pi_3RU0cUD5R7gDAGff0yM3CMmF", "connector_reference_id": null, "merchant_connector_id": "mca_ZXKvjtgq3DVPfbpHW902", "browser_info": null, "error": null, "shipping": null, "billing": null, "attempts": null, "connector_token_details": { "token": "pm_1RU0cUD5R7gDAGff6idzjsOT", "connector_token_request_reference_id": "vjY55lNJYsW5G6nbPZ" }, "payment_method_id": "12345_pm_01971ade17337c939cc0c2e3df36cf0e", "next_action": null, "return_url": "https://google.com/success", "authentication_type": "no_three_ds", "authentication_type_applied": "no_three_ds", "is_iframe_redirection_enabled": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
835a425ded2cf26b9a3f69f29c3a26a41603b2de
835a425ded2cf26b9a3f69f29c3a26a41603b2de
juspay/hyperswitch
juspay__hyperswitch-8081
Bug: [CHORE] add adyen to the supported connectors list for network tokenization HS maintains a list of supported connectors for paying using network tokens and NTI. Adyen supports this, and needs to be added to the list - `network_tokenization_supported_connectors`
diff --git a/config/config.example.toml b/config/config.example.toml index 0c2fec16b27..16846d0c403 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -1039,7 +1039,7 @@ delete_token_url= "" # base url to delete token from token service check_token_status_url= "" # base url to check token status from token service [network_tokenization_supported_connectors] -connector_list = "cybersource" # Supported connectors for network tokenization +connector_list = "adyen,cybersource" # Supported connectors for network tokenization [network_transaction_id_supported_connectors] connector_list = "adyen,archipel,cybersource,novalnet,stripe,worldpay" # Supported connectors for network transaction id diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index a29f54990ef..accbcfff05e 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -726,7 +726,7 @@ connector_list = "" card_networks = "Visa, AmericanExpress, Mastercard" [network_tokenization_supported_connectors] -connector_list = "cybersource" +connector_list = "adyen,cybersource" [platform] enabled = true diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index caf6e764846..0c32b15a3bc 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -742,7 +742,7 @@ connector_list = "" card_networks = "Visa, AmericanExpress, Mastercard" [network_tokenization_supported_connectors] -connector_list = "cybersource" +connector_list = "adyen,cybersource" [platform] enabled = false diff --git a/config/development.toml b/config/development.toml index d6b5e891742..158f8b0116e 100644 --- a/config/development.toml +++ b/config/development.toml @@ -1125,7 +1125,7 @@ id = "12345" card_networks = "Visa, AmericanExpress, Mastercard" [network_tokenization_supported_connectors] -connector_list = "cybersource" +connector_list = "adyen,cybersource" [grpc_client.dynamic_routing_client] host = "localhost" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index f1954a86fa9..5a425bd89ff 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -1022,7 +1022,7 @@ id = "12345" card_networks = "Visa, AmericanExpress, Mastercard" [network_tokenization_supported_connectors] -connector_list = "cybersource" +connector_list = "adyen,cybersource" # EmailClient configuration. Only applicable when the `email` feature flag is enabled. [email]
2025-05-20T10:53:08Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR enables processing payment transactions via Adyen using network tokens and NTI ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [x] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context This help merchants who has enabled processing network tokens in Adyen to use NetworkTokens along with NTI reference for processing MIT. ## How did you test it? Cannot be tested locally. ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
d91cf70ae346cbf613ce5c1cfad2ae8a28c71d1c
d91cf70ae346cbf613ce5c1cfad2ae8a28c71d1c
juspay/hyperswitch
juspay__hyperswitch-8084
Bug: [FEATURE] Add api-key support for routing APIs ### Feature Description Need to add api-key auth for all routing APIs ### Possible Implementation Just need to change auth implementation on handler ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index c65a8c6b9ec..e5cbd1b653f 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -1752,10 +1752,13 @@ where let algo_type_enabled_features = algo_type.get_enabled_features(); if *algo_type_enabled_features == feature_to_enable { // algorithm already has the required feature - return Err(errors::ApiErrorResponse::PreconditionFailed { - message: format!("{} is already enabled", dynamic_routing_type), - } - .into()); + let routing_algorithm = db + .find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algo_type_algorithm_id) + .await + .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; + let updated_routing_record = routing_algorithm.foreign_into(); + + return Ok(ApplicationResponse::Json(updated_routing_record)); }; *algo_type_enabled_features = feature_to_enable; dynamic_routing_algo_ref.update_enabled_features(dynamic_routing_type, feature_to_enable); diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs index 3dcc947d133..ba041cbe5ac 100644 --- a/crates/router/src/routes/routing.rs +++ b/crates/router/src/routes/routing.rs @@ -42,7 +42,6 @@ pub async fn routing_create_config( transaction_type, ) }, - #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, @@ -53,10 +52,6 @@ pub async fn routing_create_config( }, req.headers(), ), - #[cfg(feature = "release")] - &auth::JWTAuth { - permission: Permission::ProfileRoutingWrite, - }, api_locking::LockAction::NotApplicable, )) .await @@ -134,7 +129,6 @@ pub async fn routing_link_config( transaction_type, ) }, - #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, @@ -145,10 +139,6 @@ pub async fn routing_link_config( }, req.headers(), ), - #[cfg(feature = "release")] - &auth::JWTAuth { - permission: Permission::ProfileRoutingWrite, - }, api_locking::LockAction::NotApplicable, )) .await @@ -233,7 +223,6 @@ pub async fn routing_retrieve_config( algorithm_id, ) }, - #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, @@ -244,10 +233,6 @@ pub async fn routing_retrieve_config( }, req.headers(), ), - #[cfg(feature = "release")] - &auth::JWTAuth { - permission: Permission::ProfileRoutingRead, - }, api_locking::LockAction::NotApplicable, )) .await @@ -324,7 +309,6 @@ pub async fn list_routing_configs( transaction_type, ) }, - #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, @@ -335,10 +319,6 @@ pub async fn list_routing_configs( }, req.headers(), ), - #[cfg(feature = "release")] - &auth::JWTAuth { - permission: Permission::MerchantRoutingRead, - }, api_locking::LockAction::NotApplicable, )) .await @@ -370,7 +350,6 @@ pub async fn list_routing_configs_for_profile( transaction_type, ) }, - #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, @@ -381,10 +360,6 @@ pub async fn list_routing_configs_for_profile( }, req.headers(), ), - #[cfg(feature = "release")] - &auth::JWTAuth { - permission: Permission::ProfileRoutingRead, - }, api_locking::LockAction::NotApplicable, )) .await @@ -464,7 +439,6 @@ pub async fn routing_unlink_config( transaction_type, ) }, - #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, @@ -475,10 +449,6 @@ pub async fn routing_unlink_config( }, req.headers(), ), - #[cfg(feature = "release")] - &auth::JWTAuth { - permission: Permission::ProfileRoutingWrite, - }, api_locking::LockAction::NotApplicable, )) .await @@ -556,7 +526,6 @@ pub async fn routing_update_default_config( transaction_type, ) }, - #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, @@ -567,10 +536,6 @@ pub async fn routing_update_default_config( }, req.headers(), ), - #[cfg(feature = "release")] - &auth::JWTAuth { - permission: Permission::MerchantRoutingWrite, - }, api_locking::LockAction::NotApplicable, )) .await @@ -644,9 +609,16 @@ pub async fn routing_retrieve_default_config( transaction_type, ) }, - &auth::JWTAuth { - permission: Permission::ProfileRoutingRead, - }, + auth::auth_type( + &auth::HeaderAuth(auth::ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: false, + }), + &auth::JWTAuth { + permission: Permission::ProfileRoutingRead, + }, + req.headers(), + ), api_locking::LockAction::NotApplicable, )) .await @@ -992,7 +964,6 @@ pub async fn routing_retrieve_linked_config( transaction_type, ) }, - #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, @@ -1004,11 +975,6 @@ pub async fn routing_retrieve_linked_config( }, req.headers(), ), - #[cfg(feature = "release")] - &auth::JWTAuthProfileFromRoute { - profile_id, - required_permission: Permission::ProfileRoutingRead, - }, api_locking::LockAction::NotApplicable, )) .await @@ -1030,7 +996,6 @@ pub async fn routing_retrieve_linked_config( transaction_type, ) }, - #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, @@ -1041,10 +1006,6 @@ pub async fn routing_retrieve_linked_config( }, req.headers(), ), - #[cfg(feature = "release")] - &auth::JWTAuth { - permission: Permission::ProfileRoutingRead, - }, api_locking::LockAction::NotApplicable, )) .await @@ -1184,7 +1145,6 @@ pub async fn routing_update_default_config_for_profile( transaction_type, ) }, - #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, @@ -1196,11 +1156,6 @@ pub async fn routing_update_default_config_for_profile( }, req.headers(), ), - #[cfg(feature = "release")] - &auth::JWTAuthProfileFromRoute { - profile_id: routing_payload_wrapper.profile_id, - required_permission: Permission::ProfileRoutingWrite, - }, api_locking::LockAction::NotApplicable, )) .await
2025-05-20T11:36:55Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Added api-key auth for routing APIs Earlier, all routing endpoints were only JWT auth based for release build and (api-key + JWT) for local development build. Have removed the feature flag based distinction and refactored auth for all routing endpoints to be (api-key + JWT) for both builds. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Test all routing APIs with api-key auth 1. Create routing config (`/routing`) 2. List routing config (`/routing`) 3. List active routing config (`/routing/active`) 4. List for profile (`/routing/list/profile`) 5. activate config (`routing/:id/activate`) 6. retrieve config (`routing/:id`) 7. deactivate (`routing/deactivate`) 8. default profile (`routing/default/profile`) 9. update default profile (`routing/default/profile/:profile_id`) 10. update default config (`/routing/default`) ``` curl --location 'http://127.0.0.1:8080/routing' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_nvORdH8glyzL3AyPwkWcb7GsLD7xi7PU7kHZpvRWlPJNnEz1dQPrCN1swXFFjKEk' \ --data ' { "name": "advanced config", "description": "It is my ADVANCED config", "profile_id": "pro_rfW0Fv5J0Cct1Bnw2EuS", "algorithm": { "type": "advanced", "data": { "defaultSelection": { "type": "priority", "data": [ { "connector": "stripe", "merchant_connector_id": "mca_aHTJXYcakT5Nlx48kuSh" } ] }, "rules": [ { "name": "cybersource first", "connectorSelection": { "type": "priority", "data": [ { "connector": "cybersource", "merchant_connector_id": "mca_rJu5LzTmK2SjYgoRMWZ4" } ] }, "statements": [ { "condition": [ { "lhs": "upi", "comparison": "equal", "value": { "type": "enum_variant", "value": "upi_collect" }, "metadata": {} } ], "nested": [ { "condition": [ { "lhs": "amount", "comparison": "greater_than", "value": { "type": "number", "value": 5000 }, "metadata": {} }, { "lhs": "currency", "comparison": "equal", "value": { "type": "enum_variant", "value": "USD" }, "metadata": {} } ] }, { "condition": [ { "lhs": "amount", "comparison": "greater_than", "value": { "type": "number", "value": 10000 }, "metadata": {} } ] } ] } ] } ], "metadata": {} } } }' ``` ``` curl -X GET --location 'http://127.0.0.1:8080/routing' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_Qe471NOXDpSt0z1VFlmFpFrKNZ9vbxKju4iIyBWaJ0iOXwHpvqFDc26LfhF06Rio' ``` ``` curl -X GET --location 'http://127.0.0.1:8080/routing' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZDA1ODU2ZWEtYWMxMy00MjcwLTg3NDAtNWFjOTk1NGFlZjhhIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ3ODIzMjg1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0Nzk5NzIyMCwib3JnX2lkIjoib3JnX1MyU2t6WXRyMUREcFJrdHJiam5kIiwicHJvZmlsZV9pZCI6InByb19tNUd5bEw2azE1ejl6QXBjMjhmTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.GlOzvYtOi5FRHp1zwdf_6K6D14gdOx1N06TzpodI7Sg' \ --cookie "login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZDA1ODU2ZWEtYWMxMy00MjcwLTg3NDAtNWFjOTk1NGFlZjhhIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ3ODIzMjg1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0Nzk5NzIyMCwib3JnX2lkIjoib3JnX1MyU2t6WXRyMUREcFJrdHJiam5kIiwicHJvZmlsZV9pZCI6InByb19tNUd5bEw2azE1ejl6QXBjMjhmTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.GlOzvYtOi5FRHp1zwdf_6K6D14gdOx1N06TzpodI7Sg" ``` ``` curl -X GET --location 'http://127.0.0.1:8080/routing/active' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_Qe471NOXDpSt0z1VFlmFpFrKNZ9vbxKju4iIyBWaJ0iOXwHpvqFDc26LfhF06Rio' ``` ``` curl -X GET --location 'http://127.0.0.1:8080/routing/active' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZDA1ODU2ZWEtYWMxMy00MjcwLTg3NDAtNWFjOTk1NGFlZjhhIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ3ODIzMjg1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0Nzk5NzIyMCwib3JnX2lkIjoib3JnX1MyU2t6WXRyMUREcFJrdHJiam5kIiwicHJvZmlsZV9pZCI6InByb19tNUd5bEw2azE1ejl6QXBjMjhmTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.GlOzvYtOi5FRHp1zwdf_6K6D14gdOx1N06TzpodI7Sg' \ --cookie "login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZDA1ODU2ZWEtYWMxMy00MjcwLTg3NDAtNWFjOTk1NGFlZjhhIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ3ODIzMjg1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0Nzk5NzIyMCwib3JnX2lkIjoib3JnX1MyU2t6WXRyMUREcFJrdHJiam5kIiwicHJvZmlsZV9pZCI6InByb19tNUd5bEw2azE1ejl6QXBjMjhmTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.GlOzvYtOi5FRHp1zwdf_6K6D14gdOx1N06TzpodI7Sg" ``` ``` curl --location 'http://127.0.0.1:8080/routing/list/profile' \ --header 'api-key: dev_Qe471NOXDpSt0z1VFlmFpFrKNZ9vbxKju4iIyBWaJ0iOXwHpvqFDc26LfhF06Ri ``` ``` curl --location 'http://127.0.0.1:8080/routing/list/profile' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZDA1ODU2ZWEtYWMxMy00MjcwLTg3NDAtNWFjOTk1NGFlZjhhIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ3ODIzMjg1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0Nzk5NzIyMCwib3JnX2lkIjoib3JnX1MyU2t6WXRyMUREcFJrdHJiam5kIiwicHJvZmlsZV9pZCI6InByb19tNUd5bEw2azE1ejl6QXBjMjhmTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.GlOzvYtOi5FRHp1zwdf_6K6D14gdOx1N06TzpodI7Sg' \ --cookie "login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZDA1ODU2ZWEtYWMxMy00MjcwLTg3NDAtNWFjOTk1NGFlZjhhIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ3ODIzMjg1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0Nzk5NzIyMCwib3JnX2lkIjoib3JnX1MyU2t6WXRyMUREcFJrdHJiam5kIiwicHJvZmlsZV9pZCI6InByb19tNUd5bEw2azE1ejl6QXBjMjhmTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.GlOzvYtOi5FRHp1zwdf_6K6D14gdOx1N06TzpodI7Sg" ``` ``` curl --location --request POST 'http://localhost:8080/routing/routing_o7xnnpZ8MtkbuEpsDsjK/activate' \ --header 'api-key: dev_Qe471NOXDpSt0z1VFlmFpFrKNZ9vbxKju4iIyBWaJ0iOXwHpvqFDc26LfhF06Rio' ``` ``` curl --location --request POST 'http://localhost:8080/routing/routing_o7xnnpZ8MtkbuEpsDsjK/activate' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZDA1ODU2ZWEtYWMxMy00MjcwLTg3NDAtNWFjOTk1NGFlZjhhIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ3ODIzMjg1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0Nzk5NzIyMCwib3JnX2lkIjoib3JnX1MyU2t6WXRyMUREcFJrdHJiam5kIiwicHJvZmlsZV9pZCI6InByb19tNUd5bEw2azE1ejl6QXBjMjhmTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.GlOzvYtOi5FRHp1zwdf_6K6D14gdOx1N06TzpodI7Sg' \ --cookie "login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZDA1ODU2ZWEtYWMxMy00MjcwLTg3NDAtNWFjOTk1NGFlZjhhIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ3ODIzMjg1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0Nzk5NzIyMCwib3JnX2lkIjoib3JnX1MyU2t6WXRyMUREcFJrdHJiam5kIiwicHJvZmlsZV9pZCI6InByb19tNUd5bEw2azE1ejl6QXBjMjhmTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.GlOzvYtOi5FRHp1zwdf_6K6D14gdOx1N06TzpodI7Sg" ``` ``` curl --location 'http://127.0.0.1:8080/routing/routing_WkgC0lnKAnxSkBthgnK9' \ --header 'api-key: dev_Qe471NOXDpSt0z1VFlmFpFrKNZ9vbxKju4iIyBWaJ0iOXwHpvqFDc26LfhF06Rio' ``` ``` curl --location 'http://127.0.0.1:8080/routing/routing_WkgC0lnKAnxSkBthgnK9' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZDA1ODU2ZWEtYWMxMy00MjcwLTg3NDAtNWFjOTk1NGFlZjhhIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ3ODIzMjg1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0Nzk5NzIyMCwib3JnX2lkIjoib3JnX1MyU2t6WXRyMUREcFJrdHJiam5kIiwicHJvZmlsZV9pZCI6InByb19tNUd5bEw2azE1ejl6QXBjMjhmTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.GlOzvYtOi5FRHp1zwdf_6K6D14gdOx1N06TzpodI7Sg' \ --cookie "login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZDA1ODU2ZWEtYWMxMy00MjcwLTg3NDAtNWFjOTk1NGFlZjhhIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ3ODIzMjg1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0Nzk5NzIyMCwib3JnX2lkIjoib3JnX1MyU2t6WXRyMUREcFJrdHJiam5kIiwicHJvZmlsZV9pZCI6InByb19tNUd5bEw2azE1ejl6QXBjMjhmTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.GlOzvYtOi5FRHp1zwdf_6K6D14gdOx1N06TzpodI7Sg" ``` ``` curl --location 'http://127.0.0.1:8080/routing/deactivate' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_Qe471NOXDpSt0z1VFlmFpFrKNZ9vbxKju4iIyBWaJ0iOXwHpvqFDc26LfhF06Rio' \ --data '{ "profile_id": "pro_rfW0Fv5J0Cct1Bnw2EuS" }' ``` ``` curl --location 'http://127.0.0.1:8080/routing/deactivate' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZDA1ODU2ZWEtYWMxMy00MjcwLTg3NDAtNWFjOTk1NGFlZjhhIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ3ODIzMjg1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0Nzk5NzIyMCwib3JnX2lkIjoib3JnX1MyU2t6WXRyMUREcFJrdHJiam5kIiwicHJvZmlsZV9pZCI6InByb19tNUd5bEw2azE1ejl6QXBjMjhmTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.GlOzvYtOi5FRHp1zwdf_6K6D14gdOx1N06TzpodI7Sg' \ --cookie "login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZDA1ODU2ZWEtYWMxMy00MjcwLTg3NDAtNWFjOTk1NGFlZjhhIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ3ODIzMjg1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0Nzk5NzIyMCwib3JnX2lkIjoib3JnX1MyU2t6WXRyMUREcFJrdHJiam5kIiwicHJvZmlsZV9pZCI6InByb19tNUd5bEw2azE1ejl6QXBjMjhmTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.GlOzvYtOi5FRHp1zwdf_6K6D14gdOx1N06TzpodI7Sg" \ --data '{ "profile_id": "pro_rfW0Fv5J0Cct1Bnw2EuS" }' ``` ``` curl --location 'http://127.0.0.1:8080/routing/default/profile' \ --header 'api-key: dev_Qe471NOXDpSt0z1VFlmFpFrKNZ9vbxKju4iIyBWaJ0iOXwHpvqFDc26LfhF06Rio' ``` ``` curl --location 'http://127.0.0.1:8080/routing/default/profile' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZDA1ODU2ZWEtYWMxMy00MjcwLTg3NDAtNWFjOTk1NGFlZjhhIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ3ODIzMjg1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0Nzk5NzIyMCwib3JnX2lkIjoib3JnX1MyU2t6WXRyMUREcFJrdHJiam5kIiwicHJvZmlsZV9pZCI6InByb19tNUd5bEw2azE1ejl6QXBjMjhmTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.GlOzvYtOi5FRHp1zwdf_6K6D14gdOx1N06TzpodI7Sg' \ --cookie "login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZDA1ODU2ZWEtYWMxMy00MjcwLTg3NDAtNWFjOTk1NGFlZjhhIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ3ODIzMjg1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0Nzk5NzIyMCwib3JnX2lkIjoib3JnX1MyU2t6WXRyMUREcFJrdHJiam5kIiwicHJvZmlsZV9pZCI6InByb19tNUd5bEw2azE1ejl6QXBjMjhmTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.GlOzvYtOi5FRHp1zwdf_6K6D14gdOx1N06TzpodI7Sg" ``` ``` curl --location 'http://127.0.0.1:8080/routing/default/profile/pro_rfW0Fv5J0Cct1Bnw2EuS' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_nvORdH8glyzL3AyPwkWcb7GsLD7xi7PU7kHZpvRWlPJNnEz1dQPrCN1swXFFjKEk' \ --data '[ { "connector": "paypal", "merchant_connector_id": "mca_yHGYuTt4V8DGigmrfwYc" } ]' ``` ``` curl --location 'http://127.0.0.1:8080/routing/default/profile/pro_rfW0Fv5J0Cct1Bnw2EuS' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZDA1ODU2ZWEtYWMxMy00MjcwLTg3NDAtNWFjOTk1NGFlZjhhIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ3ODIzMjg1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0Nzk5NzIyMCwib3JnX2lkIjoib3JnX1MyU2t6WXRyMUREcF \ --cookie "login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZDA1ODU2ZWEtYWMxMy00MjcwLTg3NDAtNWFjOTk1NGFlZjhhIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ3ODIzMjg1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0Nzk5NzIyMCwib3JnX2lkIjoib3JnX1MyU2t6WXRyMUREcFJrdHJiam5kIiwicHJvZmlsZV9pZCI6InByb19tNUd5bEw2azE1ejl6QXBjMjhmTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.GlOzvYtOi5FRHp1zwdf_6K6D14gdOx1N06TzpodI7Sg" ``` ``` curl --location 'http://127.0.0.1:8080/routing/default' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_Qe471NOXDpSt0z1VFlmFpFrKNZ9vbxKju4iIyBWaJ0iOXwHpvqFDc26LfhF06Rio' \ --data '[ { "connector": "paypal", "merchant_connector_id": "mca_yHGYuTt4V8DGigmrfwYc" } ]' ``` ``` curl --location 'http://127.0.0.1:8080/routing/default/profile/pro_rfW0Fv5J0Cct1Bnw2EuS' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZDA1ODU2ZWEtYWMxMy00MjcwLTg3NDAtNWFjOTk1NGFlZjhhIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ3ODIzMjg1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0Nzk5NzIyMCwib3JnX2lkIjoib3JnX1MyU2t6WXRyMUREcFJrdHJiam5kIiwicHJvZmlsZV9pZCI6InByb19tNUd5bEw2azE1ejl6QXBjMjhmTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.GlOzvYtOi5FRHp1zwdf_6K6D14gdOx1N06TzpodI7Sg' \ --cookie "login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZDA1ODU2ZWEtYWMxMy00MjcwLTg3NDAtNWFjOTk1NGFlZjhhIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzQ3ODIzMjg1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTc0Nzk5NzIyMCwib3JnX2lkIjoib3JnX1MyU2t6WXRyMUREcFJrdHJiam5kIiwicHJvZmlsZV9pZCI6InByb19tNUd5bEw2azE1ejl6QXBjMjhmTyIsInRlbmFudF9pZCI6InB1YmxpYyJ9.GlOzvYtOi5FRHp1zwdf_6K6D14gdOx1N06TzpodI7Sg" \ --data '[ { "connector": "paypal", "merchant_connector_id": "mca_yHGYuTt4V8DGigmrfwYc" } ]' ``` Response in case of incorrect api-key used - ``` {"error":{"type":"invalid_request","message":"API key not provided or invalid API key used","code":"IR_01"} ``` --> For SR based routing Hit this curl consecutively two time. earlier it would have errored out saying the specific routing is already enabled, but now it will provide back the `routing_dictionary_record`. ``` curl --location --request POST 'http://localhost:8080/account/merchant_1747754221/business_profile/pro_zynmxiTVItHGAekOFaum/dynamic_routing/success_based/toggle?enable=metrics' \ --header 'api-key: dev_es32CnydqbfAKJTxccqSW25IhfJOjkvAAX5raCzR9BdZjdZ28jQy8uoGMNbwv5Kk' ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
344dcd6e43022c3e5479629b57bff255b903d5b5
344dcd6e43022c3e5479629b57bff255b903d5b5
juspay/hyperswitch
juspay__hyperswitch-8077
Bug: [REFACTOR] enable ORF feature for Fiuu connector for FPX payment methods ORF feature for refunds allows skipping mandatory information required for refunds, like - beneficiary's name, bank code and other details. Currently, HS integration for Fiuu sends this field during refund initiation. This needs to be omitted for using the ORF feature.
diff --git a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs index f2b5c982459..343fb99009d 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs @@ -1,6 +1,6 @@ use std::collections::HashMap; -use api_models::payments::{self, AdditionalPaymentData}; +use api_models::payments; use cards::CardNumber; use common_enums::{enums, BankNames, CaptureMethod, Currency}; use common_utils::{ @@ -1073,8 +1073,6 @@ pub struct FiuuRefundRequest { pub signature: Secret<String>, #[serde(rename = "notify_url")] pub notify_url: Option<Url>, - #[serde(skip_serializing_if = "Option::is_none")] - pub bank_code: Option<BankCode>, } #[derive(Debug, Serialize, Display)] pub enum RefundType { @@ -1107,28 +1105,6 @@ impl TryFrom<&FiuuRouterData<&RefundsRouterData<Execute>>> for FiuuRefundRequest Url::parse(&item.router_data.request.get_webhook_url()?) .change_context(errors::ConnectorError::RequestEncodingFailed)?, ), - bank_code: item - .router_data - .request - .additional_payment_method_data - .as_ref() - .and_then(|data| { - if let AdditionalPaymentData::BankRedirect { bank_name, .. } = data { - bank_name.and_then(|name| { - BankCode::try_from(name) - .map_err(|e| { - router_env::logger::error!( - "Error converting bank name to BankCode: {:?}", - e - ); - e - }) - .ok() - }) - } else { - None - } - }), }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs b/crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs index cbc1b5ac2f7..ebdd048c682 100644 --- a/crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs @@ -90,7 +90,7 @@ pub struct EmvThreedsData { browser_accept_header: Option<String>, browser_user_agent: Option<String>, browser_java_enabled: Option<bool>, - browser_java_script_enabled: Option<bool>, + browser_javascript_enabled: Option<bool>, browser_language: Option<String>, browser_color_depth: Option<String>, browser_screen_height: Option<String>, @@ -139,7 +139,7 @@ impl EmvThreedsData { browser_accept_header: None, browser_user_agent: None, browser_java_enabled: None, - browser_java_script_enabled: None, + browser_javascript_enabled: None, browser_language: None, browser_color_depth: None, browser_screen_height: None, @@ -159,7 +159,7 @@ impl EmvThreedsData { self.browser_accept_header = Some(browser_info.get_accept_header()?); self.browser_user_agent = Some(browser_info.get_user_agent()?); self.browser_java_enabled = Some(browser_info.get_java_enabled()?); - self.browser_java_script_enabled = browser_info.get_java_script_enabled().ok(); + self.browser_javascript_enabled = browser_info.get_java_script_enabled().ok(); self.browser_language = Some(browser_info.get_language()?); self.browser_color_depth = Some(browser_info.get_color_depth()?.to_string()); self.browser_screen_height = Some(browser_info.get_screen_height()?.to_string());
2025-05-20T08:40:02Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR contains changes for two connector integrations 1. Fiuu - omit `bank_code` from the refund request for enabling ORF feature from Fiuu's side 2. RedSys - fix the field for sending `browserJavascriptEnabled` field properly ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## Motivation and Context This change fixes the issues for Fiuu and RedSys integrations. Fiuu for refunds flow, and RedSys for 3ds card transactions. ## How did you test it? Can only be tested in production. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
e62f8ee8aba4ba05041b221e9af6f30100fdefcb
e62f8ee8aba4ba05041b221e9af6f30100fdefcb
juspay/hyperswitch
juspay__hyperswitch-8070
Bug: [FEATURE] Add support for multiple retry algorithms in revenue recovery workflow #7 Add support for Process tracker revenue recovery workflow to support multiple retry algorithms. - The retry algorithm is a runtime config
diff --git a/config/config.example.toml b/config/config.example.toml index 6be49be237f..a81d79c52e8 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -1065,6 +1065,10 @@ url = "http://localhost:8080" # Open Router URL [billing_connectors_invoice_sync] billing_connectors_which_requires_invoice_sync_call = "recurly" # List of billing connectors which has invoice sync api call +[revenue_recovery] +monitoring_threshold_in_seconds = 2592000 # 30*24*60*60 secs , threshold for monitoring the retry system +retry_algorithm_type = "cascading" # type of retry algorithm + [clone_connector_allowlist] merchant_ids = "merchant_ids" # Comma-separated list of allowed merchant IDs connector_names = "connector_names" # Comma-separated list of allowed connector names diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index ba92854fd47..31942ae55e9 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -730,5 +730,10 @@ billing_connectors_which_require_payment_sync = "stripebilling, recurly" [billing_connectors_invoice_sync] billing_connectors_which_requires_invoice_sync_call = "recurly" + +[revenue_recovery] +monitoring_threshold_in_seconds = 2592000 +retry_algorithm_type = "cascading" + [authentication_providers] click_to_pay = {connector_list = "adyen, cybersource"} \ No newline at end of file diff --git a/config/deployments/production.toml b/config/deployments/production.toml index efdce9d016c..425196aac9d 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -739,4 +739,9 @@ billing_connectors_which_require_payment_sync = "stripebilling, recurly" billing_connectors_which_requires_invoice_sync_call = "recurly" [authentication_providers] -click_to_pay = {connector_list = "adyen, cybersource"} \ No newline at end of file +click_to_pay = {connector_list = "adyen, cybersource"} + + +[revenue_recovery] +monitoring_threshold_in_seconds = 2592000 +retry_algorithm_type = "cascading" \ No newline at end of file diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 3c3b5f5f403..d405ee30d1a 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -746,4 +746,8 @@ billing_connectors_which_require_payment_sync = "stripebilling, recurly" billing_connectors_which_requires_invoice_sync_call = "recurly" [authentication_providers] -click_to_pay = {connector_list = "adyen, cybersource"} \ No newline at end of file +click_to_pay = {connector_list = "adyen, cybersource"} + +[revenue_recovery] +monitoring_threshold_in_seconds = 2592000 +retry_algorithm_type = "cascading" \ No newline at end of file diff --git a/config/development.toml b/config/development.toml index 2bdb4d6a806..565669f366a 100644 --- a/config/development.toml +++ b/config/development.toml @@ -1161,6 +1161,10 @@ click_to_pay = {connector_list = "adyen, cybersource"} enabled = false url = "http://localhost:8080" +[revenue_recovery] +monitoring_threshold_in_seconds = 2592000 +retry_algorithm_type = "cascading" + [clone_connector_allowlist] merchant_ids = "merchant_123, merchant_234" # Comma-separated list of allowed merchant IDs connector_names = "stripe, adyen" # Comma-separated list of allowed connector names diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 2f8ff2b2ab0..0da38ee1588 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -1051,6 +1051,10 @@ enabled = true [authentication_providers] click_to_pay = {connector_list = "adyen, cybersource"} +[revenue_recovery] +monitoring_threshold_in_seconds = 2592000 # threshold for monitoring the retry system +retry_algorithm_type = "cascading" # type of retry algorithm + [clone_connector_allowlist] merchant_ids = "merchant_123, merchant_234" # Comma-separated list of allowed merchant IDs connector_names = "stripe, adyen" # Comma-separated list of allowed connector names diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 226471dcc74..a39c7cf9a26 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -216,6 +216,7 @@ pub enum CardDiscovery { Clone, Copy, Debug, + Default, Hash, Eq, PartialEq, @@ -230,6 +231,7 @@ pub enum CardDiscovery { #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RevenueRecoveryAlgorithmType { + #[default] Monitoring, Smart, Cascading, diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs index a7c606fb94b..ec2207946b2 100644 --- a/crates/diesel_models/src/business_profile.rs +++ b/crates/diesel_models/src/business_profile.rs @@ -5,6 +5,7 @@ use common_types::primitive_wrappers; use common_utils::{encryption::Encryption, pii}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::Secret; +use time::Duration; #[cfg(feature = "v1")] use crate::schema::business_profile; @@ -796,4 +797,12 @@ pub struct RevenueRecoveryAlgorithmData { pub monitoring_configured_timestamp: time::PrimitiveDateTime, } +impl RevenueRecoveryAlgorithmData { + pub fn has_exceeded_monitoring_threshold(&self, monitoring_threshold_in_seconds: i64) -> bool { + let total_threshold_time = self.monitoring_configured_timestamp + + Duration::seconds(monitoring_threshold_in_seconds); + common_utils::date_time::now() >= total_threshold_time + } +} + common_utils::impl_to_sql_from_sql_json!(RevenueRecoveryAlgorithmData); diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index 49800dd3c89..e3f1b6abce2 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -536,6 +536,8 @@ pub(crate) async fn fetch_raw_secrets( platform: conf.platform, authentication_providers: conf.authentication_providers, open_router: conf.open_router, + #[cfg(feature = "v2")] + revenue_recovery: conf.revenue_recovery, debit_routing_config: conf.debit_routing_config, clone_connector_allowlist: conf.clone_connector_allowlist, } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 34270971efb..fb40451888f 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -43,6 +43,8 @@ use storage_impl::config::QueueStrategy; #[cfg(feature = "olap")] use crate::analytics::{AnalyticsConfig, AnalyticsProvider}; +#[cfg(feature = "v2")] +use crate::types::storage::revenue_recovery; use crate::{ configs, core::errors::{ApplicationError, ApplicationResult}, @@ -51,7 +53,6 @@ use crate::{ routes::app, AppState, }; - pub const REQUIRED_FIELDS_CONFIG_FILE: &str = "payment_required_fields_v2.toml"; #[derive(clap::Parser, Default)] @@ -154,6 +155,8 @@ pub struct Settings<S: SecretState> { pub platform: Platform, pub authentication_providers: AuthenticationProviders, pub open_router: OpenRouter, + #[cfg(feature = "v2")] + pub revenue_recovery: revenue_recovery::RevenueRecoverySettings, pub clone_connector_allowlist: Option<CloneConnectorAllowlistConfig>, } diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 14a6900693e..a58570e158c 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -2994,14 +2994,15 @@ pub async fn create_connector( #[cfg(feature = "v2")] if req.connector_type == common_enums::ConnectorType::BillingProcessor { - update_revenue_recovery_algorithm_under_profile( - business_profile.clone(), - store, - key_manager_state, - merchant_context.get_merchant_key_store(), - common_enums::RevenueRecoveryAlgorithmType::Monitoring, - ) - .await?; + let profile_wrapper = ProfileWrapper::new(business_profile.clone()); + profile_wrapper + .update_revenue_recovery_algorithm_under_profile( + store, + key_manager_state, + merchant_context.get_merchant_key_store(), + common_enums::RevenueRecoveryAlgorithmType::Monitoring, + ) + .await?; } core_utils::validate_profile_id_from_auth_layer(auth_profile_id, &business_profile)?; @@ -4702,33 +4703,35 @@ impl ProfileWrapper { .attach_printable("Failed to update routing algorithm ref in business profile")?; Ok(()) } -} -#[cfg(feature = "v2")] -pub async fn update_revenue_recovery_algorithm_under_profile( - profile: domain::Profile, - db: &dyn StorageInterface, - key_manager_state: &KeyManagerState, - merchant_key_store: &domain::MerchantKeyStore, - revenue_recovery_retry_algorithm_type: common_enums::RevenueRecoveryAlgorithmType, -) -> RouterResult<()> { - let recovery_algorithm_data = diesel_models::business_profile::RevenueRecoveryAlgorithmData { - monitoring_configured_timestamp: date_time::now(), - }; - let profile_update = domain::ProfileUpdate::RevenueRecoveryAlgorithmUpdate { - revenue_recovery_retry_algorithm_type, - revenue_recovery_retry_algorithm_data: Some(recovery_algorithm_data), - }; + pub async fn update_revenue_recovery_algorithm_under_profile( + self, + db: &dyn StorageInterface, + key_manager_state: &KeyManagerState, + merchant_key_store: &domain::MerchantKeyStore, + revenue_recovery_retry_algorithm_type: common_enums::RevenueRecoveryAlgorithmType, + ) -> RouterResult<()> { + let recovery_algorithm_data = + diesel_models::business_profile::RevenueRecoveryAlgorithmData { + monitoring_configured_timestamp: date_time::now(), + }; + let profile_update = domain::ProfileUpdate::RevenueRecoveryAlgorithmUpdate { + revenue_recovery_retry_algorithm_type, + revenue_recovery_retry_algorithm_data: Some(recovery_algorithm_data), + }; - db.update_profile_by_profile_id( - key_manager_state, - merchant_key_store, - profile, - profile_update, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to update revenue recovery retry algorithm in business profile")?; - Ok(()) + db.update_profile_by_profile_id( + key_manager_state, + merchant_key_store, + self.profile, + profile_update, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "Failed to update revenue recovery retry algorithm in business profile", + )?; + Ok(()) + } } pub async fn extended_card_info_toggle( diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index 0a50ca42382..31a2b11a04d 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -483,6 +483,10 @@ pub enum RevenueRecoveryError { RetryCountFetchFailed, #[error("Failed to get the billing threshold retry count")] BillingThresholdRetryCountFetchFailed, + #[error("Failed to get the retry algorithm type")] + RetryAlgorithmTypeNotFound, + #[error("Failed to update the retry algorithm type")] + RetryAlgorithmUpdationFailed, #[error("Failed to create the revenue recovery attempt data")] RevenueRecoveryAttemptDataCreateFailed, } diff --git a/crates/router/src/core/files.rs b/crates/router/src/core/files.rs index 12b87fd1e67..d27cfaa9a07 100644 --- a/crates/router/src/core/files.rs +++ b/crates/router/src/core/files.rs @@ -31,7 +31,7 @@ pub async fn files_create_core( .get_string_repr(), file_id ); - let file_new = diesel_models::file::FileMetadataNew { + let file_new: diesel_models::FileMetadataNew = diesel_models::file::FileMetadataNew { file_id: file_id.clone(), merchant_id: merchant_context.get_merchant_account().get_id().clone(), file_name: create_file_request.file_name.clone(), diff --git a/crates/router/src/core/revenue_recovery.rs b/crates/router/src/core/revenue_recovery.rs index 31831bddf0c..d6091d8aa1a 100644 --- a/crates/router/src/core/revenue_recovery.rs +++ b/crates/router/src/core/revenue_recovery.rs @@ -7,7 +7,7 @@ use common_utils::{ ext_traits::{OptionExt, ValueExt}, id_type, }; -use diesel_models::process_tracker::business_status; +use diesel_models::{enums as diesel_enum, process_tracker::business_status}; use error_stack::{self, ResultExt}; use hyperswitch_domain_models::{payments::PaymentIntent, ApiModelToDieselModelConvertor}; use scheduler::errors as sch_errors; @@ -135,6 +135,7 @@ pub async fn perform_execute_payment( revenue_recovery_payment_data.profile.get_id().clone(), attempt_id.clone(), storage::ProcessTrackerRunner::PassiveRecoveryWorkflow, + tracking_data.revenue_recovery_retry, ) .await?; @@ -196,6 +197,7 @@ pub async fn perform_execute_payment( Ok(()) } +#[allow(clippy::too_many_arguments)] async fn insert_psync_pcr_task_to_pt( billing_mca_id: id_type::MerchantConnectorAccountId, db: &dyn StorageInterface, @@ -204,6 +206,7 @@ async fn insert_psync_pcr_task_to_pt( profile_id: id_type::ProfileId, payment_attempt_id: id_type::GlobalAttemptId, runner: storage::ProcessTrackerRunner, + revenue_recovery_retry: diesel_enum::RevenueRecoveryAlgorithmType, ) -> RouterResult<storage::ProcessTracker> { let task = PSYNC_WORKFLOW; let process_tracker_id = payment_attempt_id.get_psync_revenue_recovery_id(task, runner); @@ -214,6 +217,7 @@ async fn insert_psync_pcr_task_to_pt( merchant_id, profile_id, payment_attempt_id, + revenue_recovery_retry, }; let tag = ["REVENUE_RECOVERY"]; let process_tracker_entry = storage::ProcessTrackerNew::new( diff --git a/crates/router/src/core/revenue_recovery/types.rs b/crates/router/src/core/revenue_recovery/types.rs index e551340e102..e8adf91e07c 100644 --- a/crates/router/src/core/revenue_recovery/types.rs +++ b/crates/router/src/core/revenue_recovery/types.rs @@ -310,6 +310,7 @@ impl Action { db, merchant_id, process.clone(), + revenue_recovery_payment_data, &payment_data.payment_attempt, ) .await @@ -354,6 +355,7 @@ impl Action { revenue_recovery_payment_data.profile.get_id().to_owned(), payment_attempt.id.clone(), storage::ProcessTrackerRunner::PassiveRecoveryWorkflow, + revenue_recovery_payment_data.retry_algorithm, ) .await .change_context(errors::RecoveryError::ProcessTrackerFailure) @@ -478,13 +480,17 @@ impl Action { pub async fn payment_sync_call( state: &SessionState, - pcr_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, + revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, global_payment_id: &id_type::GlobalPaymentId, process: &storage::ProcessTracker, payment_attempt: payment_attempt::PaymentAttempt, ) -> RecoveryResult<Self> { - let response = - revenue_recovery_core::api::call_psync_api(state, global_payment_id, pcr_data).await; + let response = revenue_recovery_core::api::call_psync_api( + state, + global_payment_id, + revenue_recovery_payment_data, + ) + .await; let db = &*state.store; match response { Ok(_payment_data) => match payment_attempt.status.foreign_into() { @@ -494,8 +500,9 @@ impl Action { RevenueRecoveryPaymentsAttemptStatus::Failed => { Self::decide_retry_failure_action( db, - pcr_data.merchant_account.get_id(), + revenue_recovery_payment_data.merchant_account.get_id(), process.clone(), + revenue_recovery_payment_data, &payment_attempt, ) .await @@ -688,10 +695,14 @@ impl Action { db: &dyn StorageInterface, merchant_id: &id_type::MerchantId, pt: storage::ProcessTracker, + revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, payment_attempt: &payment_attempt::PaymentAttempt, ) -> RecoveryResult<Self> { - let schedule_time = - get_schedule_time_to_retry_mit_payments(db, merchant_id, pt.retry_count + 1).await; + let next_retry_count = pt.retry_count + 1; + let schedule_time = revenue_recovery_payment_data + .get_schedule_time_based_on_retry_type(db, merchant_id, next_retry_count) + .await; + match schedule_time { Some(schedule_time) => Ok(Self::RetryPayment(schedule_time)), diff --git a/crates/router/src/core/webhooks/recovery_incoming.rs b/crates/router/src/core/webhooks/recovery_incoming.rs index 79994a48e85..87c1a79aa12 100644 --- a/crates/router/src/core/webhooks/recovery_incoming.rs +++ b/crates/router/src/core/webhooks/recovery_incoming.rs @@ -1,6 +1,6 @@ use std::{marker::PhantomData, str::FromStr}; -use api_models::{payments as api_payments, webhooks}; +use api_models::{enums as api_enums, payments as api_payments, webhooks}; use common_utils::{ ext_traits::{AsyncExt, ValueExt}, id_type, @@ -17,6 +17,7 @@ use router_env::{instrument, tracing}; use crate::{ core::{ + admin, errors::{self, CustomResult}, payments::{self, helpers}, }, @@ -54,7 +55,7 @@ pub async fn recovery_incoming_webhook_flow( )) })?; - let connector = api_models::enums::Connector::from_str(connector_name) + let connector = api_enums::Connector::from_str(connector_name) .change_context(errors::RevenueRecoveryError::InvoiceWebhookProcessingFailed) .attach_printable_lazy(|| format!("unable to parse connector name {connector_name:?}"))?; @@ -155,19 +156,37 @@ pub async fn recovery_incoming_webhook_flow( match action { revenue_recovery::RecoveryAction::CancelInvoice => todo!(), revenue_recovery::RecoveryAction::ScheduleFailedPayment => { - handle_schedule_failed_payment( - &billing_connector_account, - intent_retry_count, - mca_retry_threshold, - &state, - &merchant_context, - &( - recovery_attempt_from_payment_attempt, - recovery_intent_from_payment_attempt, - ), - &business_profile, - ) - .await + let recovery_algorithm_type = business_profile + .revenue_recovery_retry_algorithm_type + .ok_or(report!( + errors::RevenueRecoveryError::RetryAlgorithmTypeNotFound + ))?; + match recovery_algorithm_type { + api_enums::RevenueRecoveryAlgorithmType::Monitoring => { + handle_monitoring_threshold( + &state, + &business_profile, + merchant_context.get_merchant_key_store(), + ) + .await + } + revenue_recovery_retry_type => { + handle_schedule_failed_payment( + &billing_connector_account, + intent_retry_count, + mca_retry_threshold, + &state, + &merchant_context, + &( + recovery_attempt_from_payment_attempt, + recovery_intent_from_payment_attempt, + ), + &business_profile, + revenue_recovery_retry_type, + ) + .await + } + } } revenue_recovery::RecoveryAction::SuccessPaymentExternal => { // Need to add recovery stop flow for this scenario @@ -195,6 +214,38 @@ pub async fn recovery_incoming_webhook_flow( } } +async fn handle_monitoring_threshold( + state: &SessionState, + business_profile: &domain::Profile, + key_store: &domain::MerchantKeyStore, +) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> { + let db = &*state.store; + let key_manager_state = &(state).into(); + let monitoring_threshold_config = state.conf.revenue_recovery.monitoring_threshold_in_seconds; + let retry_algorithm_type = state.conf.revenue_recovery.retry_algorithm_type; + let revenue_recovery_retry_algorithm = business_profile + .revenue_recovery_retry_algorithm_data + .clone() + .ok_or(report!( + errors::RevenueRecoveryError::RetryAlgorithmTypeNotFound + ))?; + if revenue_recovery_retry_algorithm + .has_exceeded_monitoring_threshold(monitoring_threshold_config) + { + let profile_wrapper = admin::ProfileWrapper::new(business_profile.clone()); + profile_wrapper + .update_revenue_recovery_algorithm_under_profile( + db, + key_manager_state, + key_store, + retry_algorithm_type, + ) + .await + .change_context(errors::RevenueRecoveryError::RetryAlgorithmUpdationFailed)?; + } + Ok(webhooks::WebhookResponseTracker::NoEffect) +} +#[allow(clippy::too_many_arguments)] async fn handle_schedule_failed_payment( billing_connector_account: &domain::MerchantConnectorAccount, intent_retry_count: u16, @@ -206,6 +257,7 @@ async fn handle_schedule_failed_payment( revenue_recovery::RecoveryPaymentIntent, ), business_profile: &domain::Profile, + revenue_recovery_retry: api_enums::RevenueRecoveryAlgorithmType, ) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> { let (recovery_attempt_from_payment_attempt, recovery_intent_from_payment_attempt) = payment_attempt_with_recovery_intent; @@ -230,6 +282,7 @@ async fn handle_schedule_failed_payment( .as_ref() .map(|attempt| attempt.attempt_id.clone()), storage::ProcessTrackerRunner::PassiveRecoveryWorkflow, + revenue_recovery_retry, ) .await }) @@ -697,6 +750,7 @@ impl RevenueRecoveryAttempt { intent_retry_count: u16, payment_attempt_id: Option<id_type::GlobalAttemptId>, runner: storage::ProcessTrackerRunner, + revenue_recovery_retry: api_enums::RevenueRecoveryAlgorithmType, ) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> { let task = "EXECUTE_WORKFLOW"; @@ -731,6 +785,7 @@ impl RevenueRecoveryAttempt { merchant_id, profile_id, payment_attempt_id, + revenue_recovery_retry, }; let tag = ["PCR"]; diff --git a/crates/router/src/types/storage/revenue_recovery.rs b/crates/router/src/types/storage/revenue_recovery.rs index 73248a40f7f..c672c5ecffb 100644 --- a/crates/router/src/types/storage/revenue_recovery.rs +++ b/crates/router/src/types/storage/revenue_recovery.rs @@ -1,17 +1,21 @@ use std::fmt::Debug; +use common_enums::enums; use common_utils::id_type; use hyperswitch_domain_models::{ business_profile, merchant_account, merchant_connector_account, merchant_key_store, }; +use router_env::logger; -#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)] +use crate::{db::StorageInterface, workflows::revenue_recovery}; +#[derive(serde::Serialize, serde::Deserialize, Debug)] pub struct RevenueRecoveryWorkflowTrackingData { pub merchant_id: id_type::MerchantId, pub profile_id: id_type::ProfileId, pub global_payment_id: id_type::GlobalPaymentId, pub payment_attempt_id: id_type::GlobalAttemptId, pub billing_mca_id: id_type::MerchantConnectorAccountId, + pub revenue_recovery_retry: enums::RevenueRecoveryAlgorithmType, } #[derive(Debug, Clone)] @@ -20,4 +24,37 @@ pub struct RevenueRecoveryPaymentData { pub profile: business_profile::Profile, pub key_store: merchant_key_store::MerchantKeyStore, pub billing_mca: merchant_connector_account::MerchantConnectorAccount, + pub retry_algorithm: enums::RevenueRecoveryAlgorithmType, +} +impl RevenueRecoveryPaymentData { + pub async fn get_schedule_time_based_on_retry_type( + &self, + db: &dyn StorageInterface, + merchant_id: &id_type::MerchantId, + retry_count: i32, + ) -> Option<time::PrimitiveDateTime> { + match self.retry_algorithm { + enums::RevenueRecoveryAlgorithmType::Monitoring => { + logger::error!("Monitoring type found for Revenue Recovery retry payment"); + None + } + enums::RevenueRecoveryAlgorithmType::Cascading => { + revenue_recovery::get_schedule_time_to_retry_mit_payments( + db, + merchant_id, + retry_count, + ) + .await + } + enums::RevenueRecoveryAlgorithmType::Smart => { + // TODO: Integrate the smart retry call to return back a schedule time + None + } + } + } +} +#[derive(Debug, serde::Deserialize, Clone, Default)] +pub struct RevenueRecoverySettings { + pub monitoring_threshold_in_seconds: i64, + pub retry_algorithm_type: enums::RevenueRecoveryAlgorithmType, } diff --git a/crates/router/src/workflows/revenue_recovery.rs b/crates/router/src/workflows/revenue_recovery.rs index ad10b1c8268..af27d6f45d1 100644 --- a/crates/router/src/workflows/revenue_recovery.rs +++ b/crates/router/src/workflows/revenue_recovery.rs @@ -20,8 +20,8 @@ use storage_impl::errors as storage_errors; #[cfg(feature = "v2")] use crate::{ core::{ - admin, payments, - revenue_recovery::{self as pcr, types}, + payments, + revenue_recovery::{self as pcr}, }, db::StorageInterface, errors::StorageError, @@ -155,6 +155,7 @@ pub(crate) async fn extract_data_and_perform_action( profile, key_store, billing_mca, + retry_algorithm: tracking_data.revenue_recovery_retry, }; Ok(pcr_payment_data) }
2025-04-28T09:12:37Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description - This PR adds support for updating the retry Algorithm from Monitoring to Smart , once the threshold is reached - It also adds support in the process tracker workflow for revenue recovery , to consume schedule time for retry based on different retry algorithms ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? - Create a MA and a Billing connector - The retry_Algorithm type in business profile will be switched to Monitoring - Once the time in the revenue_recovery_config is surpassed , the `retry_Algorithm type` field in business profile will be updated to Cascading ![Screenshot 2025-05-15 at 7 45 53 PM](https://github.com/user-attachments/assets/24d3349f-9177-46f6-ba55-8e284e641458) ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
344dcd6e43022c3e5479629b57bff255b903d5b5
344dcd6e43022c3e5479629b57bff255b903d5b5
juspay/hyperswitch
juspay__hyperswitch-8078
Bug: [BUG] failing 3DS transactions for Redsys ### Bug Description Redsys 3ds card transactions are failing in production with following error ``` Error code - SIS0653 Error message - Operacion de autenticacion rechazada, browserJavascriptEnabled no indicado ``` ### Expected Behavior Redsys 3ds card transactions should complete 3DS card transactions. ### Actual Behavior Payment transactions failing. ### Context For The Bug This is happening as one of the fields `browserJavascriptEnabled` is not being sent in the right manner. Fix - update the request structure ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs index f2b5c982459..343fb99009d 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs @@ -1,6 +1,6 @@ use std::collections::HashMap; -use api_models::payments::{self, AdditionalPaymentData}; +use api_models::payments; use cards::CardNumber; use common_enums::{enums, BankNames, CaptureMethod, Currency}; use common_utils::{ @@ -1073,8 +1073,6 @@ pub struct FiuuRefundRequest { pub signature: Secret<String>, #[serde(rename = "notify_url")] pub notify_url: Option<Url>, - #[serde(skip_serializing_if = "Option::is_none")] - pub bank_code: Option<BankCode>, } #[derive(Debug, Serialize, Display)] pub enum RefundType { @@ -1107,28 +1105,6 @@ impl TryFrom<&FiuuRouterData<&RefundsRouterData<Execute>>> for FiuuRefundRequest Url::parse(&item.router_data.request.get_webhook_url()?) .change_context(errors::ConnectorError::RequestEncodingFailed)?, ), - bank_code: item - .router_data - .request - .additional_payment_method_data - .as_ref() - .and_then(|data| { - if let AdditionalPaymentData::BankRedirect { bank_name, .. } = data { - bank_name.and_then(|name| { - BankCode::try_from(name) - .map_err(|e| { - router_env::logger::error!( - "Error converting bank name to BankCode: {:?}", - e - ); - e - }) - .ok() - }) - } else { - None - } - }), }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs b/crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs index cbc1b5ac2f7..ebdd048c682 100644 --- a/crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs @@ -90,7 +90,7 @@ pub struct EmvThreedsData { browser_accept_header: Option<String>, browser_user_agent: Option<String>, browser_java_enabled: Option<bool>, - browser_java_script_enabled: Option<bool>, + browser_javascript_enabled: Option<bool>, browser_language: Option<String>, browser_color_depth: Option<String>, browser_screen_height: Option<String>, @@ -139,7 +139,7 @@ impl EmvThreedsData { browser_accept_header: None, browser_user_agent: None, browser_java_enabled: None, - browser_java_script_enabled: None, + browser_javascript_enabled: None, browser_language: None, browser_color_depth: None, browser_screen_height: None, @@ -159,7 +159,7 @@ impl EmvThreedsData { self.browser_accept_header = Some(browser_info.get_accept_header()?); self.browser_user_agent = Some(browser_info.get_user_agent()?); self.browser_java_enabled = Some(browser_info.get_java_enabled()?); - self.browser_java_script_enabled = browser_info.get_java_script_enabled().ok(); + self.browser_javascript_enabled = browser_info.get_java_script_enabled().ok(); self.browser_language = Some(browser_info.get_language()?); self.browser_color_depth = Some(browser_info.get_color_depth()?.to_string()); self.browser_screen_height = Some(browser_info.get_screen_height()?.to_string());
2025-05-20T08:40:02Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR contains changes for two connector integrations 1. Fiuu - omit `bank_code` from the refund request for enabling ORF feature from Fiuu's side 2. RedSys - fix the field for sending `browserJavascriptEnabled` field properly ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## Motivation and Context This change fixes the issues for Fiuu and RedSys integrations. Fiuu for refunds flow, and RedSys for 3ds card transactions. ## How did you test it? Can only be tested in production. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
e62f8ee8aba4ba05041b221e9af6f30100fdefcb
e62f8ee8aba4ba05041b221e9af6f30100fdefcb
juspay/hyperswitch
juspay__hyperswitch-8067
Bug: [FEATURE] [Barclaycard] Implement Card Flows ### Feature Description Implement card flows for Barclaycard ### Possible Implementation Implement card flows for Barclaycard ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 00e3e7bc4ff..08b4860a5f4 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -8016,6 +8016,7 @@ "bambora", "bamboraapac", "bankofamerica", + "barclaycard", "billwerk", "bitpay", "bluesnap", @@ -21588,6 +21589,7 @@ "archipel", "authorizedotnet", "bankofamerica", + "barclaycard", "billwerk", "bitpay", "bambora", diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 3ab7d8d45c0..48c3adf8635 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -9940,6 +9940,7 @@ "bambora", "bamboraapac", "bankofamerica", + "barclaycard", "billwerk", "bitpay", "bluesnap", @@ -25968,6 +25969,7 @@ "archipel", "authorizedotnet", "bankofamerica", + "barclaycard", "billwerk", "bitpay", "bambora", diff --git a/config/config.example.toml b/config/config.example.toml index 52ee69bec10..62bb8e816f9 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -188,7 +188,7 @@ authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api" bambora.base_url = "https://api.na.bambora.com" bamboraapac.base_url = "https://demo.ippayments.com.au/interface/api" bankofamerica.base_url = "https://apitest.merchant-services.bankofamerica.com/" -barclaycard.base_url = "https://api.smartpayfuse-test.barclaycard/pts/v2/" +barclaycard.base_url = "https://api.smartpayfuse-test.barclaycard/" billwerk.base_url = "https://api.reepay.com/" billwerk.secondary_base_url = "https://card.reepay.com/" bitpay.base_url = "https://test.bitpay.com" diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 734fa08c88f..aaa79b633b5 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -32,7 +32,7 @@ authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api" bambora.base_url = "https://api.na.bambora.com" bamboraapac.base_url = "https://demo.ippayments.com.au/interface/api" bankofamerica.base_url = "https://apitest.merchant-services.bankofamerica.com/" -barclaycard.base_url = "https://api.smartpayfuse-test.barclaycard/pts/v2/" +barclaycard.base_url = "https://api.smartpayfuse-test.barclaycard/" billwerk.base_url = "https://api.reepay.com/" billwerk.secondary_base_url = "https://card.reepay.com/" bitpay.base_url = "https://test.bitpay.com" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 16e114a7543..1dfa26c4457 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -36,7 +36,7 @@ authorizedotnet.base_url = "https://api.authorize.net/xml/v1/request.api" bambora.base_url = "https://api.na.bambora.com" bamboraapac.base_url = "https://www.bambora.co.nz/interface/api/dts.asmx" bankofamerica.base_url = "https://api.merchant-services.bankofamerica.com/" -barclaycard.base_url = "https://api.smartpayfuse-test.barclaycard/pts/v2/" +barclaycard.base_url = "https://api.smartpayfuse-test.barclaycard/" billwerk.base_url = "https://api.reepay.com/" billwerk.secondary_base_url = "https://card.reepay.com/" bitpay.base_url = "https://bitpay.com" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index ec6572fd71a..9b77ccbac01 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -36,7 +36,7 @@ authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api" bambora.base_url = "https://api.na.bambora.com" bamboraapac.base_url = "https://demo.ippayments.com.au/interface/api" bankofamerica.base_url = "https://apitest.merchant-services.bankofamerica.com/" -barclaycard.base_url = "https://api.smartpayfuse-test.barclaycard/pts/v2/" +barclaycard.base_url = "https://api.smartpayfuse-test.barclaycard/" billwerk.base_url = "https://api.reepay.com/" billwerk.secondary_base_url = "https://card.reepay.com/" bitpay.base_url = "https://test.bitpay.com" diff --git a/config/development.toml b/config/development.toml index 7deb3b46992..912173c9d8b 100644 --- a/config/development.toml +++ b/config/development.toml @@ -239,7 +239,7 @@ authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api" bambora.base_url = "https://api.na.bambora.com" bamboraapac.base_url = "https://demo.ippayments.com.au/interface/api" bankofamerica.base_url = "https://apitest.merchant-services.bankofamerica.com/" -barclaycard.base_url = "https://api.smartpayfuse-test.barclaycard/pts/v2/" +barclaycard.base_url = "https://api.smartpayfuse-test.barclaycard/" billwerk.base_url = "https://api.reepay.com/" billwerk.secondary_base_url = "https://card.reepay.com/" bitpay.base_url = "https://test.bitpay.com" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 855bed5ebd0..1eb4524686a 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -119,7 +119,7 @@ authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api" bambora.base_url = "https://api.na.bambora.com" bamboraapac.base_url = "https://demo.ippayments.com.au/interface/api" bankofamerica.base_url = "https://apitest.merchant-services.bankofamerica.com/" -barclaycard.base_url = "https://api.smartpayfuse-test.barclaycard/pts/v2/" +barclaycard.base_url = "https://api.smartpayfuse-test.barclaycard/" billwerk.base_url = "https://api.reepay.com/" billwerk.secondary_base_url = "https://card.reepay.com/" bitpay.base_url = "https://test.bitpay.com" diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index 0b3d03e6a91..e5db9ec451f 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -65,7 +65,7 @@ pub enum RoutableConnectors { Archipel, Authorizedotnet, Bankofamerica, - // Barclaycard, + Barclaycard, Billwerk, Bitpay, Bambora, @@ -219,7 +219,7 @@ pub enum Connector { Bambora, Bamboraapac, Bankofamerica, - // Barclaycard, + Barclaycard, Billwerk, Bitpay, Bluesnap, @@ -393,7 +393,7 @@ impl Connector { | Self::Bambora | Self::Bamboraapac | Self::Bankofamerica - // | Self::Barclaycard + | Self::Barclaycard | Self::Billwerk | Self::Bitpay | Self::Bluesnap @@ -546,7 +546,7 @@ impl From<RoutableConnectors> for Connector { RoutableConnectors::Archipel => Self::Archipel, RoutableConnectors::Authorizedotnet => Self::Authorizedotnet, RoutableConnectors::Bankofamerica => Self::Bankofamerica, - // RoutableConnectors::Barclaycard => Self::Barclaycard, + RoutableConnectors::Barclaycard => Self::Barclaycard, RoutableConnectors::Billwerk => Self::Billwerk, RoutableConnectors::Bitpay => Self::Bitpay, RoutableConnectors::Bambora => Self::Bambora, @@ -660,7 +660,7 @@ impl TryFrom<Connector> for RoutableConnectors { Connector::Archipel => Ok(Self::Archipel), Connector::Authorizedotnet => Ok(Self::Authorizedotnet), Connector::Bankofamerica => Ok(Self::Bankofamerica), - // Connector::Barclaycard => Ok(Self::Barclaycard), + Connector::Barclaycard => Ok(Self::Barclaycard), Connector::Billwerk => Ok(Self::Billwerk), Connector::Bitpay => Ok(Self::Bitpay), Connector::Bambora => Ok(Self::Bambora), diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index 45a26489113..4652b0206e1 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -358,6 +358,7 @@ impl ConnectorConfig { Connector::Authorizedotnet => Ok(connector_data.authorizedotnet), Connector::Bamboraapac => Ok(connector_data.bamboraapac), Connector::Bankofamerica => Ok(connector_data.bankofamerica), + Connector::Barclaycard => Ok(connector_data.barclaycard), Connector::Billwerk => Ok(connector_data.billwerk), Connector::Bitpay => Ok(connector_data.bitpay), Connector::Bluesnap => Ok(connector_data.bluesnap), diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 3269efbe596..b4d343356b4 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -949,6 +949,51 @@ required=true type="MultiSelect" options=["visa","masterCard","amex","discover"] +[barclaycard] +[[barclaycard.credit]] + payment_method_type = "Mastercard" +[[barclaycard.credit]] + payment_method_type = "Visa" +[[barclaycard.credit]] + payment_method_type = "AmericanExpress" +[[barclaycard.credit]] + payment_method_type = "JCB" +[[barclaycard.credit]] + payment_method_type = "Discover" +[[barclaycard.credit]] + payment_method_type = "Maestro" +[[barclaycard.credit]] + payment_method_type = "Interac" +[[barclaycard.credit]] + payment_method_type = "DinersClub" +[[barclaycard.credit]] + payment_method_type = "CartesBancaires" +[[barclaycard.credit]] + payment_method_type = "UnionPay" +[[barclaycard.debit]] + payment_method_type = "Mastercard" +[[barclaycard.debit]] + payment_method_type = "Visa" +[[barclaycard.debit]] + payment_method_type = "AmericanExpress" +[[barclaycard.debit]] + payment_method_type = "JCB" +[[barclaycard.debit]] + payment_method_type = "Discover" +[[barclaycard.debit]] + payment_method_type = "Maestro" +[[barclaycard.debit]] + payment_method_type = "Interac" +[[barclaycard.debit]] + payment_method_type = "DinersClub" +[[barclaycard.debit]] + payment_method_type = "CartesBancaires" +[[barclaycard.debit]] + payment_method_type = "UnionPay" +[barclaycard.connector_auth.SignatureKey] +api_key="Key" +key1="Merchant ID" +api_secret="Shared Secret" [bitpay] [[bitpay.crypto]] diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index e467ee970d3..e1f8b6c31d0 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -947,6 +947,51 @@ required=true type="MultiSelect" options=["PAN_ONLY", "CRYPTOGRAM_3DS"] +[barclaycard] +[[barclaycard.credit]] + payment_method_type = "Mastercard" +[[barclaycard.credit]] + payment_method_type = "Visa" +[[barclaycard.credit]] + payment_method_type = "AmericanExpress" +[[barclaycard.credit]] + payment_method_type = "JCB" +[[barclaycard.credit]] + payment_method_type = "Discover" +[[barclaycard.credit]] + payment_method_type = "Maestro" +[[barclaycard.credit]] + payment_method_type = "Interac" +[[barclaycard.credit]] + payment_method_type = "DinersClub" +[[barclaycard.credit]] + payment_method_type = "CartesBancaires" +[[barclaycard.credit]] + payment_method_type = "UnionPay" +[[barclaycard.debit]] + payment_method_type = "Mastercard" +[[barclaycard.debit]] + payment_method_type = "Visa" +[[barclaycard.debit]] + payment_method_type = "AmericanExpress" +[[barclaycard.debit]] + payment_method_type = "JCB" +[[barclaycard.debit]] + payment_method_type = "Discover" +[[barclaycard.debit]] + payment_method_type = "Maestro" +[[barclaycard.debit]] + payment_method_type = "Interac" +[[barclaycard.debit]] + payment_method_type = "DinersClub" +[[barclaycard.debit]] + payment_method_type = "CartesBancaires" +[[barclaycard.debit]] + payment_method_type = "UnionPay" +[barclaycard.connector_auth.SignatureKey] +api_key="Key" +key1="Merchant ID" +api_secret="Shared Secret" [cashtocode] [[cashtocode.reward]] diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index e8cfdae9e69..2778ff1e82c 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -949,6 +949,51 @@ required=true type="MultiSelect" options=["visa","masterCard","amex","discover"] +[barclaycard] +[[barclaycard.credit]] + payment_method_type = "Mastercard" +[[barclaycard.credit]] + payment_method_type = "Visa" +[[barclaycard.credit]] + payment_method_type = "AmericanExpress" +[[barclaycard.credit]] + payment_method_type = "JCB" +[[barclaycard.credit]] + payment_method_type = "Discover" +[[barclaycard.credit]] + payment_method_type = "Maestro" +[[barclaycard.credit]] + payment_method_type = "Interac" +[[barclaycard.credit]] + payment_method_type = "DinersClub" +[[barclaycard.credit]] + payment_method_type = "CartesBancaires" +[[barclaycard.credit]] + payment_method_type = "UnionPay" +[[barclaycard.debit]] + payment_method_type = "Mastercard" +[[barclaycard.debit]] + payment_method_type = "Visa" +[[barclaycard.debit]] + payment_method_type = "AmericanExpress" +[[barclaycard.debit]] + payment_method_type = "JCB" +[[barclaycard.debit]] + payment_method_type = "Discover" +[[barclaycard.debit]] + payment_method_type = "Maestro" +[[barclaycard.debit]] + payment_method_type = "Interac" +[[barclaycard.debit]] + payment_method_type = "DinersClub" +[[barclaycard.debit]] + payment_method_type = "CartesBancaires" +[[barclaycard.debit]] + payment_method_type = "UnionPay" +[barclaycard.connector_auth.SignatureKey] +api_key="Key" +key1="Merchant ID" +api_secret="Shared Secret" [bitpay] [[bitpay.crypto]] diff --git a/crates/hyperswitch_connectors/src/connectors/barclaycard.rs b/crates/hyperswitch_connectors/src/connectors/barclaycard.rs index 9397d063ff6..950b985fa68 100644 --- a/crates/hyperswitch_connectors/src/connectors/barclaycard.rs +++ b/crates/hyperswitch_connectors/src/connectors/barclaycard.rs @@ -1,10 +1,13 @@ pub mod transformers; +use std::sync::LazyLock; +use base64::Engine; +use common_enums::enums; use common_utils::{ + consts, errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, - types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ @@ -19,10 +22,13 @@ use hyperswitch_domain_models::{ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, + }, types::{ - PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, - RefundSyncRouterData, RefundsRouterData, + PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, + PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ @@ -33,24 +39,72 @@ use hyperswitch_interfaces::{ configs::Connectors, errors, events::connector_api_logs::ConnectorEvent, - types::{self, Response}, + types::{self, PaymentsVoidType, Response}, webhooks, }; -use masking::{ExposeInterface, Mask}; +use masking::{ExposeInterface, Mask, Maskable, PeekInterface}; +use ring::{digest, hmac}; +use time::OffsetDateTime; use transformers as barclaycard; +use url::Url; + +use crate::{ + constants::{self, headers}, + types::ResponseRouterData, + utils::RefundsRequestData, +}; -use crate::{constants::headers, types::ResponseRouterData, utils}; +pub const V_C_MERCHANT_ID: &str = "v-c-merchant-id"; #[derive(Clone)] -pub struct Barclaycard { - amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), -} +pub struct Barclaycard; impl Barclaycard { - pub fn new() -> &'static Self { - &Self { - amount_converter: &StringMinorUnitForConnector, - } + pub fn generate_digest(&self, payload: &[u8]) -> String { + let payload_digest = digest::digest(&digest::SHA256, payload); + consts::BASE64_ENGINE.encode(payload_digest) + } + + pub fn generate_signature( + &self, + auth: barclaycard::BarclaycardAuthType, + host: String, + resource: &str, + payload: &String, + date: OffsetDateTime, + http_method: Method, + ) -> CustomResult<String, errors::ConnectorError> { + let barclaycard::BarclaycardAuthType { + api_key, + merchant_account, + api_secret, + } = auth; + let is_post_method = matches!(http_method, Method::Post); + let digest_str = if is_post_method { "digest " } else { "" }; + let headers = format!("host date (request-target) {digest_str}{V_C_MERCHANT_ID}"); + let request_target = if is_post_method { + format!("(request-target): post {resource}\ndigest: SHA-256={payload}\n") + } else { + format!("(request-target): get {resource}\n") + }; + let signature_string = format!( + "host: {host}\ndate: {date}\n{request_target}{V_C_MERCHANT_ID}: {}", + merchant_account.peek() + ); + let key_value = consts::BASE64_ENGINE + .decode(api_secret.expose()) + .change_context(errors::ConnectorError::InvalidConnectorConfig { + config: "connector_account_details.api_secret", + })?; + let key = hmac::Key::new(hmac::HMAC_SHA256, &key_value); + let signature_value = + consts::BASE64_ENGINE.encode(hmac::sign(&key, signature_string.as_bytes()).as_ref()); + let signature_header = format!( + r#"keyid="{}", algorithm="HmacSHA256", headers="{headers}", signature="{signature_value}""#, + api_key.peek() + ); + + Ok(signature_header) } } @@ -80,15 +134,55 @@ where fn build_headers( &self, req: &RouterData<Flow, Request, Response>, - _connectors: &Connectors, - ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { - let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - self.get_content_type().to_string().into(), - )]; - let mut api_key = self.get_auth_header(&req.connector_auth_type)?; - header.append(&mut api_key); - Ok(header) + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { + let date = OffsetDateTime::now_utc(); + let barclaycard_req = self.get_request_body(req, connectors)?; + let http_method = self.get_http_method(); + let auth = barclaycard::BarclaycardAuthType::try_from(&req.connector_auth_type)?; + let merchant_account = auth.merchant_account.clone(); + let base_url = connectors.barclaycard.base_url.as_str(); + let barclaycard_host = + Url::parse(base_url).change_context(errors::ConnectorError::RequestEncodingFailed)?; + let host = barclaycard_host + .host_str() + .ok_or(errors::ConnectorError::RequestEncodingFailed)?; + let path: String = self + .get_url(req, connectors)? + .chars() + .skip(base_url.len() - 1) + .collect(); + let sha256 = self.generate_digest(barclaycard_req.get_inner_value().expose().as_bytes()); + let signature = self.generate_signature( + auth, + host.to_string(), + path.as_str(), + &sha256, + date, + http_method, + )?; + + let mut headers = vec![ + ( + headers::CONTENT_TYPE.to_string(), + self.get_content_type().to_string().into(), + ), + ( + headers::ACCEPT.to_string(), + "application/hal+json;charset=utf-8".to_string().into(), + ), + (V_C_MERCHANT_ID.to_string(), merchant_account.into_masked()), + ("Date".to_string(), date.to_string().into()), + ("Host".to_string(), host.to_string().into()), + ("Signature".to_string(), signature.into_masked()), + ]; + if matches!(http_method, Method::Post | Method::Put) { + headers.push(( + "Digest".to_string(), + format!("SHA-256={sha256}").into_masked(), + )); + } + Ok(headers) } } @@ -112,7 +206,7 @@ impl ConnectorCommon for Barclaycard { fn get_auth_header( &self, auth_type: &ConnectorAuthType, - ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { let auth = barclaycard::BarclaycardAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( @@ -134,17 +228,83 @@ impl ConnectorCommon for Barclaycard { event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(ErrorResponse { - status_code: res.status_code, - code: response.code, - message: response.message, - reason: response.reason, - attempt_status: None, - connector_transaction_id: None, - network_decline_code: None, - network_advice_code: None, - network_error_message: None, - }) + let error_message = if res.status_code == 401 { + constants::CONNECTOR_UNAUTHORIZED_ERROR + } else { + hyperswitch_interfaces::consts::NO_ERROR_MESSAGE + }; + match response { + transformers::BarclaycardErrorResponse::StandardError(response) => { + let (code, message, reason) = match response.error_information { + Some(ref error_info) => { + let detailed_error_info = error_info.details.as_ref().map(|details| { + details + .iter() + .map(|det| format!("{} : {}", det.field, det.reason)) + .collect::<Vec<_>>() + .join(", ") + }); + ( + error_info.reason.clone(), + error_info.reason.clone(), + transformers::get_error_reason( + Some(error_info.message.clone()), + detailed_error_info, + None, + ), + ) + } + None => { + let detailed_error_info = response.details.map(|details| { + details + .iter() + .map(|det| format!("{} : {}", det.field, det.reason)) + .collect::<Vec<_>>() + .join(", ") + }); + ( + response.reason.clone().map_or( + hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(), + |reason| reason.to_string(), + ), + response + .reason + .map_or(error_message.to_string(), |reason| reason.to_string()), + transformers::get_error_reason( + response.message, + detailed_error_info, + None, + ), + ) + } + }; + + Ok(ErrorResponse { + status_code: res.status_code, + code, + message, + reason, + attempt_status: None, + connector_transaction_id: None, + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + }) + } + transformers::BarclaycardErrorResponse::AuthenticationError(response) => { + Ok(ErrorResponse { + status_code: res.status_code, + code: hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(), + message: response.response.rmsg.clone(), + reason: Some(response.response.rmsg), + attempt_status: None, + connector_transaction_id: None, + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + }) + } + } } } @@ -168,7 +328,7 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, - ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -179,9 +339,12 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData fn get_url( &self, _req: &PaymentsAuthorizeRouterData, - _connectors: &Connectors, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + Ok(format!( + "{}pts/v2/payments", + ConnectorCommon::base_url(self, connectors) + )) } fn get_request_body( @@ -189,13 +352,12 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let amount = utils::convert_amount( - self.amount_converter, - req.request.minor_amount, + let connector_router_data = barclaycard::BarclaycardRouterData::try_from(( + &self.get_currency_unit(), req.request.currency, - )?; - - let connector_router_data = barclaycard::BarclaycardRouterData::from((amount, req)); + req.request.amount, + req, + ))?; let connector_req = barclaycard::BarclaycardPaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) @@ -249,6 +411,43 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + + fn get_5xx_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: barclaycard::BarclaycardServerErrorResponse = res + .response + .parse_struct("BarclaycardServerErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|event| event.set_response_body(&response)); + router_env::logger::info!(error_response=?response); + + let attempt_status = match response.reason { + Some(reason) => match reason { + transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure), + transformers::Reason::ServerTimeout | transformers::Reason::ServiceTimeout => None, + }, + None => None, + }; + Ok(ErrorResponse { + status_code: res.status_code, + reason: response.status.clone(), + code: response + .status + .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()), + message: response + .message + .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), + attempt_status, + connector_transaction_id: None, + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + }) + } } impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Barclaycard { @@ -256,7 +455,7 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Bar &self, req: &PaymentsSyncRouterData, connectors: &Connectors, - ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -264,12 +463,24 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Bar self.common_get_content_type() } + fn get_http_method(&self) -> Method { + Method::Get + } + fn get_url( &self, - _req: &PaymentsSyncRouterData, - _connectors: &Connectors, + req: &PaymentsSyncRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + let connector_payment_id = req + .request + .connector_transaction_id + .get_connector_transaction_id() + .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; + Ok(format!( + "{}tss/v2/transactions/{connector_payment_id}", + self.base_url(connectors) + )) } fn build_request( @@ -293,9 +504,9 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Bar event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { - let response: barclaycard::BarclaycardPaymentsResponse = res + let response: barclaycard::BarclaycardTransactionResponse = res .response - .parse_struct("barclaycard PaymentsSyncResponse") + .parse_struct("Barclaycard PaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -320,7 +531,7 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, - ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -330,18 +541,30 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo fn get_url( &self, - _req: &PaymentsCaptureRouterData, - _connectors: &Connectors, + req: &PaymentsCaptureRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + let connector_payment_id = req.request.connector_transaction_id.clone(); + Ok(format!( + "{}pts/v2/payments/{connector_payment_id}/captures", + self.base_url(connectors) + )) } fn get_request_body( &self, - _req: &PaymentsCaptureRouterData, + req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) + let connector_router_data = barclaycard::BarclaycardRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount_to_capture, + req, + ))?; + let connector_req = + barclaycard::BarclaycardCaptureRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( @@ -390,16 +613,167 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } + + fn get_5xx_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: barclaycard::BarclaycardServerErrorResponse = res + .response + .parse_struct("BarclaycardServerErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|event| event.set_response_body(&response)); + router_env::logger::info!(error_response=?response); + + Ok(ErrorResponse { + status_code: res.status_code, + reason: response.status.clone(), + code: response + .status + .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()), + message: response + .message + .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), + attempt_status: None, + connector_transaction_id: None, + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + }) + } } -impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Barclaycard {} +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Barclaycard { + fn get_headers( + &self, + req: &PaymentsCancelRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_url( + &self, + req: &PaymentsCancelRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let connector_payment_id = req.request.connector_transaction_id.clone(); + Ok(format!( + "{}pts/v2/payments/{connector_payment_id}/reversals", + self.base_url(connectors) + )) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_request_body( + &self, + req: &PaymentsCancelRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_router_data = barclaycard::BarclaycardRouterData::try_from(( + &self.get_currency_unit(), + req.request + .currency + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "Currency", + })?, + req.request + .amount + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "Amount", + })?, + req, + ))?; + let connector_req = barclaycard::BarclaycardVoidRequest::try_from(&connector_router_data)?; + + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &PaymentsCancelRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsVoidType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(PaymentsVoidType::get_headers(self, req, connectors)?) + .set_body(PaymentsVoidType::get_request_body(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> { + let response: barclaycard::BarclaycardPaymentsResponse = res + .response + .parse_struct("Barclaycard PaymentResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } + + fn get_5xx_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: barclaycard::BarclaycardServerErrorResponse = res + .response + .parse_struct("BarclaycardServerErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|event| event.set_response_body(&response)); + router_env::logger::info!(error_response=?response); + + Ok(ErrorResponse { + status_code: res.status_code, + reason: response.status.clone(), + code: response + .status + .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()), + message: response + .message + .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), + attempt_status: None, + connector_transaction_id: None, + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + }) + } +} impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Barclaycard { fn get_headers( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, - ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -409,10 +783,14 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Barclay fn get_url( &self, - _req: &RefundsRouterData<Execute>, - _connectors: &Connectors, + req: &RefundsRouterData<Execute>, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + let connector_payment_id = req.request.connector_transaction_id.clone(); + Ok(format!( + "{}pts/v2/payments/{connector_payment_id}/refunds", + self.base_url(connectors) + )) } fn get_request_body( @@ -420,13 +798,12 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Barclay req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let refund_amount = utils::convert_amount( - self.amount_converter, - req.request.minor_refund_amount, + let connector_router_data = barclaycard::BarclaycardRouterData::try_from(( + &self.get_currency_unit(), req.request.currency, - )?; - - let connector_router_data = barclaycard::BarclaycardRouterData::from((refund_amount, req)); + req.request.refund_amount, + req, + ))?; let connector_req = barclaycard::BarclaycardRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) @@ -457,7 +834,7 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Barclay event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { - let response: barclaycard::RefundResponse = res + let response: barclaycard::BarclaycardRefundResponse = res .response .parse_struct("barclaycard RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; @@ -484,7 +861,7 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Barclayca &self, req: &RefundSyncRouterData, connectors: &Connectors, - ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -492,12 +869,20 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Barclayca self.common_get_content_type() } + fn get_http_method(&self) -> Method { + Method::Get + } + fn get_url( &self, - _req: &RefundSyncRouterData, - _connectors: &Connectors, + req: &RefundSyncRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + let refund_id = req.request.get_connector_refund_id()?; + Ok(format!( + "{}tss/v2/transactions/{refund_id}", + self.base_url(connectors) + )) } fn build_request( @@ -524,7 +909,7 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Barclayca event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { - let response: barclaycard::RefundResponse = res + let response: barclaycard::BarclaycardRsyncResponse = res .response .parse_struct("barclaycard RefundSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; @@ -570,4 +955,88 @@ impl webhooks::IncomingWebhook for Barclaycard { } } -impl ConnectorSpecifications for Barclaycard {} +static BARCLAYCARD_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(|| { + let supported_capture_methods = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::Manual, + enums::CaptureMethod::SequentialAutomatic, + ]; + + let supported_card_network = vec![ + common_enums::CardNetwork::Mastercard, + common_enums::CardNetwork::Visa, + common_enums::CardNetwork::AmericanExpress, + common_enums::CardNetwork::JCB, + common_enums::CardNetwork::Discover, + common_enums::CardNetwork::Maestro, + common_enums::CardNetwork::Interac, + common_enums::CardNetwork::DinersClub, + common_enums::CardNetwork::CartesBancaires, + common_enums::CardNetwork::UnionPay, + ]; + + let mut barclaycard_supported_payment_methods = SupportedPaymentMethods::new(); + + barclaycard_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Credit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + specific_features: Some( + api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ + api_models::feature_matrix::CardSpecificFeatures { + three_ds: common_enums::FeatureStatus::NotSupported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network.clone(), + } + }), + ), + }, + ); + + barclaycard_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Debit, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods, + specific_features: Some( + api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ + api_models::feature_matrix::CardSpecificFeatures { + three_ds: common_enums::FeatureStatus::NotSupported, + no_three_ds: common_enums::FeatureStatus::Supported, + supported_card_networks: supported_card_network, + } + }), + ), + }, + ); + + barclaycard_supported_payment_methods + }); + +static BARCLAYCARD_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "BarclayCard SmartPay Fuse", + description: "Barclaycard, part of Barclays Bank UK PLC, is a leading global payment business that helps consumers, retailers and businesses to make and take payments flexibly, and to access short-term credit and point of sale finance.", + connector_type: enums::PaymentConnectorCategory::BankAcquirer, +}; + +static BARCLAYCARD_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; + +impl ConnectorSpecifications for Barclaycard { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&BARCLAYCARD_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*BARCLAYCARD_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&BARCLAYCARD_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs b/crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs index 1a994d3d2a0..14425bb118a 100644 --- a/crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs @@ -1,52 +1,458 @@ use common_enums::enums; -use common_utils::types::StringMinorUnit; +use common_utils::pii; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, - router_data::{ConnectorAuthType, RouterData}, + router_data::{ + AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData, + ErrorResponse, RouterData, + }, router_flow_types::refunds::{Execute, RSync}, - router_request_types::ResponseId, + router_request_types::{ + PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSyncData, + ResponseId, + }, router_response_types::{PaymentsResponseData, RefundsResponseData}, - types::{PaymentsAuthorizeRouterData, RefundsRouterData}, + types::{ + PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, + RefundsRouterData, + }, }; -use hyperswitch_interfaces::errors; -use masking::Secret; +use hyperswitch_interfaces::{api, errors}; +use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; +use serde_json::Value; use crate::{ + constants, types::{RefundsResponseRouterData, ResponseRouterData}, - utils::PaymentsAuthorizeRequestData, + utils::{ + self, AddressDetailsData, CardData, PaymentsAuthorizeRequestData, PaymentsSyncRequestData, + RouterData as OtherRouterData, + }, }; +pub struct BarclaycardAuthType { + pub(super) api_key: Secret<String>, + pub(super) merchant_account: Secret<String>, + pub(super) api_secret: Secret<String>, +} + +impl TryFrom<&ConnectorAuthType> for BarclaycardAuthType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { + if let ConnectorAuthType::SignatureKey { + api_key, + key1, + api_secret, + } = auth_type + { + Ok(Self { + api_key: api_key.to_owned(), + merchant_account: key1.to_owned(), + api_secret: api_secret.to_owned(), + }) + } else { + Err(errors::ConnectorError::FailedToObtainAuthType)? + } + } +} -//TODO: Fill the struct with respective fields pub struct BarclaycardRouterData<T> { - pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. + pub amount: String, pub router_data: T, } -impl<T> From<(StringMinorUnit, T)> for BarclaycardRouterData<T> { - fn from((amount, item): (StringMinorUnit, T)) -> Self { - //Todo : use utils to convert the amount to the type of amount that a connector accepts - Self { +impl<T> TryFrom<(&api::CurrencyUnit, api_models::enums::Currency, i64, T)> + for BarclaycardRouterData<T> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (currency_unit, currency, amount, item): ( + &api::CurrencyUnit, + api_models::enums::Currency, + i64, + T, + ), + ) -> Result<Self, Self::Error> { + let amount = utils::get_amount_as_string(currency_unit, amount, currency)?; + Ok(Self { amount, router_data: item, - } + }) } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Serialize, PartialEq)] +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] pub struct BarclaycardPaymentsRequest { - amount: StringMinorUnit, - card: BarclaycardCard, + processing_information: ProcessingInformation, + payment_information: PaymentInformation, + order_information: OrderInformationWithBill, + client_reference_information: ClientReferenceInformation, + #[serde(skip_serializing_if = "Option::is_none")] + consumer_authentication_information: Option<BarclaycardConsumerAuthInformation>, + #[serde(skip_serializing_if = "Option::is_none")] + merchant_defined_information: Option<Vec<MerchantDefinedInformation>>, } -#[derive(Default, Debug, Serialize, Eq, PartialEq)] -pub struct BarclaycardCard { +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ProcessingInformation { + commerce_indicator: String, + capture: Option<bool>, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct MerchantDefinedInformation { + key: u8, + value: String, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BarclaycardConsumerAuthInformation { + ucaf_collection_indicator: Option<String>, + cavv: Option<String>, + ucaf_authentication_data: Option<Secret<String>>, + xid: Option<String>, + directory_server_transaction_id: Option<Secret<String>>, + specification_version: Option<String>, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CardPaymentInformation { + card: Card, +} + +#[derive(Debug, Serialize)] +#[serde(untagged)] +pub enum PaymentInformation { + Cards(Box<CardPaymentInformation>), +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Card { number: cards::CardNumber, - expiry_month: Secret<String>, - expiry_year: Secret<String>, - cvc: Secret<String>, - complete: bool, + expiration_month: Secret<String>, + expiration_year: Secret<String>, + security_code: Secret<String>, + #[serde(rename = "type")] + card_type: Option<String>, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct OrderInformationWithBill { + amount_details: Amount, + bill_to: Option<BillTo>, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Amount { + total_amount: String, + currency: api_models::enums::Currency, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BillTo { + first_name: Option<Secret<String>>, + last_name: Option<Secret<String>>, + address1: Option<Secret<String>>, + locality: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + administrative_area: Option<Secret<String>>, + #[serde(skip_serializing_if = "Option::is_none")] + postal_code: Option<Secret<String>>, + country: Option<enums::CountryAlpha2>, + email: pii::Email, +} + +fn build_bill_to( + address_details: Option<&hyperswitch_domain_models::address::Address>, + email: pii::Email, +) -> Result<BillTo, error_stack::Report<errors::ConnectorError>> { + let default_address = BillTo { + first_name: None, + last_name: None, + address1: None, + locality: None, + administrative_area: None, + postal_code: None, + country: None, + email: email.clone(), + }; + + Ok(address_details + .and_then(|addr| { + addr.address.as_ref().map(|addr| { + let administrative_area = addr.to_state_code_as_optional().unwrap_or_else(|_| { + addr.state + .clone() + .map(|state| Secret::new(format!("{:.20}", state.expose()))) + }); + + BillTo { + first_name: addr.first_name.clone(), + last_name: addr.last_name.clone(), + address1: addr.line1.clone(), + locality: addr.city.clone(), + administrative_area, + postal_code: addr.zip.clone(), + country: addr.country, + email, + } + }) + }) + .unwrap_or(default_address)) +} + +fn get_barclaycard_card_type(card_network: common_enums::CardNetwork) -> Option<&'static str> { + match card_network { + common_enums::CardNetwork::Visa => Some("001"), + common_enums::CardNetwork::Mastercard => Some("002"), + common_enums::CardNetwork::AmericanExpress => Some("003"), + common_enums::CardNetwork::JCB => Some("007"), + common_enums::CardNetwork::DinersClub => Some("005"), + common_enums::CardNetwork::Discover => Some("004"), + common_enums::CardNetwork::CartesBancaires => Some("006"), + common_enums::CardNetwork::UnionPay => Some("062"), + //"042" is the type code for Masetro Cards(International). For Maestro Cards(UK-Domestic) the mapping should be "024" + common_enums::CardNetwork::Maestro => Some("042"), + common_enums::CardNetwork::Interac + | common_enums::CardNetwork::RuPay + | common_enums::CardNetwork::Star + | common_enums::CardNetwork::Accel + | common_enums::CardNetwork::Pulse + | common_enums::CardNetwork::Nyce => None, + } +} + +impl + From<( + &BarclaycardRouterData<&PaymentsAuthorizeRouterData>, + Option<BillTo>, + )> for OrderInformationWithBill +{ + fn from( + (item, bill_to): ( + &BarclaycardRouterData<&PaymentsAuthorizeRouterData>, + Option<BillTo>, + ), + ) -> Self { + Self { + amount_details: Amount { + total_amount: item.amount.to_owned(), + currency: item.router_data.request.currency, + }, + bill_to, + } + } +} + +impl + TryFrom<( + &BarclaycardRouterData<&PaymentsAuthorizeRouterData>, + Option<String>, + )> for ProcessingInformation +{ + type Error = error_stack::Report<errors::ConnectorError>; + + fn try_from( + (item, network): ( + &BarclaycardRouterData<&PaymentsAuthorizeRouterData>, + Option<String>, + ), + ) -> Result<Self, Self::Error> { + let commerce_indicator = get_commerce_indicator(network); + + Ok(Self { + capture: Some(matches!( + item.router_data.request.capture_method, + Some(enums::CaptureMethod::Automatic) | None + )), + commerce_indicator, + }) + } +} + +impl From<&BarclaycardRouterData<&PaymentsAuthorizeRouterData>> for ClientReferenceInformation { + fn from(item: &BarclaycardRouterData<&PaymentsAuthorizeRouterData>) -> Self { + Self { + code: Some(item.router_data.connector_request_reference_id.clone()), + } + } +} + +fn convert_metadata_to_merchant_defined_info(metadata: Value) -> Vec<MerchantDefinedInformation> { + let hashmap: std::collections::BTreeMap<String, Value> = + serde_json::from_str(&metadata.to_string()).unwrap_or(std::collections::BTreeMap::new()); + let mut vector = Vec::new(); + let mut iter = 1; + for (key, value) in hashmap { + vector.push(MerchantDefinedInformation { + key: iter, + value: format!("{key}={value}"), + }); + iter += 1; + } + vector +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ClientReferenceInformation { + code: Option<String>, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClientProcessorInformation { + avs: Option<Avs>, + card_verification: Option<CardVerification>, + processor: Option<ProcessorResponse>, + network_transaction_id: Option<Secret<String>>, + approval_code: Option<String>, + merchant_advice: Option<MerchantAdvice>, + response_code: Option<String>, + ach_verification: Option<AchVerification>, + system_trace_audit_number: Option<String>, + event_status: Option<String>, + retrieval_reference_number: Option<String>, + consumer_authentication_response: Option<ConsumerAuthenticationResponse>, + response_details: Option<String>, + transaction_id: Option<Secret<String>>, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct MerchantAdvice { + code: Option<String>, + code_raw: Option<String>, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ConsumerAuthenticationResponse { + code: Option<String>, + code_raw: Option<String>, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AchVerification { + result_code_raw: Option<String>, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ProcessorResponse { + name: Option<String>, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CardVerification { + result_code: Option<String>, + result_code_raw: Option<String>, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ClientRiskInformation { + rules: Option<Vec<ClientRiskInformationRules>>, + profile: Option<Profile>, + score: Option<Score>, + info_codes: Option<InfoCodes>, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct InfoCodes { + address: Option<Vec<String>>, + identity_change: Option<Vec<String>>, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Score { + factor_codes: Option<Vec<String>>, + result: Option<RiskResult>, + model_used: Option<String>, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub enum RiskResult { + StringVariant(String), + IntVariant(u64), +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Profile { + early_decision: Option<String>, + name: Option<String>, + decision: Option<String>, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +pub struct ClientRiskInformationRules { + name: Option<Secret<String>>, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Avs { + code: Option<String>, + code_raw: Option<String>, +} + +impl + TryFrom<( + &BarclaycardRouterData<&PaymentsAuthorizeRouterData>, + hyperswitch_domain_models::payment_method_data::Card, + )> for BarclaycardPaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (item, ccard): ( + &BarclaycardRouterData<&PaymentsAuthorizeRouterData>, + hyperswitch_domain_models::payment_method_data::Card, + ), + ) -> Result<Self, Self::Error> { + if item.router_data.is_three_ds() { + Err(errors::ConnectorError::NotSupported { + message: "Card 3DS".to_string(), + connector: "Barclaycard", + })? + }; + + let email = item.router_data.request.get_email()?; + let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; + let order_information = OrderInformationWithBill::from((item, Some(bill_to))); + let payment_information = PaymentInformation::try_from(&ccard)?; + let processing_information = ProcessingInformation::try_from((item, None))?; + let client_reference_information = ClientReferenceInformation::from(item); + let merchant_defined_information = item + .router_data + .request + .metadata + .clone() + .map(convert_metadata_to_merchant_defined_info); + + Ok(Self { + processing_information, + payment_information, + order_information, + client_reference_information, + merchant_defined_information, + consumer_authentication_information: None, + }) + } } impl TryFrom<&BarclaycardRouterData<&PaymentsAuthorizeRouterData>> for BarclaycardPaymentsRequest { @@ -55,174 +461,1157 @@ impl TryFrom<&BarclaycardRouterData<&PaymentsAuthorizeRouterData>> for Barclayca item: &BarclaycardRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { - PaymentMethodData::Card(req_card) => { - let card = BarclaycardCard { - number: req_card.card_number, - expiry_month: req_card.card_exp_month, - expiry_year: req_card.card_exp_year, - cvc: req_card.card_cvc, - complete: item.router_data.request.is_auto_capture()?, + PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)), + PaymentMethodData::Wallet(_) + | PaymentMethodData::MandatePayment + | PaymentMethodData::CardRedirect(_) + | PaymentMethodData::PayLater(_) + | PaymentMethodData::BankRedirect(_) + | PaymentMethodData::BankDebit(_) + | PaymentMethodData::BankTransfer(_) + | PaymentMethodData::Crypto(_) + | PaymentMethodData::Reward + | PaymentMethodData::RealTimePayment(_) + | PaymentMethodData::MobilePayment(_) + | PaymentMethodData::Upi(_) + | PaymentMethodData::Voucher(_) + | PaymentMethodData::GiftCard(_) + | PaymentMethodData::OpenBanking(_) + | PaymentMethodData::CardToken(_) + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Barclaycard"), + ) + .into()) + } + } + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum BarclaycardPaymentStatus { + Authorized, + Succeeded, + Failed, + Voided, + Reversed, + Pending, + Declined, + Rejected, + Challenge, + AuthorizedPendingReview, + AuthorizedRiskDeclined, + Transmitted, + InvalidRequest, + ServerError, + PendingAuthentication, + PendingReview, + Accepted, + Cancelled, + //PartialAuthorized, not being consumed yet. +} + +fn map_barclaycard_attempt_status( + (status, auto_capture): (BarclaycardPaymentStatus, bool), +) -> enums::AttemptStatus { + match status { + BarclaycardPaymentStatus::Authorized + | BarclaycardPaymentStatus::AuthorizedPendingReview => { + if auto_capture { + // Because Barclaycard will return Payment Status as Authorized even in AutoCapture Payment + enums::AttemptStatus::Charged + } else { + enums::AttemptStatus::Authorized + } + } + BarclaycardPaymentStatus::Pending => { + if auto_capture { + enums::AttemptStatus::Charged + } else { + enums::AttemptStatus::Pending + } + } + BarclaycardPaymentStatus::Succeeded | BarclaycardPaymentStatus::Transmitted => { + enums::AttemptStatus::Charged + } + BarclaycardPaymentStatus::Voided + | BarclaycardPaymentStatus::Reversed + | BarclaycardPaymentStatus::Cancelled => enums::AttemptStatus::Voided, + BarclaycardPaymentStatus::Failed + | BarclaycardPaymentStatus::Declined + | BarclaycardPaymentStatus::AuthorizedRiskDeclined + | BarclaycardPaymentStatus::InvalidRequest + | BarclaycardPaymentStatus::Rejected + | BarclaycardPaymentStatus::ServerError => enums::AttemptStatus::Failure, + BarclaycardPaymentStatus::PendingAuthentication => { + enums::AttemptStatus::AuthenticationPending + } + BarclaycardPaymentStatus::PendingReview + | BarclaycardPaymentStatus::Challenge + | BarclaycardPaymentStatus::Accepted => enums::AttemptStatus::Pending, + } +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(untagged)] +pub enum BarclaycardPaymentsResponse { + ClientReferenceInformation(Box<BarclaycardClientReferenceResponse>), + ErrorInformation(Box<BarclaycardErrorInformationResponse>), +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BarclaycardClientReferenceResponse { + id: String, + status: BarclaycardPaymentStatus, + client_reference_information: ClientReferenceInformation, + processor_information: Option<ClientProcessorInformation>, + processing_information: Option<ProcessingInformationResponse>, + payment_information: Option<PaymentInformationResponse>, + payment_insights_information: Option<PaymentInsightsInformation>, + risk_information: Option<ClientRiskInformation>, + error_information: Option<BarclaycardErrorInformation>, + issuer_information: Option<IssuerInformation>, + sender_information: Option<SenderInformation>, + payment_account_information: Option<PaymentAccountInformation>, + reconciliation_id: Option<String>, + consumer_authentication_information: Option<ConsumerAuthenticationInformation>, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ConsumerAuthenticationInformation { + eci_raw: Option<String>, + eci: Option<String>, + acs_transaction_id: Option<String>, + cavv: Option<String>, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SenderInformation { + payment_information: Option<PaymentInformationResponse>, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PaymentInsightsInformation { + response_insights: Option<ResponseInsights>, + rule_results: Option<RuleResults>, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ResponseInsights { + category_code: Option<String>, + category: Option<String>, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RuleResults { + id: Option<String>, + decision: Option<String>, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PaymentInformationResponse { + tokenized_card: Option<CardResponseObject>, + customer: Option<CustomerResponseObject>, + card: Option<CardResponseObject>, + scheme: Option<String>, + bin: Option<String>, + account_type: Option<String>, + issuer: Option<String>, + bin_country: Option<enums::CountryAlpha2>, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CustomerResponseObject { + customer_id: Option<String>, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PaymentAccountInformation { + card: Option<PaymentAccountCardInformation>, + features: Option<PaymentAccountFeatureInformation>, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PaymentAccountFeatureInformation { + health_card: Option<String>, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PaymentAccountCardInformation { + #[serde(rename = "type")] + card_type: Option<String>, + hashed_number: Option<String>, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ProcessingInformationResponse { + payment_solution: Option<String>, + commerce_indicator: Option<String>, + commerce_indicator_label: Option<String>, + ecommerce_indicator: Option<String>, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct IssuerInformation { + country: Option<enums::CountryAlpha2>, + discretionary_data: Option<String>, + country_specific_discretionary_data: Option<String>, + response_code: Option<String>, + pin_request_indicator: Option<String>, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CardResponseObject { + suffix: Option<String>, + prefix: Option<String>, + expiration_month: Option<Secret<String>>, + expiration_year: Option<Secret<String>>, + #[serde(rename = "type")] + card_type: Option<String>, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BarclaycardErrorInformationResponse { + id: String, + error_information: BarclaycardErrorInformation, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct BarclaycardErrorInformation { + reason: Option<String>, + message: Option<String>, + details: Option<Vec<Details>>, +} + +fn map_error_response<F, T>( + error_response: &BarclaycardErrorInformationResponse, + item: ResponseRouterData<F, BarclaycardPaymentsResponse, T, PaymentsResponseData>, + transaction_status: Option<enums::AttemptStatus>, +) -> RouterData<F, T, PaymentsResponseData> { + let detailed_error_info = error_response + .error_information + .details + .as_ref() + .map(|details| { + details + .iter() + .map(|details| format!("{} : {}", details.field, details.reason)) + .collect::<Vec<_>>() + .join(", ") + }); + + let reason = get_error_reason( + error_response.error_information.message.clone(), + detailed_error_info, + None, + ); + let response = Err(ErrorResponse { + code: error_response + .error_information + .reason + .clone() + .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()), + message: error_response + .error_information + .reason + .clone() + .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), + reason, + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(error_response.id.clone()), + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + }); + + match transaction_status { + Some(status) => RouterData { + response, + status, + ..item.data + }, + None => RouterData { + response, + ..item.data + }, + } +} + +fn get_error_response_if_failure( + (info_response, status, http_code): ( + &BarclaycardClientReferenceResponse, + enums::AttemptStatus, + u16, + ), +) -> Option<ErrorResponse> { + if utils::is_payment_failure(status) { + Some(get_error_response( + &info_response.error_information, + &info_response.processor_information, + &info_response.risk_information, + Some(status), + http_code, + info_response.id.clone(), + )) + } else { + None + } +} + +fn get_payment_response( + (info_response, status, http_code): ( + &BarclaycardClientReferenceResponse, + enums::AttemptStatus, + u16, + ), +) -> Result<PaymentsResponseData, Box<ErrorResponse>> { + let error_response = get_error_response_if_failure((info_response, status, http_code)); + match error_response { + Some(error) => Err(Box::new(error)), + None => Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(info_response.id.clone()), + redirection_data: Box::new(None), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: Some( + info_response + .client_reference_information + .code + .clone() + .unwrap_or(info_response.id.clone()), + ), + incremental_authorization_allowed: None, + charges: None, + }), + } +} + +impl<F> + TryFrom< + ResponseRouterData< + F, + BarclaycardPaymentsResponse, + PaymentsAuthorizeData, + PaymentsResponseData, + >, + > for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData< + F, + BarclaycardPaymentsResponse, + PaymentsAuthorizeData, + PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + match item.response { + BarclaycardPaymentsResponse::ClientReferenceInformation(info_response) => { + let status = map_barclaycard_attempt_status(( + info_response.status.clone(), + item.data.request.is_auto_capture()?, + )); + let response = get_payment_response((&info_response, status, item.http_code)) + .map_err(|err| *err); + let connector_response = match item.data.payment_method { + common_enums::PaymentMethod::Card => info_response + .processor_information + .as_ref() + .and_then(|processor_information| { + info_response + .consumer_authentication_information + .as_ref() + .map(|consumer_auth_information| { + convert_to_additional_payment_method_connector_response( + processor_information, + consumer_auth_information, + ) + }) + }) + .map(ConnectorResponseData::with_additional_payment_method_data), + common_enums::PaymentMethod::CardRedirect + | common_enums::PaymentMethod::PayLater + | common_enums::PaymentMethod::Wallet + | common_enums::PaymentMethod::BankRedirect + | common_enums::PaymentMethod::BankTransfer + | common_enums::PaymentMethod::Crypto + | common_enums::PaymentMethod::BankDebit + | common_enums::PaymentMethod::Reward + | common_enums::PaymentMethod::RealTimePayment + | common_enums::PaymentMethod::MobilePayment + | common_enums::PaymentMethod::Upi + | common_enums::PaymentMethod::Voucher + | common_enums::PaymentMethod::OpenBanking + | common_enums::PaymentMethod::GiftCard => None, }; + Ok(Self { - amount: item.amount.clone(), - card, + status, + response, + connector_response, + ..item.data }) } - _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), + BarclaycardPaymentsResponse::ErrorInformation(ref error_response) => { + Ok(map_error_response( + &error_response.clone(), + item, + Some(enums::AttemptStatus::Failure), + )) + } } } } -//TODO: Fill the struct with respective fields -// Auth Struct -pub struct BarclaycardAuthType { - pub(super) api_key: Secret<String>, +fn convert_to_additional_payment_method_connector_response( + processor_information: &ClientProcessorInformation, + consumer_authentication_information: &ConsumerAuthenticationInformation, +) -> AdditionalPaymentMethodConnectorResponse { + let payment_checks = Some(serde_json::json!({ + "avs_response": processor_information.avs, + "card_verification": processor_information.card_verification, + "approval_code": processor_information.approval_code, + "consumer_authentication_response": processor_information.consumer_authentication_response, + "cavv": consumer_authentication_information.cavv, + "eci": consumer_authentication_information.eci, + "eci_raw": consumer_authentication_information.eci_raw, + })); + + let authentication_data = Some(serde_json::json!({ + "retrieval_reference_number": processor_information.retrieval_reference_number, + "acs_transaction_id": consumer_authentication_information.acs_transaction_id, + "system_trace_audit_number": processor_information.system_trace_audit_number, + })); + + AdditionalPaymentMethodConnectorResponse::Card { + authentication_data, + payment_checks, + card_network: None, + domestic_network: None, + } } -impl TryFrom<&ConnectorAuthType> for BarclaycardAuthType { +impl<F> + TryFrom< + ResponseRouterData< + F, + BarclaycardPaymentsResponse, + PaymentsCaptureData, + PaymentsResponseData, + >, + > for RouterData<F, PaymentsCaptureData, PaymentsResponseData> +{ type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { - match auth_type { - ConnectorAuthType::HeaderKey { api_key } => Ok(Self { - api_key: api_key.to_owned(), - }), - _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + fn try_from( + item: ResponseRouterData< + F, + BarclaycardPaymentsResponse, + PaymentsCaptureData, + PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + match item.response { + BarclaycardPaymentsResponse::ClientReferenceInformation(info_response) => { + let status = map_barclaycard_attempt_status((info_response.status.clone(), true)); + let response = get_payment_response((&info_response, status, item.http_code)) + .map_err(|err| *err); + Ok(Self { + status, + response, + ..item.data + }) + } + BarclaycardPaymentsResponse::ErrorInformation(ref error_response) => { + Ok(map_error_response(&error_response.clone(), item, None)) + } } } } -// PaymentsResponse -//TODO: Append the remaining status flags -#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] -#[serde(rename_all = "lowercase")] -pub enum BarclaycardPaymentStatus { - Succeeded, - Failed, - #[default] - Processing, -} -impl From<BarclaycardPaymentStatus> for common_enums::AttemptStatus { - fn from(item: BarclaycardPaymentStatus) -> Self { - match item { - BarclaycardPaymentStatus::Succeeded => Self::Charged, - BarclaycardPaymentStatus::Failed => Self::Failure, - BarclaycardPaymentStatus::Processing => Self::Authorizing, +impl<F> + TryFrom< + ResponseRouterData< + F, + BarclaycardPaymentsResponse, + PaymentsCancelData, + PaymentsResponseData, + >, + > for RouterData<F, PaymentsCancelData, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData< + F, + BarclaycardPaymentsResponse, + PaymentsCancelData, + PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + match item.response { + BarclaycardPaymentsResponse::ClientReferenceInformation(info_response) => { + let status = map_barclaycard_attempt_status((info_response.status.clone(), false)); + let response = get_payment_response((&info_response, status, item.http_code)) + .map_err(|err| *err); + Ok(Self { + status, + response, + ..item.data + }) + } + BarclaycardPaymentsResponse::ErrorInformation(ref error_response) => { + Ok(map_error_response(&error_response.clone(), item, None)) + } } } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct BarclaycardPaymentsResponse { - status: BarclaycardPaymentStatus, +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BarclaycardTransactionResponse { id: String, + application_information: ApplicationInformation, + client_reference_information: Option<ClientReferenceInformation>, + processor_information: Option<ClientProcessorInformation>, + processing_information: Option<ProcessingInformationResponse>, + payment_information: Option<PaymentInformationResponse>, + payment_insights_information: Option<PaymentInsightsInformation>, + error_information: Option<BarclaycardErrorInformation>, + fraud_marking_information: Option<FraudMarkingInformation>, + risk_information: Option<ClientRiskInformation>, + reconciliation_id: Option<String>, + consumer_authentication_information: Option<ConsumerAuthenticationInformation>, } -impl<F, T> TryFrom<ResponseRouterData<F, BarclaycardPaymentsResponse, T, PaymentsResponseData>> - for RouterData<F, T, PaymentsResponseData> +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FraudMarkingInformation { + reason: Option<String>, +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ApplicationInformation { + status: Option<BarclaycardPaymentStatus>, +} + +impl<F> + TryFrom< + ResponseRouterData< + F, + BarclaycardTransactionResponse, + PaymentsSyncData, + PaymentsResponseData, + >, + > for RouterData<F, PaymentsSyncData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: ResponseRouterData<F, BarclaycardPaymentsResponse, T, PaymentsResponseData>, + item: ResponseRouterData< + F, + BarclaycardTransactionResponse, + PaymentsSyncData, + PaymentsResponseData, + >, ) -> Result<Self, Self::Error> { - Ok(Self { - status: common_enums::AttemptStatus::from(item.response.status), - response: Ok(PaymentsResponseData::TransactionResponse { - resource_id: ResponseId::ConnectorTransactionId(item.response.id), - redirection_data: Box::new(None), - mandate_reference: Box::new(None), - connector_metadata: None, - network_txn_id: None, - connector_response_reference_id: None, - incremental_authorization_allowed: None, - charges: None, + match item.response.application_information.status { + Some(app_status) => { + let status = map_barclaycard_attempt_status(( + app_status, + item.data.request.is_auto_capture()?, + )); + + let connector_response = match item.data.payment_method { + common_enums::PaymentMethod::Card => item + .response + .processor_information + .as_ref() + .and_then(|processor_information| { + item.response + .consumer_authentication_information + .as_ref() + .map(|consumer_auth_information| { + convert_to_additional_payment_method_connector_response( + processor_information, + consumer_auth_information, + ) + }) + }) + .map(ConnectorResponseData::with_additional_payment_method_data), + common_enums::PaymentMethod::CardRedirect + | common_enums::PaymentMethod::PayLater + | common_enums::PaymentMethod::Wallet + | common_enums::PaymentMethod::BankRedirect + | common_enums::PaymentMethod::BankTransfer + | common_enums::PaymentMethod::Crypto + | common_enums::PaymentMethod::BankDebit + | common_enums::PaymentMethod::Reward + | common_enums::PaymentMethod::RealTimePayment + | common_enums::PaymentMethod::MobilePayment + | common_enums::PaymentMethod::Upi + | common_enums::PaymentMethod::Voucher + | common_enums::PaymentMethod::OpenBanking + | common_enums::PaymentMethod::GiftCard => None, + }; + + let risk_info: Option<ClientRiskInformation> = None; + if utils::is_payment_failure(status) { + Ok(Self { + response: Err(get_error_response( + &item.response.error_information, + &item.response.processor_information, + &risk_info, + Some(status), + item.http_code, + item.response.id.clone(), + )), + status: enums::AttemptStatus::Failure, + connector_response, + ..item.data + }) + } else { + Ok(Self { + status, + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + item.response.id.clone(), + ), + redirection_data: Box::new(None), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: item + .response + .client_reference_information + .map(|cref| cref.code) + .unwrap_or(Some(item.response.id)), + incremental_authorization_allowed: None, + charges: None, + }), + connector_response, + ..item.data + }) + } + } + None => Ok(Self { + status: item.data.status, + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), + redirection_data: Box::new(None), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: Some(item.response.id), + incremental_authorization_allowed: None, + charges: None, + }), + ..item.data }), - ..item.data + } + } +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct OrderInformation { + amount_details: Amount, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BarclaycardCaptureRequest { + order_information: OrderInformation, + client_reference_information: ClientReferenceInformation, + #[serde(skip_serializing_if = "Option::is_none")] + merchant_defined_information: Option<Vec<MerchantDefinedInformation>>, +} + +impl TryFrom<&BarclaycardRouterData<&PaymentsCaptureRouterData>> for BarclaycardCaptureRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + value: &BarclaycardRouterData<&PaymentsCaptureRouterData>, + ) -> Result<Self, Self::Error> { + let merchant_defined_information = value + .router_data + .request + .metadata + .clone() + .map(convert_metadata_to_merchant_defined_info); + Ok(Self { + order_information: OrderInformation { + amount_details: Amount { + total_amount: value.amount.to_owned(), + currency: value.router_data.request.currency, + }, + }, + client_reference_information: ClientReferenceInformation { + code: Some(value.router_data.connector_request_reference_id.clone()), + }, + merchant_defined_information, }) } } -//TODO: Fill the struct with respective fields -// REFUND : -// Type definition for RefundRequest -#[derive(Default, Debug, Serialize)] -pub struct BarclaycardRefundRequest { - pub amount: StringMinorUnit, +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BarclaycardVoidRequest { + client_reference_information: ClientReferenceInformation, + reversal_information: ReversalInformation, + #[serde(skip_serializing_if = "Option::is_none")] + merchant_defined_information: Option<Vec<MerchantDefinedInformation>>, + // The connector documentation does not mention the merchantDefinedInformation field for Void requests. But this has been still added because it works! } -impl<F> TryFrom<&BarclaycardRouterData<&RefundsRouterData<F>>> for BarclaycardRefundRequest { +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ReversalInformation { + amount_details: Amount, + reason: String, +} + +impl TryFrom<&BarclaycardRouterData<&PaymentsCancelRouterData>> for BarclaycardVoidRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &BarclaycardRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { + fn try_from( + value: &BarclaycardRouterData<&PaymentsCancelRouterData>, + ) -> Result<Self, Self::Error> { + let merchant_defined_information = value + .router_data + .request + .metadata + .clone() + .map(convert_metadata_to_merchant_defined_info); Ok(Self { - amount: item.amount.to_owned(), + client_reference_information: ClientReferenceInformation { + code: Some(value.router_data.connector_request_reference_id.clone()), + }, + reversal_information: ReversalInformation { + amount_details: Amount { + total_amount: value.amount.to_owned(), + currency: value.router_data.request.currency.ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "Currency", + }, + )?, + }, + reason: value + .router_data + .request + .cancellation_reason + .clone() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "Cancellation Reason", + })?, + }, + merchant_defined_information, }) } } -// Type definition for Refund Response +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BarclaycardRefundRequest { + order_information: OrderInformation, + client_reference_information: ClientReferenceInformation, +} -#[allow(dead_code)] -#[derive(Debug, Serialize, Default, Deserialize, Clone)] -pub enum RefundStatus { - Succeeded, - Failed, - #[default] - Processing, +impl<F> TryFrom<&BarclaycardRouterData<&RefundsRouterData<F>>> for BarclaycardRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &BarclaycardRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { + Ok(Self { + order_information: OrderInformation { + amount_details: Amount { + total_amount: item.amount.clone(), + currency: item.router_data.request.currency, + }, + }, + client_reference_information: ClientReferenceInformation { + code: Some(item.router_data.request.refund_id.clone()), + }, + }) + } } -impl From<RefundStatus> for enums::RefundStatus { - fn from(item: RefundStatus) -> Self { - match item { - RefundStatus::Succeeded => Self::Success, - RefundStatus::Failed => Self::Failure, - RefundStatus::Processing => Self::Pending, - //TODO: Review mapping +impl From<BarclaycardRefundResponse> for enums::RefundStatus { + fn from(item: BarclaycardRefundResponse) -> Self { + let error_reason = item + .error_information + .and_then(|error_info| error_info.reason); + match item.status { + BarclaycardRefundStatus::Succeeded | BarclaycardRefundStatus::Transmitted => { + Self::Success + } + BarclaycardRefundStatus::Cancelled + | BarclaycardRefundStatus::Failed + | BarclaycardRefundStatus::Voided => Self::Failure, + BarclaycardRefundStatus::Pending => Self::Pending, + BarclaycardRefundStatus::TwoZeroOne => { + if error_reason == Some("PROCESSOR_DECLINED".to_string()) { + Self::Failure + } else { + Self::Pending + } + } } } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Clone, Serialize, Deserialize)] -pub struct RefundResponse { +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BarclaycardRefundResponse { id: String, - status: RefundStatus, + status: BarclaycardRefundStatus, + error_information: Option<BarclaycardErrorInformation>, } -impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { +impl TryFrom<RefundsResponseRouterData<Execute, BarclaycardRefundResponse>> + for RefundsRouterData<Execute> +{ type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: RefundsResponseRouterData<Execute, RefundResponse>, + item: RefundsResponseRouterData<Execute, BarclaycardRefundResponse>, ) -> Result<Self, Self::Error> { + let refund_status = enums::RefundStatus::from(item.response.clone()); + let response = if utils::is_refund_failure(refund_status) { + Err(get_error_response( + &item.response.error_information, + &None, + &None, + None, + item.http_code, + item.response.id, + )) + } else { + Ok(RefundsResponseData { + connector_refund_id: item.response.id, + refund_status, + }) + }; + Ok(Self { - response: Ok(RefundsResponseData { - connector_refund_id: item.response.id.to_string(), - refund_status: enums::RefundStatus::from(item.response.status), - }), + response, ..item.data }) } } -impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum BarclaycardRefundStatus { + Succeeded, + Transmitted, + Failed, + Pending, + Voided, + Cancelled, + #[serde(rename = "201")] + TwoZeroOne, +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RsyncApplicationInformation { + status: Option<BarclaycardRefundStatus>, +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BarclaycardRsyncResponse { + id: String, + application_information: Option<RsyncApplicationInformation>, + error_information: Option<BarclaycardErrorInformation>, +} + +impl TryFrom<RefundsResponseRouterData<RSync, BarclaycardRsyncResponse>> + for RefundsRouterData<RSync> +{ type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: RefundsResponseRouterData<RSync, RefundResponse>, + item: RefundsResponseRouterData<RSync, BarclaycardRsyncResponse>, ) -> Result<Self, Self::Error> { - Ok(Self { - response: Ok(RefundsResponseData { - connector_refund_id: item.response.id.to_string(), - refund_status: enums::RefundStatus::from(item.response.status), + let response = match item + .response + .application_information + .and_then(|application_information| application_information.status) + { + Some(status) => { + let error_reason = item + .response + .error_information + .clone() + .and_then(|error_info| error_info.reason); + let refund_status = match status { + BarclaycardRefundStatus::Succeeded | BarclaycardRefundStatus::Transmitted => { + enums::RefundStatus::Success + } + BarclaycardRefundStatus::Cancelled + | BarclaycardRefundStatus::Failed + | BarclaycardRefundStatus::Voided => enums::RefundStatus::Failure, + BarclaycardRefundStatus::Pending => enums::RefundStatus::Pending, + BarclaycardRefundStatus::TwoZeroOne => { + if error_reason == Some("PROCESSOR_DECLINED".to_string()) { + enums::RefundStatus::Failure + } else { + enums::RefundStatus::Pending + } + } + }; + if utils::is_refund_failure(refund_status) { + if status == BarclaycardRefundStatus::Voided { + Err(get_error_response( + &Some(BarclaycardErrorInformation { + message: Some(constants::REFUND_VOIDED.to_string()), + reason: Some(constants::REFUND_VOIDED.to_string()), + details: None, + }), + &None, + &None, + None, + item.http_code, + item.response.id.clone(), + )) + } else { + Err(get_error_response( + &item.response.error_information, + &None, + &None, + None, + item.http_code, + item.response.id.clone(), + )) + } + } else { + Ok(RefundsResponseData { + connector_refund_id: item.response.id, + refund_status, + }) + } + } + + None => Ok(RefundsResponseData { + connector_refund_id: item.response.id.clone(), + refund_status: match item.data.response { + Ok(response) => response.refund_status, + Err(_) => common_enums::RefundStatus::Pending, + }, }), + }; + + Ok(Self { + response, ..item.data }) } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] -pub struct BarclaycardErrorResponse { - pub status_code: u16, - pub code: String, - pub message: String, +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BarclaycardStandardErrorResponse { + pub error_information: Option<ErrorInformation>, + pub status: Option<String>, + pub message: Option<String>, pub reason: Option<String>, + pub details: Option<Vec<Details>>, +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BarclaycardServerErrorResponse { + pub status: Option<String>, + pub message: Option<String>, + pub reason: Option<Reason>, +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum Reason { + SystemError, + ServerTimeout, + ServiceTimeout, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct BarclaycardAuthenticationErrorResponse { + pub response: AuthenticationErrorInformation, +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(untagged)] +pub enum BarclaycardErrorResponse { + AuthenticationError(BarclaycardAuthenticationErrorResponse), + StandardError(BarclaycardStandardErrorResponse), +} + +#[derive(Debug, Deserialize, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Details { + pub field: String, + pub reason: String, +} + +#[derive(Debug, Default, Deserialize, Serialize)] +pub struct ErrorInformation { + pub message: String, + pub reason: String, + pub details: Option<Vec<Details>>, +} + +#[derive(Debug, Default, Deserialize, Serialize)] +pub struct AuthenticationErrorInformation { + pub rmsg: String, +} + +fn get_error_response( + error_data: &Option<BarclaycardErrorInformation>, + processor_information: &Option<ClientProcessorInformation>, + risk_information: &Option<ClientRiskInformation>, + attempt_status: Option<enums::AttemptStatus>, + status_code: u16, + transaction_id: String, +) -> ErrorResponse { + let avs_message = risk_information + .clone() + .map(|client_risk_information| { + client_risk_information.rules.map(|rules| { + rules + .iter() + .map(|risk_info| { + risk_info.name.clone().map_or("".to_string(), |name| { + format!(" , {}", name.clone().expose()) + }) + }) + .collect::<Vec<String>>() + .join("") + }) + }) + .unwrap_or(Some("".to_string())); + + let detailed_error_info = error_data.to_owned().and_then(|error_info| { + error_info.details.map(|error_details| { + error_details + .iter() + .map(|details| format!("{} : {}", details.field, details.reason)) + .collect::<Vec<_>>() + .join(", ") + }) + }); + let network_decline_code = processor_information + .as_ref() + .and_then(|info| info.response_code.clone()); + let network_advice_code = processor_information.as_ref().and_then(|info| { + info.merchant_advice + .as_ref() + .and_then(|merchant_advice| merchant_advice.code_raw.clone()) + }); + + let reason = get_error_reason( + error_data + .clone() + .and_then(|error_details| error_details.message), + detailed_error_info, + avs_message, + ); + let error_message = error_data + .clone() + .and_then(|error_details| error_details.reason); + + ErrorResponse { + code: error_message + .clone() + .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()), + message: error_message + .clone() + .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()), + reason, + status_code, + attempt_status, + connector_transaction_id: Some(transaction_id.clone()), + network_advice_code, + network_decline_code, + network_error_message: None, + } +} + +impl TryFrom<&hyperswitch_domain_models::payment_method_data::Card> for PaymentInformation { + type Error = error_stack::Report<errors::ConnectorError>; + + fn try_from( + ccard: &hyperswitch_domain_models::payment_method_data::Card, + ) -> Result<Self, Self::Error> { + let card_type = match ccard + .card_network + .clone() + .and_then(get_barclaycard_card_type) + { + Some(card_network) => Some(card_network.to_string()), + None => ccard.get_card_issuer().ok().map(String::from), + }; + Ok(Self::Cards(Box::new(CardPaymentInformation { + card: Card { + number: ccard.card_number.clone(), + expiration_month: ccard.card_exp_month.clone(), + expiration_year: ccard.card_exp_year.clone(), + security_code: ccard.card_cvc.clone(), + card_type, + }, + }))) + } +} + +fn get_commerce_indicator(network: Option<String>) -> String { + match network { + Some(card_network) => match card_network.to_lowercase().as_str() { + "amex" => "aesk", + "discover" => "dipb", + "mastercard" => "spa", + "visa" => "internet", + _ => "internet", + }, + None => "internet", + } + .to_string() +} + +pub fn get_error_reason( + error_info: Option<String>, + detailed_error_info: Option<String>, + avs_error_info: Option<String>, +) -> Option<String> { + match (error_info, detailed_error_info, avs_error_info) { + (Some(message), Some(details), Some(avs_message)) => Some(format!( + "{}, detailed_error_information: {}, avs_message: {}", + message, details, avs_message + )), + (Some(message), Some(details), None) => Some(format!( + "{}, detailed_error_information: {}", + message, details + )), + (Some(message), None, Some(avs_message)) => { + Some(format!("{}, avs_message: {}", message, avs_message)) + } + (None, Some(details), Some(avs_message)) => { + Some(format!("{}, avs_message: {}", details, avs_message)) + } + (Some(message), None, None) => Some(message), + (None, Some(details), None) => Some(details), + (None, None, Some(avs_message)) => Some(avs_message), + (None, None, None) => None, + } } diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 860d82ab487..8e31533d5f9 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1379,10 +1379,10 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> { bankofamerica::transformers::BankOfAmericaAuthType::try_from(self.auth_type)?; Ok(()) } - // api_enums::Connector::Barclaycard => { - // barclaycard::transformers::BarclaycardAuthType::try_from(self.auth_type)?; - // Ok(()) - // }, + api_enums::Connector::Barclaycard => { + barclaycard::transformers::BarclaycardAuthType::try_from(self.auth_type)?; + Ok(()) + } api_enums::Connector::Billwerk => { billwerk::transformers::BillwerkAuthType::try_from(self.auth_type)?; Ok(()) diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 25e6fde8b33..8592753ae91 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -352,9 +352,9 @@ impl ConnectorData { enums::Connector::Bankofamerica => { Ok(ConnectorEnum::Old(Box::new(&connector::Bankofamerica))) } - // enums::Connector::Barclaycard => { - // Ok(ConnectorEnum::Old(Box::new(connector::Barclaycard))) - // } + enums::Connector::Barclaycard => { + Ok(ConnectorEnum::Old(Box::new(&connector::Barclaycard))) + } enums::Connector::Billwerk => { Ok(ConnectorEnum::Old(Box::new(connector::Billwerk::new()))) } diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index e2ff8e3941e..566c9d83961 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -219,7 +219,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { api_enums::Connector::Bambora => Self::Bambora, api_enums::Connector::Bamboraapac => Self::Bamboraapac, api_enums::Connector::Bankofamerica => Self::Bankofamerica, - // api_enums::Connector::Barclaycard => Self::Barclaycard, + api_enums::Connector::Barclaycard => Self::Barclaycard, api_enums::Connector::Billwerk => Self::Billwerk, api_enums::Connector::Bitpay => Self::Bitpay, api_enums::Connector::Bluesnap => Self::Bluesnap, diff --git a/crates/router/tests/connectors/barclaycard.rs b/crates/router/tests/connectors/barclaycard.rs index 2087131c4e6..c2c21bbcc08 100644 --- a/crates/router/tests/connectors/barclaycard.rs +++ b/crates/router/tests/connectors/barclaycard.rs @@ -11,7 +11,7 @@ impl utils::Connector for BarclaycardTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Barclaycard; utils::construct_connector_data_old( - Box::new(Barclaycard::new()), + Box::new(&Barclaycard), types::Connector::DummyConnector1, api::GetToken::Connector, None, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index d3edab05109..06f967fba7c 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -86,7 +86,7 @@ authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api" bambora.base_url = "https://api.na.bambora.com" bamboraapac.base_url = "https://demo.ippayments.com.au/interface/api" bankofamerica.base_url = "https://apitest.merchant-services.bankofamerica.com/" -barclaycard.base_url = "https://api.smartpayfuse-test.barclaycard/pts/v2/" +barclaycard.base_url = "https://api.smartpayfuse-test.barclaycard/" billwerk.base_url = "https://api.reepay.com/" billwerk.secondary_base_url = "https://card.reepay.com/" bitpay.base_url = "https://test.bitpay.com"
2025-05-19T04:39:22Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD Closes this [issue](https://github.com/juspay/hyperswitch/issues/8067) ## Description <!-- Describe your changes in detail --> Added Authorize, Capture, Void, Refund, PSync and RSync flow for cards payment method for Barclaycard. Also added connector specifications for the same connector. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Postman Tests 1. Payment Connector - Create Request: ``` curl --location 'http://localhost:8080/account/merchant_1747726068/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: ••••••' \ --data '{ "connector_type": "payment_processor", "connector_name": "barclaycard", "connector_account_details": { "auth_type": auth_type, "api_secret": api_secret, "api_key": api_key, "key1": key1 }, "test_mode": false, "disabled": false, "business_country": "US", "business_label": "default", "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "debit", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ] }' ``` Response: ``` { "connector_type": "payment_processor", "connector_name": "barclaycard", "connector_label": "barclaycard_US_default", "merchant_connector_id": "mca_BSrgu17zDqS7EXYvqz9O", "profile_id": "pro_pehtYfNAEJUejck1GkP6", "connector_account_details": { "auth_type": auth_type, "api_key": "************************************", "key1": "*****************", "api_secret": "********************************************" }, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "debit", "payment_experience": null, "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "connector_webhook_details": null, "metadata": null, "test_mode": false, "disabled": false, "frm_configs": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "applepay_verified_domains": null, "pm_auth_config": null, "status": "active", "additional_merchant_data": null, "connector_wallets_details": null } ``` 2. Payments - Create Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: api-key' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "customer_123", "email": "[email protected]", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4347699988887777", "card_exp_month": "1", "card_exp_year": "26", "card_holder_name": "joseph Doe", "card_cvc": "555" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country":"US", "first_name": "PiX" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "128.0.0.1" } }' ``` Response: ``` { "payment_id": "pay_U1YF8Oy30dykRHfSzRLz", "merchant_id": "merchant_1747726068", "status": "succeeded", "amount": 6540, "net_amount": 6540, "shipping_cost": null, "amount_capturable": 0, "amount_received": 6540, "connector": "barclaycard", "client_secret": "pay_U1YF8Oy30dykRHfSzRLz_secret_9BQZ2PGg3e7ZIeIT6BAq", "created": "2025-05-20T07:31:28.562Z", "currency": "USD", "customer_id": "customer_123", "customer": { "id": "customer_123", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "7777", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "434769", "card_extended_bin": null, "card_exp_month": "1", "card_exp_year": "26", "card_holder_name": "joseph Doe", "payment_checks": { "eci": null, "cavv": null, "eci_raw": null, "avs_response": { "code": "Y", "codeRaw": "Y" }, "approval_code": "831000", "card_verification": { "resultCode": "M", "resultCodeRaw": "M" }, "consumer_authentication_response": { "code": "2", "codeRaw": "2" } }, "authentication_data": { "acs_transaction_id": null, "system_trace_audit_number": "149277", "retrieval_reference_number": "514007149277" } }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": null, "phone": null, "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "customer_123", "created_at": 1747726288, "expires": 1747729888, "secret": "epk_8d2cca87e0544416b980cee5bb5a1ab3" }, "manual_retry_allowed": false, "connector_transaction_id": "7477262936786891604805", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_U1YF8Oy30dykRHfSzRLz_1", "payment_link": null, "profile_id": "pro_pehtYfNAEJUejck1GkP6", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_BSrgu17zDqS7EXYvqz9O", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-05-20T07:46:28.562Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "128.0.0.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-05-20T07:31:34.524Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": null } ``` 3. Payments - Retrieve Request: ``` curl --location 'http://localhost:8080/payments/pay_U1YF8Oy30dykRHfSzRLz?expand_captures=true&expand_attempts=true&all_keys_required=true&force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_zH1HhEd5Y4Nybo7VUkUC55IO7p9hNkJPiSSuBTBuLLWzhn7CsNdR5jZEyXzP41b1' ``` Response: ``` { "payment_id": "pay_U1YF8Oy30dykRHfSzRLz", "merchant_id": "merchant_1747726068", "status": "succeeded", "amount": 6540, "net_amount": 6540, "shipping_cost": null, "amount_capturable": 0, "amount_received": 6540, "connector": "barclaycard", "client_secret": "pay_U1YF8Oy30dykRHfSzRLz_secret_9BQZ2PGg3e7ZIeIT6BAq", "created": "2025-05-20T07:31:28.562Z", "currency": "USD", "customer_id": "customer_123", "customer": { "id": "customer_123", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": "Its my first payment request", "refunds": null, "disputes": null, "attempts": [ { "attempt_id": "pay_U1YF8Oy30dykRHfSzRLz_1", "status": "charged", "amount": 6540, "order_tax_amount": null, "currency": "USD", "connector": "barclaycard", "error_message": null, "payment_method": "card", "connector_transaction_id": "7477262936786891604805", "capture_method": "automatic", "authentication_type": "no_three_ds", "created_at": "2025-05-20T07:31:28.562Z", "modified_at": "2025-05-20T07:31:34.524Z", "cancellation_reason": null, "mandate_id": null, "error_code": null, "payment_token": null, "connector_metadata": null, "payment_experience": null, "payment_method_type": null, "reference_id": "pay_U1YF8Oy30dykRHfSzRLz_1", "unified_code": null, "unified_message": null, "client_source": null, "client_version": null } ], "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "7777", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "434769", "card_extended_bin": null, "card_exp_month": "1", "card_exp_year": "26", "card_holder_name": "joseph Doe", "payment_checks": { "eci": null, "cavv": null, "eci_raw": null, "avs_response": { "code": "Y", "codeRaw": "Y" }, "approval_code": "831000", "card_verification": { "resultCode": "M", "resultCodeRaw": "M" }, "consumer_authentication_response": { "code": "2", "codeRaw": "2" } }, "authentication_data": { "acs_transaction_id": null, "system_trace_audit_number": "149277", "retrieval_reference_number": "514007149277" } }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": null, "phone": null, "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "7477262936786891604805", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_U1YF8Oy30dykRHfSzRLz_1", "payment_link": null, "profile_id": "pro_pehtYfNAEJUejck1GkP6", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_BSrgu17zDqS7EXYvqz9O", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-05-20T07:46:28.562Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "128.0.0.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-05-20T07:33:57.427Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null, "whole_connector_response": "{\"id\":\"7477262936786891604805\",\"rootId\":\"7477262936786891604805\",\"reconciliationId\":\"7477262936786891604805\",\"submitTimeUTC\":\"2025-05-20T07:31:33Z\",\"merchantId\":\"juspay_us_sandbox\",\"applicationInformation\":{\"status\":\"PENDING\",\"reasonCode\":100,\"applications\":[{\"name\":\"ics_auth\",\"reasonCode\":\"100\",\"rCode\":\"1\",\"rFlag\":\"SOK\",\"reconciliationId\":\"7477262936786891604805\",\"rMessage\":\"Request was processed successfully.\",\"returnCode\":1010000},{\"name\":\"ics_bill\",\"status\":\"PENDING\",\"reasonCode\":\"100\",\"rCode\":\"1\",\"rFlag\":\"SOK\",\"reconciliationId\":\"7477262936786891604805\",\"rMessage\":\"Request was processed successfully.\",\"returnCode\":1260000},{\"name\":\"ics_decision\",\"reasonCode\":\"100\",\"rCode\":\"1\",\"rFlag\":\"SOK\",\"rMessage\":\"Service processed successfully\",\"returnCode\":1320000},{\"name\":\"ics_decision_early\",\"reasonCode\":\"100\",\"rCode\":\"1\",\"returnCode\":9999999}]},\"buyerInformation\":{},\"clientReferenceInformation\":{\"code\":\"pay_U1YF8Oy30dykRHfSzRLz_1\",\"applicationName\":\"REST API\",\"applicationVersion\":\"1.0\",\"partner\":{}},\"consumerAuthenticationInformation\":{\"eciRaw\":\"7\",\"strongAuthentication\":{}},\"deviceInformation\":{},\"errorInformation\":{\"message\":\"Request was processed successfully.\"},\"installmentInformation\":{},\"fraudMarkingInformation\":{},\"merchantDefinedInformation\":[{\"key\":\"1\",\"value\":\"login_date=\\\"2019-09-10T10:11:12Z\\\"\"},{\"key\":\"2\",\"value\":\"new_customer=\\\"true\\\"\"},{\"key\":\"3\",\"value\":\"udf1=\\\"value1\\\"\"}],\"merchantInformation\":{\"merchantDescriptor\":{\"name\":\"juspay_us_sandbox\"}},\"orderInformation\":{\"billTo\":{\"firstName\":\"JOSEPH\",\"lastName\":\"DOE\",\"address1\":\"1467\",\"locality\":\"San Fransico\",\"administrativeArea\":\"CA\",\"postalCode\":\"94122\",\"email\":\"[email protected]\",\"country\":\"US\"},\"shipTo\":{},\"amountDetails\":{\"totalAmount\":\"65.4\",\"currency\":\"USD\",\"taxAmount\":\"0\",\"authorizedAmount\":\"65.4\"},\"shippingDetails\":{},\"invoiceDetails\":{},\"lineItems\":[{\"productCode\":\"default\",\"taxAmount\":0,\"quantity\":1,\"unitPrice\":65.4}]},\"paymentInformation\":{\"customer\":{},\"paymentInstrument\":{},\"instrumentIdentifier\":{},\"shippingAddress\":{},\"paymentType\":{\"name\":\"vdcvantiv\",\"type\":\"credit card\",\"method\":\"VI\"},\"card\":{\"suffix\":\"7777\",\"prefix\":\"434769\",\"expirationMonth\":\"1 \",\"expirationYear\":\"26 \",\"type\":\"001\"},\"invoice\":{},\"accountFeatures\":{},\"fluidData\":{},\"issuerInformation\":{\"country\":\"US\"},\"paymentAccountInformation\":{\"card\":{},\"features\":{},\"network\":{}}},\"paymentInsightsInformation\":{\"responseInsights\":{},\"ruleResults\":{}},\"payoutInformation\":{\"pushFunds\":{},\"pullFunds\":{}},\"payoutOptions\":{},\"processingInformation\":{\"paymentSolution\":\"Visa\",\"commerceIndicator\":\"7\",\"commerceIndicatorLabel\":\"internet\",\"authorizationOptions\":{\"authType\":\"O\",\"initiator\":{\"merchantInitiatedTransaction\":{}},\"cardVerificationIndicator\":false},\"bankTransferOptions\":{},\"japanPaymentOptions\":{},\"fundingOptions\":{\"firstRecurringPayment\":false},\"ecommerceIndicator\":\"7\",\"reconciliationId\":\"7477262936786891604805\",\"captureOptions\":{}},\"processorInformation\":{\"processor\":{\"name\":\"vdcvantiv\"},\"networkTransactionId\":\"016153570198200\",\"approvalCode\":\"831000\",\"responseCode\":\"00\",\"avs\":{\"code\":\"Y\",\"codeRaw\":\"Y\"},\"cardVerification\":{\"resultCode\":\"M\"},\"achVerification\":{\"resultCodeRaw\":\"00\"},\"electronicVerificationResults\":{},\"systemTraceAuditNumber\":\"149277\",\"eventStatus\":\"Pending\",\"retrievalReferenceNumber\":\"514007149277\"},\"pointOfSaleInformation\":{},\"riskInformation\":{\"profile\":{\"name\":\"Standard mid-market profile\",\"decision\":\"ACCEPT\"},\"rules\":[{\"name\":\"Fraud Score - Monitor\",\"decision\":\"IGNORE\"},{\"name\":\"Fraud Score - Reject\",\"decision\":\"IGNORE\"},{\"name\":\"Fraud Score - Review\",\"decision\":\"IGNORE\"},{\"name\":\"Invalid Address\",\"decision\":\"IGNORE\"}],\"score\":{\"factorCodes\":[\"H\",\"P\"],\"result\":3}},\"recipientInformation\":{},\"senderInformation\":{\"account\":{},\"paymentInformation\":{\"customer\":{},\"paymentType\":{\"name\":\"vdcvantiv\",\"type\":\"credit card\",\"method\":\"VI\"},\"card\":{\"suffix\":\"7777\",\"expirationMonth\":\"1 \",\"expirationYear\":\"26 \",\"type\":\"001\"},\"invoice\":{},\"accountFeatures\":{},\"fluidData\":{},\"issuerInformation\":{},\"paymentAccountInformation\":{}}},\"tokenInformation\":{},\"_links\":{\"self\":{\"href\":\"https://api.smartpayfuse-test.barclaycard/tss/v2/transactions/7477262936786891604805\",\"method\":\"GET\"}},\"recurringPaymentInformation\":{},\"unscheduledPaymentInformation\":{}}" } ``` 4. Refunds - Create Request: ``` curl --location 'http://localhost:8080/refunds' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: api-key' \ --data '{ "payment_id": "pay_U1YF8Oy30dykRHfSzRLz", "amount": 6540, "reason": "Customer returned product", "refund_type": "instant" }' ``` Response: ``` { "refund_id": "ref_9KXjMEdZ4PZDcFWAwNmC", "payment_id": "pay_U1YF8Oy30dykRHfSzRLz", "amount": 6540, "currency": "USD", "status": "pending", "reason": "Customer returned product", "metadata": null, "error_message": null, "error_code": null, "unified_code": null, "unified_message": null, "created_at": "2025-05-20T07:35:51.909Z", "updated_at": "2025-05-20T07:35:53.786Z", "connector": "barclaycard", "profile_id": "pro_pehtYfNAEJUejck1GkP6", "merchant_connector_id": "mca_BSrgu17zDqS7EXYvqz9O", "split_refunds": null, "issuer_error_code": null, "issuer_error_message": null } ``` 5. Refunds - Retrieve Request: ``` curl --location 'http://localhost:8080/refunds/ref_9KXjMEdZ4PZDcFWAwNmC' \ --header 'Accept: application/json' \ --header 'api-key: api-key' ``` Response: ``` { "refund_id": "ref_9KXjMEdZ4PZDcFWAwNmC", "payment_id": "pay_U1YF8Oy30dykRHfSzRLz", "amount": 6540, "currency": "USD", "status": "pending", "reason": "Customer returned product", "metadata": null, "error_message": null, "error_code": null, "unified_code": null, "unified_message": null, "created_at": "2025-05-20T07:35:51.909Z", "updated_at": "2025-05-20T07:37:20.756Z", "connector": "barclaycard", "profile_id": "pro_pehtYfNAEJUejck1GkP6", "merchant_connector_id": "mca_BSrgu17zDqS7EXYvqz9O", "split_refunds": null, "issuer_error_code": null, "issuer_error_message": null } ``` 6. Feature Matrix Request: ``` curl --location 'http://localhost:8080/feature_matrix' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: api-key' ``` Response: ``` { "connector_count": 1, "connectors": [ { "name": "BARCLAYCARD", "display_name": "BarclayCard SmartPay Fuse", "description": "Barclaycard, part of Barclays Bank UK PLC, is a leading global payment business that helps consumers, retailers and businesses to make and take payments flexibly, and to access short-term credit and point of sale finance.", "category": "bank_acquirer", "supported_payment_methods": [ { "payment_method": "card", "payment_method_type": "credit", "payment_method_type_display_name": "Credit Card", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "not_supported", "no_three_ds": "supported", "supported_card_networks": [ "Mastercard", "Visa", "AmericanExpress", "JCB", "Discover", "Maestro", "Interac", "DinersClub", "CartesBancaires", "UnionPay" ], "supported_countries": null, "supported_currencies": null, }, { "payment_method": "card", "payment_method_type": "debit", "payment_method_type_display_name": "Debit Card", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "three_ds": "not_supported", "no_three_ds": "supported", "supported_card_networks": [ "Mastercard", "Visa", "AmericanExpress", "JCB", "Discover", "Maestro", "Interac", "DinersClub", "CartesBancaires", "UnionPay" ], "supported_countries": null, "supported_currencies": null, } ], "supported_webhook_flows": [] } ] } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
3a451907a45035e40a04c335531a5b69414b3e04
3a451907a45035e40a04c335531a5b69414b3e04
juspay/hyperswitch
juspay__hyperswitch-8064
Bug: [CHORE] FIX TYPOS IN THE REPO Its been months since the typos in the repo being unaddressed. This has resulted in negligence leading to even more typos being introduced.
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 00e3e7bc4ff..956d6d6697c 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -9017,7 +9017,7 @@ ], "nullable": true }, - "encypted_payload": { + "encrypted_payload": { "type": "string", "description": "Encrypted payload", "nullable": true diff --git a/api-reference/hyperswitch_intelligent_router_open_api_spec.yml b/api-reference/hyperswitch_intelligent_router_open_api_spec.yml index 341bcc6d209..58bff737f3e 100644 --- a/api-reference/hyperswitch_intelligent_router_open_api_spec.yml +++ b/api-reference/hyperswitch_intelligent_router_open_api_spec.yml @@ -579,7 +579,7 @@ paths: /euclid.EuclidService/Evaluate: post: operationId: EvaluateRule - summary: Evaludate an existing routing Rule + summary: Evaluate an existing routing Rule description: Evaluates a given routing rule tags: - Static Routing diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index d7f3cd41808..5eb85a6a059 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -10970,7 +10970,7 @@ ], "nullable": true }, - "encypted_payload": { + "encrypted_payload": { "type": "string", "description": "Encrypted payload", "nullable": true diff --git a/config/dashboard.toml b/config/dashboard.toml index e6763b6bb60..33a32696621 100644 --- a/config/dashboard.toml +++ b/config/dashboard.toml @@ -66,7 +66,7 @@ dev_intelligent_routing_v2=false dev_modularity_v2=false dev_alt_payment_methods=false dev_hypersense_v2_product=false -maintainence_alert="" +maintenance_alert="" [default.merchant_config] [default.merchant_config.new_analytics] diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 5286f071a1a..fd150d0fda3 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1183,7 +1183,7 @@ pub struct CtpServiceDetails { pub provider: Option<api_enums::CtpServiceProvider>, /// Encrypted payload #[schema(value_type = Option<String>)] - pub encypted_payload: Option<Secret<String>>, + pub encrypted_payload: Option<Secret<String>>, } impl CtpServiceDetails { diff --git a/crates/common_types/src/payment_methods.rs b/crates/common_types/src/payment_methods.rs index 4b05c3747eb..fc52b807dba 100644 --- a/crates/common_types/src/payment_methods.rs +++ b/crates/common_types/src/payment_methods.rs @@ -29,7 +29,7 @@ pub struct PaymentMethodsEnabled { pub payment_method_subtypes: Option<Vec<RequestPaymentMethodTypes>>, } -// Custom FromSql implmentation to handle deserialization of v1 data format +// Custom FromSql implementation to handle deserialization of v1 data format impl FromSql<Json, diesel::pg::Pg> for PaymentMethodsEnabled { fn from_sql(bytes: <diesel::pg::Pg as Backend>::RawValue<'_>) -> deserialize::Result<Self> { let helper: PaymentMethodsEnabledHelper = serde_json::from_slice(bytes.as_bytes()) diff --git a/crates/common_utils/src/macros.rs b/crates/common_utils/src/macros.rs index 8dcffbb6643..dd736d0af3f 100644 --- a/crates/common_utils/src/macros.rs +++ b/crates/common_utils/src/macros.rs @@ -463,9 +463,9 @@ macro_rules! type_name { /// * **Invalid:** `VariantA(i32)` (tuple variant) /// * **Invalid:** `VariantA` or `VariantA {}` (no field) /// * **Invalid:** `VariantA { value: i32, other: bool }` (multiple fields) -/// 4. **Tag Delimiter:** The macro invocation must specify a `tag_delimeter` literal, +/// 4. **Tag Delimiter:** The macro invocation must specify a `tag_delimiter` literal, /// which is the character used to separate the variant name from the field data in -/// the string representation (e.g., `tag_delimeter = ":",`). +/// the string representation (e.g., `tag_delimiter = ":",`). /// 5. **Field Type Requirements:** The type of the single field in each variant (`$field_ty`) /// must implement: /// * `core::str::FromStr`: To parse the field's data from the string part. @@ -484,7 +484,7 @@ macro_rules! type_name { /// When `serde` features are enabled and the necessary traits are derived or implemented, /// this macro implements `Serialize` and `Deserialize` for the enum: /// -/// **Serialization:** An enum value like `MyEnum::VariantA { value: 123 }` (with `tag_delimeter = ":",`) +/// **Serialization:** An enum value like `MyEnum::VariantA { value: 123 }` (with `tag_delimiter = ":",`) /// will be serialized into the string `"VariantA:123"`. If serializing to JSON, this results /// in a JSON string: `"\"VariantA:123\""`. /// **Deserialization:** The macro expects a string matching the format `"VariantName<delimiter>FieldValue"`. @@ -503,7 +503,7 @@ macro_rules! type_name { /// use std::str::FromStr; /// /// crate::impl_enum_str!( -/// tag_delimeter = ":", +/// tag_delimiter = ":", /// #[derive(Debug, PartialEq, Clone)] // Add other derives as needed /// pub enum Setting { /// Timeout { duration_ms: u32 }, @@ -554,7 +554,7 @@ macro_rules! type_name { #[macro_export] macro_rules! impl_enum_str { ( - tag_delimeter = $tag_delim:literal, + tag_delimiter = $tag_delim:literal, $(#[$enum_attr:meta])* pub enum $enum_name:ident { $( @@ -701,7 +701,7 @@ mod tests { use crate::impl_enum_str; impl_enum_str!( - tag_delimeter = ":", + tag_delimiter = ":", #[derive(Debug, PartialEq, Clone)] pub enum TestEnum { VariantA { value: i32 }, diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs index 40b37b6b3c5..1ff0dcb20ba 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -1364,7 +1364,7 @@ where } impl_enum_str!( - tag_delimeter = ":", + tag_delimiter = ":", /// CreatedBy conveys the information about the creator (identifier) as well as the origin or /// trigger (Api, Jwt) of the record. #[derive(Eq, PartialEq, Debug, Clone)] diff --git a/crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs b/crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs index e74715535a0..4c4e766f450 100644 --- a/crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs @@ -2038,7 +2038,7 @@ pub struct DisputeEvidence { pub(crate) fn get_dispute_stage(code: &str) -> Result<enums::DisputeStage, errors::ConnectorError> { match code { "CHARGEBACK" => Ok(enums::DisputeStage::Dispute), - "PRE_ARBITATION" => Ok(enums::DisputeStage::PreArbitration), + "PRE_ARBITRATION" => Ok(enums::DisputeStage::PreArbitration), "RETRIEVAL" => Ok(enums::DisputeStage::PreDispute), _ => Err(errors::ConnectorError::WebhookBodyDecodingFailed), } diff --git a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs index 343fb99009d..367f800a1d4 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs @@ -1458,7 +1458,7 @@ impl TryFrom<FiuuSyncStatus> for enums::AttemptStatus { match (sync_status.stat_code, sync_status.stat_name) { (StatCode::Success, StatName::Captured | StatName::Settled) => Ok(Self::Charged), // For Success as StatCode we can only expect Captured,Settled and Authorized as StatName. (StatCode::Success, StatName::Authorized) => Ok(Self::Authorized), - (StatCode::Pending, StatName::Pending) => Ok(Self::AuthenticationPending), // For Pending as StatCode we can only expect Pending and Unknow as StatName. + (StatCode::Pending, StatName::Pending) => Ok(Self::AuthenticationPending), // For Pending as StatCode we can only expect Pending and Unknown as StatName. (StatCode::Pending, StatName::Unknown) => Ok(Self::Pending), (StatCode::Failure, StatName::Cancelled) | (StatCode::Failure, StatName::ReqCancel) => { Ok(Self::Voided) @@ -1897,7 +1897,7 @@ pub enum FiuuWebhooksRefundType { } #[derive(Debug, Deserialize, Serialize, Clone)] -pub struct FiuuWebhookSignauture { +pub struct FiuuWebhookSignature { pub skey: Secret<String>, } diff --git a/crates/hyperswitch_connectors/src/connectors/recurly.rs b/crates/hyperswitch_connectors/src/connectors/recurly.rs index 02dea67d9b9..bb7ea02a931 100644 --- a/crates/hyperswitch_connectors/src/connectors/recurly.rs +++ b/crates/hyperswitch_connectors/src/connectors/recurly.rs @@ -52,7 +52,7 @@ const STATUS_FAILED_ENDPOINT: &str = "mark_failed"; const RECURLY_API_VERSION: &str = "application/vnd.recurly.v2021-02-25"; -// We don't need an amount converter beacuse we are not using it anywhere in code, but it's important to note that Float Major Unit is the standard format used by Recurly. +// We don't need an amount converter because we are not using it anywhere in code, but it's important to note that Float Major Unit is the standard format used by Recurly. #[derive(Clone)] pub struct Recurly { // amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync), diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay/response.rs b/crates/hyperswitch_connectors/src/connectors/worldpay/response.rs index bb0ead48caf..e0cf0d3bff8 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldpay/response.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldpay/response.rs @@ -199,7 +199,7 @@ pub struct ActionLinks { settle_payment: Option<ActionLink>, partially_settle_payment: Option<ActionLink>, refund_payment: Option<ActionLink>, - partiall_refund_payment: Option<ActionLink>, + partially_refund_payment: Option<ActionLink>, cancel_payment: Option<ActionLink>, } diff --git a/crates/hyperswitch_domain_models/src/router_request_types/unified_authentication_service.rs b/crates/hyperswitch_domain_models/src/router_request_types/unified_authentication_service.rs index 40237a1daca..5c2435881e0 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types/unified_authentication_service.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types/unified_authentication_service.rs @@ -21,7 +21,7 @@ pub struct AuthenticationInfo { pub is_authenticated: bool, pub locale: Option<String>, pub supported_card_brands: Option<String>, - pub encypted_payload: Option<Secret<String>>, + pub encrypted_payload: Option<Secret<String>>, } #[derive(Clone, Debug)] pub struct UasAuthenticationRequestData { diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 702b81f9720..ca42f81a1ac 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -214,7 +214,7 @@ pub async fn initiate_pm_collect_link( ) .await?; - // Create DB entrie + // Create DB entry let pm_collect_link = create_pm_collect_db_entry( &state, &merchant_context, diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index bfe7f7962d2..4c3894d5d37 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -8287,7 +8287,7 @@ pub trait OperationSessionSetters<F> { fn set_card_network(&mut self, card_network: enums::CardNetwork); fn set_co_badged_card_data( &mut self, - debit_routing_ouput: &api_models::open_router::DebitRoutingOutput, + debit_routing_output: &api_models::open_router::DebitRoutingOutput, ); #[cfg(feature = "v1")] fn set_capture_method_in_attempt(&mut self, capture_method: enums::CaptureMethod); @@ -8538,11 +8538,11 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentData<F> { fn set_co_badged_card_data( &mut self, - debit_routing_ouput: &api_models::open_router::DebitRoutingOutput, + debit_routing_output: &api_models::open_router::DebitRoutingOutput, ) { let co_badged_card_data = - api_models::payment_methods::CoBadgedCardData::from(debit_routing_ouput); - let card_type = debit_routing_ouput + api_models::payment_methods::CoBadgedCardData::from(debit_routing_output); + let card_type = debit_routing_output .card_type .clone() .to_string() @@ -8793,7 +8793,7 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentIntentData<F> { fn set_co_badged_card_data( &mut self, - debit_routing_ouput: &api_models::open_router::DebitRoutingOutput, + debit_routing_output: &api_models::open_router::DebitRoutingOutput, ) { todo!() } @@ -9052,7 +9052,7 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentConfirmData<F> { fn set_co_badged_card_data( &mut self, - debit_routing_ouput: &api_models::open_router::DebitRoutingOutput, + debit_routing_output: &api_models::open_router::DebitRoutingOutput, ) { todo!() } @@ -9283,7 +9283,7 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentStatusData<F> { fn set_co_badged_card_data( &mut self, - debit_routing_ouput: &api_models::open_router::DebitRoutingOutput, + debit_routing_output: &api_models::open_router::DebitRoutingOutput, ) { todo!() } @@ -9524,7 +9524,7 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentCaptureData<F> { fn set_co_badged_card_data( &mut self, - debit_routing_ouput: &api_models::open_router::DebitRoutingOutput, + debit_routing_output: &api_models::open_router::DebitRoutingOutput, ) { todo!() } diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index 241a189d68d..a7d8fecfe87 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -617,7 +617,7 @@ pub fn make_new_payment_attempt( old_payment_attempt: storage::PaymentAttempt, new_attempt_count: i16, is_step_up: bool, - setup_futture_usage_intent: Option<storage_enums::FutureUsage>, + setup_future_usage_intent: Option<storage_enums::FutureUsage>, ) -> storage::PaymentAttemptNew { let created_at @ modified_at @ last_synced = Some(common_utils::date_time::now()); storage::PaymentAttemptNew { @@ -688,7 +688,7 @@ pub fn make_new_payment_attempt( card_discovery: old_payment_attempt.card_discovery, processor_merchant_id: old_payment_attempt.processor_merchant_id, created_by: old_payment_attempt.created_by, - setup_future_usage_applied: setup_futture_usage_intent, // setup future usage is picked from intent for new payment attempt + setup_future_usage_applied: setup_future_usage_intent, // setup future usage is picked from intent for new payment attempt } } diff --git a/crates/router/src/core/revenue_recovery.rs b/crates/router/src/core/revenue_recovery.rs index d6091d8aa1a..9eb57c4503a 100644 --- a/crates/router/src/core/revenue_recovery.rs +++ b/crates/router/src/core/revenue_recovery.rs @@ -161,7 +161,7 @@ pub async fn perform_execute_payment( types::Decision::ReviewForFailedPayment(triggered_by) => { match triggered_by { enums::TriggeredBy::Internal => { - // requeue the current taks to update the fields for rescheduling a payment + // requeue the current tasks to update the fields for rescheduling a payment let pt_update = storage::ProcessTrackerUpdate::StatusUpdate { status: enums::ProcessTrackerStatus::Pending, business_status: Some(String::from( diff --git a/crates/router/src/core/unified_authentication_service.rs b/crates/router/src/core/unified_authentication_service.rs index eba57642065..3820d8d7edb 100644 --- a/crates/router/src/core/unified_authentication_service.rs +++ b/crates/router/src/core/unified_authentication_service.rs @@ -75,10 +75,10 @@ impl<F: Clone + Sync> UnifiedAuthenticationService<F> for ClickToPay { is_authenticated: false, // This is not relevant in this flow so keeping it as false locale: None, supported_card_brands: None, - encypted_payload: payment_data + encrypted_payload: payment_data .service_details .as_ref() - .and_then(|details| details.encypted_payload.clone()), + .and_then(|details| details.encrypted_payload.clone()), }); Ok(UasPreAuthenticationRequestData { service_details: Some(service_details), diff --git a/crates/router/src/utils/currency.rs b/crates/router/src/utils/currency.rs index aaabc9ffc2f..6e35353af64 100644 --- a/crates/router/src/utils/currency.rs +++ b/crates/router/src/utils/currency.rs @@ -381,7 +381,7 @@ pub async fn fetch_forex_rates_from_fallback_api( .await .change_context(ForexError::ParsingError) .attach_printable( - "Unable to parse response received from falback api into ForexResponse", + "Unable to parse response received from fallback api into ForexResponse", )?; logger::info!(fallback_forex_response=?fallback_forex_response,"forex_log"); diff --git a/postman/collection-dir/archipel/Flow Testcases/Happy Cases/Scenario5-Create a mandate and recurring payment/List payment methods for a Customer/event.test.js b/postman/collection-dir/archipel/Flow Testcases/Happy Cases/Scenario5-Create a mandate and recurring payment/List payment methods for a Customer/event.test.js index 8f940e049a6..036d9ce0475 100644 --- a/postman/collection-dir/archipel/Flow Testcases/Happy Cases/Scenario5-Create a mandate and recurring payment/List payment methods for a Customer/event.test.js +++ b/postman/collection-dir/archipel/Flow Testcases/Happy Cases/Scenario5-Create a mandate and recurring payment/List payment methods for a Customer/event.test.js @@ -1,4 +1,4 @@ -// Validate status 2xx +// Validate status 2xx pm.test("[GET]::/payment_methods/:customer_id - Status code is 2xx", function () { pm.response.to.be.success; }); @@ -19,10 +19,10 @@ if (jsonData?.customer_payment_methods[0]?.payment_token) { console.log('INFO - Unable to assign variable {{payment_token}}, as jsonData.customer_payment_methods[0].payment_token is undefined.'); } -// Response body should have at least one card payment mehod" +// Response body should have at least one card payment method" pm.test( "[GET]::/payment_methods/:customer_id - Content check body has at least one customer_payment_methods", function () { pm.expect(jsonData.customer_payment_methods.length).greaterThan(0); }, -); \ No newline at end of file +); diff --git a/postman/collection-dir/archipel/Flow Testcases/Happy Cases/Scenario6-Saved card flow/.meta.json b/postman/collection-dir/archipel/Flow Testcases/Happy Cases/Scenario6-Saved card flow/.meta.json index 6f5f51da5e5..480eee064ee 100644 --- a/postman/collection-dir/archipel/Flow Testcases/Happy Cases/Scenario6-Saved card flow/.meta.json +++ b/postman/collection-dir/archipel/Flow Testcases/Happy Cases/Scenario6-Saved card flow/.meta.json @@ -4,7 +4,7 @@ "Payments - Confirm first and save card", "Payment methods - List and get token", "Payments - Create second", - "Payments - Confirm secod and use saved card", + "Payments - Confirm second and use saved card", "Payments - Retrieve" ] -} \ No newline at end of file +} diff --git a/postman/collection-dir/archipel/Flow Testcases/Happy Cases/Scenario6-Saved card flow/Payment methods - List and get token/event.test.js b/postman/collection-dir/archipel/Flow Testcases/Happy Cases/Scenario6-Saved card flow/Payment methods - List and get token/event.test.js index 52c82b92010..75e5de27609 100644 --- a/postman/collection-dir/archipel/Flow Testcases/Happy Cases/Scenario6-Saved card flow/Payment methods - List and get token/event.test.js +++ b/postman/collection-dir/archipel/Flow Testcases/Happy Cases/Scenario6-Saved card flow/Payment methods - List and get token/event.test.js @@ -1,4 +1,4 @@ -// Validate status 2xx +// Validate status 2xx pm.test("[GET]::/payment_methods/:customer_id - Status code is 2xx", function () { pm.response.to.be.success; }); @@ -12,7 +12,7 @@ pm.test("[GET]::/payment_methods/:customer_id - Content-Type is application/json let jsonData = {}; try {jsonData = pm.response.json();}catch(e){} -// Response body should have at least one card payment mehod" +// Response body should have at least one card payment method" pm.test( "[GET]::/payment_methods/:customer_id - Content check body has at least one customer_payment_methods", function () { @@ -25,4 +25,4 @@ if (jsonData?.customer_payment_methods[0]?.payment_token) { console.log("- use {{payment_token}} as collection variable for value", jsonData.customer_payment_methods[0].payment_token); } else { console.log('INFO - Unable to assign variable {{payment_token}}, as jsonData.customer_payment_methods[0].payment_token is undefined.'); -} \ No newline at end of file +} diff --git a/postman/collection-dir/archipel/Flow Testcases/Happy Cases/Scenario6-Saved card flow/Payments - Confirm secod and use saved card/.event.meta.json b/postman/collection-dir/archipel/Flow Testcases/Happy Cases/Scenario6-Saved card flow/Payments - Confirm second and use saved card/.event.meta.json similarity index 100% rename from postman/collection-dir/archipel/Flow Testcases/Happy Cases/Scenario6-Saved card flow/Payments - Confirm secod and use saved card/.event.meta.json rename to postman/collection-dir/archipel/Flow Testcases/Happy Cases/Scenario6-Saved card flow/Payments - Confirm second and use saved card/.event.meta.json diff --git a/postman/collection-dir/archipel/Flow Testcases/Happy Cases/Scenario6-Saved card flow/Payments - Confirm secod and use saved card/event.test.js b/postman/collection-dir/archipel/Flow Testcases/Happy Cases/Scenario6-Saved card flow/Payments - Confirm second and use saved card/event.test.js similarity index 100% rename from postman/collection-dir/archipel/Flow Testcases/Happy Cases/Scenario6-Saved card flow/Payments - Confirm secod and use saved card/event.test.js rename to postman/collection-dir/archipel/Flow Testcases/Happy Cases/Scenario6-Saved card flow/Payments - Confirm second and use saved card/event.test.js diff --git a/postman/collection-dir/archipel/Flow Testcases/Happy Cases/Scenario6-Saved card flow/Payments - Confirm secod and use saved card/request.json b/postman/collection-dir/archipel/Flow Testcases/Happy Cases/Scenario6-Saved card flow/Payments - Confirm second and use saved card/request.json similarity index 100% rename from postman/collection-dir/archipel/Flow Testcases/Happy Cases/Scenario6-Saved card flow/Payments - Confirm secod and use saved card/request.json rename to postman/collection-dir/archipel/Flow Testcases/Happy Cases/Scenario6-Saved card flow/Payments - Confirm second and use saved card/request.json diff --git a/postman/collection-dir/archipel/Flow Testcases/Happy Cases/Scenario6-Saved card flow/Payments - Confirm secod and use saved card/response.json b/postman/collection-dir/archipel/Flow Testcases/Happy Cases/Scenario6-Saved card flow/Payments - Confirm second and use saved card/response.json similarity index 100% rename from postman/collection-dir/archipel/Flow Testcases/Happy Cases/Scenario6-Saved card flow/Payments - Confirm secod and use saved card/response.json rename to postman/collection-dir/archipel/Flow Testcases/Happy Cases/Scenario6-Saved card flow/Payments - Confirm second and use saved card/response.json diff --git a/postman/collection-dir/archipel/Flow Testcases/Negative Cases/Scenario6-Create a recurring payment with greater mandate amount/Recurring Payments - Create/request.json b/postman/collection-dir/archipel/Flow Testcases/Negative Cases/Scenario6-Create a recurring payment with greater mandate amount/Recurring Payments - Create/request.json index a7da97361d0..08ee6a23c8d 100644 --- a/postman/collection-dir/archipel/Flow Testcases/Negative Cases/Scenario6-Create a recurring payment with greater mandate amount/Recurring Payments - Create/request.json +++ b/postman/collection-dir/archipel/Flow Testcases/Negative Cases/Scenario6-Create a recurring payment with greater mandate amount/Recurring Payments - Create/request.json @@ -25,7 +25,7 @@ "capture_method": "automatic", "capture_on": "{{$isoTimestamp}}", "customer_id": "{{customer_id}}", - "description": "[Archipel Connector][Variation Cases][Scenario6] - Create recurring payment greather than mandate amount", + "description": "[Archipel Connector][Variation Cases][Scenario6] - Create recurring payment greater than mandate amount", "authentication_type": "no_three_ds", "mandate_id": "{{mandate_id}}", "off_session": true, diff --git a/postman/collection-json/archipel.postman_collection.json b/postman/collection-json/archipel.postman_collection.json index 8d899988043..51678f33523 100644 --- a/postman/collection-json/archipel.postman_collection.json +++ b/postman/collection-json/archipel.postman_collection.json @@ -4903,7 +4903,7 @@ " console.log('INFO - Unable to assign variable {{payment_token}}, as jsonData.customer_payment_methods[0].payment_token is undefined.');", "}", "", - "// Response body should have at least one card payment mehod\"", + "// Response body should have at least one card payment method\"", "pm.test(", "\"[GET]::/payment_methods/:customer_id - Content check body has at least one customer_payment_methods\",", "function () {", @@ -5476,7 +5476,7 @@ "let jsonData = {};", "try {jsonData = pm.response.json();}catch(e){}", "", - "// Response body should have at least one card payment mehod\"", + "// Response body should have at least one card payment method\"", "pm.test(", "\"[GET]::/payment_methods/:customer_id - Content check body has at least one customer_payment_methods\",", "function () {", @@ -5613,7 +5613,7 @@ "response": [] }, { - "name": "Payments - Confirm secod and use saved card", + "name": "Payments - Confirm second and use saved card", "event": [ { "listen": "test", @@ -10152,7 +10152,7 @@ "language": "json" } }, - "raw": "{\"amount\":9000,\"currency\":\"EUR\",\"confirm\":true,\"profile_id\":\"{{profile_id}}\",\"capture_method\":\"automatic\",\"capture_on\":\"{{$isoTimestamp}}\",\"customer_id\":\"{{customer_id}}\",\"description\":\"[Archipel Connector][Variation Cases][Scenario6] - Create recurring payment greather than mandate amount\",\"authentication_type\":\"no_three_ds\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"billing\":{\"address\":{\"line1\":\"2 ter\",\"line2\":\"rue du château\",\"line3\":\"\",\"city\":\"Neuilly-sur-Seine\",\"state\":\"France\",\"zip\":\"92200\",\"country\":\"FR\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}}}" + "raw": "{\"amount\":9000,\"currency\":\"EUR\",\"confirm\":true,\"profile_id\":\"{{profile_id}}\",\"capture_method\":\"automatic\",\"capture_on\":\"{{$isoTimestamp}}\",\"customer_id\":\"{{customer_id}}\",\"description\":\"[Archipel Connector][Variation Cases][Scenario6] - Create recurring payment greater than mandate amount\",\"authentication_type\":\"no_three_ds\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"billing\":{\"address\":{\"line1\":\"2 ter\",\"line2\":\"rue du château\",\"line3\":\"\",\"city\":\"Neuilly-sur-Seine\",\"state\":\"France\",\"zip\":\"92200\",\"country\":\"FR\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}}}" }, "url": { "raw": "{{baseUrl}}/payments", diff --git a/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql b/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql index ea3b08be15f..199609d3242 100644 --- a/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql +++ b/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql @@ -4,7 +4,7 @@ ALTER TABLE organization DROP CONSTRAINT organization_pkey, ALTER COLUMN org_id DROP NOT NULL; -- Create index on org_id in organization table --- This is done to mullify the effects of droping primary key for v1 +-- This is done to nullify the effects of dropping primary key for v1 CREATE INDEX idx_organization_org_id ON organization (org_id); @@ -16,7 +16,7 @@ ALTER TABLE merchant_account ALTER COLUMN primary_business_details DROP NOT NULL, ALTER COLUMN is_recon_enabled DROP NOT NULL; --- This is done to mullify the effects of droping primary key for v1 +-- This is done to nullify the effects of dropping primary key for v1 CREATE INDEX idx_merchant_account_merchant_id ON merchant_account (merchant_id); ------------------------ Business Profile ------------------- @@ -24,21 +24,21 @@ ALTER TABLE business_profile DROP CONSTRAINT business_profile_pkey, ALTER COLUMN profile_id DROP NOT NULL; --- This is done to mullify the effects of droping primary key for v1 +-- This is done to nullify the effects of dropping primary key for v1 CREATE INDEX idx_business_profile_profile_id ON business_profile (profile_id); ---------------- Merchant Connector Account ----------------- ALTER TABLE merchant_connector_account DROP CONSTRAINT merchant_connector_account_pkey, ALTER COLUMN merchant_connector_id DROP NOT NULL; --- This is done to mullify the effects of droping primary key for v1 +-- This is done to nullify the effects of dropping primary key for v1 CREATE INDEX idx_merchant_connector_account_merchant_connector_id ON merchant_connector_account (merchant_connector_id); ------------------------ Customers -------------------------- ALTER TABLE customers DROP CONSTRAINT customers_pkey, ALTER COLUMN customer_id DROP NOT NULL; --- This is done to mullify the effects of droping primary key for v1 +-- This is done to nullify the effects of dropping primary key for v1 CREATE INDEX idx_customers_merchant_id_customer_id ON customers (merchant_id, customer_id); ---------------------- Payment Intent ----------------------- @@ -47,7 +47,7 @@ ALTER TABLE payment_intent ALTER COLUMN payment_id DROP NOT NULL, ALTER COLUMN active_attempt_id DROP NOT NULL, ALTER COLUMN active_attempt_id DROP DEFAULT; --- This is done to mullify the effects of droping primary key for v1 +-- This is done to nullify the effects of dropping primary key for v1 CREATE INDEX idx_payment_intent_payment_id_merchant_id ON payment_intent (payment_id, merchant_id); ---------------------- Payment Attempt ---------------------- @@ -55,19 +55,19 @@ ALTER TABLE payment_attempt DROP CONSTRAINT payment_attempt_pkey, ALTER COLUMN attempt_id DROP NOT NULL, ALTER COLUMN amount DROP NOT NULL; --- This is done to mullify the effects of droping primary key for v1 +-- This is done to nullify the effects of dropping primary key for v1 CREATE INDEX idx_payment_attempt_attempt_id_merchant_id ON payment_attempt (attempt_id, merchant_id); ---------------------- Payment Methods ---------------------- ALTER TABLE payment_methods DROP CONSTRAINT payment_methods_pkey, ALTER COLUMN payment_method_id DROP NOT NULL; --- This is done to mullify the effects of droping primary key for v1 +-- This is done to nullify the effects of dropping primary key for v1 CREATE INDEX idx_payment_methods_payment_method_id ON payment_methods (payment_method_id); ---------------------- Refunds ---------------------- ALTER TABLE refund DROP CONSTRAINT refund_pkey, ALTER COLUMN refund_id DROP NOT NULL; --- This is done to mullify the effects of droping primary key for v1 +-- This is done to nullify the effects of dropping primary key for v1 CREATE INDEX idx_refund_refund_id_merchant_id ON refund (refund_id, merchant_id); \ No newline at end of file
2025-05-17T07:43:29Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR updates all the typos in the repository. For reference, check: https://github.com/juspay/hyperswitch/actions/runs/15082629873/job/42401247676?pr=8056 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Fix typos. Closes #8064 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ```sh cargo +nightly fmt --all && just clippy && just clippy_v2 ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `just clippy && just clippy_v2` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
8e9bad6457449ef2a435be03a9f97acc2dd2108a
8e9bad6457449ef2a435be03a9f97acc2dd2108a
juspay/hyperswitch
juspay__hyperswitch-8055
Bug: [FEATURE] [CONNECTOR] Nordea Integrate a new connector Nordea. Developer Docs: https://developer.nordeaopenbanking.com/documentation Login Dashboard: https://developer.nordeaopenbanking.com/login
diff --git a/config/config.example.toml b/config/config.example.toml index 5bc55238294..52ee69bec10 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -245,6 +245,7 @@ nexixpay.base_url = "https://xpaysandbox.nexigroup.com/api/phoenix-0.0/psp/api/v nmi.base_url = "https://secure.nmi.com/" nomupay.base_url = "https://payout-api.sandbox.nomupay.com" noon.base_url = "https://api-test.noonpayments.com/" +nordea.base_url = "https://api.nordeaopenbanking.com" novalnet.base_url = "https://payport.novalnet.de/v2" noon.key_mode = "Test" nuvei.base_url = "https://ppp-test.nuvei.com/" diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index a05db876f28..734fa08c88f 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -88,6 +88,7 @@ nexixpay.base_url = "https://xpaysandbox.nexigroup.com/api/phoenix-0.0/psp/api/v nmi.base_url = "https://secure.nmi.com/" nomupay.base_url = "https://payout-api.sandbox.nomupay.com" noon.base_url = "https://api-test.noonpayments.com/" +nordea.base_url = "https://api.nordeaopenbanking.com" noon.key_mode = "Test" novalnet.base_url = "https://payport.novalnet.de/v2" nuvei.base_url = "https://ppp-test.nuvei.com/" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 828b144f1bc..16e114a7543 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -92,6 +92,7 @@ nexixpay.base_url = "https://xpay.nexigroup.com/api/phoenix-0.0/psp/api/v1" nmi.base_url = "https://secure.nmi.com/" nomupay.base_url = "https://payout-api.nomupay.com" noon.base_url = "https://api.noonpayments.com/" +nordea.base_url = "https://openapi.portal.nordea.com" noon.key_mode = "Live" novalnet.base_url = "https://payport.novalnet.de/v2" nuvei.base_url = "https://secure.safecharge.com/" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index b12149d0dc7..ec6572fd71a 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -92,6 +92,7 @@ nexixpay.base_url = "https://xpaysandbox.nexigroup.com/api/phoenix-0.0/psp/api/v nmi.base_url = "https://secure.nmi.com/" nomupay.base_url = "https://payout-api.sandbox.nomupay.com" noon.base_url = "https://api-test.noonpayments.com/" +nordea.base_url = "https://api.nordeaopenbanking.com" noon.key_mode = "Test" novalnet.base_url = "https://payport.novalnet.de/v2" nuvei.base_url = "https://ppp-test.nuvei.com/" diff --git a/config/development.toml b/config/development.toml index 035671dec19..7deb3b46992 100644 --- a/config/development.toml +++ b/config/development.toml @@ -167,6 +167,7 @@ cards = [ "nmi", "nomupay", "noon", + "nordea", "novalnet", "nuvei", "opayo", @@ -295,6 +296,7 @@ nexixpay.base_url = "https://xpaysandbox.nexigroup.com/api/phoenix-0.0/psp/api/v nmi.base_url = "https://secure.nmi.com/" nomupay.base_url = "https://payout-api.sandbox.nomupay.com" noon.base_url = "https://api-test.noonpayments.com/" +nordea.base_url = "https://api.nordeaopenbanking.com" novalnet.base_url = "https://payport.novalnet.de/v2" noon.key_mode = "Test" nuvei.base_url = "https://ppp-test.nuvei.com/" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 08c32cb894f..855bed5ebd0 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -176,6 +176,7 @@ nexixpay.base_url = "https://xpaysandbox.nexigroup.com/api/phoenix-0.0/psp/api/v nmi.base_url = "https://secure.nmi.com/" nomupay.base_url = "https://payout-api.sandbox.nomupay.com" noon.base_url = "https://api-test.noonpayments.com/" +nordea.base_url = "https://api.nordeaopenbanking.com" novalnet.base_url = "https://payport.novalnet.de/v2" noon.key_mode = "Test" nuvei.base_url = "https://ppp-test.nuvei.com/" @@ -288,6 +289,7 @@ cards = [ "nexixpay", "nmi", "noon", + "nordea", "novalnet", "nuvei", "opayo", diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index 76979d26d62..0b3d03e6a91 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -111,6 +111,7 @@ pub enum RoutableConnectors { Nmi, Nomupay, Noon, + // Nordea, Novalnet, Nuvei, // Opayo, added as template code for future usage @@ -267,6 +268,7 @@ pub enum Connector { Nmi, Nomupay, Noon, + // Nordea, Novalnet, Nuvei, // Opayo, added as template code for future usage @@ -432,6 +434,7 @@ impl Connector { | Self::Nexinets | Self::Nexixpay | Self::Nomupay + // | Self::Nordea | Self::Novalnet | Self::Nuvei | Self::Opennode @@ -586,6 +589,7 @@ impl From<RoutableConnectors> for Connector { RoutableConnectors::Nmi => Self::Nmi, RoutableConnectors::Nomupay => Self::Nomupay, RoutableConnectors::Noon => Self::Noon, + // RoutableConnectors::Nordea => Self::Nordea, RoutableConnectors::Novalnet => Self::Novalnet, RoutableConnectors::Nuvei => Self::Nuvei, RoutableConnectors::Opennode => Self::Opennode, @@ -699,6 +703,7 @@ impl TryFrom<Connector> for RoutableConnectors { Connector::Nmi => Ok(Self::Nmi), Connector::Nomupay => Ok(Self::Nomupay), Connector::Noon => Ok(Self::Noon), + // Connector::Nordea => Ok(Self::Nordea), Connector::Novalnet => Ok(Self::Novalnet), Connector::Nuvei => Ok(Self::Nuvei), Connector::Opennode => Ok(Self::Opennode), diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index bfa63d59394..45a26489113 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -224,6 +224,7 @@ pub struct ConnectorConfig { pub nmi: Option<ConnectorTomlConfig>, pub nomupay_payout: Option<ConnectorTomlConfig>, pub noon: Option<ConnectorTomlConfig>, + pub nordea: Option<ConnectorTomlConfig>, pub novalnet: Option<ConnectorTomlConfig>, pub nuvei: Option<ConnectorTomlConfig>, pub paybox: Option<ConnectorTomlConfig>, diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs index b2f6bb1e708..a635800152f 100644 --- a/crates/hyperswitch_connectors/src/connectors.rs +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -56,6 +56,7 @@ pub mod nexixpay; pub mod nmi; pub mod nomupay; pub mod noon; +pub mod nordea; pub mod novalnet; pub mod nuvei; pub mod opayo; @@ -114,10 +115,10 @@ pub use self::{ itaubank::Itaubank, jpmorgan::Jpmorgan, juspaythreedsserver::Juspaythreedsserver, klarna::Klarna, mifinity::Mifinity, mollie::Mollie, moneris::Moneris, multisafepay::Multisafepay, netcetera::Netcetera, nexinets::Nexinets, nexixpay::Nexixpay, - nmi::Nmi, nomupay::Nomupay, noon::Noon, novalnet::Novalnet, nuvei::Nuvei, opayo::Opayo, - opennode::Opennode, paybox::Paybox, payeezy::Payeezy, payme::Payme, payone::Payone, - paypal::Paypal, paystack::Paystack, payu::Payu, placetopay::Placetopay, plaid::Plaid, - powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, + nmi::Nmi, nomupay::Nomupay, noon::Noon, nordea::Nordea, novalnet::Novalnet, nuvei::Nuvei, + opayo::Opayo, opennode::Opennode, paybox::Paybox, payeezy::Payeezy, payme::Payme, + payone::Payone, paypal::Paypal, paystack::Paystack, payu::Payu, placetopay::Placetopay, + plaid::Plaid, powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, recurly::Recurly, redsys::Redsys, riskified::Riskified, shift4::Shift4, signifyd::Signifyd, square::Square, stax::Stax, stripe::Stripe, stripebilling::Stripebilling, taxjar::Taxjar, threedsecureio::Threedsecureio, thunes::Thunes, trustpay::Trustpay, tsys::Tsys, diff --git a/crates/hyperswitch_connectors/src/connectors/nordea.rs b/crates/hyperswitch_connectors/src/connectors/nordea.rs new file mode 100644 index 00000000000..9230d856f8d --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/nordea.rs @@ -0,0 +1,568 @@ +pub mod transformers; + +use common_utils::{ + errors::CustomResult, + ext_traits::BytesExt, + request::{Method, Request, RequestBuilder, RequestContent}, + types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}, +}; +use error_stack::{report, ResultExt}; +use hyperswitch_domain_models::{ + router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, + router_flow_types::{ + access_token_auth::AccessTokenAuth, + payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, + refunds::{Execute, RSync}, + }, + router_request_types::{ + AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, + RefundsData, SetupMandateRequestData, + }, + router_response_types::{PaymentsResponseData, RefundsResponseData}, + types::{ + PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, + RefundSyncRouterData, RefundsRouterData, + }, +}; +use hyperswitch_interfaces::{ + api::{ + self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, + ConnectorValidation, + }, + configs::Connectors, + errors, + events::connector_api_logs::ConnectorEvent, + types::{self, Response}, + webhooks, +}; +use masking::{ExposeInterface, Mask}; +use transformers as nordea; + +use crate::{constants::headers, types::ResponseRouterData, utils}; + +#[derive(Clone)] +pub struct Nordea { + amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), +} + +impl Nordea { + pub fn new() -> &'static Self { + &Self { + amount_converter: &StringMinorUnitForConnector, + } + } +} + +impl api::Payment for Nordea {} +impl api::PaymentSession for Nordea {} +impl api::ConnectorAccessToken for Nordea {} +impl api::MandateSetup for Nordea {} +impl api::PaymentAuthorize for Nordea {} +impl api::PaymentSync for Nordea {} +impl api::PaymentCapture for Nordea {} +impl api::PaymentVoid for Nordea {} +impl api::Refund for Nordea {} +impl api::RefundExecute for Nordea {} +impl api::RefundSync for Nordea {} +impl api::PaymentToken for Nordea {} + +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Nordea +{ + // Not Implemented (R) +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Nordea +where + Self: ConnectorIntegration<Flow, Request, Response>, +{ + fn build_headers( + &self, + req: &RouterData<Flow, Request, Response>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let mut header = vec![( + headers::CONTENT_TYPE.to_string(), + self.get_content_type().to_string().into(), + )]; + let mut api_key = self.get_auth_header(&req.connector_auth_type)?; + header.append(&mut api_key); + Ok(header) + } +} + +impl ConnectorCommon for Nordea { + fn id(&self) -> &'static str { + "nordea" + } + + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Base + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { + connectors.nordea.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let auth = nordea::NordeaAuthType::try_from(auth_type) + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + Ok(vec![( + headers::AUTHORIZATION.to_string(), + auth.api_key.expose().into_masked(), + )]) + } + + fn build_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: nordea::NordeaErrorResponse = res + .response + .parse_struct("NordeaErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + + Ok(ErrorResponse { + status_code: res.status_code, + code: response.code, + message: response.message, + reason: response.reason, + attempt_status: None, + connector_transaction_id: None, + network_decline_code: None, + network_advice_code: None, + network_error_message: None, + }) + } +} + +impl ConnectorValidation for Nordea { + //TODO: implement functions when support enabled +} + +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Nordea { + //TODO: implement sessions flow +} + +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Nordea {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Nordea {} + +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Nordea { + fn get_headers( + &self, + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let amount = utils::convert_amount( + self.amount_converter, + req.request.minor_amount, + req.request.currency, + )?; + + let connector_router_data = nordea::NordeaRouterData::from((amount, req)); + let connector_req = nordea::NordeaPaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::PaymentsAuthorizeType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsAuthorizeType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { + let response: nordea::NordeaPaymentsResponse = res + .response + .parse_struct("Nordea PaymentsAuthorizeResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Nordea { + fn get_headers( + &self, + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &PaymentsSyncRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn build_request( + &self, + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Get) + .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { + let response: nordea::NordeaPaymentsResponse = res + .response + .parse_struct("nordea PaymentsSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Nordea { + fn get_headers( + &self, + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &PaymentsCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + _req: &PaymentsCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) + } + + fn build_request( + &self, + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PaymentsCaptureType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsCaptureType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { + let response: nordea::NordeaPaymentsResponse = res + .response + .parse_struct("Nordea PaymentsCaptureResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Nordea {} + +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Nordea { + fn get_headers( + &self, + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &RefundsRouterData<Execute>, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + req: &RefundsRouterData<Execute>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let refund_amount = utils::convert_amount( + self.amount_converter, + req.request.minor_refund_amount, + req.request.currency, + )?; + + let connector_router_data = nordea::NordeaRouterData::from((refund_amount, req)); + let connector_req = nordea::NordeaRefundRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&types::RefundExecuteType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::RefundExecuteType::get_headers( + self, req, connectors, + )?) + .set_body(types::RefundExecuteType::get_request_body( + self, req, connectors, + )?) + .build(); + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &RefundsRouterData<Execute>, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { + let response: nordea::RefundResponse = + res.response + .parse_struct("nordea RefundResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Nordea { + fn get_headers( + &self, + req: &RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &RefundSyncRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn build_request( + &self, + req: &RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Get) + .url(&types::RefundSyncType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::RefundSyncType::get_headers(self, req, connectors)?) + .set_body(types::RefundSyncType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { + let response: nordea::RefundResponse = res + .response + .parse_struct("nordea RefundSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +#[async_trait::async_trait] +impl webhooks::IncomingWebhook for Nordea { + fn get_webhook_object_reference_id( + &self, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } + + fn get_webhook_event_type( + &self, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } + + fn get_webhook_resource_object( + &self, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } +} + +impl ConnectorSpecifications for Nordea {} diff --git a/crates/hyperswitch_connectors/src/connectors/nordea/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nordea/transformers.rs new file mode 100644 index 00000000000..bea06d53e39 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/nordea/transformers.rs @@ -0,0 +1,228 @@ +use common_enums::enums; +use common_utils::types::StringMinorUnit; +use hyperswitch_domain_models::{ + payment_method_data::PaymentMethodData, + router_data::{ConnectorAuthType, RouterData}, + router_flow_types::refunds::{Execute, RSync}, + router_request_types::ResponseId, + router_response_types::{PaymentsResponseData, RefundsResponseData}, + types::{PaymentsAuthorizeRouterData, RefundsRouterData}, +}; +use hyperswitch_interfaces::errors; +use masking::Secret; +use serde::{Deserialize, Serialize}; + +use crate::{ + types::{RefundsResponseRouterData, ResponseRouterData}, + utils::PaymentsAuthorizeRequestData, +}; + +//TODO: Fill the struct with respective fields +pub struct NordeaRouterData<T> { + pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. + pub router_data: T, +} + +impl<T> From<(StringMinorUnit, T)> for NordeaRouterData<T> { + fn from((amount, item): (StringMinorUnit, T)) -> Self { + //Todo : use utils to convert the amount to the type of amount that a connector accepts + Self { + amount, + router_data: item, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Serialize, PartialEq)] +pub struct NordeaPaymentsRequest { + amount: StringMinorUnit, + card: NordeaCard, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct NordeaCard { + number: cards::CardNumber, + expiry_month: Secret<String>, + expiry_year: Secret<String>, + cvc: Secret<String>, + complete: bool, +} + +impl TryFrom<&NordeaRouterData<&PaymentsAuthorizeRouterData>> for NordeaPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &NordeaRouterData<&PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + PaymentMethodData::Card(req_card) => { + let card = NordeaCard { + number: req_card.card_number, + expiry_month: req_card.card_exp_month, + expiry_year: req_card.card_exp_year, + cvc: req_card.card_cvc, + complete: item.router_data.request.is_auto_capture()?, + }; + Ok(Self { + amount: item.amount.clone(), + card, + }) + } + _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), + } + } +} + +//TODO: Fill the struct with respective fields +// Auth Struct +pub struct NordeaAuthType { + pub(super) api_key: Secret<String>, +} + +impl TryFrom<&ConnectorAuthType> for NordeaAuthType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { + match auth_type { + ConnectorAuthType::HeaderKey { api_key } => Ok(Self { + api_key: api_key.to_owned(), + }), + _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + } + } +} +// PaymentsResponse +//TODO: Append the remaining status flags +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum NordeaPaymentStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<NordeaPaymentStatus> for common_enums::AttemptStatus { + fn from(item: NordeaPaymentStatus) -> Self { + match item { + NordeaPaymentStatus::Succeeded => Self::Charged, + NordeaPaymentStatus::Failed => Self::Failure, + NordeaPaymentStatus::Processing => Self::Authorizing, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct NordeaPaymentsResponse { + status: NordeaPaymentStatus, + id: String, +} + +impl<F, T> TryFrom<ResponseRouterData<F, NordeaPaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData<F, NordeaPaymentsResponse, T, PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: common_enums::AttemptStatus::from(item.response.status), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.id), + redirection_data: Box::new(None), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: None, + incremental_authorization_allowed: None, + charges: None, + }), + ..item.data + }) + } +} + +//TODO: Fill the struct with respective fields +// REFUND : +// Type definition for RefundRequest +#[derive(Default, Debug, Serialize)] +pub struct NordeaRefundRequest { + pub amount: StringMinorUnit, +} + +impl<F> TryFrom<&NordeaRouterData<&RefundsRouterData<F>>> for NordeaRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &NordeaRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { + Ok(Self { + amount: item.amount.to_owned(), + }) + } +} + +// Type definition for Refund Response + +#[allow(dead_code)] +#[derive(Debug, Serialize, Default, Deserialize, Clone)] +pub enum RefundStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<RefundStatus> for enums::RefundStatus { + fn from(item: RefundStatus) -> Self { + match item { + RefundStatus::Succeeded => Self::Success, + RefundStatus::Failed => Self::Failure, + RefundStatus::Processing => Self::Pending, + //TODO: Review mapping + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize)] +pub struct RefundResponse { + id: String, + status: RefundStatus, +} + +impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: RefundsResponseRouterData<Execute, RefundResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(RefundsResponseData { + connector_refund_id: item.response.id.to_string(), + refund_status: enums::RefundStatus::from(item.response.status), + }), + ..item.data + }) + } +} + +impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: RefundsResponseRouterData<RSync, RefundResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(RefundsResponseData { + connector_refund_id: item.response.id.to_string(), + refund_status: enums::RefundStatus::from(item.response.status), + }), + ..item.data + }) + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +pub struct NordeaErrorResponse { + pub status_code: u16, + pub code: String, + pub message: String, + pub reason: Option<String>, +} diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index ed5f0135a65..f4689525cc3 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -168,6 +168,7 @@ default_imp_for_authorize_session_token!( connectors::Nmi, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -293,6 +294,7 @@ default_imp_for_calculate_tax!( connectors::Nmi, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nuvei, connectors::Payeezy, @@ -410,6 +412,7 @@ default_imp_for_session_update!( connectors::Nmi, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -527,6 +530,7 @@ default_imp_for_post_session_tokens!( connectors::Nmi, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -641,6 +645,7 @@ default_imp_for_update_metadata!( connectors::Netcetera, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -747,6 +752,7 @@ default_imp_for_complete_authorize!( connectors::Netcetera, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Opayo, @@ -850,6 +856,7 @@ default_imp_for_incremental_authorization!( connectors::Nmi, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -970,6 +977,7 @@ default_imp_for_create_customer!( connectors::Nmi, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -1079,6 +1087,7 @@ default_imp_for_connector_redirect_response!( connectors::Netcetera, connectors::Nexinets, connectors::Nexixpay, + connectors::Nordea, connectors::Opayo, connectors::Opennode, connectors::Payeezy, @@ -1177,6 +1186,7 @@ default_imp_for_pre_processing_steps!( connectors::Netcetera, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Opayo, @@ -1288,6 +1298,7 @@ default_imp_for_post_processing_steps!( connectors::Nmi, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -1405,6 +1416,7 @@ default_imp_for_approve!( connectors::Netcetera, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -1525,6 +1537,7 @@ default_imp_for_reject!( connectors::Nmi, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -1644,6 +1657,7 @@ default_imp_for_webhook_source_verification!( connectors::Nmi, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -1761,6 +1775,7 @@ default_imp_for_accept_dispute!( connectors::Nmi, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -1878,6 +1893,7 @@ default_imp_for_submit_evidence!( connectors::Nmi, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -1994,6 +2010,7 @@ default_imp_for_defend_dispute!( connectors::Nmi, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -2120,6 +2137,7 @@ default_imp_for_file_upload!( connectors::Nmi, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -2229,6 +2247,7 @@ default_imp_for_payouts!( connectors::Multisafepay, connectors::Nexinets, connectors::Nexixpay, + connectors::Nordea, connectors::Opayo, connectors::Opennode, connectors::Paybox, @@ -2342,6 +2361,7 @@ default_imp_for_payouts_create!( connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, + connectors::Nordea, connectors::Opayo, connectors::Opennode, connectors::Nuvei, @@ -2456,6 +2476,7 @@ default_imp_for_payouts_retrieve!( connectors::Netcetera, connectors::Nmi, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -2573,6 +2594,7 @@ default_imp_for_payouts_eligibility!( connectors::Netcetera, connectors::Nmi, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -2687,6 +2709,7 @@ default_imp_for_payouts_fulfill!( connectors::Klarna, connectors::Netcetera, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -2802,6 +2825,7 @@ default_imp_for_payouts_cancel!( connectors::Netcetera, connectors::Nmi, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -2919,6 +2943,7 @@ default_imp_for_payouts_quote!( connectors::Netcetera, connectors::Nmi, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -3037,6 +3062,7 @@ default_imp_for_payouts_recipient!( connectors::Netcetera, connectors::Nmi, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -3155,6 +3181,7 @@ default_imp_for_payouts_recipient_account!( connectors::Netcetera, connectors::Nmi, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -3275,6 +3302,7 @@ default_imp_for_frm_sale!( connectors::Nomupay, connectors::Nmi, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -3394,6 +3422,7 @@ default_imp_for_frm_checkout!( connectors::Nmi, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -3513,6 +3542,7 @@ default_imp_for_frm_transaction!( connectors::Nmi, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -3632,6 +3662,7 @@ default_imp_for_frm_fulfillment!( connectors::Nmi, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -3751,6 +3782,7 @@ default_imp_for_frm_record_return!( connectors::Nmi, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -3864,6 +3896,7 @@ default_imp_for_revoking_mandates!( connectors::Netcetera, connectors::Nmi, connectors::Nomupay, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -3981,6 +4014,7 @@ default_imp_for_uas_pre_authentication!( connectors::Nmi, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -4097,6 +4131,7 @@ default_imp_for_uas_post_authentication!( connectors::Nmi, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -4214,6 +4249,7 @@ default_imp_for_uas_authentication_confirmation!( connectors::Nmi, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -4322,6 +4358,7 @@ default_imp_for_connector_request_id!( connectors::Netcetera, connectors::Nmi, connectors::Nomupay, + connectors::Nordea, connectors::Novalnet, connectors::Noon, connectors::Nexixpay, @@ -4434,6 +4471,7 @@ default_imp_for_fraud_check!( connectors::Netcetera, connectors::Nmi, connectors::Nomupay, + connectors::Nordea, connectors::Novalnet, connectors::Noon, connectors::Nexinets, @@ -4574,6 +4612,7 @@ default_imp_for_connector_authentication!( connectors::Nmi, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -4688,6 +4727,7 @@ default_imp_for_uas_authentication!( connectors::Netcetera, connectors::Nmi, connectors::Nomupay, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -4799,6 +4839,7 @@ default_imp_for_revenue_recovery! { connectors::Nmi, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -4919,6 +4960,7 @@ default_imp_for_billing_connector_payment_sync!( connectors::Netcetera, connectors::Nmi, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -5037,6 +5079,7 @@ default_imp_for_revenue_recovery_record_back!( connectors::Nmi, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Nexinets, connectors::Nexixpay, @@ -5154,6 +5197,7 @@ default_imp_for_billing_connector_invoice_sync!( connectors::Nomupay, connectors::Nmi, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index 9148bdb1135..3188126f4cc 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -288,6 +288,7 @@ default_imp_for_new_connector_integration_payment!( connectors::Klarna, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, @@ -407,6 +408,7 @@ default_imp_for_new_connector_integration_refund!( connectors::Klarna, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, @@ -521,6 +523,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Klarna, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, @@ -640,6 +643,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Klarna, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, @@ -758,6 +762,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Klarna, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, @@ -877,6 +882,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Klarna, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, @@ -1006,6 +1012,7 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Klarna, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, @@ -1127,6 +1134,7 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Klarna, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, @@ -1248,6 +1256,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Klarna, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, @@ -1369,6 +1378,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Klarna, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, @@ -1490,6 +1500,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Klarna, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, @@ -1611,6 +1622,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Klarna, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, @@ -1732,6 +1744,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Klarna, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, @@ -1853,6 +1866,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Klarna, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, @@ -1974,6 +1988,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Klarna, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, @@ -2093,6 +2108,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Klarna, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, @@ -2214,6 +2230,7 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Klarna, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, @@ -2335,6 +2352,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Klarna, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, @@ -2456,6 +2474,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Klarna, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, @@ -2577,6 +2596,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Klarna, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, @@ -2698,6 +2718,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Klarna, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, @@ -2816,6 +2837,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Klarna, connectors::Nomupay, connectors::Noon, + connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, @@ -2912,6 +2934,7 @@ default_imp_for_new_connector_integration_frm!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Nomupay, + connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, @@ -3030,6 +3053,7 @@ default_imp_for_new_connector_integration_connector_authentication!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Nomupay, + connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, @@ -3137,6 +3161,7 @@ default_imp_for_new_connector_integration_revenue_recovery!( connectors::Jpmorgan, connectors::Juspaythreedsserver, connectors::Nomupay, + connectors::Nordea, connectors::Novalnet, connectors::Netcetera, connectors::Nexinets, diff --git a/crates/hyperswitch_domain_models/src/configs.rs b/crates/hyperswitch_domain_models/src/configs.rs index 7ce8b2cad01..bc06fbeb499 100644 --- a/crates/hyperswitch_domain_models/src/configs.rs +++ b/crates/hyperswitch_domain_models/src/configs.rs @@ -73,6 +73,7 @@ pub struct Connectors { pub nmi: ConnectorParams, pub nomupay: ConnectorParams, pub noon: ConnectorParamsWithModeType, + pub nordea: ConnectorParams, pub novalnet: ConnectorParams, pub nuvei: ConnectorParams, pub opayo: ConnectorParams, diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index 20f09c0ab9a..6106aa27bfb 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -23,17 +23,17 @@ pub use hyperswitch_connectors::connectors::{ juspaythreedsserver::Juspaythreedsserver, klarna, klarna::Klarna, mifinity, mifinity::Mifinity, mollie, mollie::Mollie, moneris, moneris::Moneris, multisafepay, multisafepay::Multisafepay, netcetera, netcetera::Netcetera, nexinets, nexinets::Nexinets, nexixpay, nexixpay::Nexixpay, - nmi, nmi::Nmi, nomupay, nomupay::Nomupay, noon, noon::Noon, novalnet, novalnet::Novalnet, - nuvei, nuvei::Nuvei, opayo, opayo::Opayo, opennode, opennode::Opennode, paybox, paybox::Paybox, - payeezy, payeezy::Payeezy, payme, payme::Payme, payone, payone::Payone, paypal, paypal::Paypal, - paystack, paystack::Paystack, payu, payu::Payu, placetopay, placetopay::Placetopay, plaid, - plaid::Plaid, powertranz, powertranz::Powertranz, prophetpay, prophetpay::Prophetpay, rapyd, - rapyd::Rapyd, razorpay, razorpay::Razorpay, recurly, recurly::Recurly, redsys, redsys::Redsys, - riskified, riskified::Riskified, shift4, shift4::Shift4, signifyd, signifyd::Signifyd, square, - square::Square, stax, stax::Stax, stripe, stripe::Stripe, stripebilling, - stripebilling::Stripebilling, taxjar, taxjar::Taxjar, threedsecureio, - threedsecureio::Threedsecureio, thunes, thunes::Thunes, trustpay, trustpay::Trustpay, tsys, - tsys::Tsys, unified_authentication_service, + nmi, nmi::Nmi, nomupay, nomupay::Nomupay, noon, noon::Noon, nordea, nordea::Nordea, novalnet, + novalnet::Novalnet, nuvei, nuvei::Nuvei, opayo, opayo::Opayo, opennode, opennode::Opennode, + paybox, paybox::Paybox, payeezy, payeezy::Payeezy, payme, payme::Payme, payone, payone::Payone, + paypal, paypal::Paypal, paystack, paystack::Paystack, payu, payu::Payu, placetopay, + placetopay::Placetopay, plaid, plaid::Plaid, powertranz, powertranz::Powertranz, prophetpay, + prophetpay::Prophetpay, rapyd, rapyd::Rapyd, razorpay, razorpay::Razorpay, recurly, + recurly::Recurly, redsys, redsys::Redsys, riskified, riskified::Riskified, shift4, + shift4::Shift4, signifyd, signifyd::Signifyd, square, square::Square, stax, stax::Stax, stripe, + stripe::Stripe, stripebilling, stripebilling::Stripebilling, taxjar, taxjar::Taxjar, + threedsecureio, threedsecureio::Threedsecureio, thunes, thunes::Thunes, trustpay, + trustpay::Trustpay, tsys, tsys::Tsys, unified_authentication_service, unified_authentication_service::UnifiedAuthenticationService, vgs, vgs::Vgs, volt, volt::Volt, wellsfargo, wellsfargo::Wellsfargo, wellsfargopayout, wellsfargopayout::Wellsfargopayout, wise, wise::Wise, worldline, worldline::Worldline, worldpay, worldpay::Worldpay, worldpayxml, diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 4a877092d84..5db9e708a47 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1554,6 +1554,10 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> { noon::transformers::NoonAuthType::try_from(self.auth_type)?; Ok(()) } + // api_enums::Connector::Nordea => { + // nordea::transformers::NordeaAuthType::try_from(self.auth_type)?; + // Ok(()) + // } api_enums::Connector::Novalnet => { novalnet::transformers::NovalnetAuthType::try_from(self.auth_type)?; Ok(()) diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 9296503c36e..6838ec5b040 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -484,6 +484,7 @@ impl ConnectorData { Ok(ConnectorEnum::Old(Box::new(connector::Nomupay::new()))) } enums::Connector::Noon => Ok(ConnectorEnum::Old(Box::new(connector::Noon::new()))), + // enums::Connector::Nordea => Ok(ConnectorEnum::Old(Box::new(connector::Nordea::new()))), enums::Connector::Novalnet => { Ok(ConnectorEnum::Old(Box::new(connector::Novalnet::new()))) } diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index e40456b7d98..a882ee19279 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -288,6 +288,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { api_enums::Connector::Nmi => Self::Nmi, api_enums::Connector::Nomupay => Self::Nomupay, api_enums::Connector::Noon => Self::Noon, + // api_enums::Connector::Nordea => Self::Nordea, api_enums::Connector::Novalnet => Self::Novalnet, api_enums::Connector::Nuvei => Self::Nuvei, api_enums::Connector::Opennode => Self::Opennode, diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 2726363635e..a51c85c1dca 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -62,6 +62,7 @@ mod nexixpay; mod nmi; mod nomupay; mod noon; +mod nordea; mod novalnet; mod nuvei; #[cfg(feature = "dummy_connector")] diff --git a/crates/router/tests/connectors/nordea.rs b/crates/router/tests/connectors/nordea.rs new file mode 100644 index 00000000000..af5d7b4d4b0 --- /dev/null +++ b/crates/router/tests/connectors/nordea.rs @@ -0,0 +1,420 @@ +use masking::Secret; +use router::types::{self, api, domain, storage::enums}; +use test_utils::connector_auth; + +use crate::utils::{self, ConnectorActions}; + +#[derive(Clone, Copy)] +struct NordeaTest; +impl ConnectorActions for NordeaTest {} +impl utils::Connector for NordeaTest { + fn get_data(&self) -> api::ConnectorData { + use router::connector::Nordea; + utils::construct_connector_data_old( + Box::new(Nordea::new()), + types::Connector::DummyConnector1, + api::GetToken::Connector, + None, + ) + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + utils::to_connector_auth_type( + connector_auth::ConnectorAuthentication::new() + .nordea + .expect("Missing connector authentication configuration") + .into(), + ) + } + + fn get_name(&self) -> String { + "nordea".to_string() + } +} + +static CONNECTOR: NordeaTest = NordeaTest {}; + +fn get_default_payment_info() -> Option<utils::PaymentInfo> { + None +} + +fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { + None +} + +// Cards Positive Tests +// Creates a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_only_authorize_payment() { + let response = CONNECTOR + .authorize_payment(payment_method_details(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + assert_eq!(response.status, enums::AttemptStatus::Authorized); +} + +// Captures a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_capture_authorized_payment() { + let response = CONNECTOR + .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) + .await + .expect("Capture payment response"); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +// Partially captures a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_capture_authorized_payment() { + let response = CONNECTOR + .authorize_and_capture_payment( + payment_method_details(), + Some(types::PaymentsCaptureData { + amount_to_capture: 50, + ..utils::PaymentCaptureType::default().0 + }), + get_default_payment_info(), + ) + .await + .expect("Capture payment response"); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +// Synchronizes a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_authorized_payment() { + let authorize_response = CONNECTOR + .authorize_payment(payment_method_details(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: types::ResponseId::ConnectorTransactionId( + txn_id.unwrap(), + ), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .expect("PSync response"); + assert_eq!(response.status, enums::AttemptStatus::Authorized,); +} + +// Voids a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_void_authorized_payment() { + let response = CONNECTOR + .authorize_and_void_payment( + payment_method_details(), + Some(types::PaymentsCancelData { + connector_transaction_id: String::from(""), + cancellation_reason: Some("requested_by_customer".to_string()), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .expect("Void payment response"); + assert_eq!(response.status, enums::AttemptStatus::Voided); +} + +// Refunds a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_manually_captured_payment() { + let response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Partially refunds a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_refund_manually_captured_payment() { + let response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Synchronizes a refund using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_manually_captured_refund() { + let refund_response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + let response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Success, + refund_response.response.unwrap().connector_refund_id, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Creates a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_make_payment() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); +} + +// Synchronizes a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_auto_captured_payment() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + assert_ne!(txn_id, None, "Empty connector transaction id"); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Charged, + Some(types::PaymentsSyncData { + connector_transaction_id: types::ResponseId::ConnectorTransactionId( + txn_id.unwrap(), + ), + capture_method: Some(enums::CaptureMethod::Automatic), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::Charged,); +} + +// Refunds a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_auto_captured_payment() { + let response = CONNECTOR + .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Partially refunds a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_refund_succeeded_payment() { + let refund_response = CONNECTOR + .make_payment_and_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + refund_response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_succeeded_payment_multiple_times() { + CONNECTOR + .make_payment_and_multiple_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await; +} + +// Synchronizes a refund using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_refund() { + let refund_response = CONNECTOR + .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) + .await + .unwrap(); + let response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Success, + refund_response.response.unwrap().connector_refund_id, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Cards Negative scenarios +// Creates a payment with incorrect CVC. +#[actix_web::test] +async fn should_fail_payment_for_incorrect_cvc() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { + card_cvc: Secret::new("12345".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's security code is invalid.".to_string(), + ); +} + +// Creates a payment with incorrect expiry month. +#[actix_web::test] +async fn should_fail_payment_for_invalid_exp_month() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { + card_exp_month: Secret::new("20".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's expiration month is invalid.".to_string(), + ); +} + +// Creates a payment with incorrect expiry year. +#[actix_web::test] +async fn should_fail_payment_for_incorrect_expiry_year() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { + card_exp_year: Secret::new("2000".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's expiration year is invalid.".to_string(), + ); +} + +// Voids a payment using automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_fail_void_payment_for_auto_capture() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + assert_ne!(txn_id, None, "Empty connector transaction id"); + let void_response = CONNECTOR + .void_payment(txn_id.unwrap(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + void_response.response.unwrap_err().message, + "You cannot cancel this PaymentIntent because it has a status of succeeded." + ); +} + +// Captures a payment using invalid connector payment id. +#[actix_web::test] +async fn should_fail_capture_for_invalid_payment() { + let capture_response = CONNECTOR + .capture_payment("123456789".to_string(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + capture_response.response.unwrap_err().message, + String::from("No such payment_intent: '123456789'") + ); +} + +// Refunds a payment with refund amount higher than payment amount. +#[actix_web::test] +async fn should_fail_for_refund_amount_higher_than_payment_amount() { + let response = CONNECTOR + .make_payment_and_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 150, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Refund amount (₹1.50) is greater than charge amount (₹1.00)", + ); +} + +// Connector dependent test cases goes here + +// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index 7d208c5464e..00dbfb66983 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -285,6 +285,10 @@ api_secret = "Consumer Secret" [taxjar] api_key = "API Key" +[nordea] +api_key = "Client Secret" +key1 = "Client ID" + [novalnet] api_key="API Key" diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index b9873776e09..dd2cfe6cf7b 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -69,6 +69,7 @@ pub struct ConnectorAuthentication { pub nexixpay: Option<HeaderKey>, pub nomupay: Option<BodyKey>, pub noon: Option<SignatureKey>, + pub nordea: Option<BodyKey>, pub novalnet: Option<HeaderKey>, pub nmi: Option<HeaderKey>, pub nuvei: Option<SignatureKey>, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 8ccb694a386..d3edab05109 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -143,6 +143,7 @@ nexixpay.base_url = "https://xpaysandbox.nexigroup.com/api/phoenix-0.0/psp/api/v nmi.base_url = "https://secure.nmi.com/" nomupay.base_url = "https://payout-api.sandbox.nomupay.com" noon.base_url = "https://api-test.noonpayments.com/" +nordea.base_url = "https://api.nordeaopenbanking.com" noon.key_mode = "Test" novalnet.base_url = "https://payport.novalnet.de/v2" nuvei.base_url = "https://ppp-test.nuvei.com/" @@ -254,6 +255,7 @@ cards = [ "nexixpay", "nmi", "noon", + "nordea", "novalnet", "nuvei", "opayo", diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index bf27a84958c..9b0fab85059 100755 --- a/scripts/add_connector.sh +++ b/scripts/add_connector.sh @@ -6,7 +6,7 @@ function find_prev_connector() { git checkout $self cp $self $self.tmp # Add new connector to existing list and sort it - connectors=(aci adyen adyenplatform airwallex amazonpay applepay archipel authorizedotnet bambora bamboraapac bankofamerica barclaycard billwerk bitpay bluesnap boku braintree cashtocode chargebee checkout coinbase cryptopay ctp_visa cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector ebanx elavon facilitapay fiserv fiservemea fiuu forte getnet globalpay globepay gocardless gpayments helcim hipay iatapay inespay itaubank jpmorgan juspaythreedsserver klarna mifinity mollie moneris multisafepay netcetera nexinets nexixpay nomupay noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal paystack payu placetopay plaid powertranz prophetpay rapyd razorpay recurly redsys shift4 square stax stripe stripebilling taxjar threedsecureio thunes trustpay tsys unified_authentication_service vgs volt wellsfargo wellsfargopayout wise worldline worldpay worldpayxml xendit zsl "$1") + connectors=(aci adyen adyenplatform airwallex amazonpay applepay archipel authorizedotnet bambora bamboraapac bankofamerica barclaycard billwerk bitpay bluesnap boku braintree cashtocode chargebee checkout coinbase cryptopay ctp_visa cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector ebanx elavon facilitapay fiserv fiservemea fiuu forte getnet globalpay globepay gocardless gpayments helcim hipay iatapay inespay itaubank jpmorgan juspaythreedsserver klarna mifinity mollie moneris multisafepay netcetera nexinets nexixpay nomupay noon nordea novalnet nuvei opayo opennode paybox payeezy payme payone paypal paystack payu placetopay plaid powertranz prophetpay rapyd razorpay recurly redsys shift4 square stax stripe stripebilling taxjar threedsecureio thunes trustpay tsys unified_authentication_service vgs volt wellsfargo wellsfargopayout wise worldline worldpay worldpayxml xendit zsl "$1") IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS res="$(echo ${sorted[@]})" sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp
2025-05-16T09:39:31Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Connector template code for new connector `Nordea`. Developer Docs: https://developer.nordeaopenbanking.com/documentation Login Dashboard: https://developer.nordeaopenbanking.com/login ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [x] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> closes #8055 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> This is a template PR for Nordea, just checked for compilation. Nothing else to test. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `just clippy && just clippy_v2` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
151b57fa104259df174a38d863acab39277c8473
151b57fa104259df174a38d863acab39277c8473
juspay/hyperswitch
juspay__hyperswitch-8045
Bug: [FEATURE] Decision Engine Config API integration ### Feature Description Need to integrate config APIs of Decision Engine with Hyperswitch ### Possible Implementation We'll update the dynamic routing config API flows to incorporate the decision engine calls as well. ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index d7f3cd41808..3ab7d8d45c0 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -11706,6 +11706,123 @@ } } }, + "DecisionEngineEliminationData": { + "type": "object", + "required": [ + "threshold" + ], + "properties": { + "threshold": { + "type": "number", + "format": "double" + } + } + }, + "DecisionEngineGatewayWiseExtraScore": { + "type": "object", + "required": [ + "gatewayName", + "gatewaySigmaFactor" + ], + "properties": { + "gatewayName": { + "type": "string" + }, + "gatewaySigmaFactor": { + "type": "number", + "format": "double" + } + } + }, + "DecisionEngineSRSubLevelInputConfig": { + "type": "object", + "properties": { + "paymentMethodType": { + "type": "string", + "nullable": true + }, + "paymentMethod": { + "type": "string", + "nullable": true + }, + "latencyThreshold": { + "type": "number", + "format": "double", + "nullable": true + }, + "bucketSize": { + "type": "integer", + "format": "int32", + "nullable": true + }, + "hedgingPercent": { + "type": "number", + "format": "double", + "nullable": true + }, + "lowerResetFactor": { + "type": "number", + "format": "double", + "nullable": true + }, + "upperResetFactor": { + "type": "number", + "format": "double", + "nullable": true + }, + "gatewayExtraScore": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DecisionEngineGatewayWiseExtraScore" + }, + "nullable": true + } + } + }, + "DecisionEngineSuccessRateData": { + "type": "object", + "properties": { + "defaultLatencyThreshold": { + "type": "number", + "format": "double", + "nullable": true + }, + "defaultBucketSize": { + "type": "integer", + "format": "int32", + "nullable": true + }, + "defaultHedgingPercent": { + "type": "number", + "format": "double", + "nullable": true + }, + "defaultLowerResetFactor": { + "type": "number", + "format": "double", + "nullable": true + }, + "defaultUpperResetFactor": { + "type": "number", + "format": "double", + "nullable": true + }, + "defaultGatewayExtraScore": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DecisionEngineGatewayWiseExtraScore" + }, + "nullable": true + }, + "subLevelInputConfig": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DecisionEngineSRSubLevelInputConfig" + }, + "nullable": true + } + } + }, "DecoupledAuthenticationType": { "type": "string", "enum": [ @@ -27140,6 +27257,9 @@ }, "SuccessBasedRoutingConfig": { "type": "object", + "required": [ + "decision_engine_configs" + ], "properties": { "params": { "type": "array", @@ -27155,6 +27275,9 @@ } ], "nullable": true + }, + "decision_engine_configs": { + "$ref": "#/components/schemas/DecisionEngineSuccessRateData" } } }, diff --git a/crates/api_models/src/open_router.rs b/crates/api_models/src/open_router.rs index f80623efc64..f15d9cbcfeb 100644 --- a/crates/api_models/src/open_router.rs +++ b/crates/api_models/src/open_router.rs @@ -9,6 +9,7 @@ pub use euclid::{ }, }; use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; use crate::{ enums::{Currency, PaymentMethod}, @@ -172,3 +173,148 @@ pub enum TxnStatus { Failure, Declined, } + +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct DecisionEngineConfigSetupRequest { + pub merchant_id: String, + pub config: DecisionEngineConfigVariant, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(tag = "type", content = "data")] +#[serde(rename_all = "camelCase")] +pub enum DecisionEngineConfigVariant { + SuccessRate(DecisionEngineSuccessRateData), + Elimination(DecisionEngineEliminationData), +} + +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct DecisionEngineSuccessRateData { + pub default_latency_threshold: Option<f64>, + pub default_bucket_size: Option<i32>, + pub default_hedging_percent: Option<f64>, + pub default_lower_reset_factor: Option<f64>, + pub default_upper_reset_factor: Option<f64>, + pub default_gateway_extra_score: Option<Vec<DecisionEngineGatewayWiseExtraScore>>, + pub sub_level_input_config: Option<Vec<DecisionEngineSRSubLevelInputConfig>>, +} + +impl DecisionEngineSuccessRateData { + pub fn update(&mut self, new_config: Self) { + if let Some(threshold) = new_config.default_latency_threshold { + self.default_latency_threshold = Some(threshold); + } + if let Some(bucket_size) = new_config.default_bucket_size { + self.default_bucket_size = Some(bucket_size); + } + if let Some(hedging_percent) = new_config.default_hedging_percent { + self.default_hedging_percent = Some(hedging_percent); + } + if let Some(lower_reset_factor) = new_config.default_lower_reset_factor { + self.default_lower_reset_factor = Some(lower_reset_factor); + } + if let Some(upper_reset_factor) = new_config.default_upper_reset_factor { + self.default_upper_reset_factor = Some(upper_reset_factor); + } + if let Some(gateway_extra_score) = new_config.default_gateway_extra_score { + self.default_gateway_extra_score + .as_mut() + .map(|score| score.extend(gateway_extra_score)); + } + if let Some(sub_level_input_config) = new_config.sub_level_input_config { + self.sub_level_input_config.as_mut().map(|config| { + config.extend(sub_level_input_config); + }); + } + } +} +#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct DecisionEngineSRSubLevelInputConfig { + pub payment_method_type: Option<String>, + pub payment_method: Option<String>, + pub latency_threshold: Option<f64>, + pub bucket_size: Option<i32>, + pub hedging_percent: Option<f64>, + pub lower_reset_factor: Option<f64>, + pub upper_reset_factor: Option<f64>, + pub gateway_extra_score: Option<Vec<DecisionEngineGatewayWiseExtraScore>>, +} + +impl DecisionEngineSRSubLevelInputConfig { + pub fn update(&mut self, new_config: Self) { + if let Some(payment_method_type) = new_config.payment_method_type { + self.payment_method_type = Some(payment_method_type); + } + if let Some(payment_method) = new_config.payment_method { + self.payment_method = Some(payment_method); + } + if let Some(latency_threshold) = new_config.latency_threshold { + self.latency_threshold = Some(latency_threshold); + } + if let Some(bucket_size) = new_config.bucket_size { + self.bucket_size = Some(bucket_size); + } + if let Some(hedging_percent) = new_config.hedging_percent { + self.hedging_percent = Some(hedging_percent); + } + if let Some(lower_reset_factor) = new_config.lower_reset_factor { + self.lower_reset_factor = Some(lower_reset_factor); + } + if let Some(upper_reset_factor) = new_config.upper_reset_factor { + self.upper_reset_factor = Some(upper_reset_factor); + } + if let Some(gateway_extra_score) = new_config.gateway_extra_score { + self.gateway_extra_score + .as_mut() + .map(|score| score.extend(gateway_extra_score)); + } + } +} + +#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct DecisionEngineGatewayWiseExtraScore { + pub gateway_name: String, + pub gateway_sigma_factor: f64, +} + +impl DecisionEngineGatewayWiseExtraScore { + pub fn update(&mut self, new_config: Self) { + self.gateway_name = new_config.gateway_name; + self.gateway_sigma_factor = new_config.gateway_sigma_factor; + } +} + +#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct DecisionEngineEliminationData { + pub threshold: f64, +} + +impl DecisionEngineEliminationData { + pub fn update(&mut self, new_config: Self) { + self.threshold = new_config.threshold; + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct MerchantAccount { + pub merchant_id: String, + pub gateway_success_rate_based_decider_input: Option<String>, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct FetchRoutingConfig { + pub merchant_id: String, + pub algorithm: AlgorithmType, +} + +#[derive(Debug, Serialize, Deserialize, Clone, Copy)] +#[serde(rename_all = "camelCase")] +pub enum AlgorithmType { + SuccessRate, + Elimination, + DebitRouting, +} diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index e1802ab56f5..12075935cd4 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -1,6 +1,10 @@ use std::fmt::Debug; -use common_utils::{errors::ParsingError, ext_traits::ValueExt, pii}; +use common_utils::{ + errors::{ParsingError, ValidationError}, + ext_traits::ValueExt, + pii, +}; pub use euclid::{ dssa::types::EuclidAnalysable, frontend::{ @@ -11,7 +15,17 @@ pub use euclid::{ use serde::{Deserialize, Serialize}; use utoipa::ToSchema; -use crate::enums::{RoutableConnectors, TransactionType}; +use crate::{ + enums::{RoutableConnectors, TransactionType}, + open_router, +}; + +// Define constants for default values +const DEFAULT_LATENCY_THRESHOLD: f64 = 90.0; +const DEFAULT_BUCKET_SIZE: i32 = 200; +const DEFAULT_HEDGING_PERCENT: f64 = 5.0; +const DEFAULT_ELIMINATION_THRESHOLD: f64 = 0.35; +const DEFAULT_PAYMENT_METHOD: &str = "CARD"; #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] @@ -834,6 +848,8 @@ pub struct ToggleDynamicRoutingPath { pub struct EliminationRoutingConfig { pub params: Option<Vec<DynamicRoutingConfigParams>>, pub elimination_analyser_config: Option<EliminationAnalyserConfig>, + #[schema(value_type = DecisionEngineEliminationData)] + pub decision_engine_configs: Option<open_router::DecisionEngineEliminationData>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy, ToSchema)] @@ -861,6 +877,7 @@ impl Default for EliminationRoutingConfig { bucket_size: Some(5), bucket_leak_interval_in_secs: Some(60), }), + decision_engine_configs: None, } } } @@ -875,6 +892,34 @@ impl EliminationRoutingConfig { .as_mut() .map(|config| config.update(new_config)); } + if let Some(new_config) = new.decision_engine_configs { + self.decision_engine_configs + .as_mut() + .map(|config| config.update(new_config)); + } + } + + pub fn open_router_config_default() -> Self { + Self { + elimination_analyser_config: None, + params: None, + decision_engine_configs: Some(open_router::DecisionEngineEliminationData { + threshold: DEFAULT_ELIMINATION_THRESHOLD, + }), + } + } + + pub fn get_decision_engine_configs( + &self, + ) -> Result<open_router::DecisionEngineEliminationData, error_stack::Report<ValidationError>> + { + self.decision_engine_configs + .clone() + .ok_or(error_stack::Report::new( + ValidationError::MissingRequiredField { + field_name: "decision_engine_configs".to_string(), + }, + )) } } @@ -882,6 +927,8 @@ impl EliminationRoutingConfig { pub struct SuccessBasedRoutingConfig { pub params: Option<Vec<DynamicRoutingConfigParams>>, pub config: Option<SuccessBasedRoutingConfigBody>, + #[schema(value_type = DecisionEngineSuccessRateData)] + pub decision_engine_configs: Option<open_router::DecisionEngineSuccessRateData>, } impl Default for SuccessBasedRoutingConfig { @@ -898,6 +945,7 @@ impl Default for SuccessBasedRoutingConfig { }), specificity_level: SuccessRateSpecificityLevel::default(), }), + decision_engine_configs: None, } } } @@ -982,6 +1030,51 @@ impl SuccessBasedRoutingConfig { if let Some(new_config) = new.config { self.config.as_mut().map(|config| config.update(new_config)); } + if let Some(new_config) = new.decision_engine_configs { + self.decision_engine_configs + .as_mut() + .map(|config| config.update(new_config)); + } + } + + pub fn open_router_config_default() -> Self { + Self { + params: None, + config: None, + decision_engine_configs: Some(open_router::DecisionEngineSuccessRateData { + default_latency_threshold: Some(DEFAULT_LATENCY_THRESHOLD), + default_bucket_size: Some(DEFAULT_BUCKET_SIZE), + default_hedging_percent: Some(DEFAULT_HEDGING_PERCENT), + default_lower_reset_factor: None, + default_upper_reset_factor: None, + default_gateway_extra_score: None, + sub_level_input_config: Some(vec![ + open_router::DecisionEngineSRSubLevelInputConfig { + payment_method_type: Some(DEFAULT_PAYMENT_METHOD.to_string()), + payment_method: None, + latency_threshold: None, + bucket_size: Some(DEFAULT_BUCKET_SIZE), + hedging_percent: Some(DEFAULT_HEDGING_PERCENT), + lower_reset_factor: None, + upper_reset_factor: None, + gateway_extra_score: None, + }, + ]), + }), + } + } + + pub fn get_decision_engine_configs( + &self, + ) -> Result<open_router::DecisionEngineSuccessRateData, error_stack::Report<ValidationError>> + { + self.decision_engine_configs + .clone() + .ok_or(error_stack::Report::new( + ValidationError::MissingRequiredField { + field_name: "decision_engine_configs".to_string(), + }, + )) } } diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 79c4467f039..b042d2bdbd6 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -743,6 +743,10 @@ Never share your secret api keys. Keep them guarded and secure. api_models::feature_matrix::PaymentMethodSpecificFeatures, api_models::feature_matrix::CardSpecificFeatures, api_models::feature_matrix::SupportedPaymentMethod, + api_models::open_router::DecisionEngineSuccessRateData, + api_models::open_router::DecisionEngineGatewayWiseExtraScore, + api_models::open_router::DecisionEngineSRSubLevelInputConfig, + api_models::open_router::DecisionEngineEliminationData, )), modifiers(&SecurityAddon) )] diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 5db9e708a47..860d82ab487 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -258,6 +258,26 @@ pub async fn create_merchant_account( .await .to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount)?; + // Call to DE here + // Check if creation should be based on default profile + #[cfg(all(feature = "dynamic_routing", feature = "v1"))] + { + if state.conf.open_router.enabled { + merchant_account + .default_profile + .as_ref() + .async_map(|profile_id| { + routing::helpers::create_decision_engine_merchant(&state, profile_id) + }) + .await + .transpose() + .map_err(|err| { + crate::logger::error!("Failed to create merchant in Decision Engine {err:?}"); + }) + .ok(); + } + } + let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( merchant_account.clone(), key_store.clone(), @@ -1171,6 +1191,25 @@ pub async fn merchant_account_delete( is_deleted = is_merchant_account_deleted && is_merchant_key_store_deleted; } + // Call to DE here + #[cfg(all(feature = "dynamic_routing", feature = "v1"))] + { + if state.conf.open_router.enabled && is_deleted { + merchant_account + .default_profile + .as_ref() + .async_map(|profile_id| { + routing::helpers::delete_decision_engine_merchant(&state, profile_id) + }) + .await + .transpose() + .map_err(|err| { + crate::logger::error!("Failed to delete merchant in Decision Engine {err:?}"); + }) + .ok(); + } + } + let state = state.clone(); authentication::decision::spawn_tracked_job( async move { diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 83d3abef44e..2b851c192b0 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -59,7 +59,9 @@ use crate::core::routing::transformers::OpenRouterDecideGatewayRequestExt; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use crate::headers; use crate::{ - core::{errors, errors as oss_errors, payments::routing::utils::EuclidApiHandler, routing}, + core::{ + errors, errors as oss_errors, payments::routing::utils::DecisionEngineApiHandler, routing, + }, logger, services, types::{ api::{self, routing as routing_types}, @@ -1605,14 +1607,15 @@ pub async fn perform_open_routing_for_debit_routing( Some(or_types::RankingAlgorithm::NtwBasedRouting), ); - let response: RoutingResult<DecidedGateway> = utils::EuclidApiClient::send_euclid_request( - state, - services::Method::Post, - "decide-gateway", - Some(open_router_req_body), - None, - ) - .await; + let response: RoutingResult<DecidedGateway> = + utils::EuclidApiClient::send_decision_engine_request( + state, + services::Method::Post, + "decide-gateway", + Some(open_router_req_body), + None, + ) + .await; let output = match response { Ok(decided_gateway) => { diff --git a/crates/router/src/core/payments/routing/utils.rs b/crates/router/src/core/payments/routing/utils.rs index 551694a0aaf..e82ab1d8bee 100644 --- a/crates/router/src/core/payments/routing/utils.rs +++ b/crates/router/src/core/payments/routing/utils.rs @@ -18,8 +18,8 @@ use crate::{ // New Trait for handling Euclid API calls #[async_trait] -pub trait EuclidApiHandler { - async fn send_euclid_request<Req, Res>( +pub trait DecisionEngineApiHandler { + async fn send_decision_engine_request<Req, Res>( state: &SessionState, http_method: services::Method, path: &str, @@ -30,7 +30,7 @@ pub trait EuclidApiHandler { Req: Serialize + Send + Sync + 'static, Res: serde::de::DeserializeOwned + Send + 'static + std::fmt::Debug; - async fn send_euclid_request_without_response_parsing<Req>( + async fn send_decision_engine_request_without_response_parsing<Req>( state: &SessionState, http_method: services::Method, path: &str, @@ -41,65 +41,132 @@ pub trait EuclidApiHandler { Req: Serialize + Send + Sync + 'static; } -// Struct to implement the EuclidApiHandler trait +// Struct to implement the DecisionEngineApiHandler trait pub struct EuclidApiClient; -impl EuclidApiClient { - async fn build_and_send_euclid_http_request<Req>( +pub struct ConfigApiClient; + +pub async fn build_and_send_decision_engine_http_request<Req>( + state: &SessionState, + http_method: services::Method, + path: &str, + request_body: Option<Req>, + timeout: Option<u64>, + context_message: &str, +) -> RoutingResult<reqwest::Response> +where + Req: Serialize + Send + Sync + 'static, +{ + let decision_engine_base_url = &state.conf.open_router.url; + let url = format!("{}/{}", decision_engine_base_url, path); + logger::debug!(decision_engine_api_call_url = %url, decision_engine_request_path = %path, http_method = ?http_method, "decision_engine: Initiating decision_engine API call ({})", context_message); + + let mut request_builder = services::RequestBuilder::new() + .method(http_method) + .url(&url); + + if let Some(body_content) = request_body { + let body = common_utils::request::RequestContent::Json(Box::new(body_content)); + request_builder = request_builder.set_body(body); + } + + let http_request = request_builder.build(); + logger::info!(?http_request, decision_engine_request_path = %path, "decision_engine: Constructed Decision Engine API request details ({})", context_message); + + state + .api_client + .send_request(state, http_request, timeout, false) + .await + .change_context(errors::RoutingError::DslExecutionError) + .attach_printable_lazy(|| { + format!( + "Decision Engine API call to path '{}' unresponsive ({})", + path, context_message + ) + }) +} + +#[async_trait] +impl DecisionEngineApiHandler for EuclidApiClient { + async fn send_decision_engine_request<Req, Res>( state: &SessionState, http_method: services::Method, path: &str, - request_body: Option<Req>, + request_body: Option<Req>, // Option to handle GET/DELETE requests without body timeout: Option<u64>, - context_message: &str, - ) -> RoutingResult<reqwest::Response> + ) -> RoutingResult<Res> where Req: Serialize + Send + Sync + 'static, + Res: serde::de::DeserializeOwned + Send + 'static + std::fmt::Debug, { - let euclid_base_url = &state.conf.open_router.url; - let url = format!("{}/{}", euclid_base_url, path); - logger::debug!(euclid_api_call_url = %url, euclid_request_path = %path, http_method = ?http_method, "decision_engine_euclid: Initiating Euclid API call ({})", context_message); - - let mut request_builder = services::RequestBuilder::new() - .method(http_method) - .url(&url); - - if let Some(body_content) = request_body { - let body = common_utils::request::RequestContent::Json(Box::new(body_content)); - request_builder = request_builder.set_body(body); - } - - let http_request = request_builder.build(); - logger::info!(?http_request, euclid_request_path = %path, "decision_engine_euclid: Constructed Euclid API request details ({})", context_message); + let response = build_and_send_decision_engine_http_request( + state, + http_method, + path, + request_body, + timeout, + "parsing response", + ) + .await?; + logger::debug!(euclid_response = ?response, euclid_request_path = %path, "decision_engine_euclid: Received raw response from Euclid API"); - state - .api_client - .send_request(state, http_request, timeout, false) + let parsed_response = response + .json::<Res>() .await - .change_context(errors::RoutingError::DslExecutionError) + .change_context(errors::RoutingError::GenericConversionError { + from: "ApiResponse".to_string(), + to: std::any::type_name::<Res>().to_string(), + }) .attach_printable_lazy(|| { format!( - "Euclid API call to path '{}' unresponsive ({})", - path, context_message + "Unable to parse response of type '{}' received from Euclid API path: {}", + std::any::type_name::<Res>(), + path ) - }) + })?; + logger::debug!(parsed_response = ?parsed_response, response_type = %std::any::type_name::<Res>(), euclid_request_path = %path, "decision_engine_euclid: Successfully parsed response from Euclid API"); + Ok(parsed_response) + } + + async fn send_decision_engine_request_without_response_parsing<Req>( + state: &SessionState, + http_method: services::Method, + path: &str, + request_body: Option<Req>, + timeout: Option<u64>, + ) -> RoutingResult<()> + where + Req: Serialize + Send + Sync + 'static, + { + let response = build_and_send_decision_engine_http_request( + state, + http_method, + path, + request_body, + timeout, + "not parsing response", + ) + .await?; + + logger::debug!(euclid_response = ?response, euclid_request_path = %path, "decision_engine_routing: Received raw response from Euclid API"); + Ok(()) } } #[async_trait] -impl EuclidApiHandler for EuclidApiClient { - async fn send_euclid_request<Req, Res>( +impl DecisionEngineApiHandler for ConfigApiClient { + async fn send_decision_engine_request<Req, Res>( state: &SessionState, http_method: services::Method, path: &str, - request_body: Option<Req>, // Option to handle GET/DELETE requests without body + request_body: Option<Req>, timeout: Option<u64>, ) -> RoutingResult<Res> where Req: Serialize + Send + Sync + 'static, Res: serde::de::DeserializeOwned + Send + 'static + std::fmt::Debug, { - let response = Self::build_and_send_euclid_http_request( + let response = build_and_send_decision_engine_http_request( state, http_method, path, @@ -108,7 +175,7 @@ impl EuclidApiHandler for EuclidApiClient { "parsing response", ) .await?; - logger::debug!(euclid_response = ?response, euclid_request_path = %path, "decision_engine_euclid: Received raw response from Euclid API"); + logger::debug!(decision_engine_config_response = ?response, decision_engine_request_path = %path, "decision_engine_config: Received raw response from Decision Engine config API"); let parsed_response = response .json::<Res>() @@ -119,16 +186,16 @@ impl EuclidApiHandler for EuclidApiClient { }) .attach_printable_lazy(|| { format!( - "Unable to parse response of type '{}' received from Euclid API path: {}", + "Unable to parse response of type '{}' received from Decision Engine config API path: {}", std::any::type_name::<Res>(), path ) })?; - logger::debug!(parsed_response = ?parsed_response, response_type = %std::any::type_name::<Res>(), euclid_request_path = %path, "decision_engine_euclid: Successfully parsed response from Euclid API"); + logger::debug!(parsed_response = ?parsed_response, response_type = %std::any::type_name::<Res>(), decision_engine_request_path = %path, "decision_engine_config: Successfully parsed response from Decision Engine config API"); Ok(parsed_response) } - async fn send_euclid_request_without_response_parsing<Req>( + async fn send_decision_engine_request_without_response_parsing<Req>( state: &SessionState, http_method: services::Method, path: &str, @@ -138,7 +205,7 @@ impl EuclidApiHandler for EuclidApiClient { where Req: Serialize + Send + Sync + 'static, { - let response = Self::build_and_send_euclid_http_request( + let response = build_and_send_decision_engine_http_request( state, http_method, path, @@ -148,7 +215,7 @@ impl EuclidApiHandler for EuclidApiClient { ) .await?; - logger::debug!(euclid_response = ?response, euclid_request_path = %path, "decision_engine_routing: Received raw response from Euclid API"); + logger::debug!(decision_engine_response = ?response, decision_engine_request_path = %path, "decision_engine_config: Received raw response from Decision Engine config API"); Ok(()) } } @@ -164,7 +231,7 @@ pub async fn perform_decision_euclid_routing( let routing_request = convert_backend_input_to_routing_eval(created_by, input)?; - let euclid_response: RoutingEvaluateResponse = EuclidApiClient::send_euclid_request( + let euclid_response: RoutingEvaluateResponse = EuclidApiClient::send_decision_engine_request( state, services::Method::Post, "routing/evaluate", @@ -186,7 +253,7 @@ pub async fn create_de_euclid_routing_algo( logger::debug!("decision_engine_euclid: create api call for euclid routing rule creation"); logger::debug!(decision_engine_euclid_request=?routing_request,"decision_engine_euclid"); - let euclid_response: RoutingDictionaryRecord = EuclidApiClient::send_euclid_request( + let euclid_response: RoutingDictionaryRecord = EuclidApiClient::send_decision_engine_request( state, services::Method::Post, "routing/create", @@ -205,7 +272,7 @@ pub async fn link_de_euclid_routing_algorithm( ) -> RoutingResult<()> { logger::debug!("decision_engine_euclid: link api call for euclid routing algorithm"); - EuclidApiClient::send_euclid_request_without_response_parsing( + EuclidApiClient::send_decision_engine_request_without_response_parsing( state, services::Method::Post, "routing/activate", @@ -224,7 +291,7 @@ pub async fn list_de_euclid_routing_algorithms( ) -> RoutingResult<Vec<api_routing::RoutingDictionaryRecord>> { logger::debug!("decision_engine_euclid: list api call for euclid routing algorithms"); let created_by = routing_list_request.created_by; - let response: Vec<RoutingAlgorithmRecord> = EuclidApiClient::send_euclid_request( + let response: Vec<RoutingAlgorithmRecord> = EuclidApiClient::send_decision_engine_request( state, services::Method::Post, format!("routing/list/{created_by}").as_str(), diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs index 6b86bb83f54..893c66af24c 100644 --- a/crates/router/src/core/routing.rs +++ b/crates/router/src/core/routing.rs @@ -19,6 +19,8 @@ use external_services::grpc_client::dynamic_routing::{ elimination_based_client::EliminationBasedRouting, success_rate_client::SuccessBasedDynamicRouting, }; +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +use helpers::update_decision_engine_dynamic_routing_setup; use hyperswitch_domain_models::{mandates, payment_address}; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use router_env::logger; @@ -564,6 +566,24 @@ pub async fn link_routing_config( .enabled_feature, routing_types::DynamicRoutingType::SuccessRateBasedRouting, ); + + // Call to DE here to update SR configs + #[cfg(all(feature = "dynamic_routing", feature = "v1"))] + { + if state.conf.open_router.enabled { + update_decision_engine_dynamic_routing_setup( + &state, + business_profile.get_id(), + routing_algorithm.algorithm_data.clone(), + routing_types::DynamicRoutingType::SuccessRateBasedRouting, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "Failed to update the success rate routing config in Decision Engine", + )?; + } + } } else if routing_algorithm.name == helpers::ELIMINATION_BASED_DYNAMIC_ROUTING_ALGORITHM { dynamic_routing_ref.update_algorithm_id( @@ -578,6 +598,22 @@ pub async fn link_routing_config( .enabled_feature, routing_types::DynamicRoutingType::EliminationRouting, ); + #[cfg(all(feature = "dynamic_routing", feature = "v1"))] + { + if state.conf.open_router.enabled { + update_decision_engine_dynamic_routing_setup( + &state, + business_profile.get_id(), + routing_algorithm.algorithm_data.clone(), + routing_types::DynamicRoutingType::EliminationRouting, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "Failed to update the elimination routing config in Decision Engine", + )?; + } + } } else if routing_algorithm.name == helpers::CONTRACT_BASED_DYNAMIC_ROUTING_ALGORITHM { dynamic_routing_ref.update_algorithm_id( algorithm_id, @@ -1516,7 +1552,7 @@ pub async fn success_based_routing_update_configs( name: dynamic_routing_algo_to_update.name, description: dynamic_routing_algo_to_update.description, kind: dynamic_routing_algo_to_update.kind, - algorithm_data: serde_json::json!(config_to_update), + algorithm_data: serde_json::json!(config_to_update.clone()), created_at: timestamp, modified_at: timestamp, algorithm_for: dynamic_routing_algo_to_update.algorithm_for, @@ -1551,23 +1587,25 @@ pub async fn success_based_routing_update_configs( router_env::metric_attributes!(("profile_id", profile_id.clone())), ); - state - .grpc_client - .dynamic_routing - .success_rate_client - .as_ref() - .async_map(|sr_client| async { - sr_client - .invalidate_success_rate_routing_keys( - profile_id.get_string_repr().into(), - state.get_grpc_headers(), - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to invalidate the routing keys") - }) - .await - .transpose()?; + if !state.conf.open_router.enabled { + state + .grpc_client + .dynamic_routing + .success_rate_client + .as_ref() + .async_map(|sr_client| async { + sr_client + .invalidate_success_rate_routing_keys( + profile_id.get_string_repr().into(), + state.get_grpc_headers(), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to invalidate the routing keys") + }) + .await + .transpose()?; + } Ok(service_api::ApplicationResponse::Json(new_record)) } @@ -1653,23 +1691,25 @@ pub async fn elimination_routing_update_configs( router_env::metric_attributes!(("profile_id", profile_id.clone())), ); - state - .grpc_client - .dynamic_routing - .elimination_based_client - .as_ref() - .async_map(|er_client| async { - er_client - .invalidate_elimination_bucket( - profile_id.get_string_repr().into(), - state.get_grpc_headers(), - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to invalidate the elimination routing keys") - }) - .await - .transpose()?; + if !state.conf.open_router.enabled { + state + .grpc_client + .dynamic_routing + .elimination_based_client + .as_ref() + .async_map(|er_client| async { + er_client + .invalidate_elimination_bucket( + profile_id.get_string_repr().into(), + state.get_grpc_headers(), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to invalidate the elimination routing keys") + }) + .await + .transpose()?; + } Ok(service_api::ApplicationResponse::Json(new_record)) } diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index e5cbd1b653f..1a092c8cf68 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -52,7 +52,12 @@ use crate::{ }; #[cfg(all(feature = "dynamic_routing", feature = "v1"))] use crate::{ - core::{metrics as core_metrics, routing}, + core::{ + metrics as core_metrics, + payments::routing::utils::{self as routing_utils, DecisionEngineApiHandler}, + routing, + }, + services, types::transformers::ForeignInto, }; pub const SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM: &str = @@ -62,6 +67,12 @@ pub const ELIMINATION_BASED_DYNAMIC_ROUTING_ALGORITHM: &str = pub const CONTRACT_BASED_DYNAMIC_ROUTING_ALGORITHM: &str = "Contract based dynamic routing algorithm"; +pub const DECISION_ENGINE_RULE_CREATE_ENDPOINT: &str = "rule/create"; +pub const DECISION_ENGINE_RULE_UPDATE_ENDPOINT: &str = "rule/update"; +pub const DECISION_ENGINE_RULE_DELETE_ENDPOINT: &str = "rule/delete"; +pub const DECISION_ENGINE_MERCHANT_BASE_ENDPOINT: &str = "merchant-account"; +pub const DECISION_ENGINE_MERCHANT_CREATE_ENDPOINT: &str = "merchant-account/create"; + /// Provides us with all the configured configs of the Merchant in the ascending time configured /// manner and chooses the first of them pub async fn get_merchant_default_config( @@ -1625,6 +1636,18 @@ pub async fn disable_dynamic_routing_algorithm( } }; + // Call to DE here + if state.conf.open_router.enabled { + disable_decision_engine_dynamic_routing_setup( + state, + business_profile.get_id(), + dynamic_routing_type, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to disable dynamic routing setup in decision engine")?; + } + // redact cache for dynamic routing config let _ = cache::redact_from_redis_and_publish( state.store.get_cache_store().as_ref(), @@ -1801,8 +1824,12 @@ pub async fn default_specific_dynamic_routing_setup( let timestamp = common_utils::date_time::now(); let algo = match dynamic_routing_type { routing_types::DynamicRoutingType::SuccessRateBasedRouting => { - let default_success_based_routing_config = - routing_types::SuccessBasedRoutingConfig::default(); + let default_success_based_routing_config = if state.conf.open_router.enabled { + routing_types::SuccessBasedRoutingConfig::open_router_config_default() + } else { + routing_types::SuccessBasedRoutingConfig::default() + }; + routing_algorithm::RoutingAlgorithm { algorithm_id: algorithm_id.clone(), profile_id: profile_id.clone(), @@ -1818,8 +1845,11 @@ pub async fn default_specific_dynamic_routing_setup( } } routing_types::DynamicRoutingType::EliminationRouting => { - let default_elimination_routing_config = - routing_types::EliminationRoutingConfig::default(); + let default_elimination_routing_config = if state.conf.open_router.enabled { + routing_types::EliminationRoutingConfig::open_router_config_default() + } else { + routing_types::EliminationRoutingConfig::default() + }; routing_algorithm::RoutingAlgorithm { algorithm_id: algorithm_id.clone(), profile_id: profile_id.clone(), @@ -1843,6 +1873,19 @@ pub async fn default_specific_dynamic_routing_setup( } }; + // Call to DE here + // Need to map out the cases if this call should always be made or not + if state.conf.open_router.enabled { + enable_decision_engine_dynamic_routing_setup( + state, + business_profile.get_id(), + dynamic_routing_type, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to setup decision engine dynamic routing")?; + } + let record = db .insert_routing_algorithm(algo) .await @@ -1945,3 +1988,234 @@ impl DynamicRoutingConfigParamsInterpolator { parts.join(":") } } + +#[cfg(all(feature = "dynamic_routing", feature = "v1"))] +#[instrument(skip_all)] +pub async fn enable_decision_engine_dynamic_routing_setup( + state: &SessionState, + profile_id: &id_type::ProfileId, + dynamic_routing_type: routing_types::DynamicRoutingType, +) -> RouterResult<()> { + logger::debug!( + "performing call with open_router for profile {}", + profile_id.get_string_repr() + ); + + let default_engine_config_request = match dynamic_routing_type { + routing_types::DynamicRoutingType::SuccessRateBasedRouting => { + let default_success_based_routing_config = + routing_types::SuccessBasedRoutingConfig::open_router_config_default(); + open_router::DecisionEngineConfigSetupRequest { + merchant_id: profile_id.get_string_repr().to_string(), + config: open_router::DecisionEngineConfigVariant::SuccessRate( + default_success_based_routing_config + .get_decision_engine_configs() + .change_context(errors::ApiErrorResponse::GenericNotFoundError { + message: "Decision engine config not found".to_string(), + }) + .attach_printable("Decision engine config not found")?, + ), + } + } + routing_types::DynamicRoutingType::EliminationRouting => { + let default_elimination_based_routing_config = + routing_types::EliminationRoutingConfig::open_router_config_default(); + open_router::DecisionEngineConfigSetupRequest { + merchant_id: profile_id.get_string_repr().to_string(), + config: open_router::DecisionEngineConfigVariant::Elimination( + default_elimination_based_routing_config + .get_decision_engine_configs() + .change_context(errors::ApiErrorResponse::GenericNotFoundError { + message: "Decision engine config not found".to_string(), + }) + .attach_printable("Decision engine config not found")?, + ), + } + } + routing_types::DynamicRoutingType::ContractBasedRouting => { + return Err((errors::ApiErrorResponse::InvalidRequestData { + message: "Contract routing cannot be set as default".to_string(), + }) + .into()) + } + }; + + routing_utils::ConfigApiClient::send_decision_engine_request::<_, String>( + state, + services::Method::Post, + DECISION_ENGINE_RULE_CREATE_ENDPOINT, + Some(default_engine_config_request), + None, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to setup decision engine dynamic routing")?; + + Ok(()) +} + +#[cfg(all(feature = "dynamic_routing", feature = "v1"))] +#[instrument(skip_all)] +pub async fn update_decision_engine_dynamic_routing_setup( + state: &SessionState, + profile_id: &id_type::ProfileId, + request: serde_json::Value, + dynamic_routing_type: routing_types::DynamicRoutingType, +) -> RouterResult<()> { + logger::debug!( + "performing call with open_router for profile {}", + profile_id.get_string_repr() + ); + + let decision_engine_request = match dynamic_routing_type { + routing_types::DynamicRoutingType::SuccessRateBasedRouting => { + let success_rate_config: routing_types::SuccessBasedRoutingConfig = request + .parse_value("SuccessBasedRoutingConfig") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to deserialize SuccessBasedRoutingConfig")?; + + open_router::DecisionEngineConfigSetupRequest { + merchant_id: profile_id.get_string_repr().to_string(), + config: open_router::DecisionEngineConfigVariant::SuccessRate( + success_rate_config + .get_decision_engine_configs() + .change_context(errors::ApiErrorResponse::GenericNotFoundError { + message: "Decision engine config not found".to_string(), + }) + .attach_printable("Decision engine config not found")?, + ), + } + } + routing_types::DynamicRoutingType::EliminationRouting => { + let elimination_config: routing_types::EliminationRoutingConfig = request + .parse_value("EliminationRoutingConfig") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to deserialize EliminationRoutingConfig")?; + + open_router::DecisionEngineConfigSetupRequest { + merchant_id: profile_id.get_string_repr().to_string(), + config: open_router::DecisionEngineConfigVariant::Elimination( + elimination_config + .get_decision_engine_configs() + .change_context(errors::ApiErrorResponse::GenericNotFoundError { + message: "Decision engine config not found".to_string(), + }) + .attach_printable("Decision engine config not found")?, + ), + } + } + routing_types::DynamicRoutingType::ContractBasedRouting => { + return Err((errors::ApiErrorResponse::InvalidRequestData { + message: "Contract routing cannot be set as default".to_string(), + }) + .into()) + } + }; + + routing_utils::ConfigApiClient::send_decision_engine_request::<_, String>( + state, + services::Method::Post, + DECISION_ENGINE_RULE_UPDATE_ENDPOINT, + Some(decision_engine_request), + None, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to update decision engine dynamic routing")?; + + Ok(()) +} + +#[cfg(all(feature = "dynamic_routing", feature = "v1"))] +#[instrument(skip_all)] +pub async fn disable_decision_engine_dynamic_routing_setup( + state: &SessionState, + profile_id: &id_type::ProfileId, + dynamic_routing_type: routing_types::DynamicRoutingType, +) -> RouterResult<()> { + logger::debug!( + "performing call with open_router for profile {}", + profile_id.get_string_repr() + ); + + let decision_engine_request = open_router::FetchRoutingConfig { + merchant_id: profile_id.get_string_repr().to_string(), + algorithm: match dynamic_routing_type { + routing_types::DynamicRoutingType::SuccessRateBasedRouting => { + open_router::AlgorithmType::SuccessRate + } + routing_types::DynamicRoutingType::EliminationRouting => { + open_router::AlgorithmType::Elimination + } + routing_types::DynamicRoutingType::ContractBasedRouting => { + return Err((errors::ApiErrorResponse::InvalidRequestData { + message: "Contract routing is not enabled for decision engine".to_string(), + }) + .into()) + } + }, + }; + + routing_utils::ConfigApiClient::send_decision_engine_request::<_, String>( + state, + services::Method::Post, + DECISION_ENGINE_RULE_DELETE_ENDPOINT, + Some(decision_engine_request), + None, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to disable decision engine dynamic routing")?; + + Ok(()) +} + +#[cfg(all(feature = "dynamic_routing", feature = "v1"))] +#[instrument(skip_all)] +pub async fn create_decision_engine_merchant( + state: &SessionState, + profile_id: &id_type::ProfileId, +) -> RouterResult<()> { + let merchant_account_req = open_router::MerchantAccount { + merchant_id: profile_id.get_string_repr().to_string(), + gateway_success_rate_based_decider_input: None, + }; + + routing_utils::ConfigApiClient::send_decision_engine_request::<_, String>( + state, + services::Method::Post, + DECISION_ENGINE_MERCHANT_CREATE_ENDPOINT, + Some(merchant_account_req), + None, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to create merchant account on decision engine")?; + + Ok(()) +} + +#[cfg(all(feature = "dynamic_routing", feature = "v1"))] +#[instrument(skip_all)] +pub async fn delete_decision_engine_merchant( + state: &SessionState, + profile_id: &id_type::ProfileId, +) -> RouterResult<()> { + let path = format!( + "{}/{}", + DECISION_ENGINE_MERCHANT_BASE_ENDPOINT, + profile_id.get_string_repr() + ); + routing_utils::ConfigApiClient::send_decision_engine_request_without_response_parsing::<()>( + state, + services::Method::Delete, + &path, + None, + None, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to delete merchant account on decision engine")?; + + Ok(()) +}
2025-05-15T12:16:45Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR integrates the decision engine config APIs The integration sits in the dynamic routing config flows. Based on ENV, if decision engine is enabled, we would call DE instead of Dynamo. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create a merchant account (Call to Decision Engine should be made for merchant creation) <img width="791" alt="image" src="https://github.com/user-attachments/assets/d01b64a5-9767-4fb2-ae88-8ebbe187dafe" /> 2. Toggle SR config (Call to Decision Engine should be made for SR config creation) ``` curl --location --request POST 'http://localhost:8080/account/merchant_1747841259/business_profile/pro_GUovaynfuaBwH3DUaBbJ/dynamic_routing/success_based/toggle?enable=dynamic_connector_selection' \ --header 'api-key: dev_9gwSrzjH1Xbs7HMswLgx0Av8upsibfu8wORNxyzpIls3NvT08auKe4RBQlkBgqRl' ``` ``` {"id":"routing_wd4JSbjaMmLDB96OxP7d","profile_id":"pro_GUovaynfuaBwH3DUaBbJ","name":"Success rate based dynamic routing algorithm","kind":"dynamic","description":"","created_at":1747841362,"modified_at":1747841362,"algorithm_for":"payment","decision_engine_routing_id":null} ``` <img width="816" alt="image" src="https://github.com/user-attachments/assets/92a3dba9-b77a-4f54-a004-51e52b452334" /> 3. Update SR config ``` curl --location --request PATCH 'http://localhost:8080/account/merchant_1747841259/business_profile/pro_GUovaynfuaBwH3DUaBbJ/dynamic_routing/success_based/config/routing_wd4JSbjaMmLDB96OxP7d' \ --header 'api-key: dev_9gwSrzjH1Xbs7HMswLgx0Av8upsibfu8wORNxyzpIls3NvT08auKe4RBQlkBgqRl' \ --header 'Content-Type: application/json' \ --data '{ "decision_engine_configs": { "defaultLatencyThreshold": 90, "defaultSuccessRate": 0.5, "defaultBucketSize": 200, "defaultHedgingPercent": 5, "subLevelInputConfig": [ { "paymentMethodType": "upi", "paymentMethod": "upi_collect", "bucketSize": 250, "hedgingPercent": 1 } ] } }' ``` ``` {"id":"routing_tgng0ubQwdK3hSaSjRye","profile_id":"pro_GUovaynfuaBwH3DUaBbJ","name":"Success rate based dynamic routing algorithm","kind":"dynamic","description":"","created_at":1747841498,"modified_at":1747841498,"algorithm_for":"payment","decision_engine_routing_id":null} ``` 4. Activate updated SR config (Call to Decision Engine should be made for SR config updation) ``` curl --location --request POST 'http://localhost:8080/routing/routing_tgng0ubQwdK3hSaSjRye/activate' \ --header 'api-key: dev_9gwSrzjH1Xbs7HMswLgx0Av8upsibfu8wORNxyzpIls3NvT08auKe4RBQlkBgqRl' ``` <img width="805" alt="image" src="https://github.com/user-attachments/assets/09345e37-8cf7-478f-b53a-44043883df4b" /> 4. Enable volume split ``` curl --location --request POST 'http://localhost:8080/account/merchant_1747841259/business_profile/pro_GUovaynfuaBwH3DUaBbJ/dynamic_routing/set_volume_split?split=100' \ --header 'api-key: dev_9gwSrzjH1Xbs7HMswLgx0Av8upsibfu8wORNxyzpIls3NvT08auKe4RBQlkBgqRl' ``` 5. Toggle ER config (Call to Decision Engine should be made for ER config creation) ``` curl --location --request POST 'http://localhost:8080/account/merchant_1747380349/business_profile/pro_28WNE1lOkSX9w3VdEPAN/dynamic_routing/elimination/toggle?enable=dynamic_connector_selection' \ --header 'api-key: dev_d87bY8HlyzBj4YYtGOIK2cj6yZLnPTxEkJN2o3lNJSxck0t3RghiH9zwrOR6Rexs' ``` ``` {"id":"routing_S5d4ArS1VLlyrnpZ3tTx","profile_id":"pro_28WNE1lOkSX9w3VdEPAN","name":"Elimination based dynamic routing algorithm","kind":"dynamic","description":"","created_at":1747380532,"modified_at":1747380532,"algorithm_for":"payment"} ``` <img width="1559" alt="image" src="https://github.com/user-attachments/assets/f849243c-1f51-4a7f-94e6-9f7c60917dfd" /> 6. Update ER config ``` curl --location --request PATCH 'http://localhost:8080/account/merchant_1747380349/business_profile/pro_28WNE1lOkSX9w3VdEPAN/dynamic_routing/elimination/config/routing_S5d4ArS1VLlyrnpZ3tTx' \ --header 'api-key: dev_d87bY8HlyzBj4YYtGOIK2cj6yZLnPTxEkJN2o3lNJSxck0t3RghiH9zwrOR6Rexs' \ --header 'Content-Type: application/json' \ --data '{ "decision_engine_configs": { "threshold": 0.45 } }' ``` ``` {"id":"routing_vOZoBnvZarFhmmLVXElW","profile_id":"pro_28WNE1lOkSX9w3VdEPAN","name":"Elimination based dynamic routing algorithm","kind":"dynamic","description":"","created_at":1747380711,"modified_at":1747380711,"algorithm_for":"payment"} ``` 7. Activate updated ER config (Call to Decision Engine should be made for ER config updation) ``` curl --location --request POST 'http://localhost:8080/routing/routing_vOZoBnvZarFhmmLVXElW/activate' \ --header 'api-key: dev_d87bY8HlyzBj4YYtGOIK2cj6yZLnPTxEkJN2o3lNJSxck0t3RghiH9zwrOR6Rexs' ``` <img width="1536" alt="image" src="https://github.com/user-attachments/assets/21c83167-e5c4-4f5b-9b1e-ca9b1e2f91ef" /> 8. Disable ER config ``` curl --location --request POST 'http://localhost:8080/account/merchant_1747380349/business_profile/pro_28WNE1lOkSX9w3VdEPAN/dynamic_routing/elimination/toggle?enable=none' \ --header 'api-key: dev_d87bY8HlyzBj4YYtGOIK2cj6yZLnPTxEkJN2o3lNJSxck0t3RghiH9zwrOR6Rexs' ``` <img width="1545" alt="image" src="https://github.com/user-attachments/assets/6e5ca5b1-06ef-4083-8271-603b6e108000" /> 9. make a payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_d87bY8HlyzBj4YYtGOIK2cj6yZLnPTxEkJN2o3lNJSxck0t3RghiH9zwrOR6Rexs' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ``` {"payment_id":"pay_WMa1HPuv2m4y1eUa8bJf","merchant_id":"merchant_1747380349","status":"succeeded","amount":6540,"net_amount":6540,"shipping_cost":null,"amount_capturable":0,"amount_received":6540,"connector":"stripe","client_secret":"pay_WMa1HPuv2m4y1eUa8bJf_secret_dLcjgQ2dafDp8Nl1vWZ7","created":"2025-05-16T07:52:09.020Z","currency":"USD","customer_id":"StripeCustomer","customer":{"id":"StripeCustomer","name":"John Doe","email":"[email protected]","phone":"999999999","phone_country_code":"+1"},"description":"Its my first payment request","refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"4242","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"424242","card_extended_bin":null,"card_exp_month":"10","card_exp_year":"25","card_holder_name":"joseph Doe","payment_checks":{"cvc_check":"pass","address_line1_check":"pass","address_postal_code_check":"pass"},"authentication_data":null},"billing":null},"payment_token":null,"shipping":{"address":{"city":"San Fransico","country":"US","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"California","first_name":"joseph","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":null},"billing":{"address":{"city":"San Fransico","country":"US","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"California","first_name":"joseph","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"},"email":null},"order_details":null,"email":"[email protected]","name":"John Doe","phone":"999999999","return_url":"https://google.com/","authentication_type":"no_three_ds","statement_descriptor_name":"joseph","statement_descriptor_suffix":"JS","next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"credit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"StripeCustomer","created_at":1747381929,"expires":1747385529,"secret":"epk_30f63c59ee2f4ce8b0d4e34a1bdd9119"},"manual_retry_allowed":false,"connector_transaction_id":"pi_3RPJ3tD5R7gDAGff0Jgz3U6C","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":null,"reference_id":"pi_3RPJ3tD5R7gDAGff0Jgz3U6C","payment_link":null,"profile_id":"pro_28WNE1lOkSX9w3VdEPAN","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_Zm1nyERaPTww6jSUgtak","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-05-16T08:07:09.020Z","fingerprint":null,"browser_info":null,"payment_method_id":null,"payment_method_status":null,"updated":"2025-05-16T07:52:10.486Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":"manual","force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null} ``` <img width="1253" alt="image" src="https://github.com/user-attachments/assets/ec3600d7-08f5-47d1-ac08-992890ea1bcd" /> <img width="1241" alt="image" src="https://github.com/user-attachments/assets/2d51e889-3e75-428f-b995-bf936c0cb905" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
d1fe2841c188a80b3bf46850540827844e1a426c
d1fe2841c188a80b3bf46850540827844e1a426c
juspay/hyperswitch
juspay__hyperswitch-8058
Bug: FIX[Config]: Add VGS baseurl to deployment toml files Need to add baseurl for VGS in `config/deployments/{integration_test, production, sandbox}.toml`
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 554e41b5021..79074230917 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -122,6 +122,7 @@ thunes.base_url = "https://api.limonetikqualif.com/" trustpay.base_url = "https://test-tpgw.trustpay.eu/" trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/" tsys.base_url = "https://stagegw.transnox.com/" +vgs.base_url = "https://sandbox.vault-api.verygoodvault.com" volt.base_url = "https://api.sandbox.volt.io/" wellsfargo.base_url = "https://apitest.cybersource.com/" wellsfargopayout.base_url = "https://api-sandbox.wellsfargo.com/" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index d93add96204..11beb9f0219 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -126,6 +126,7 @@ thunes.base_url = "https://api.limonetik.com/" trustpay.base_url = "https://tpgw.trustpay.eu/" trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/" tsys.base_url = "https://gateway.transit-pass.com/" +vgs.base_url = "https://sandbox.vault-api.verygoodvault.com" volt.base_url = "https://api.volt.io/" wellsfargo.base_url = "https://api.cybersource.com/" wellsfargopayout.base_url = "https://api.wellsfargo.com/" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index b5d3cb69cb2..43f764f4e02 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -126,6 +126,7 @@ thunes.base_url = "https://api.limonetikqualif.com/" trustpay.base_url = "https://test-tpgw.trustpay.eu/" trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/" tsys.base_url = "https://stagegw.transnox.com/" +vgs.base_url = "https://sandbox.vault-api.verygoodvault.com" volt.base_url = "https://api.sandbox.volt.io/" wellsfargo.base_url = "https://apitest.cybersource.com/" wellsfargopayout.base_url = "https://api-sandbox.wellsfargo.com/"
2025-05-16T12:01:10Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> Added baseurl for `VGS` connector in relevant deployment TOML files ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [x] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> - `config/deployments/integration_test.toml` - `config/deployments/production.toml` - `config/deployments/sandbox.toml` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #8058 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
3d095cec0cfc96ef907694be99087cc3668ba4b7
3d095cec0cfc96ef907694be99087cc3668ba4b7
juspay/hyperswitch
juspay__hyperswitch-8040
Bug: [REFACTOR] Refactor API Event Metric implementation for refunds v2 apis Refactor API Event Metric implementation for refunds v2 apis for logging and analytics.
diff --git a/crates/api_models/src/events/refund.rs b/crates/api_models/src/events/refund.rs index 08c6dd52c39..7a50af69284 100644 --- a/crates/api_models/src/events/refund.rs +++ b/crates/api_models/src/events/refund.rs @@ -22,13 +22,6 @@ impl ApiEventMetric for RefundRequest { } } -#[cfg(feature = "v2")] -impl ApiEventMetric for refunds::RefundsCreateRequest { - fn get_api_event_type(&self) -> Option<ApiEventsType> { - None - } -} - #[cfg(feature = "v1")] impl ApiEventMetric for refunds::RefundResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { @@ -43,7 +36,7 @@ impl ApiEventMetric for refunds::RefundResponse { impl ApiEventMetric for refunds::RefundResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Refund { - payment_id: self.payment_id.clone(), + payment_id: Some(self.payment_id.clone()), refund_id: self.id.clone(), }) } @@ -62,7 +55,10 @@ impl ApiEventMetric for RefundsRetrieveRequest { #[cfg(feature = "v2")] impl ApiEventMetric for refunds::RefundsRetrieveRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { - None + Some(ApiEventsType::Refund { + payment_id: None, + refund_id: self.refund_id.clone(), + }) } } diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs index f7a068b8e49..da7b9a873db 100644 --- a/crates/common_utils/src/events.rs +++ b/crates/common_utils/src/events.rs @@ -29,7 +29,7 @@ pub enum ApiEventsType { }, #[cfg(feature = "v2")] Refund { - payment_id: id_type::GlobalPaymentId, + payment_id: Option<id_type::GlobalPaymentId>, refund_id: id_type::GlobalRefundId, }, #[cfg(feature = "v1")] diff --git a/crates/diesel_models/src/refund.rs b/crates/diesel_models/src/refund.rs index 927965a5338..0defac38a45 100644 --- a/crates/diesel_models/src/refund.rs +++ b/crates/diesel_models/src/refund.rs @@ -811,7 +811,7 @@ impl common_utils::events::ApiEventMetric for Refund { impl common_utils::events::ApiEventMetric for Refund { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Refund { - payment_id: self.payment_id.clone(), + payment_id: Some(self.payment_id.clone()), refund_id: self.id.clone(), }) } diff --git a/crates/router/src/core/refunds_v2.rs b/crates/router/src/core/refunds_v2.rs index 922b9dce245..00e4a38cb8e 100644 --- a/crates/router/src/core/refunds_v2.rs +++ b/crates/router/src/core/refunds_v2.rs @@ -40,6 +40,7 @@ pub async fn refund_create_core( state: SessionState, merchant_context: domain::MerchantContext, req: refunds::RefundsCreateRequest, + global_refund_id: id_type::GlobalRefundId, ) -> errors::RouterResponse<refunds::RefundResponse> { let db = &*state.store; let (payment_intent, payment_attempt, amount); @@ -94,8 +95,6 @@ pub async fn refund_create_core( .await .to_not_found_response(errors::ApiErrorResponse::SuccessfulPaymentNotFound)?; - let global_refund_id = id_type::GlobalRefundId::generate(&state.conf.cell_information.id); - tracing::Span::current().record("global_refund_id", global_refund_id.get_string_repr()); Box::pin(validate_and_create_refund( diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs index 1ae4412807c..efc6fa2e93c 100644 --- a/crates/router/src/routes/refunds.rs +++ b/crates/router/src/routes/refunds.rs @@ -35,12 +35,11 @@ mod internal_payload_types { { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { let refund_id = self.global_refund_id.clone(); - self.payment_id - .clone() - .map(|payment_id| common_utils::events::ApiEventsType::Refund { - payment_id, - refund_id, - }) + let payment_id = self.payment_id.clone(); + Some(common_utils::events::ApiEventsType::Refund { + payment_id, + refund_id, + }) } } } @@ -105,16 +104,32 @@ pub async fn refunds_create( ) -> HttpResponse { let flow = Flow::RefundsCreate; + let global_refund_id = + common_utils::id_type::GlobalRefundId::generate(&state.conf.cell_information.id); + let payload = json_payload.into_inner(); + + let internal_refund_create_payload = + internal_payload_types::RefundsGenericRequestWithResourceId { + global_refund_id: global_refund_id.clone(), + payment_id: Some(payload.payment_id.clone()), + payload, + }; + Box::pin(api::server_wrap( flow, state, &req, - json_payload.into_inner(), + internal_refund_create_payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); - refund_create_core(state, merchant_context, req) + refund_create_core( + state, + merchant_context, + req.payload, + global_refund_id.clone(), + ) }, auth::auth_type( &auth::V2ApiKeyAuth {
2025-05-15T10:23:25Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR adds support for API Event Metric logging, the events will be logged to clickhouse when a request/response is triggered. In refunds v2, it will be for requests and responses for 4 apis 1. Refunds Create 2. Refunds Metadata Update 3. Refunds Retrieve 4. Refunds List ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> It will help us in keeping track of the requests/response and for analytical purposes and help in debugging. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - This will be tested when kafka and clickhouse is enabled for v2. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
3a451907a45035e40a04c335531a5b69414b3e04
3a451907a45035e40a04c335531a5b69414b3e04
juspay/hyperswitch
juspay__hyperswitch-8025
Bug: [BUG] Worldpay redirection flow stuck in endless DDC submission loop ### Bug Description Worldpay's redirection flow (3DS cards) is stuck in an endless loop of submit DDC form. This is happening for special cases where payment IDs contain non alphanumeric characters. For example - 100000091279-518099-3202453221111 #### Why does this happen? After DDC, the data needs to be submitted to WP which returns a collectionReference, which is passed on to the next step of HS - CompleteAuthorize. At this step, there is a regex which handles updating the redirectUrl from `/payments/redirect/PAYMENT_ID/MID/PAYMENT_ATTEMPT_ID` to `/payments/PAYMENT_ID/MID/redirect/complete/worldpay`. This regex considers only alphanumeric values for payment ID and merchant ID, leading to forming the same URL again, and submitting the same URL, and eventually getting stuck in a loop. ### Expected Behavior After DDC submission, the redirection should happen to /redirect/complete for invoking the CompleteAuthorize flow ### Actual Behavior After DDC submission, this step is stuck in an endless loop. ### Steps To Reproduce 1. Create a payment with non alphanumeric characters in the payment ID (auth_type: 3DS) 2. Open the redirection URL ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 3fef01a8c21..4bc57cfdaa8 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -1733,7 +1733,7 @@ pub fn build_redirection_form( (PreEscaped(format!( r#" function submitCollectionReference(collectionReference) {{ - var redirectPathname = window.location.pathname.replace(/payments\/redirect\/(\w+)\/(\w+)\/\w+/, "payments/$1/$2/redirect/complete/worldpay"); + var redirectPathname = window.location.pathname.replace(/payments\/redirect\/([^\/]+)\/([^\/]+)\/[^\/]+/, "payments/$1/$2/redirect/complete/worldpay"); var redirectUrl = window.location.origin + redirectPathname; try {{ if (typeof collectionReference === "string" && collectionReference.length > 0) {{ @@ -1746,7 +1746,7 @@ pub fn build_redirection_form( input.value = collectionReference; form.appendChild(input); document.body.appendChild(form); - form.submit();; + form.submit(); }} else {{ window.location.replace(redirectUrl); }}
2025-05-14T10:49:54Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR updates the regex used for forming the CompleteAuthorize URL for Worldpay post DDC submission. Change made - the regex is updated to match any character except `/` for matching the query parameters. Earlier `/w` was being used which matched only the alphanumeric characters and underscore. Defined in https://github.com/juspay/hyperswitch/issues/8025 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Fixes the 3DS flows for Worldpay connector where consumers send the payment IDs (which may include non alphanumeric characters) ## How did you test it? Steps for testing - <details> <summary>1. Create a payment with non alphanumeric characters in payment ID</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_TnDKeLU9mvDKwpEbzt1wd69xKW9drPRLLSjrsd9lnrF9WlaYI9Fxb38mBT9lGgF1' \ --data-raw '{"amount":10000,"payment_id":"pay-93bd1c5d-daad-4b28-9968-a3312fe6a83d","currency":"EUR","confirm":true,"profile_id":"pro_4VVXVGE88DgoRaP6ynQI","capture_method":"automatic","capture_on":"2022-09-10T10:11:12Z","authentication_type":"three_ds","customer_id":"cus_Wz8ND2QMGUTQCZBgO4Jx","email":"[email protected]","return_url":"https://google.com","payment_method":"card","payment_method_type":"debit","payment_method_data":{"card":{"card_number":"4000000000002503","card_exp_month":"12","card_exp_year":"2028","card_holder_name":"John Doe","card_cvc":"829"}},"metadata":{"Force-PSP":"Adyen","udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"browser_info":{"user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"en-US","color_depth":32,"screen_height":1117,"screen_width":1728,"time_zone":-330,"java_enabled":true,"java_script_enabled":true,"ip_address":"127.0.0.1"},"customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"connector_metadata":{"adyen":{"testing":{}}},"session_expiry":60}' Response {"payment_id":"pay-70b37ad5-dff2-447f-aa35-3638ee8f49a2","merchant_id":"merchant_1747207118","status":"requires_customer_action","amount":10000,"net_amount":10000,"shipping_cost":null,"amount_capturable":10000,"amount_received":null,"connector":"worldpay","client_secret":"pay-70b37ad5-dff2-447f-aa35-3638ee8f49a2_secret_yHFganGnHhl61BLGOu7t","created":"2025-05-14T10:46:44.551Z","currency":"EUR","customer_id":"cus_Wz8ND2QMGUTQCZBgO4Jx","customer":{"id":"cus_Wz8ND2QMGUTQCZBgO4Jx","name":null,"email":"[email protected]","phone":null,"phone_country_code":null},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"2503","card_type":"CREDIT","card_network":"Visa","card_issuer":"INTL HDQTRS-CENTER OWNED","card_issuing_country":"UNITEDSTATES","card_isin":"400000","card_extended_bin":null,"card_exp_month":"12","card_exp_year":"2028","card_holder_name":"John Doe","payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":null,"order_details":null,"email":"[email protected]","name":null,"phone":null,"return_url":"https://google.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":{"type":"redirect_to_url","redirect_to_url":"http://localhost:8080/payments/redirect/pay-70b37ad5-dff2-447f-aa35-3638ee8f49a2/merchant_1747207118/pay-70b37ad5-dff2-447f-aa35-3638ee8f49a2_1"},"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"credit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_Wz8ND2QMGUTQCZBgO4Jx","created_at":1747219604,"expires":1747223204,"secret":"epk_87fd2e1ca6d4420cb2d9b1be49aac61c"},"manual_retry_allowed":null,"connector_transaction_id":"eyJrIjoxLCJkIjoidjh4TDNMbk9jNGJyeVhHeVJlRVN6TXV6VDl2SlBrRzBSSE9VZ09JVWxjNFB4MFNVUVlGVEpHS1ZPTGZnaXZnK0M2QUZSRzROQnJmZU12dXl6T3ZqOWc9PSJ9_1","frm_message":null,"metadata":{"udf1":"value1","Force-PSP":"Adyen","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":{"apple_pay":null,"airwallex":null,"noon":null,"braintree":null,"adyen":{"testing":{"holder_name":null}}},"feature_metadata":null,"reference_id":"47d77e52-3bf1-457d-b32f-2b64671269b3","payment_link":null,"profile_id":"pro_4VVXVGE88DgoRaP6ynQI","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_R9QZT88xlIImFvkbzRjS","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-05-14T10:47:44.551Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":32,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_method_id":null,"payment_method_status":null,"updated":"2025-05-14T10:46:45.055Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":"manual","force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null} </details> 2. Proceed with the payment <details> <summary>3. Retrieve the payment</summary> cURL curl --location --request GET 'http://localhost:8080/payments/pay-70b37ad5-dff2-447f-aa35-3638ee8f49a2?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: snd_TyCUg91YvGEf7k0FZjoyx3rIiH8RuP3H051L38LFsaBOyFC2DzoV112sVcLcOIju' Response {"payment_id":"pay_rXpDVF7rBTlK81BLCk78","merchant_id":"merchant_1681193734270","status":"succeeded","amount":1000,"net_amount":1000,"shipping_cost":null,"amount_capturable":0,"amount_received":1000,"connector":"novalnet","client_secret":"pay_rXpDVF7rBTlK81BLCk78_secret_jYyGNnraiAbHZflZ1cUe","created":"2025-05-14T08:30:16.439Z","currency":"EUR","customer_id":"cus_zBM97pQlSjmFTtTZlXnn","customer":{"id":"cus_zBM97pQlSjmFTtTZlXnn","name":"John Nether","email":"[email protected]","phone":"6168205362","phone_country_code":"+1"},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":null,"payment_method":"wallet","payment_method_data":{"wallet":{},"billing":null},"payment_token":null,"shipping":null,"billing":{"address":null,"phone":null,"email":"[email protected]"},"order_details":null,"email":"[email protected]","name":"John Nether","phone":"6168205362","return_url":"https://www.example.com/","authentication_type":"three_ds","statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":"redirect_to_url","payment_method_type":"paypal","connector_label":null,"business_country":null,"business_label":null,"business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":null,"manual_retry_allowed":false,"connector_transaction_id":"15185400044502956","frm_message":null,"metadata":null,"connector_metadata":null,"feature_metadata":null,"reference_id":"15185400044502956","payment_link":{"link":"https://gdpp-dev.zurich.com/payment_link/merchant_1681193734270/pay_rXpDVF7rBTlK81BLCk78?locale=en","secure_link":"https://gdpp-dev.zurich.com/payment_link/s/merchant_1681193734270/pay_rXpDVF7rBTlK81BLCk78?locale=en","payment_link_id":"plink_Rth6buCuxL0WM34L3ZgE"},"profile_id":"pro_E7pM8kGERopEKEhqwfWQ","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_76uMkQC2ErtAXZ3zTMXT","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-05-14T08:45:16.436Z","fingerprint":null,"browser_info":{"os_type":"macOS","language":"en-US","time_zone":-330,"ip_address":"122.172.83.222","os_version":"10.15.7","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.4 Safari/605.1.15","color_depth":24,"device_model":"Macintosh","java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"accept_language":"en","java_script_enabled":true},"payment_method_id":"pm_EHYfLI1wWenwsVsIC5P3","payment_method_status":"active","updated":"2025-05-14T08:30:45.990Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":null,"force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null} </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
46e830a87f60c1c2117c4b48a1c2ecbb6cf9e4d7
46e830a87f60c1c2117c4b48a1c2ecbb6cf9e4d7
juspay/hyperswitch
juspay__hyperswitch-8026
Bug: [chore]: use crates.io version of async-bb8-diesel crate Currently we are using a [forked](https://github.com/jarnura/async-bb8-diesel) version of this dependency. We need to migrate to the crates.io version
diff --git a/Cargo.lock b/Cargo.lock index d2ae0213703..6df00ec7517 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -559,15 +559,16 @@ dependencies = [ [[package]] name = "async-bb8-diesel" -version = "0.1.0" -source = "git+https://github.com/jarnura/async-bb8-diesel?rev=53b4ab901aab7635c8215fd1c2d542c8db443094#53b4ab901aab7635c8215fd1c2d542c8db443094" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc03a2806f66f36513d65e0a7f34200382230250cadcf8a8397cfbe3f26b795" dependencies = [ "async-trait", "bb8", "diesel", + "futures 0.3.30", "thiserror 1.0.63", "tokio 1.40.0", - "tracing", ] [[package]] diff --git a/crates/diesel_models/Cargo.toml b/crates/diesel_models/Cargo.toml index ca7e85628bd..e10428c5daf 100644 --- a/crates/diesel_models/Cargo.toml +++ b/crates/diesel_models/Cargo.toml @@ -17,7 +17,7 @@ payment_methods_v2 = [] refunds_v2 = [] [dependencies] -async-bb8-diesel = { git = "https://github.com/jarnura/async-bb8-diesel", rev = "53b4ab901aab7635c8215fd1c2d542c8db443094" } +async-bb8-diesel = "0.2.1" diesel = { version = "2.2.3", features = ["postgres", "serde_json", "time", "128-column-tables"] } error-stack = "0.4.1" rustc-hash = "1.1.0" diff --git a/crates/drainer/Cargo.toml b/crates/drainer/Cargo.toml index ce7301a0305..a783e8c9128 100644 --- a/crates/drainer/Cargo.toml +++ b/crates/drainer/Cargo.toml @@ -14,7 +14,7 @@ v1 = ["diesel_models/v1", "hyperswitch_interfaces/v1", "common_utils/v1"] [dependencies] actix-web = "4.5.1" -async-bb8-diesel = { git = "https://github.com/jarnura/async-bb8-diesel", rev = "53b4ab901aab7635c8215fd1c2d542c8db443094" } +async-bb8-diesel = "0.2.1" async-trait = "0.1.79" bb8 = "0.8" clap = { version = "4.4.18", default-features = false, features = ["std", "derive", "help", "usage"] } diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 5395e538c29..06fd5ce67b1 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -53,7 +53,7 @@ actix-multipart = "0.6.1" actix-rt = "2.9.0" actix-web = "4.5.1" argon2 = { version = "0.5.3", features = ["std"] } -async-bb8-diesel = { git = "https://github.com/jarnura/async-bb8-diesel", rev = "53b4ab901aab7635c8215fd1c2d542c8db443094" } +async-bb8-diesel = "0.2.1" async-trait = "0.1.79" base64 = "0.22.0" bb8 = "0.8" diff --git a/crates/storage_impl/Cargo.toml b/crates/storage_impl/Cargo.toml index 06b551d8312..ad712565b52 100644 --- a/crates/storage_impl/Cargo.toml +++ b/crates/storage_impl/Cargo.toml @@ -32,7 +32,7 @@ router_derive = { version = "0.1.0", path = "../router_derive" } router_env = { version = "0.1.0", path = "../router_env" } # Third party crates -async-bb8-diesel = { git = "https://github.com/jarnura/async-bb8-diesel", rev = "53b4ab901aab7635c8215fd1c2d542c8db443094" } +async-bb8-diesel = "0.2.1" async-trait = "0.1.79" bb8 = "0.8.3" bytes = "1.6.0"
2025-05-14T10:53:34Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [x] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Changed `async-bb8-diesel crate from custom [fork](https://github.com/jarnura/async-bb8-diesel) to crates.io [version](https://github.com/oxidecomputer/async-bb8-diesel) ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #8026 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Ran clippy and tested multiple endpoints in the `router` binary ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
46e830a87f60c1c2117c4b48a1c2ecbb6cf9e4d7
46e830a87f60c1c2117c4b48a1c2ecbb6cf9e4d7
juspay/hyperswitch
juspay__hyperswitch-8037
Bug: [FEATURE] Revolut pay wallet integration for stripe ### Feature Description Docs: https://docs.stripe.com/payments/revolut-pay API: https://docs.stripe.com/api/payment_methods/create?api-version=2025-04-30.basil ### Possible Implementation - integrate Revolut pay ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 956d6d6697c..1ef5d7ef462 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -16854,7 +16854,8 @@ "mifinity", "open_banking_pis", "direct_carrier_billing", - "instant_bank_transfer" + "instant_bank_transfer", + "revolut_pay" ] }, "PaymentMethodUpdate": { @@ -21534,6 +21535,9 @@ } } }, + "RevolutPayData": { + "type": "object" + }, "RewardData": { "type": "object", "required": [ @@ -24298,6 +24302,17 @@ "$ref": "#/components/schemas/MifinityData" } } + }, + { + "type": "object", + "required": [ + "revolut_pay" + ], + "properties": { + "revolut_pay": { + "$ref": "#/components/schemas/RevolutPayData" + } + } } ] }, diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index ed5757c1875..c192ef38b77 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -18948,7 +18948,8 @@ "mifinity", "open_banking_pis", "direct_carrier_billing", - "instant_bank_transfer" + "instant_bank_transfer", + "revolut_pay" ] }, "PaymentMethodUpdate": { @@ -25910,6 +25911,9 @@ } } }, + "RevolutPayData": { + "type": "object" + }, "RewardData": { "type": "object", "required": [ @@ -28679,6 +28683,17 @@ "$ref": "#/components/schemas/MifinityData" } } + }, + { + "type": "object", + "required": [ + "revolut_pay" + ], + "properties": { + "revolut_pay": { + "$ref": "#/components/schemas/RevolutPayData" + } + } } ] }, diff --git a/config/deployments/production.toml b/config/deployments/production.toml index ea2c520a9d3..63cb6754674 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -551,6 +551,7 @@ ideal = { country = "NL", currency = "EUR" } klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NL,NZ,NO,PL,PT,ES,SE,CH,GB,US", currency = "AUD,CAD,CHF,CZK,DKK,EUR,GBP,NOK,NZD,PLN,SEK,USD" } multibanco = { country = "PT", currency = "EUR" } ach = { country = "US", currency = "USD" } +revolut_pay = { currency = "EUR,GBP" } [pm_filters.volt] open_banking_uk = {country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT,NL,PT,SI,SK,BG,CZ,DK,HU,NO,PL,RO,SE,AU,BR", currency = "EUR,GBP,DKK,NOK,PLN,SEK,AUD,BRL"} diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 8b0575f462d..f13435cbc5e 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -559,6 +559,7 @@ ideal = { country = "NL", currency = "EUR" } klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NL,NZ,NO,PL,PT,ES,SE,CH,GB,US", currency = "AUD,CAD,CHF,CZK,DKK,EUR,GBP,NOK,NZD,PLN,SEK,USD" } multibanco = { country = "PT", currency = "EUR" } ach = { country = "US", currency = "USD" } +revolut_pay = { currency = "EUR,GBP" } [pm_filters.volt] open_banking_uk = { country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT,NL,PT,SI,SK,BG,CZ,DK,HU,NO,PL,RO,SE,AU,BR", currency = "EUR,GBP,DKK,NOK,PLN,SEK,AUD,BRL" } diff --git a/config/development.toml b/config/development.toml index 08194747a73..6d71cfa1d8c 100644 --- a/config/development.toml +++ b/config/development.toml @@ -442,6 +442,7 @@ ideal = { country = "NL", currency = "EUR" } cashapp = { country = "US", currency = "USD" } multibanco = { country = "PT", currency = "EUR" } ach = { country = "US", currency = "USD" } +revolut_pay = { currency = "EUR,GBP" } [pm_filters.volt] open_banking_uk = { country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT,NL,PT,SI,SK,BG,CZ,DK,HU,NO,PL,RO,SE,AU,BR", currency = "EUR,GBP,DKK,NOK,PLN,SEK,AUD,BRL" } diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 4b17d1e3caf..7ab8bc19361 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -2685,6 +2685,7 @@ impl GetPaymentMethodType for WalletData { Self::CashappQr(_) => api_enums::PaymentMethodType::Cashapp, Self::SwishQr(_) => api_enums::PaymentMethodType::Swish, Self::Mifinity(_) => api_enums::PaymentMethodType::Mifinity, + Self::RevolutPay(_) => api_enums::PaymentMethodType::RevolutPay, } } } @@ -3609,6 +3610,8 @@ pub enum WalletData { SwishQr(SwishQrData), // The wallet data for Mifinity Ewallet Mifinity(MifinityData), + // The wallet data for RevolutPay + RevolutPay(RevolutPayData), } impl GetAddressFromPaymentMethodData for WalletData { @@ -3660,7 +3663,8 @@ impl GetAddressFromPaymentMethodData for WalletData { | Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) | Self::CashappQr(_) - | Self::SwishQr(_) => None, + | Self::SwishQr(_) + | Self::RevolutPay(_) => None, } } } @@ -3895,6 +3899,9 @@ pub struct TouchNGoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SwishQrData {} +#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] +pub struct RevolutPayData {} + #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MifinityData { #[schema(value_type = Date)] diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index b3ab41b020a..498055bd18c 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1922,6 +1922,7 @@ pub enum PaymentMethodType { OpenBankingPIS, DirectCarrierBilling, InstantBankTransfer, + RevolutPay, } impl PaymentMethodType { @@ -2034,6 +2035,7 @@ impl PaymentMethodType { Self::Mifinity => "MiFinity", Self::OpenBankingPIS => "Open Banking PIS", Self::DirectCarrierBilling => "Direct Carrier Billing", + Self::RevolutPay => "RevolutPay", }; display_name.to_string() } diff --git a/crates/common_enums/src/transformers.rs b/crates/common_enums/src/transformers.rs index 2a130edbd84..5a14e5056af 100644 --- a/crates/common_enums/src/transformers.rs +++ b/crates/common_enums/src/transformers.rs @@ -1894,6 +1894,7 @@ impl From<PaymentMethodType> for PaymentMethod { PaymentMethodType::PayEasy => Self::Voucher, PaymentMethodType::OpenBankingPIS => Self::OpenBanking, PaymentMethodType::DirectCarrierBilling => Self::MobilePayment, + PaymentMethodType::RevolutPay => Self::Wallet, } } } diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index b912505dd27..55d469c4635 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -4006,6 +4006,8 @@ merchant_secret="Source verification key" [[stripe.wallet]] payment_method_type = "cashapp" payment_experience = "display_qr_code" +[[stripe.wallet]] + payment_method_type = "revolut_pay" is_verifiable = true [stripe.connector_auth.HeaderKey] api_key="Secret Key" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 02aeb3fca58..4d4456cf715 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -2846,6 +2846,8 @@ merchant_secret="Source verification key" payment_method_type = "apple_pay" [[stripe.wallet]] payment_method_type = "google_pay" +[[stripe.wallet]] + payment_method_type = "revolut_pay" is_verifiable = true [stripe.connector_auth.HeaderKey] api_key="Secret Key" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 8532765ee4f..28227a72554 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -3967,6 +3967,8 @@ merchant_secret="Source verification key" payment_method_type = "ali_pay" [[stripe.wallet]] payment_method_type = "cashapp" +[[stripe.wallet]] + payment_method_type = "revolut_pay" is_verifiable = true [stripe.connector_auth.HeaderKey] api_key="Secret Key" diff --git a/crates/euclid/src/frontend/dir/enums.rs b/crates/euclid/src/frontend/dir/enums.rs index 9fbb86fa0c1..3ea17b93c32 100644 --- a/crates/euclid/src/frontend/dir/enums.rs +++ b/crates/euclid/src/frontend/dir/enums.rs @@ -96,6 +96,7 @@ pub enum WalletType { Venmo, Mifinity, Paze, + RevolutPay, } #[derive( diff --git a/crates/euclid/src/frontend/dir/lowering.rs b/crates/euclid/src/frontend/dir/lowering.rs index ea5a8cd7c4b..c84aa83d485 100644 --- a/crates/euclid/src/frontend/dir/lowering.rs +++ b/crates/euclid/src/frontend/dir/lowering.rs @@ -62,6 +62,7 @@ impl From<enums::WalletType> for global_enums::PaymentMethodType { enums::WalletType::Venmo => Self::Venmo, enums::WalletType::Mifinity => Self::Mifinity, enums::WalletType::Paze => Self::Paze, + enums::WalletType::RevolutPay => Self::RevolutPay, } } } diff --git a/crates/euclid/src/frontend/dir/transformers.rs b/crates/euclid/src/frontend/dir/transformers.rs index b4b512b5234..d326bb24e49 100644 --- a/crates/euclid/src/frontend/dir/transformers.rs +++ b/crates/euclid/src/frontend/dir/transformers.rs @@ -25,6 +25,7 @@ impl IntoDirValue for (global_enums::PaymentMethodType, global_enums::PaymentMet global_enums::PaymentMethodType::GooglePay => Ok(dirval!(WalletType = GooglePay)), global_enums::PaymentMethodType::ApplePay => Ok(dirval!(WalletType = ApplePay)), global_enums::PaymentMethodType::Paypal => Ok(dirval!(WalletType = Paypal)), + global_enums::PaymentMethodType::RevolutPay => Ok(dirval!(WalletType = RevolutPay)), global_enums::PaymentMethodType::CryptoCurrency => { Ok(dirval!(CryptoType = CryptoCurrency)) } diff --git a/crates/hyperswitch_connectors/src/connectors/aci/transformers.rs b/crates/hyperswitch_connectors/src/connectors/aci/transformers.rs index 3e4ac8d80a8..e5f7ec19b50 100644 --- a/crates/hyperswitch_connectors/src/connectors/aci/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/aci/transformers.rs @@ -140,7 +140,8 @@ impl TryFrom<(&WalletData, &PaymentsAuthorizeRouterData)> for PaymentDetails { | WalletData::AliPayQr(_) | WalletData::ApplePayRedirect(_) | WalletData::GooglePayRedirect(_) - | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + | WalletData::Mifinity(_) + | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( "Payment method".to_string(), ))?, }; diff --git a/crates/hyperswitch_connectors/src/connectors/adyen.rs b/crates/hyperswitch_connectors/src/connectors/adyen.rs index a2a8b3dabdb..23fd0e5c5bc 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyen.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyen.rs @@ -327,7 +327,8 @@ impl ConnectorValidation for Adyen { | PaymentMethodType::LocalBankRedirect | PaymentMethodType::OpenBankingPIS | PaymentMethodType::InstantBankTransfer - | PaymentMethodType::SepaBankTransfer => { + | PaymentMethodType::SepaBankTransfer + | PaymentMethodType::RevolutPay => { capture_method_not_supported!(connector, capture_method, payment_method_type) } }, diff --git a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs index 26ba1cbe52b..a9b68b86a51 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs @@ -2268,7 +2268,8 @@ impl TryFrom<(&WalletData, &PaymentsAuthorizeRouterData)> for AdyenPaymentMethod | WalletData::PaypalSdk(_) | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) - | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + | WalletData::Mifinity(_) + | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Adyen"), ) .into()), diff --git a/crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs b/crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs index 9f154103c69..78e8fd318b2 100644 --- a/crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs @@ -361,7 +361,8 @@ fn get_wallet_details( | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) - | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + | WalletData::Mifinity(_) + | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("airwallex"), ))?, }; diff --git a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs index 9bd809c124f..62e483395e6 100644 --- a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs @@ -466,7 +466,8 @@ impl TryFrom<&SetupMandateRouterData> for CreateCustomerProfileRequest { | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) - | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + | WalletData::Mifinity(_) + | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("authorizedotnet"), ))?, }, @@ -1925,7 +1926,8 @@ fn get_wallet_data( | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) - | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + | WalletData::Mifinity(_) + | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("authorizedotnet"), ))?, } diff --git a/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs index 7aed189fbd7..5c1d70317ae 100644 --- a/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs @@ -327,7 +327,8 @@ impl TryFrom<&SetupMandateRouterData> for BankOfAmericaPaymentsRequest { | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) - | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + | WalletData::Mifinity(_) + | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("BankOfAmerica"), ))?, }, @@ -1109,7 +1110,8 @@ impl TryFrom<&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>> | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) - | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + | WalletData::Mifinity(_) + | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message( "Bank of America", ), diff --git a/crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs index b8ebe76e5d1..1aa3c450e51 100644 --- a/crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs @@ -391,7 +391,8 @@ impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>> for Blues | WalletData::CashappQr(_) | WalletData::SwishQr(_) | WalletData::WeChatPayQr(_) - | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + | WalletData::Mifinity(_) + | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("bluesnap"), )), }, diff --git a/crates/hyperswitch_connectors/src/connectors/boku/transformers.rs b/crates/hyperswitch_connectors/src/connectors/boku/transformers.rs index 1565b959a9b..6884974aa61 100644 --- a/crates/hyperswitch_connectors/src/connectors/boku/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/boku/transformers.rs @@ -200,7 +200,8 @@ fn get_wallet_type(wallet_data: &WalletData) -> Result<String, errors::Connector | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) - | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + | WalletData::Mifinity(_) + | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("boku"), )), } diff --git a/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs b/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs index d3150a3b049..ec8368f0ab6 100644 --- a/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs @@ -131,7 +131,8 @@ impl TryFrom<&TokenizationRouterData> for TokenRequest { | WalletData::CashappQr(_) | WalletData::SwishQr(_) | WalletData::WeChatPayQr(_) - | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + | WalletData::Mifinity(_) + | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("checkout"), ) .into()), @@ -385,7 +386,8 @@ impl TryFrom<&CheckoutRouterData<&PaymentsAuthorizeRouterData>> for PaymentsRequ | WalletData::CashappQr(_) | WalletData::SwishQr(_) | WalletData::WeChatPayQr(_) - | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + | WalletData::Mifinity(_) + | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("checkout"), )), }, diff --git a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs index 7f920f0e461..6b4101a15d2 100644 --- a/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs @@ -295,7 +295,8 @@ impl TryFrom<&SetupMandateRouterData> for CybersourceZeroMandateRequest { | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) - | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + | WalletData::Mifinity(_) + | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Cybersource"), ))?, }, @@ -2188,7 +2189,8 @@ impl TryFrom<&CybersourceRouterData<&PaymentsAuthorizeRouterData>> for Cybersour | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) - | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + | WalletData::Mifinity(_) + | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Cybersource"), ) .into()), diff --git a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs index d05654265fd..52a26f9d39b 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs @@ -587,7 +587,8 @@ impl TryFrom<&FiuuRouterData<&PaymentsAuthorizeRouterData>> for FiuuPaymentReque | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) - | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + | WalletData::Mifinity(_) + | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("fiuu"), ) .into()), diff --git a/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs index cd87eed6d20..0b6823ab9cc 100644 --- a/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs @@ -83,7 +83,8 @@ impl TryFrom<&GlobepayRouterData<&types::PaymentsAuthorizeRouterData>> for Globe | WalletData::WeChatPayRedirect(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) - | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + | WalletData::Mifinity(_) + | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("globepay"), ))?, }, diff --git a/crates/hyperswitch_connectors/src/connectors/klarna.rs b/crates/hyperswitch_connectors/src/connectors/klarna.rs index 03ef376fbbe..38077ef8749 100644 --- a/crates/hyperswitch_connectors/src/connectors/klarna.rs +++ b/crates/hyperswitch_connectors/src/connectors/klarna.rs @@ -640,7 +640,8 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData | common_enums::PaymentMethodType::DuitNow | common_enums::PaymentMethodType::PromptPay | common_enums::PaymentMethodType::VietQr - | common_enums::PaymentMethodType::OpenBankingPIS, + | common_enums::PaymentMethodType::OpenBankingPIS + | common_enums::PaymentMethodType::RevolutPay, ) => Err(error_stack::report!(errors::ConnectorError::NotSupported { message: payment_method_type.to_string(), connector: "klarna", @@ -754,7 +755,8 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData | common_enums::PaymentMethodType::DuitNow | common_enums::PaymentMethodType::PromptPay | common_enums::PaymentMethodType::VietQr - | common_enums::PaymentMethodType::OpenBankingPIS, + | common_enums::PaymentMethodType::OpenBankingPIS + | common_enums::PaymentMethodType::RevolutPay, ) => Err(error_stack::report!(errors::ConnectorError::NotSupported { message: payment_method_type.to_string(), connector: "klarna", @@ -875,7 +877,8 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData | common_enums::PaymentMethodType::DuitNow | common_enums::PaymentMethodType::PromptPay | common_enums::PaymentMethodType::VietQr - | common_enums::PaymentMethodType::OpenBankingPIS, + | common_enums::PaymentMethodType::OpenBankingPIS + | common_enums::PaymentMethodType::RevolutPay, ) => Err(error_stack::report!(errors::ConnectorError::NotSupported { message: payment_method_type.to_string(), connector: "klarna", @@ -989,7 +992,8 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData | common_enums::PaymentMethodType::DuitNow | common_enums::PaymentMethodType::PromptPay | common_enums::PaymentMethodType::VietQr - | common_enums::PaymentMethodType::OpenBankingPIS, + | common_enums::PaymentMethodType::OpenBankingPIS + | common_enums::PaymentMethodType::RevolutPay, ) => Err(error_stack::report!(errors::ConnectorError::NotSupported { message: payment_method_type.to_string(), connector: "klarna", diff --git a/crates/hyperswitch_connectors/src/connectors/mifinity/transformers.rs b/crates/hyperswitch_connectors/src/connectors/mifinity/transformers.rs index ba2fbc4c301..0a9df16eb6a 100644 --- a/crates/hyperswitch_connectors/src/connectors/mifinity/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/mifinity/transformers.rs @@ -185,7 +185,8 @@ impl TryFrom<&MifinityRouterData<&types::PaymentsAuthorizeRouterData>> for Mifin | WalletData::WeChatPayRedirect(_) | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) - | WalletData::SwishQr(_) => Err(errors::ConnectorError::NotImplemented( + | WalletData::SwishQr(_) + | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Mifinity"), ) .into()), diff --git a/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs index 9dda361088e..c7cc7967c4c 100644 --- a/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs @@ -516,7 +516,8 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) - | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + | WalletData::Mifinity(_) + | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("multisafepay"), ))?, }, @@ -582,7 +583,8 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) - | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + | WalletData::Mifinity(_) + | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("multisafepay"), ))?, }), @@ -743,7 +745,8 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) - | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + | WalletData::Mifinity(_) + | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("multisafepay"), ))?, }, diff --git a/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs index 8e4b9995040..9548c903c11 100644 --- a/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs @@ -729,7 +729,8 @@ fn get_wallet_details( | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) - | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + | WalletData::Mifinity(_) + | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("nexinets"), ))?, } diff --git a/crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs index e789cb637c3..99f3d3aac80 100644 --- a/crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs @@ -568,7 +568,8 @@ impl TryFrom<(&PaymentMethodData, Option<&PaymentsAuthorizeRouterData>)> for Pay | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) - | WalletData::Mifinity(_) => Err(report!(ConnectorError::NotImplemented( + | WalletData::Mifinity(_) + | WalletData::RevolutPay(_) => Err(report!(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("nmi"), ))), }, diff --git a/crates/hyperswitch_connectors/src/connectors/noon/transformers.rs b/crates/hyperswitch_connectors/src/connectors/noon/transformers.rs index 109c53fbde4..faa566adb08 100644 --- a/crates/hyperswitch_connectors/src/connectors/noon/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/noon/transformers.rs @@ -342,7 +342,8 @@ impl TryFrom<&NoonRouterData<&PaymentsAuthorizeRouterData>> for NoonPaymentsRequ | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) - | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + | WalletData::Mifinity(_) + | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Noon"), )), }, diff --git a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs index 7eb6398f1b3..8d257a3e579 100644 --- a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs @@ -354,7 +354,8 @@ impl TryFrom<&NovalnetRouterData<&PaymentsAuthorizeRouterData>> for NovalnetPaym | WalletDataPaymentMethod::GooglePayRedirect(_) | WalletDataPaymentMethod::GooglePayThirdPartySdk(_) | WalletDataPaymentMethod::MbWayRedirect(_) - | WalletDataPaymentMethod::MobilePayRedirect(_) => { + | WalletDataPaymentMethod::MobilePayRedirect(_) + | WalletDataPaymentMethod::RevolutPay(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("novalnet"), ) @@ -1605,7 +1606,8 @@ impl TryFrom<&SetupMandateRouterData> for NovalnetPaymentsRequest { | WalletDataPaymentMethod::GooglePayRedirect(_) | WalletDataPaymentMethod::GooglePayThirdPartySdk(_) | WalletDataPaymentMethod::MbWayRedirect(_) - | WalletDataPaymentMethod::MobilePayRedirect(_) => { + | WalletDataPaymentMethod::MobilePayRedirect(_) + | WalletDataPaymentMethod::RevolutPay(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("novalnet"), ))? diff --git a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs index e2f106f2cb0..a569b7d38ee 100644 --- a/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs @@ -948,6 +948,7 @@ where | WalletData::CashappQr(_) | WalletData::SwishQr(_) | WalletData::WeChatPayQr(_) + | WalletData::RevolutPay(_) | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("nuvei"), ) diff --git a/crates/hyperswitch_connectors/src/connectors/payme/transformers.rs b/crates/hyperswitch_connectors/src/connectors/payme/transformers.rs index 06be676ab6b..375020907a4 100644 --- a/crates/hyperswitch_connectors/src/connectors/payme/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/payme/transformers.rs @@ -425,7 +425,8 @@ impl TryFrom<&PaymentMethodData> for SalePaymentMethod { | WalletData::CashappQr(_) | WalletData::ApplePay(_) | WalletData::SwishQr(_) - | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotSupported { + | WalletData::Mifinity(_) + | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotSupported { message: "Wallet".to_string(), connector: "payme", } diff --git a/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs b/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs index fdee2022577..86396894302 100644 --- a/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs @@ -1068,6 +1068,7 @@ impl TryFrom<&PaypalRouterData<&PaymentsAuthorizeRouterData>> for PaypalPayments | WalletData::CashappQr(_) | WalletData::SwishQr(_) | WalletData::Mifinity(_) + | WalletData::RevolutPay(_) | WalletData::Paze(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Paypal"), ))?, @@ -1231,7 +1232,8 @@ impl TryFrom<&PaypalRouterData<&PaymentsAuthorizeRouterData>> for PaypalPayments | enums::PaymentMethodType::LocalBankTransfer | enums::PaymentMethodType::InstantBankTransfer | enums::PaymentMethodType::Mifinity - | enums::PaymentMethodType::Paze => { + | enums::PaymentMethodType::Paze + | enums::PaymentMethodType::RevolutPay => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("paypal"), )) diff --git a/crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs b/crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs index 63d77912ef5..9052c5fa4a9 100644 --- a/crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs @@ -313,7 +313,8 @@ impl TryFrom<&WalletData> for Shift4PaymentMethod { | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) - | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + | WalletData::Mifinity(_) + | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Shift4"), ) .into()), diff --git a/crates/hyperswitch_connectors/src/connectors/square/transformers.rs b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs index b843b4d0c38..5ff7888f182 100644 --- a/crates/hyperswitch_connectors/src/connectors/square/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs @@ -129,7 +129,8 @@ impl TryFrom<(&types::TokenizationRouterData, WalletData)> for SquareTokenReques | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) - | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + | WalletData::Mifinity(_) + | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Square"), ))?, } diff --git a/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs index 73d9007706c..f0e73f5a7a5 100644 --- a/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs @@ -562,6 +562,7 @@ pub enum StripeWallet { WechatpayPayment(WechatpayPayment), AlipayPayment(AlipayPayment), Cashapp(CashappPayment), + RevolutPay(RevolutpayPayment), ApplePayPredecryptToken(Box<StripeApplePayPredecrypt>), } @@ -611,6 +612,11 @@ pub struct AmazonpayPayment { pub payment_method_types: StripePaymentMethodType, } +#[derive(Debug, Eq, PartialEq, Serialize)] +pub struct RevolutpayPayment { + #[serde(rename = "payment_method_data[type]")] + pub payment_method_types: StripePaymentMethodType, +} #[derive(Debug, Eq, PartialEq, Serialize)] pub struct AlipayPayment { #[serde(rename = "payment_method_data[type]")] @@ -679,6 +685,7 @@ pub enum StripePaymentMethodType { Wechatpay, #[serde(rename = "cashapp")] Cashapp, + RevolutPay, } #[derive(Debug, Eq, PartialEq, Serialize)] @@ -717,6 +724,7 @@ impl TryFrom<enums::PaymentMethodType> for StripePaymentMethodType { enums::PaymentMethodType::Blik => Ok(Self::Blik), enums::PaymentMethodType::AliPay => Ok(Self::Alipay), enums::PaymentMethodType::Przelewy24 => Ok(Self::Przelewy24), + enums::PaymentMethodType::RevolutPay => Ok(Self::RevolutPay), // Stripe expects PMT as Card for Recurring Mandates Payments enums::PaymentMethodType::GooglePay => Ok(Self::Card), enums::PaymentMethodType::Boleto @@ -1082,6 +1090,7 @@ fn get_stripe_payment_method_type_from_wallet_data( WalletData::WeChatPayQr(_) => Ok(Some(StripePaymentMethodType::Wechatpay)), WalletData::CashappQr(_) => Ok(Some(StripePaymentMethodType::Cashapp)), WalletData::AmazonPayRedirect(_) => Ok(Some(StripePaymentMethodType::AmazonPay)), + WalletData::RevolutPay(_) => Ok(Some(StripePaymentMethodType::RevolutPay)), WalletData::MobilePayRedirect(_) => Err(ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("stripe"), )), @@ -1491,6 +1500,11 @@ impl TryFrom<(&WalletData, Option<PaymentMethodToken>)> for StripePaymentMethodD payment_method_types: StripePaymentMethodType::AmazonPay, }, ))), + WalletData::RevolutPay(_) => { + Ok(Self::Wallet(StripeWallet::RevolutPay(RevolutpayPayment { + payment_method_types: StripePaymentMethodType::RevolutPay, + }))) + } WalletData::GooglePay(gpay_data) => Ok(Self::try_from(gpay_data)?), WalletData::PaypalRedirect(_) | WalletData::MobilePayRedirect(_) => Err( ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message( @@ -2320,6 +2334,7 @@ pub enum StripePaymentMethodDetailsResponse { Wechatpay, Alipay, CustomerBalance, + RevolutPay, } pub struct AdditionalPaymentMethodDetails { @@ -2364,6 +2379,7 @@ impl StripePaymentMethodDetailsResponse { | Self::Wechatpay | Self::Alipay | Self::CustomerBalance + | Self::RevolutPay | Self::Cashapp { .. } => None, } } @@ -2704,6 +2720,7 @@ pub fn get_payment_method_id( | Some(StripePaymentMethodDetailsResponse::Alipay) | Some(StripePaymentMethodDetailsResponse::CustomerBalance) | Some(StripePaymentMethodDetailsResponse::Cashapp { .. }) + | Some(StripePaymentMethodDetailsResponse::RevolutPay) | None => payment_method_id_from_intent_root.expose(), }, Some(StripeChargeEnum::ChargeId(_)) | None => payment_method_id_from_intent_root.expose(), diff --git a/crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs b/crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs index c0474535f5a..705a86a05d7 100644 --- a/crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs @@ -210,7 +210,8 @@ impl TryFrom<&SetupMandateRouterData> for WellsfargoZeroMandateRequest { | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) - | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + | WalletData::Mifinity(_) + | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Wellsfargo"), ))?, }, @@ -1272,7 +1273,8 @@ impl TryFrom<&WellsfargoRouterData<&PaymentsAuthorizeRouterData>> for Wellsfargo | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) | WalletData::SwishQr(_) - | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + | WalletData::Mifinity(_) + | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Wellsfargo"), ) .into()), diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs index adee7fb2891..20b21be770e 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs @@ -175,7 +175,8 @@ fn fetch_payment_instrument( | WalletData::CashappQr(_) | WalletData::SwishQr(_) | WalletData::WeChatPayQr(_) - | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + | WalletData::Mifinity(_) + | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("worldpay"), ) .into()), diff --git a/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs index d5ebe6d6957..bcc9aaf3fde 100644 --- a/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs @@ -507,7 +507,8 @@ impl | WalletData::CashappQr(_) | WalletData::SwishQr(_) | WalletData::WeChatPayQr(_) - | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + | WalletData::Mifinity(_) + | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Zen"), ))?, }; diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index 80c9f63ca49..7a210717fd3 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -5492,6 +5492,7 @@ pub enum PaymentMethodDataType { NetworkTransactionIdAndCardDetails, DirectCarrierBilling, InstantBankTransfer, + RevolutPay, } impl From<PaymentMethodData> for PaymentMethodDataType { @@ -5542,6 +5543,7 @@ impl From<PaymentMethodData> for PaymentMethodDataType { payment_method_data::WalletData::CashappQr(_) => Self::CashappQr, payment_method_data::WalletData::SwishQr(_) => Self::SwishQr, payment_method_data::WalletData::Mifinity(_) => Self::Mifinity, + payment_method_data::WalletData::RevolutPay(_) => Self::RevolutPay, }, PaymentMethodData::PayLater(pay_later_data) => match pay_later_data { payment_method_data::PayLaterData::KlarnaRedirect { .. } => Self::KlarnaRedirect, diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 950f358ad56..0abc626bd19 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -245,6 +245,7 @@ pub enum WalletData { CashappQr(Box<CashappQr>), SwishQr(SwishQrData), Mifinity(MifinityData), + RevolutPay(RevolutPayData), } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] @@ -301,6 +302,8 @@ pub struct GooglePayWalletData { #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct ApplePayRedirectData {} +#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] +pub struct RevolutPayData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct GooglePayRedirectData {} @@ -946,6 +949,7 @@ impl From<api_models::payments::WalletData> for WalletData { language_preference: mifinity_data.language_preference, }) } + api_models::payments::WalletData::RevolutPay(_) => Self::RevolutPay(RevolutPayData {}), } } } @@ -1709,6 +1713,7 @@ impl GetPaymentMethodType for WalletData { Self::CashappQr(_) => api_enums::PaymentMethodType::Cashapp, Self::SwishQr(_) => api_enums::PaymentMethodType::Swish, Self::Mifinity(_) => api_enums::PaymentMethodType::Mifinity, + Self::RevolutPay(_) => api_enums::PaymentMethodType::RevolutPay, } } } diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs index 64b79d1563e..9b06e05b990 100644 --- a/crates/kgraph_utils/src/mca.rs +++ b/crates/kgraph_utils/src/mca.rs @@ -161,6 +161,7 @@ fn get_dir_value_payment_method( api_enums::PaymentMethodType::DirectCarrierBilling => { Ok(dirval!(MobilePaymentType = DirectCarrierBilling)) } + api_enums::PaymentMethodType::RevolutPay => Ok(dirval!(WalletType = RevolutPay)), } } diff --git a/crates/kgraph_utils/src/transformers.rs b/crates/kgraph_utils/src/transformers.rs index 1b5d3392aa2..ecfb179a834 100644 --- a/crates/kgraph_utils/src/transformers.rs +++ b/crates/kgraph_utils/src/transformers.rs @@ -151,6 +151,7 @@ impl IntoDirValue for (api_enums::PaymentMethodType, api_enums::PaymentMethod) { api_enums::PaymentMethodType::CryptoCurrency => { Ok(dirval!(CryptoType = CryptoCurrency)) } + api_enums::PaymentMethodType::RevolutPay => Ok(dirval!(WalletType = RevolutPay)), api_enums::PaymentMethodType::Ach => match self.1 { api_enums::PaymentMethod::BankDebit => Ok(dirval!(BankDebitType = Ach)), api_enums::PaymentMethod::BankTransfer => Ok(dirval!(BankTransferType = Ach)), diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index b042d2bdbd6..cec1b463a8a 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -410,6 +410,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::PaylaterResponse, api_models::payments::KlarnaSdkPaymentMethodResponse, api_models::payments::SwishQrData, + api_models::payments::RevolutPayData, api_models::payments::AirwallexData, api_models::payments::BraintreeData, api_models::payments::NoonData, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 9b8387389fe..21bba4844cf 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -386,6 +386,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::PaylaterResponse, api_models::payments::KlarnaSdkPaymentMethodResponse, api_models::payments::SwishQrData, + api_models::payments::RevolutPayData, api_models::payments::AirwallexData, api_models::payments::BraintreeData, api_models::payments::NoonData, diff --git a/crates/payment_methods/src/helpers.rs b/crates/payment_methods/src/helpers.rs index 1e483b12d7e..7a885b5f053 100644 --- a/crates/payment_methods/src/helpers.rs +++ b/crates/payment_methods/src/helpers.rs @@ -124,6 +124,7 @@ pub fn validate_payment_method_type_against_payment_method( | api_enums::PaymentMethodType::Cashapp | api_enums::PaymentMethodType::Mifinity | api_enums::PaymentMethodType::Paze + | api_enums::PaymentMethodType::RevolutPay ), api_enums::PaymentMethod::BankRedirect => matches!( payment_method_type, diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index e2db6a379c6..ad537f24967 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -2533,6 +2533,7 @@ pub enum PaymentMethodDataType { NetworkToken, DirectCarrierBilling, InstantBankTransfer, + RevolutPay, } impl From<domain::payments::PaymentMethodData> for PaymentMethodDataType { @@ -2583,6 +2584,7 @@ impl From<domain::payments::PaymentMethodData> for PaymentMethodDataType { domain::payments::WalletData::CashappQr(_) => Self::CashappQr, domain::payments::WalletData::SwishQr(_) => Self::SwishQr, domain::payments::WalletData::Mifinity(_) => Self::Mifinity, + domain::payments::WalletData::RevolutPay(_) => Self::RevolutPay, }, domain::payments::PaymentMethodData::PayLater(pay_later_data) => match pay_later_data { domain::payments::PayLaterData::KlarnaRedirect { .. } => Self::KlarnaRedirect, diff --git a/crates/router/src/types/domain/payments.rs b/crates/router/src/types/domain/payments.rs index 3f7849ae0fa..af715bdbb49 100644 --- a/crates/router/src/types/domain/payments.rs +++ b/crates/router/src/types/domain/payments.rs @@ -5,7 +5,7 @@ pub use hyperswitch_domain_models::payment_method_data::{ GiftCardDetails, GoPayRedirection, GooglePayPaymentMethodInfo, GooglePayRedirectData, GooglePayThirdPartySdkData, GooglePayWalletData, GpayTokenizationData, IndomaretVoucherData, KakaoPayRedirection, MbWayRedirection, MifinityData, NetworkTokenData, OpenBankingData, - PayLaterData, PaymentMethodData, RealTimePaymentData, SamsungPayWalletData, + PayLaterData, PaymentMethodData, RealTimePaymentData, RevolutPayData, SamsungPayWalletData, SepaAndBacsBillingDetails, SwishQrData, TokenizedBankDebitValue1, TokenizedBankDebitValue2, TokenizedBankRedirectValue1, TokenizedBankRedirectValue2, TokenizedBankTransferValue1, TokenizedBankTransferValue2, TokenizedCardValue1, TokenizedCardValue2, TokenizedWalletValue1, diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 911cacf604e..daa3eacbe4b 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -508,7 +508,8 @@ impl ForeignFrom<api_enums::PaymentMethodType> for api_enums::PaymentMethod { | api_enums::PaymentMethodType::Cashapp | api_enums::PaymentMethodType::KakaoPay | api_enums::PaymentMethodType::Venmo - | api_enums::PaymentMethodType::Mifinity => Self::Wallet, + | api_enums::PaymentMethodType::Mifinity + | api_enums::PaymentMethodType::RevolutPay => Self::Wallet, api_enums::PaymentMethodType::Affirm | api_enums::PaymentMethodType::Alma | api_enums::PaymentMethodType::AfterpayClearpay
2025-05-18T11:17:59Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Implement `revolut_pay` for stripe ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> Docs: https://docs.stripe.com/payments/revolut-pay API: https://docs.stripe.com/api/payment_methods/create?api-version=2025-04-30.basil ## How did you test it? 1. Enable revolut pay wallet in stripe https://dashboard.stripe.com/test/settings/payment_methods/pmc_1ROdpjB97BExDDPTOZMrPWhw <img width="1728" alt="Screenshot 2025-05-15 at 2 46 27 PM" src="https://github.com/user-attachments/assets/6a629470-4057-4940-aa31-7b15d4e1eee2" /> 2. test locally with stripe api if payment works ```sh curl --location 'https://api.stripe.com/v1/payment_intents' \ --header 'Content-Type: application/x-www-form-urlencoded' \ --header 'Authorization: Basic *****' \ --data-urlencode 'amount=1000' \ --data-urlencode 'currency=GBP' \ --data-urlencode 'confirm=true' \ --data-urlencode 'payment_method_types%5B%5D=revolut_pay' \ --data-urlencode 'payment_method_data%5Btype%5D=revolut_pay' \ --data-urlencode 'return_url=https://www.google.com' ``` - Response ```json { "id": "pi_3ROxvwB97BExDDPT0dHsgo6t", "object": "payment_intent", "amount": 1000, "amount_capturable": 0, "amount_details": { "tip": {} }, "amount_received": 0, "application": null, "application_fee_amount": null, "automatic_payment_methods": null, "canceled_at": null, "cancellation_reason": null, "capture_method": "automatic_async", "client_secret": "***", "confirmation_method": "automatic", "created": 1747300712, "currency": "gbp", "customer": null, "description": null, "last_payment_error": null, "latest_charge": null, "livemode": false, "metadata": {}, "next_action": { "redirect_to_url": { "return_url": "https://www.google.com", "url": "https://pm-redirects.stripe.com/authorize/acct_1ROdpBB97BExDDPT/pa_nonce_SJb8ufPcGprPwuS2U43cjPBc7Suv5EM" }, "type": "redirect_to_url" }, "on_behalf_of": null, "payment_method": "pm_1ROxvwB97BExDDPTQZMvJtAv", "payment_method_configuration_details": null, "payment_method_options": { "revolut_pay": {} }, "payment_method_types": [ "revolut_pay" ], "processing": null, "receipt_email": null, "review": null, "setup_future_usage": null, "shipping": null, "source": null, "statement_descriptor": null, "statement_descriptor_suffix": null, "status": "requires_action", "transfer_data": null, "transfer_group": null } ``` 3. Open url "https://pm-redirects.stripe.com/authorize/acct_1ROdpBB97BExDDPT/pa_nonce_SJb8ufPcGprPwuS2U43cjPBc7Suv5EM" & approve <img width="1728" alt="Screenshot 2025-05-15 at 2 49 54 PM" src="https://github.com/user-attachments/assets/b2787047-ae96-4cf3-971f-ba5966173973" /> 4. check the payment is successful ```sh curl --location 'https://api.stripe.com/v1/payment_intents/pi_3ROxvwB97BExDDPT0dHsgo6t' \ --header 'Authorization: Basic ******** ``` response ```json { "id": "pi_3ROxvwB97BExDDPT0dHsgo6t", "object": "payment_intent", "amount": 1000, "amount_capturable": 0, "amount_details": { "tip": {} }, "amount_received": 1000, "application": null, "application_fee_amount": null, "automatic_payment_methods": null, "canceled_at": null, "cancellation_reason": null, "capture_method": "automatic_async", "client_secret": "pi_3ROxvwB97BExDDPT0dHsgo6t_secret_CkX00D5AVYktG9OOiS2QaSFH9", "confirmation_method": "automatic", "created": 1747300712, "currency": "gbp", "customer": null, "description": null, "last_payment_error": null, "latest_charge": "py_3ROxvwB97BExDDPT0ZAud2QG", "livemode": false, "metadata": {}, "next_action": null, "on_behalf_of": null, "payment_method": "pm_1ROxvwB97BExDDPTQZMvJtAv", "payment_method_configuration_details": null, "payment_method_options": { "revolut_pay": {} }, "payment_method_types": [ "revolut_pay" ], "processing": null, "receipt_email": null, "review": null, "setup_future_usage": null, "shipping": null, "source": null, "statement_descriptor": null, "statement_descriptor_suffix": null, "status": "succeeded", "transfer_data": null, "transfer_group": null } ``` Similarly in hyperswitch 1. create MCA ```sh curl --location 'http://localhost:8080/account/merchant_1747238601/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-feature: integ-custom' \ --header 'api-key: dev_UAkNrfXtBq40DJA7ZNe0hlA7uNWEsnHCaKHDwq1E14bV5UVo4NFw1D3e0Nxq7w8s' \ --data '{ "connector_type": "payment_processor", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "********" }, "connector_name": "stripe", "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "revolut_pay", "recurring_enabled": false, "installment_payment_enabled": false } ] }, ], "metadata": { "city": "NY", "unit": "245" }, "connector_webhook_details": { "merchant_secret": "MyWebhookSecret" }, "business_country": "US", "business_label": "default" }' ``` 2. payment create ```sh curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_cnuJqFYwxtGHff4Q6llYITJKjoG9FRkOW21ggOIS24UQclh3D6DVezsaN7EZQTq2' \ --data '{ "amount": 111, "currency": "GBP", "confirm": true, "capture_method": "manual", "payment_method": "wallet", "payment_method_type": "revolut_pay", "payment_method_data": { "wallet": { "revolut_pay": {} } } }' ``` response ```json { "payment_id": "pay_bmOvXjRBZfqUvyQP8fus", "merchant_id": "merchant_1747377561", "status": "requires_customer_action", "amount": 111, "net_amount": 111, "shipping_cost": null, "amount_capturable": 111, "amount_received": 0, "connector": "stripe", "client_secret": "pay_bmOvXjRBZfqUvyQP8fus_secret_nKIT1jegspBnMg1eufRO", "created": "2025-05-16T07:26:35.752Z", "currency": "GBP", "customer_id": null, "customer": null, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "wallet", "payment_method_data": { "wallet": {}, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_bmOvXjRBZfqUvyQP8fus/merchant_1747377561/pay_bmOvXjRBZfqUvyQP8fus_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "revolut_pay", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "pi_3RPIfAB97BExDDPT1XSgQ3ql", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pi_3RPIfAB97BExDDPT1XSgQ3ql", "payment_link": null, "profile_id": "pro_Et1v5W5jHI8bM4MZJqZc", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_lKADRn7MC7urVbXp5MM5", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-05-16T07:41:35.752Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-05-16T07:26:37.003Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` 3. open return url "http://localhost:8080/payments/redirect/pay_RyVOqpl8ARzzfD1RjB69/merchant_1747238601/pay_RyVOqpl8ARzzfD1RjB69_1" & a approve the test payment <img width="1728" alt="Screenshot 2025-05-15 at 2 49 54 PM" src="https://github.com/user-attachments/assets/a710513d-e7ee-4e37-b2ad-7ec54d9cf0fd" /> 4. capture the payment status ```sh curl --location 'http://localhost:8080/payments/pay_bmOvXjRBZfqUvyQP8fus/capture' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_cnuJqFYwxtGHff4Q6llYITJKjoG9FRkOW21ggOIS24UQclh3D6DVezsaN7EZQTq2' \ --data '{ "metadata":"updated" }' ``` response ```json { "payment_id": "pay_bmOvXjRBZfqUvyQP8fus", "merchant_id": "merchant_1747377561", "status": "succeeded", "amount": 111, "net_amount": 111, "shipping_cost": null, "amount_capturable": 0, "amount_received": 111, "connector": "stripe", "client_secret": "pay_OkUFkYRuaAj1NOlCLjBp_secret_UHeMixoT9PNRpNVtMrci", "created": "2025-05-16T07:34:43.017Z", "currency": "GBP", "customer_id": null, "customer": null, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "wallet", "payment_method_data": { "wallet": {}, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "revolut_pay", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "pi_3RPIn2B97BExDDPT1XFiD5Sp", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pi_3RPIn2B97BExDDPT1XFiD5Sp", "payment_link": null, "profile_id": "pro_Et1v5W5jHI8bM4MZJqZc", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_lKADRn7MC7urVbXp5MM5", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-05-16T07:49:43.017Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-05-16T07:34:58.228Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` - Similarly check for refunds - supported currency `EUR`, `GBP` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
5642080025524ed2dee363984359aa9275036035
5642080025524ed2dee363984359aa9275036035
juspay/hyperswitch
juspay__hyperswitch-7997
Bug: [FEATURE]: Send whole connector response in confirm and psync call ### Feature Description Send whole connector response in confirm and psync call ### Possible Implementation Add `all_keys_required` in confirm and psync payload. If `all_keys_required` is passed as `true`, send the whole connector response. ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index b475142a570..6d52decc7ca 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -16935,6 +16935,11 @@ "type": "boolean", "description": "If enabled provides list of attempts linked to payment intent", "nullable": true + }, + "all_keys_required": { + "type": "boolean", + "description": "If enabled, provides whole connector response", + "nullable": true } } }, @@ -18283,6 +18288,11 @@ "type": "string", "description": "These are the query params that are sent in case of redirect response.\nThese can be ingested by the connector to take necessary actions.", "nullable": true + }, + "all_keys_required": { + "type": "boolean", + "description": "If enabled, provides whole connector response", + "nullable": true } } }, diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index c71ee457f5d..2315a94b5e0 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -18853,6 +18853,11 @@ "type": "boolean", "description": "If enabled provides list of attempts linked to payment intent", "nullable": true + }, + "all_keys_required": { + "type": "boolean", + "description": "If enabled, provides whole connector response", + "nullable": true } } }, @@ -19353,6 +19358,11 @@ } ], "nullable": true + }, + "all_keys_required": { + "type": "boolean", + "description": "If enabled, provides whole connector response", + "nullable": true } } }, @@ -19765,6 +19775,11 @@ } ], "nullable": true + }, + "all_keys_required": { + "type": "boolean", + "description": "If enabled, provides whole connector response", + "nullable": true } } }, @@ -20343,6 +20358,11 @@ "type": "string", "description": "Error message received from the issuer in case of failed payments", "nullable": true + }, + "whole_connector_response": { + "type": "string", + "description": "Contains whole connector response", + "nullable": true } } }, @@ -21045,6 +21065,11 @@ } ], "nullable": true + }, + "all_keys_required": { + "type": "boolean", + "description": "If enabled, provides whole connector response", + "nullable": true } }, "additionalProperties": false @@ -21649,6 +21674,11 @@ "type": "string", "description": "Error message received from the issuer in case of failed payments", "nullable": true + }, + "whole_connector_response": { + "type": "string", + "description": "Contains whole connector response", + "nullable": true } } }, @@ -21704,6 +21734,11 @@ "type": "boolean", "description": "If enabled provides list of attempts linked to payment intent", "nullable": true + }, + "all_keys_required": { + "type": "boolean", + "description": "If enabled, provides whole connector response", + "nullable": true } } }, @@ -22189,6 +22224,11 @@ } ], "nullable": true + }, + "all_keys_required": { + "type": "boolean", + "description": "If enabled, provides whole connector response", + "nullable": true } } }, diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 6e81cf80492..b313a3b3033 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1164,6 +1164,9 @@ pub struct PaymentsRequest { /// Indicates if the redirection has to open in the iframe pub is_iframe_redirection_enabled: Option<bool>, + + /// If enabled, provides whole connector response + pub all_keys_required: Option<bool>, } #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] @@ -5141,6 +5144,9 @@ pub struct PaymentsResponse { /// Indicates if the redirection has to open in the iframe pub is_iframe_redirection_enabled: Option<bool>, + + /// Contains whole connector response + pub whole_connector_response: Option<String>, } #[cfg(feature = "v2")] @@ -5558,6 +5564,8 @@ pub struct PaymentsRetrieveRequest { /// These are the query params that are sent in case of redirect response. /// These can be ingested by the connector to take necessary actions. pub param: Option<String>, + /// If enabled, provides whole connector response + pub all_keys_required: Option<bool>, } /// Error details for the payment @@ -6405,6 +6413,8 @@ pub struct PaymentsRetrieveRequest { pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, + /// If enabled, provides whole connector response + pub all_keys_required: Option<bool>, } #[derive(Debug, Default, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] @@ -7389,6 +7399,8 @@ pub struct PaymentRetrieveBody { pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, + /// If enabled, provides whole connector response + pub all_keys_required: Option<bool>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index c3c3a23baab..c24bfbc8507 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -6134,6 +6134,7 @@ pub(crate) fn convert_payment_authorize_router_response<F1, F2, T1, T2>( connector_mandate_request_reference_id: data.connector_mandate_request_reference_id.clone(), authentication_id: data.authentication_id.clone(), psd2_sca_exemption_type: data.psd2_sca_exemption_type, + whole_connector_response: data.whole_connector_response.clone(), } } diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs index d3f9a2bf8cc..793808b1342 100644 --- a/crates/hyperswitch_domain_models/src/router_data.rs +++ b/crates/hyperswitch_domain_models/src/router_data.rs @@ -102,6 +102,9 @@ pub struct RouterData<Flow, Request, Response> { pub authentication_id: Option<String>, /// Contains the type of sca exemption required for the transaction pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>, + + /// Contains whole connector response + pub whole_connector_response: Option<String>, } // Different patterns of authentication. diff --git a/crates/hyperswitch_interfaces/src/conversion_impls.rs b/crates/hyperswitch_interfaces/src/conversion_impls.rs index e01cd5ae9e4..8e2ecc8554e 100644 --- a/crates/hyperswitch_interfaces/src/conversion_impls.rs +++ b/crates/hyperswitch_interfaces/src/conversion_impls.rs @@ -83,6 +83,7 @@ fn get_default_router_data<F, Req, Resp>( connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, + whole_connector_response: None, } } diff --git a/crates/router/src/compatibility/stripe/payment_intents.rs b/crates/router/src/compatibility/stripe/payment_intents.rs index dd0bbace4fa..77e7761e67f 100644 --- a/crates/router/src/compatibility/stripe/payment_intents.rs +++ b/crates/router/src/compatibility/stripe/payment_intents.rs @@ -125,6 +125,7 @@ pub async fn payment_intents_retrieve( client_secret: query_payload.client_secret.clone(), expand_attempts: None, expand_captures: None, + all_keys_required: None, }; let api_auth = auth::ApiKeyAuth { diff --git a/crates/router/src/compatibility/stripe/setup_intents.rs b/crates/router/src/compatibility/stripe/setup_intents.rs index d39cc0c6795..00baf1ddfb2 100644 --- a/crates/router/src/compatibility/stripe/setup_intents.rs +++ b/crates/router/src/compatibility/stripe/setup_intents.rs @@ -109,6 +109,7 @@ pub async fn setup_intents_retrieve( client_secret: query_payload.client_secret.clone(), expand_attempts: None, expand_captures: None, + all_keys_required: None, }; let api_auth = auth::ApiKeyAuth { diff --git a/crates/router/src/core/authentication/transformers.rs b/crates/router/src/core/authentication/transformers.rs index ab28addb01b..e1cf04c20aa 100644 --- a/crates/router/src/core/authentication/transformers.rs +++ b/crates/router/src/core/authentication/transformers.rs @@ -206,6 +206,7 @@ pub fn construct_router_data<F: Clone, Req, Res>( connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type, + whole_connector_response: None, }) } diff --git a/crates/router/src/core/authentication/utils.rs b/crates/router/src/core/authentication/utils.rs index 0e7315c5d4a..f3554d6d704 100644 --- a/crates/router/src/core/authentication/utils.rs +++ b/crates/router/src/core/authentication/utils.rs @@ -293,6 +293,7 @@ where &router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .to_payment_failed_response()?; diff --git a/crates/router/src/core/disputes.rs b/crates/router/src/core/disputes.rs index a7c9af44e85..873401d771c 100644 --- a/crates/router/src/core/disputes.rs +++ b/crates/router/src/core/disputes.rs @@ -217,6 +217,7 @@ pub async fn accept_dispute( &router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .to_dispute_failed_response() @@ -340,6 +341,7 @@ pub async fn submit_evidence( &router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .to_dispute_failed_response() @@ -378,6 +380,7 @@ pub async fn submit_evidence( &defend_dispute_router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .to_dispute_failed_response() diff --git a/crates/router/src/core/files/helpers.rs b/crates/router/src/core/files/helpers.rs index 7b5cc9af4e9..4c585ccd22a 100644 --- a/crates/router/src/core/files/helpers.rs +++ b/crates/router/src/core/files/helpers.rs @@ -157,6 +157,7 @@ pub async fn retrieve_file_from_connector( &router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -340,6 +341,7 @@ pub async fn upload_and_get_provider_provider_file_id_profile_id( &router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/core/fraud_check.rs b/crates/router/src/core/fraud_check.rs index e18f29ea838..ae8849851e3 100644 --- a/crates/router/src/core/fraud_check.rs +++ b/crates/router/src/core/fraud_check.rs @@ -863,6 +863,7 @@ pub async fn make_fulfillment_api_call( &router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .to_payment_failed_response()?; diff --git a/crates/router/src/core/fraud_check/flows/checkout_flow.rs b/crates/router/src/core/fraud_check/flows/checkout_flow.rs index ae003997699..d71d810335e 100644 --- a/crates/router/src/core/fraud_check/flows/checkout_flow.rs +++ b/crates/router/src/core/fraud_check/flows/checkout_flow.rs @@ -161,6 +161,7 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, + whole_connector_response: None, }; Ok(router_data) @@ -215,6 +216,7 @@ pub async fn decide_frm_flow( router_data, call_connector_action, None, + None, ) .await .to_payment_failed_response()?; diff --git a/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs b/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs index 4cef8db6ced..421c255e117 100644 --- a/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs +++ b/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs @@ -128,6 +128,7 @@ pub async fn construct_fulfillment_router_data<'a>( connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, + whole_connector_response: None, }; Ok(router_data) } diff --git a/crates/router/src/core/fraud_check/flows/record_return.rs b/crates/router/src/core/fraud_check/flows/record_return.rs index b60d812f1f1..02d87853ea9 100644 --- a/crates/router/src/core/fraud_check/flows/record_return.rs +++ b/crates/router/src/core/fraud_check/flows/record_return.rs @@ -129,6 +129,7 @@ impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudCh connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, + whole_connector_response: None, }; Ok(router_data) @@ -183,6 +184,7 @@ pub async fn decide_frm_flow( router_data, call_connector_action, None, + None, ) .await .to_payment_failed_response()?; diff --git a/crates/router/src/core/fraud_check/flows/sale_flow.rs b/crates/router/src/core/fraud_check/flows/sale_flow.rs index 5defd0d4b58..138097333cd 100644 --- a/crates/router/src/core/fraud_check/flows/sale_flow.rs +++ b/crates/router/src/core/fraud_check/flows/sale_flow.rs @@ -137,6 +137,7 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResp connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, + whole_connector_response: None, }; Ok(router_data) @@ -191,6 +192,7 @@ pub async fn decide_frm_flow( router_data, call_connector_action, None, + None, ) .await .to_payment_failed_response()?; diff --git a/crates/router/src/core/fraud_check/flows/transaction_flow.rs b/crates/router/src/core/fraud_check/flows/transaction_flow.rs index cbf66632df4..ded83e9b7bc 100644 --- a/crates/router/src/core/fraud_check/flows/transaction_flow.rs +++ b/crates/router/src/core/fraud_check/flows/transaction_flow.rs @@ -146,6 +146,7 @@ impl connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, + whole_connector_response: None, }; Ok(router_data) @@ -200,6 +201,7 @@ pub async fn decide_frm_flow( router_data, call_connector_action, None, + None, ) .await .to_payment_failed_response()?; diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index a4dd1d2b198..e32709320c5 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -117,6 +117,7 @@ pub async fn revoke_mandate( &router_data, CallConnectorAction::Trigger, None, + None, ) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; diff --git a/crates/router/src/core/mandate/utils.rs b/crates/router/src/core/mandate/utils.rs index 004666d7306..642a28c5671 100644 --- a/crates/router/src/core/mandate/utils.rs +++ b/crates/router/src/core/mandate/utils.rs @@ -85,6 +85,7 @@ pub async fn construct_mandate_revoke_router_data( connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, + whole_connector_response: None, }; Ok(router_data) diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 0b4590b2bec..c27ab57504b 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -2945,6 +2945,7 @@ async fn create_single_use_tokenization_flow( connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, + whole_connector_response: None, }; let payment_method_token_response = tokenization::add_token_for_payment_method( diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index cb68ece2039..c69f22079b3 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -145,7 +145,7 @@ pub async fn payments_operation_core<F, Req, Op, FData, D>( ) -> RouterResult<(D, Req, Option<domain::Customer>, Option<u16>, Option<u128>)> where F: Send + Clone + Sync, - Req: Send + Sync, + Req: Send + Sync + Authenticate, Op: Operation<F, Req, Data = D> + Send + Sync, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, @@ -213,6 +213,7 @@ where profile, false, false, //should_retry_with_pan is set to false in case of PreDetermined ConnectorCallType + req.get_all_keys_required(), ) .await?; @@ -528,6 +529,7 @@ where false, false, None, + <Req as Authenticate>::get_all_keys_required(&req), ) .await?; @@ -651,6 +653,7 @@ where false, false, routing_decision, + <Req as Authenticate>::get_all_keys_required(&req), ) .await?; @@ -781,6 +784,7 @@ where session_surcharge_details, &business_profile, header_payload.clone(), + <Req as Authenticate>::get_all_keys_required(&req), )) .await? } @@ -909,6 +913,7 @@ pub async fn proxy_for_payments_operation_core<F, Req, Op, FData, D>( call_connector_action: CallConnectorAction, auth_flow: services::AuthFlow, header_payload: HeaderPayload, + all_keys_required: Option<bool>, ) -> RouterResult<(D, Req, Option<domain::Customer>, Option<u16>, Option<u128>)> where F: Send + Clone + Sync, @@ -1022,6 +1027,7 @@ where schedule_time, header_payload.clone(), &business_profile, + all_keys_required, ) .await?; @@ -1107,10 +1113,11 @@ pub async fn proxy_for_payments_operation_core<F, Req, Op, FData, D>( get_tracker_response: operations::GetTrackerResponse<D>, call_connector_action: CallConnectorAction, header_payload: HeaderPayload, + all_keys_required: Option<bool>, ) -> RouterResult<(D, Req, Option<u16>, Option<u128>)> where F: Send + Clone + Sync, - Req: Send + Sync, + Req: Send + Sync + Authenticate, Op: Operation<F, Req, Data = D> + Send + Sync, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, @@ -1151,6 +1158,7 @@ where call_connector_action.clone(), header_payload.clone(), &profile, + all_keys_required, ) .await?; @@ -1624,6 +1632,7 @@ pub async fn proxy_for_payments_core<F, Res, Req, Op, FData, D>( auth_flow: services::AuthFlow, call_connector_action: CallConnectorAction, header_payload: HeaderPayload, + all_keys_required: Option<bool>, ) -> RouterResponse<Res> where F: Send + Clone + Sync, @@ -1654,6 +1663,7 @@ where call_connector_action, auth_flow, header_payload.clone(), + all_keys_required, ) .await?; @@ -1682,10 +1692,11 @@ pub async fn proxy_for_payments_core<F, Res, Req, Op, FData, D>( payment_id: id_type::GlobalPaymentId, call_connector_action: CallConnectorAction, header_payload: HeaderPayload, + all_keys_required: Option<bool>, ) -> RouterResponse<Res> where F: Send + Clone + Sync, - Req: Send + Sync, + Req: Send + Sync + Authenticate, FData: Send + Sync + Clone, Op: Operation<F, Req, Data = D> + ValidateStatusForOperation + Send + Sync + Clone, Req: Debug, @@ -1733,6 +1744,7 @@ where get_tracker_response, call_connector_action, header_payload.clone(), + all_keys_required, ) .await?; @@ -1819,6 +1831,7 @@ pub async fn record_attempt_core( force_sync: true, expand_attempts: false, param: None, + all_keys_required: None, }, operations::GetTrackerResponse { payment_data: PaymentStatusData { @@ -1832,6 +1845,7 @@ pub async fn record_attempt_core( }, CallConnectorAction::Trigger, HeaderPayload::default(), + None, )) .await { @@ -1999,7 +2013,7 @@ pub async fn payments_core<F, Res, Req, Op, FData, D>( ) -> RouterResponse<Res> where F: Send + Clone + Sync, - Req: Send + Sync, + Req: Send + Sync + Authenticate, FData: Send + Sync + Clone, Op: Operation<F, Req, Data = D> + ValidateStatusForOperation + Send + Sync + Clone, Req: Debug, @@ -2555,6 +2569,7 @@ impl PaymentRedirectFlow for PaymentRedirectSync { client_secret: None, expand_attempts: None, expand_captures: None, + all_keys_required: None, }; let response = Box::pin( payments_core::<api::PSync, api::PaymentsResponse, _, _, _, _>( @@ -2687,6 +2702,7 @@ impl PaymentRedirectFlow for PaymentRedirectSync { param: Some(req.query_params.clone()), force_sync: true, expand_attempts: false, + all_keys_required: None, }; let operation = operations::PaymentGet; @@ -2931,6 +2947,7 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize { client_secret: None, expand_attempts: None, expand_captures: None, + all_keys_required: None, }; Box::pin( payments_core::<api::PSync, api::PaymentsResponse, _, _, _, _>( @@ -3069,6 +3086,7 @@ pub async fn call_connector_service<F, RouterDReq, ApiRequest, D>( is_retry_payment: bool, should_retry_with_pan: bool, routing_decision: Option<routing_helpers::RoutingDecisionData>, + all_keys_required: Option<bool>, ) -> RouterResult<( RouterData<F, RouterDReq, router_types::PaymentsResponseData>, helpers::MerchantConnectorAccountType, @@ -3303,6 +3321,7 @@ where connector_request, business_profile, header_payload.clone(), + all_keys_required, ) .await } else { @@ -3334,6 +3353,7 @@ pub async fn call_connector_service<F, RouterDReq, ApiRequest, D>( business_profile: &domain::Profile, is_retry_payment: bool, should_retry_with_pan: bool, + all_keys_required: Option<bool>, ) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>> where F: Send + Clone + Sync, @@ -3450,6 +3470,7 @@ where connector_request, business_profile, header_payload.clone(), + all_keys_required, ) .await } else { @@ -3481,6 +3502,7 @@ pub async fn proxy_for_call_connector_service<F, RouterDReq, ApiRequest, D>( header_payload: HeaderPayload, business_profile: &domain::Profile, + all_keys_required: Option<bool>, ) -> RouterResult<( RouterData<F, RouterDReq, router_types::PaymentsResponseData>, helpers::MerchantConnectorAccountType, @@ -3621,6 +3643,7 @@ where connector_request, business_profile, header_payload.clone(), + all_keys_required, ) .await } else { @@ -3647,6 +3670,7 @@ pub async fn proxy_for_call_connector_service<F, RouterDReq, ApiRequest, D>( call_connector_action: CallConnectorAction, header_payload: HeaderPayload, business_profile: &domain::Profile, + all_keys_required: Option<bool>, ) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>> where F: Send + Clone + Sync, @@ -3742,6 +3766,7 @@ where connector_request, business_profile, header_payload.clone(), + all_keys_required, ) .await } else { @@ -4003,6 +4028,7 @@ pub async fn call_multiple_connectors_service<F, Op, Req, D>( _session_surcharge_details: Option<api::SessionSurchargeDetails>, business_profile: &domain::Profile, header_payload: HeaderPayload, + all_keys_required: Option<bool>, ) -> RouterResult<D> where Op: Debug, @@ -4059,6 +4085,7 @@ where None, business_profile, header_payload.clone(), + all_keys_required, ); join_handlers.push(res); @@ -4118,6 +4145,7 @@ pub async fn call_multiple_connectors_service<F, Op, Req, D>( session_surcharge_details: Option<api::SessionSurchargeDetails>, business_profile: &domain::Profile, header_payload: HeaderPayload, + all_keys_required: Option<bool>, ) -> RouterResult<D> where Op: Debug, @@ -4179,6 +4207,7 @@ where None, business_profile, header_payload.clone(), + all_keys_required, ); join_handlers.push(res); @@ -5468,6 +5497,7 @@ where pub token_data: Option<storage::PaymentTokenData>, pub confirm: Option<bool>, pub force_sync: Option<bool>, + pub all_keys_required: Option<bool>, pub payment_method_data: Option<domain::PaymentMethodData>, pub payment_method_info: Option<domain::PaymentMethod>, pub refunds: Vec<storage::Refund>, @@ -5498,6 +5528,7 @@ where Option<hyperswitch_domain_models::card_testing_guard_data::CardTestingGuardData>, pub vault_operation: Option<domain_payments::VaultOperation>, pub threeds_method_comp_ind: Option<api_models::payments::ThreeDsCompletionIndicator>, + pub whole_connector_response: Option<String>, } #[derive(Clone, serde::Serialize, Debug)] @@ -5640,14 +5671,15 @@ where .is_none() } "PaymentStatus" => { - matches!( - payment_data.get_payment_intent().status, - storage_enums::IntentStatus::Processing - | storage_enums::IntentStatus::RequiresCustomerAction - | storage_enums::IntentStatus::RequiresMerchantAction - | storage_enums::IntentStatus::RequiresCapture - | storage_enums::IntentStatus::PartiallyCapturedAndCapturable - ) && payment_data.get_force_sync().unwrap_or(false) + payment_data.get_all_keys_required().unwrap_or(false) + || matches!( + payment_data.get_payment_intent().status, + storage_enums::IntentStatus::Processing + | storage_enums::IntentStatus::RequiresCustomerAction + | storage_enums::IntentStatus::RequiresMerchantAction + | storage_enums::IntentStatus::RequiresCapture + | storage_enums::IntentStatus::PartiallyCapturedAndCapturable + ) && payment_data.get_force_sync().unwrap_or(false) } "PaymentCancel" => matches!( payment_data.get_payment_intent().status, @@ -8113,11 +8145,13 @@ pub trait OperationSessionGetters<F> { fn get_token_data(&self) -> Option<&storage::PaymentTokenData>; fn get_mandate_connector(&self) -> Option<&MandateConnectorDetails>; fn get_force_sync(&self) -> Option<bool>; + fn get_all_keys_required(&self) -> Option<bool>; fn get_capture_method(&self) -> Option<enums::CaptureMethod>; fn get_merchant_connector_id_in_attempt(&self) -> Option<id_type::MerchantConnectorAccountId>; #[cfg(feature = "v1")] fn get_connector_customer_id(&self) -> Option<String>; + fn get_whole_connector_response(&self) -> Option<String>; #[cfg(feature = "v1")] fn get_vault_operation(&self) -> Option<&domain_payments::VaultOperation>; @@ -8308,6 +8342,14 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentData<F> { self.force_sync } + fn get_all_keys_required(&self) -> Option<bool> { + self.all_keys_required + } + + fn get_whole_connector_response(&self) -> Option<String> { + self.whole_connector_response.clone() + } + #[cfg(feature = "v1")] fn get_capture_method(&self) -> Option<enums::CaptureMethod> { self.payment_attempt.capture_method @@ -8607,6 +8649,14 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentIntentData<F> { fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt> { todo!(); } + + fn get_all_keys_required(&self) -> Option<bool> { + todo!(); + } + + fn get_whole_connector_response(&self) -> Option<String> { + todo!(); + } } #[cfg(feature = "v2")] @@ -8842,6 +8892,14 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentConfirmData<F> { fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt> { Some(&self.payment_attempt) } + + fn get_all_keys_required(&self) -> Option<bool> { + todo!() + } + + fn get_whole_connector_response(&self) -> Option<String> { + todo!() + } } #[cfg(feature = "v2")] @@ -9078,6 +9136,14 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentStatusData<F> { fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt> { self.payment_attempt.as_ref() } + + fn get_all_keys_required(&self) -> Option<bool> { + todo!() + } + + fn get_whole_connector_response(&self) -> Option<String> { + todo!() + } } #[cfg(feature = "v2")] @@ -9315,6 +9381,14 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentCaptureData<F> { fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt> { Some(&self.payment_attempt) } + + fn get_all_keys_required(&self) -> Option<bool> { + todo!(); + } + + fn get_whole_connector_response(&self) -> Option<String> { + todo!(); + } } #[cfg(feature = "v2")] diff --git a/crates/router/src/core/payments/access_token.rs b/crates/router/src/core/payments/access_token.rs index 53f7b3b4a40..f2f75964914 100644 --- a/crates/router/src/core/payments/access_token.rs +++ b/crates/router/src/core/payments/access_token.rs @@ -216,6 +216,7 @@ pub async fn refresh_connector_auth( router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await; diff --git a/crates/router/src/core/payments/customers.rs b/crates/router/src/core/payments/customers.rs index 83f01349787..c0767aaf204 100644 --- a/crates/router/src/core/payments/customers.rs +++ b/crates/router/src/core/payments/customers.rs @@ -48,6 +48,7 @@ pub async fn create_connector_customer<F: Clone, T: Clone>( &customer_router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .to_payment_failed_response()?; diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 2e4864c80ca..a27f3e0ce49 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -90,6 +90,7 @@ pub trait Feature<F, T> { connector_request: Option<services::Request>, business_profile: &domain::Profile, header_payload: hyperswitch_domain_models::payments::HeaderPayload, + all_keys_required: Option<bool>, ) -> RouterResult<Self> where Self: Sized, @@ -753,6 +754,7 @@ pub async fn call_capture_request( connector_request, business_profile, header_payload.clone(), + None, ) .await } diff --git a/crates/router/src/core/payments/flows/approve_flow.rs b/crates/router/src/core/payments/flows/approve_flow.rs index c63ad19742d..7c9bb5b4500 100644 --- a/crates/router/src/core/payments/flows/approve_flow.rs +++ b/crates/router/src/core/payments/flows/approve_flow.rs @@ -80,6 +80,7 @@ impl Feature<api::Approve, types::PaymentsApproveData> _connector_request: Option<services::Request>, _business_profile: &domain::Profile, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, + _all_keys_required: Option<bool>, ) -> RouterResult<Self> { Err(ApiErrorResponse::NotImplemented { message: NotImplementedMessage::Reason("Flow not supported".to_string()), diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index d6489dab3bc..8c4a7a585b2 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -170,6 +170,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu connector_request: Option<services::Request>, business_profile: &domain::Profile, header_payload: hyperswitch_domain_models::payments::HeaderPayload, + all_keys_required: Option<bool>, ) -> RouterResult<Self> { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::Authorize, @@ -186,6 +187,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu &self, call_connector_action.clone(), connector_request, + all_keys_required, ) .await .to_payment_failed_response()?; @@ -262,6 +264,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu authorize_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .to_payment_failed_response()?; @@ -514,6 +517,7 @@ pub async fn authorize_preprocessing_steps<F: Clone>( &preprocessing_router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .to_payment_failed_response()?; @@ -598,6 +602,7 @@ pub async fn authorize_postprocessing_steps<F: Clone>( &postprocessing_router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .to_payment_failed_response()?; diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rs index 3502e00e66b..e6eebba3127 100644 --- a/crates/router/src/core/payments/flows/cancel_flow.rs +++ b/crates/router/src/core/payments/flows/cancel_flow.rs @@ -79,6 +79,7 @@ impl Feature<api::Void, types::PaymentsCancelData> connector_request: Option<services::Request>, _business_profile: &domain::Profile, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, + _all_keys_required: Option<bool>, ) -> RouterResult<Self> { metrics::PAYMENT_CANCEL_COUNT.add( 1, @@ -97,6 +98,7 @@ impl Feature<api::Void, types::PaymentsCancelData> &self, call_connector_action, connector_request, + None, ) .await .to_payment_failed_response()?; diff --git a/crates/router/src/core/payments/flows/capture_flow.rs b/crates/router/src/core/payments/flows/capture_flow.rs index eb4c7ed0f53..9b681e107a2 100644 --- a/crates/router/src/core/payments/flows/capture_flow.rs +++ b/crates/router/src/core/payments/flows/capture_flow.rs @@ -108,6 +108,7 @@ impl Feature<api::Capture, types::PaymentsCaptureData> connector_request: Option<services::Request>, _business_profile: &domain::Profile, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, + _all_keys_required: Option<bool>, ) -> RouterResult<Self> { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::Capture, @@ -121,6 +122,7 @@ impl Feature<api::Capture, types::PaymentsCaptureData> &self, call_connector_action, connector_request, + None, ) .await .to_payment_failed_response()?; diff --git a/crates/router/src/core/payments/flows/complete_authorize_flow.rs b/crates/router/src/core/payments/flows/complete_authorize_flow.rs index a2a6de43afa..768614b1304 100644 --- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs +++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs @@ -100,6 +100,7 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData> connector_request: Option<services::Request>, business_profile: &domain::Profile, header_payload: hyperswitch_domain_models::payments::HeaderPayload, + _all_keys_required: Option<bool>, ) -> RouterResult<Self> { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::CompleteAuthorize, @@ -113,6 +114,7 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData> &self, call_connector_action.clone(), connector_request, + None, ) .await .to_payment_failed_response()?; @@ -247,6 +249,7 @@ pub async fn complete_authorize_preprocessing_steps<F: Clone>( &preprocessing_router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .to_payment_failed_response()?; diff --git a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs b/crates/router/src/core/payments/flows/incremental_authorization_flow.rs index df4897ef927..74419a5cfb3 100644 --- a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs +++ b/crates/router/src/core/payments/flows/incremental_authorization_flow.rs @@ -87,6 +87,7 @@ impl Feature<api::IncrementalAuthorization, types::PaymentsIncrementalAuthorizat connector_request: Option<services::Request>, _business_profile: &domain::Profile, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, + _all_keys_required: Option<bool>, ) -> RouterResult<Self> { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::IncrementalAuthorization, @@ -100,6 +101,7 @@ impl Feature<api::IncrementalAuthorization, types::PaymentsIncrementalAuthorizat &self, call_connector_action, connector_request, + None, ) .await .to_payment_failed_response()?; diff --git a/crates/router/src/core/payments/flows/post_session_tokens_flow.rs b/crates/router/src/core/payments/flows/post_session_tokens_flow.rs index a374eae98e4..483d04e94df 100644 --- a/crates/router/src/core/payments/flows/post_session_tokens_flow.rs +++ b/crates/router/src/core/payments/flows/post_session_tokens_flow.rs @@ -87,6 +87,7 @@ impl Feature<api::PostSessionTokens, types::PaymentsPostSessionTokensData> connector_request: Option<services::Request>, _business_profile: &domain::Profile, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, + _all_keys_required: Option<bool>, ) -> RouterResult<Self> { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::PostSessionTokens, @@ -100,6 +101,7 @@ impl Feature<api::PostSessionTokens, types::PaymentsPostSessionTokensData> &self, call_connector_action, connector_request, + None, ) .await .to_payment_failed_response()?; diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs index 58da60ed86f..de435d47b1d 100644 --- a/crates/router/src/core/payments/flows/psync_flow.rs +++ b/crates/router/src/core/payments/flows/psync_flow.rs @@ -111,6 +111,7 @@ impl Feature<api::PSync, types::PaymentsSyncData> connector_request: Option<services::Request>, _business_profile: &domain::Profile, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, + all_keys_required: Option<bool>, ) -> RouterResult<Self> { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::PSync, @@ -133,6 +134,7 @@ impl Feature<api::PSync, types::PaymentsSyncData> pending_connector_capture_id_list, call_connector_action, connector_integration, + all_keys_required, ) .await?; // Initiating Integrity checks @@ -154,6 +156,7 @@ impl Feature<api::PSync, types::PaymentsSyncData> &self, call_connector_action, connector_request, + all_keys_required, ) .await .to_payment_failed_response()?; @@ -238,6 +241,7 @@ where types::PaymentsSyncData, types::PaymentsResponseData, >, + _all_keys_required: Option<bool>, ) -> RouterResult<Self>; } @@ -255,6 +259,7 @@ impl RouterDataPSync types::PaymentsSyncData, types::PaymentsResponseData, >, + all_keys_required: Option<bool>, ) -> RouterResult<Self> { let mut capture_sync_response_map = HashMap::new(); if let payments::CallConnectorAction::HandleResponse(_) = call_connector_action { @@ -265,6 +270,7 @@ impl RouterDataPSync self, call_connector_action.clone(), None, + all_keys_required, ) .await .to_payment_failed_response()?; @@ -283,6 +289,7 @@ impl RouterDataPSync &cloned_router_data, call_connector_action.clone(), None, + all_keys_required, ) .await .to_payment_failed_response()?; diff --git a/crates/router/src/core/payments/flows/reject_flow.rs b/crates/router/src/core/payments/flows/reject_flow.rs index 9f49ebe1436..f333518db22 100644 --- a/crates/router/src/core/payments/flows/reject_flow.rs +++ b/crates/router/src/core/payments/flows/reject_flow.rs @@ -79,6 +79,7 @@ impl Feature<api::Reject, types::PaymentsRejectData> _connector_request: Option<services::Request>, _business_profile: &domain::Profile, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, + _all_keys_required: Option<bool>, ) -> RouterResult<Self> { Err(ApiErrorResponse::NotImplemented { message: NotImplementedMessage::Reason("Flow not supported".to_string()), diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 79c08ef2a3f..dcf424b4c88 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -121,6 +121,7 @@ impl Feature<api::Session, types::PaymentsSessionData> for types::PaymentsSessio _connector_request: Option<services::Request>, business_profile: &domain::Profile, header_payload: hyperswitch_domain_models::payments::HeaderPayload, + _all_keys_required: Option<bool>, ) -> RouterResult<Self> { metrics::SESSION_TOKEN_CREATED.add( 1, @@ -1298,6 +1299,7 @@ impl RouterDataSession for types::PaymentsSessionRouterData { self, call_connector_action, None, + None, ) .await .to_payment_failed_response()?; diff --git a/crates/router/src/core/payments/flows/session_update_flow.rs b/crates/router/src/core/payments/flows/session_update_flow.rs index af78904e4ab..321f368199e 100644 --- a/crates/router/src/core/payments/flows/session_update_flow.rs +++ b/crates/router/src/core/payments/flows/session_update_flow.rs @@ -87,6 +87,7 @@ impl Feature<api::SdkSessionUpdate, types::SdkPaymentsSessionUpdateData> connector_request: Option<services::Request>, _business_profile: &domain::Profile, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, + _all_keys_required: Option<bool>, ) -> RouterResult<Self> { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::SdkSessionUpdate, @@ -100,6 +101,7 @@ impl Feature<api::SdkSessionUpdate, types::SdkPaymentsSessionUpdateData> &self, call_connector_action, connector_request, + None, ) .await .to_payment_failed_response()?; diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs index 7ec5dc22d85..fa2f94873ac 100644 --- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs +++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs @@ -116,6 +116,7 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup connector_request: Option<services::Request>, _business_profile: &domain::Profile, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, + _all_keys_required: Option<bool>, ) -> RouterResult<Self> { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::SetupMandate, @@ -143,6 +144,7 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup &self, call_connector_action.clone(), connector_request, + None, ) .await .to_setup_mandate_failed_response()?; diff --git a/crates/router/src/core/payments/flows/update_metadata_flow.rs b/crates/router/src/core/payments/flows/update_metadata_flow.rs index f9a6790356a..85d942f52c7 100644 --- a/crates/router/src/core/payments/flows/update_metadata_flow.rs +++ b/crates/router/src/core/payments/flows/update_metadata_flow.rs @@ -86,6 +86,7 @@ impl Feature<api::UpdateMetadata, types::PaymentsUpdateMetadataData> connector_request: Option<services::Request>, _business_profile: &domain::Profile, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, + all_keys_required: Option<bool>, ) -> RouterResult<Self> { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::UpdateMetadata, @@ -99,6 +100,7 @@ impl Feature<api::UpdateMetadata, types::PaymentsUpdateMetadataData> &self, call_connector_action, connector_request, + all_keys_required, ) .await .to_payment_failed_response()?; diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 0cada8c368e..cce16ad6244 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -4170,6 +4170,7 @@ pub fn router_data_type_conversion<F1, F2, Req1, Req2, Res1, Res2>( connector_mandate_request_reference_id: router_data.connector_mandate_request_reference_id, authentication_id: router_data.authentication_id, psd2_sca_exemption_type: router_data.psd2_sca_exemption_type, + whole_connector_response: router_data.whole_connector_response, } } diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs index a3b182dc3c4..a16c2cd433f 100644 --- a/crates/router/src/core/payments/operations/payment_approve.rs +++ b/crates/router/src/core/payments/operations/payment_approve.rs @@ -175,6 +175,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCaptureR payment_method_data: None, payment_method_info: None, force_sync: None, + all_keys_required: None, refunds: vec![], disputes: vec![], attempts: None, @@ -201,6 +202,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCaptureR card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, + whole_connector_response: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index fb0e7c70b27..343c1f98a9d 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -186,6 +186,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCancelRe payment_method_data: None, payment_method_info: None, force_sync: None, + all_keys_required: None, refunds: vec![], disputes: vec![], attempts: None, @@ -212,6 +213,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCancelRe card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, + whole_connector_response: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index 7ac984ae8ff..8e3a765b8ad 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -218,6 +218,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentData<F>, api::Paymen payment_attempt, currency, force_sync: None, + all_keys_required: None, amount, email: None, mandate_id: None, @@ -261,6 +262,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentData<F>, api::Paymen card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, + whole_connector_response: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs index 1ec62d84a51..199b4faf629 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -340,6 +340,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> .and_then(|pmd| pmd.payment_method_data.clone().map(Into::into)), payment_method_info, force_sync: None, + all_keys_required: None, refunds: vec![], disputes: vec![], attempts: None, @@ -366,6 +367,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: request.threeds_method_comp_ind.clone(), + whole_connector_response: None, }; let customer_details = Some(CustomerDetails { diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index a99359d7ea2..8c5f72b3405 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -798,6 +798,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> payment_method_data: payment_method_data_after_card_bin_call.map(Into::into), payment_method_info, force_sync: None, + all_keys_required: None, refunds: vec![], disputes: vec![], attempts: None, @@ -824,6 +825,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, + whole_connector_response: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index fc781e1350f..8ba549c59aa 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -601,6 +601,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> disputes: vec![], attempts: None, force_sync: None, + all_keys_required: None, sessions_token: vec![], card_cvc: request.card_cvc.clone(), creds_identifier, @@ -624,6 +625,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, + whole_connector_response: None, }; let get_trackers_response = operations::GetTrackerResponse { @@ -736,6 +738,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for &router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/core/payments/operations/payment_post_session_tokens.rs b/crates/router/src/core/payments/operations/payment_post_session_tokens.rs index d8904d2c930..3df1da1827e 100644 --- a/crates/router/src/core/payments/operations/payment_post_session_tokens.rs +++ b/crates/router/src/core/payments/operations/payment_post_session_tokens.rs @@ -147,6 +147,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsPostSess payment_method_data: None, payment_method_info: None, force_sync: None, + all_keys_required: None, refunds: vec![], disputes: vec![], attempts: None, @@ -173,6 +174,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsPostSess card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, + whole_connector_response: None, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(self), diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs index 27557afa53e..33ec9a0d592 100644 --- a/crates/router/src/core/payments/operations/payment_reject.rs +++ b/crates/router/src/core/payments/operations/payment_reject.rs @@ -173,6 +173,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsCancelRequest payment_method_data: None, payment_method_info: None, force_sync: None, + all_keys_required: None, refunds: vec![], disputes: vec![], attempts: None, @@ -199,6 +200,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsCancelRequest card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, + whole_connector_response: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 0b182d249bd..57d83f0d0c4 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -1406,6 +1406,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( .as_mut() .map(|info| info.status = status) }); + payment_data.whole_connector_response = router_data.whole_connector_response.clone(); // TODO: refactor of gsm_error_category with respective feature flag #[allow(unused_variables)] diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index e105ed69ba9..b0a5f2fc133 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -195,6 +195,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsSessionR payment_method_data: None, payment_method_info: None, force_sync: None, + all_keys_required: None, refunds: vec![], disputes: vec![], attempts: None, @@ -221,6 +222,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsSessionR card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, + whole_connector_response: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index 429a1128b71..e702ba1ef50 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -183,6 +183,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsStartReq payment_method_data: None, payment_method_info: None, force_sync: None, + all_keys_required: None, refunds: vec![], disputes: vec![], attempts: None, @@ -209,6 +210,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsStartReq card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, + whole_connector_response: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index 58c784c6528..c6cf1f96fef 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -524,6 +524,7 @@ async fn get_tracker_for_sync< && (helpers::check_force_psync_precondition(payment_attempt.status) || contains_encoded_data), ), + all_keys_required: request.all_keys_required, payment_attempt, refunds, disputes, @@ -551,6 +552,7 @@ async fn get_tracker_for_sync< card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, + whole_connector_response: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 0f3a58d9b9a..4a212962986 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -477,6 +477,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> .and_then(|pmd| pmd.payment_method_data.clone().map(Into::into)), payment_method_info, force_sync: None, + all_keys_required: None, refunds: vec![], disputes: vec![], attempts: None, @@ -503,6 +504,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, + whole_connector_response: None, }; let get_trackers_response = operations::GetTrackerResponse { @@ -614,6 +616,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for &router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/core/payments/operations/payment_update_metadata.rs b/crates/router/src/core/payments/operations/payment_update_metadata.rs index d35b0b4044b..2c6841c44a4 100644 --- a/crates/router/src/core/payments/operations/payment_update_metadata.rs +++ b/crates/router/src/core/payments/operations/payment_update_metadata.rs @@ -133,6 +133,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsUpdateMe payment_method_data: None, payment_method_info: None, force_sync: None, + all_keys_required: None, refunds: vec![], disputes: vec![], attempts: None, @@ -159,6 +160,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsUpdateMe card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, + whole_connector_response: None, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(self), diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs index 662b32699d9..e5262d092c1 100644 --- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs +++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs @@ -147,6 +147,7 @@ impl<F: Send + Clone + Sync> payment_method_data: None, payment_method_info: None, force_sync: None, + all_keys_required: None, refunds: vec![], disputes: vec![], attempts: None, @@ -178,6 +179,7 @@ impl<F: Send + Clone + Sync> card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, + whole_connector_response: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/tax_calculation.rs b/crates/router/src/core/payments/operations/tax_calculation.rs index 2a261da467d..85ad5fb1cb6 100644 --- a/crates/router/src/core/payments/operations/tax_calculation.rs +++ b/crates/router/src/core/payments/operations/tax_calculation.rs @@ -162,6 +162,7 @@ impl<F: Send + Clone + Sync> payment_method_data: None, payment_method_info: None, force_sync: None, + all_keys_required: None, refunds: vec![], disputes: vec![], attempts: None, @@ -188,6 +189,7 @@ impl<F: Send + Clone + Sync> card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, + whole_connector_response: None, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(self), @@ -296,6 +298,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsDynamicTaxCalculationRequest &router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .to_payment_failed_response() diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index bfe2c99855e..241a189d68d 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -373,6 +373,7 @@ where true, should_retry_with_pan, None, + None, ) .await?; diff --git a/crates/router/src/core/payments/session_operation.rs b/crates/router/src/core/payments/session_operation.rs index 4c3d27b72ec..d018ac19107 100644 --- a/crates/router/src/core/payments/session_operation.rs +++ b/crates/router/src/core/payments/session_operation.rs @@ -185,6 +185,7 @@ where None, &profile, header_payload.clone(), + None, )) .await? } diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index ae68ea53773..5d878b54bf3 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -1174,6 +1174,7 @@ pub async fn add_payment_method_token<F: Clone, T: types::Tokenizable + Clone>( &pm_token_router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .to_payment_failed_response()?; @@ -1431,6 +1432,7 @@ pub async fn add_token_for_payment_method( &payment_method_token_router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .to_payment_failed_response()?; diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 7e715d40ce6..a8c6417e806 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -169,6 +169,7 @@ where connector_mandate_request_reference_id, authentication_id: None, psd2_sca_exemption_type: None, + whole_connector_response: None, }; Ok(router_data) } @@ -388,6 +389,7 @@ pub async fn construct_payment_router_data_for_authorize<'a>( connector_mandate_request_reference_id, authentication_id: None, psd2_sca_exemption_type: None, + whole_connector_response: None, }; Ok(router_data) @@ -550,6 +552,7 @@ pub async fn construct_payment_router_data_for_capture<'a>( connector_mandate_request_reference_id, psd2_sca_exemption_type: None, authentication_id: None, + whole_connector_response: None, }; Ok(router_data) @@ -677,6 +680,7 @@ pub async fn construct_router_data_for_psync<'a>( connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, + whole_connector_response: None, }; Ok(router_data) @@ -837,6 +841,7 @@ pub async fn construct_payment_router_data_for_sdk_session<'a>( connector_mandate_request_reference_id: None, psd2_sca_exemption_type: None, authentication_id: None, + whole_connector_response: None, }; Ok(router_data) @@ -1044,6 +1049,7 @@ pub async fn construct_payment_router_data_for_setup_mandate<'a>( connector_mandate_request_reference_id, authentication_id: None, psd2_sca_exemption_type: None, + whole_connector_response: None, }; Ok(router_data) @@ -1242,6 +1248,7 @@ where connector_mandate_request_reference_id, authentication_id: None, psd2_sca_exemption_type: payment_data.payment_intent.psd2_sca_exemption_type, + whole_connector_response: None, }; Ok(router_data) @@ -1431,6 +1438,7 @@ pub async fn construct_payment_router_data_for_update_metadata<'a>( connector_mandate_request_reference_id, authentication_id: None, psd2_sca_exemption_type: payment_data.payment_intent.psd2_sca_exemption_type, + whole_connector_response: None, }; Ok(router_data) @@ -2870,6 +2878,7 @@ where issuer_error_code: payment_attempt.issuer_error_code, issuer_error_message: payment_attempt.issuer_error_message, is_iframe_redirection_enabled: payment_intent.is_iframe_redirection_enabled, + whole_connector_response: payment_data.get_whole_connector_response(), }; services::ApplicationResponse::JsonWithHeaders((payments_response, headers)) @@ -3160,6 +3169,7 @@ impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::Pay card_discovery: pa.card_discovery, force_3ds_challenge: pi.force_3ds_challenge, force_3ds_challenge_trigger: pi.force_3ds_challenge_trigger, + whole_connector_response: None, issuer_error_code: pa.issuer_error_code, issuer_error_message: pa.issuer_error_message, is_iframe_redirection_enabled:pi.is_iframe_redirection_enabled diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index 87888ab4257..ebc462d286d 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -1205,6 +1205,7 @@ pub async fn create_recipient( &router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .to_payout_failed_response()?; @@ -1432,6 +1433,7 @@ pub async fn check_payout_eligibility( &router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .to_payout_failed_response()?; @@ -1647,6 +1649,7 @@ pub async fn create_payout( &router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .to_payout_failed_response()?; @@ -1775,6 +1778,7 @@ async fn complete_payout_quote_steps_if_required<F>( &quote_router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .to_payout_failed_response()?; @@ -1867,6 +1871,7 @@ pub async fn create_payout_retrieve( &router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .to_payout_failed_response()?; @@ -2027,6 +2032,7 @@ pub async fn create_recipient_disburse_account( &router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .to_payout_failed_response()?; @@ -2216,6 +2222,7 @@ pub async fn cancel_payout( &router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .to_payout_failed_response()?; @@ -2353,6 +2360,7 @@ pub async fn fulfill_payout( &router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .to_payout_failed_response()?; diff --git a/crates/router/src/core/payouts/access_token.rs b/crates/router/src/core/payouts/access_token.rs index 27fc2e85536..a675b5f4e35 100644 --- a/crates/router/src/core/payouts/access_token.rs +++ b/crates/router/src/core/payouts/access_token.rs @@ -155,6 +155,7 @@ pub async fn refresh_connector_auth( router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await; diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 0e3814107ab..b9c9e497f6d 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -214,6 +214,7 @@ pub async fn trigger_refund_to_gateway( &router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await; let option_refund_error_update = @@ -647,6 +648,7 @@ pub async fn sync_refund_with_gateway( &router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .to_refund_failed_response()?; diff --git a/crates/router/src/core/refunds_v2.rs b/crates/router/src/core/refunds_v2.rs index ee10e1b3081..922b9dce245 100644 --- a/crates/router/src/core/refunds_v2.rs +++ b/crates/router/src/core/refunds_v2.rs @@ -240,6 +240,7 @@ where &router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await } else { diff --git a/crates/router/src/core/relay.rs b/crates/router/src/core/relay.rs index 5aae99849c9..e3f029ecb51 100644 --- a/crates/router/src/core/relay.rs +++ b/crates/router/src/core/relay.rs @@ -160,6 +160,7 @@ impl RelayInterface for RelayRefund { &router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .to_refund_failed_response()?; @@ -463,6 +464,7 @@ pub async fn sync_relay_refund_with_gateway( &router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .to_refund_failed_response()?; diff --git a/crates/router/src/core/relay/utils.rs b/crates/router/src/core/relay/utils.rs index a473d0c20d6..effc2178ec3 100644 --- a/crates/router/src/core/relay/utils.rs +++ b/crates/router/src/core/relay/utils.rs @@ -143,6 +143,7 @@ pub async fn construct_relay_refund_router_data<F>( connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, + whole_connector_response: None, }; Ok(router_data) diff --git a/crates/router/src/core/revenue_recovery/api.rs b/crates/router/src/core/revenue_recovery/api.rs index ed0d2e250f9..60465964856 100644 --- a/crates/router/src/core/revenue_recovery/api.rs +++ b/crates/router/src/core/revenue_recovery/api.rs @@ -31,6 +31,7 @@ pub async fn call_psync_api( force_sync: false, param: None, expand_attempts: true, + all_keys_required: None, }; let merchant_context_from_revenue_recovery_data = MerchantContext::NormalMerchant(Box::new(Context( @@ -128,6 +129,7 @@ pub async fn call_proxy_api( get_tracker_response, payments::CallConnectorAction::Trigger, payments_domain::HeaderPayload::default(), + None, )) .await?; Ok(payment_data) diff --git a/crates/router/src/core/revenue_recovery/types.rs b/crates/router/src/core/revenue_recovery/types.rs index 8b30011e022..e551340e102 100644 --- a/crates/router/src/core/revenue_recovery/types.rs +++ b/crates/router/src/core/revenue_recovery/types.rs @@ -736,6 +736,7 @@ async fn record_back_to_billing_connector( &router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed) diff --git a/crates/router/src/core/unified_authentication_service/utils.rs b/crates/router/src/core/unified_authentication_service/utils.rs index cbd4c2ee2ea..bab5d412357 100644 --- a/crates/router/src/core/unified_authentication_service/utils.rs +++ b/crates/router/src/core/unified_authentication_service/utils.rs @@ -48,6 +48,7 @@ where &router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .to_payment_failed_response()?; @@ -121,6 +122,7 @@ pub fn construct_uas_router_data<F: Clone, Req, Res>( connector_mandate_request_reference_id: None, authentication_id, psd2_sca_exemption_type: None, + whole_connector_response: None, }) } diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index 7b88998953f..3d67c5e4655 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -228,6 +228,7 @@ pub async fn construct_payout_router_data<'a, F>( connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, + whole_connector_response: None, }; Ok(router_data) @@ -383,6 +384,7 @@ pub async fn construct_refund_router_data<'a, F>( connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, + whole_connector_response: None, }; Ok(router_data) @@ -585,6 +587,7 @@ pub async fn construct_refund_router_data<'a, F>( connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, + whole_connector_response: None, }; Ok(router_data) @@ -1025,6 +1028,7 @@ pub async fn construct_accept_dispute_router_data<'a>( connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, + whole_connector_response: None, }; Ok(router_data) } @@ -1122,6 +1126,7 @@ pub async fn construct_submit_evidence_router_data<'a>( connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, + whole_connector_response: None, }; Ok(router_data) } @@ -1225,6 +1230,7 @@ pub async fn construct_upload_file_router_data<'a>( connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, + whole_connector_response: None, }; Ok(router_data) } @@ -1347,6 +1353,7 @@ pub async fn construct_payments_dynamic_tax_calculation_router_data<F: Clone>( connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, + whole_connector_response: None, }; Ok(router_data) } @@ -1447,6 +1454,7 @@ pub async fn construct_defend_dispute_router_data<'a>( connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, + whole_connector_response: None, }; Ok(router_data) } @@ -1541,6 +1549,7 @@ pub async fn construct_retrieve_file_router_data<'a>( connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, + whole_connector_response: None, }; Ok(router_data) } diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs index 86769b393ca..f50308d932c 100644 --- a/crates/router/src/core/webhooks/incoming.rs +++ b/crates/router/src/core/webhooks/incoming.rs @@ -659,6 +659,7 @@ async fn payments_incoming_webhook_flow( client_secret: None, expand_attempts: None, expand_captures: None, + all_keys_required: None, }, services::AuthFlow::Merchant, consume_or_trigger_flow.clone(), @@ -1843,6 +1844,7 @@ async fn verify_webhook_source_verification_call( &router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await?; diff --git a/crates/router/src/core/webhooks/incoming_v2.rs b/crates/router/src/core/webhooks/incoming_v2.rs index 94fec01edfa..b4ac1fbc805 100644 --- a/crates/router/src/core/webhooks/incoming_v2.rs +++ b/crates/router/src/core/webhooks/incoming_v2.rs @@ -470,6 +470,7 @@ async fn payments_incoming_webhook_flow( force_sync: true, expand_attempts: false, param: None, + all_keys_required: None, }, get_trackers_response, consume_or_trigger_flow, @@ -727,6 +728,7 @@ async fn verify_webhook_source_verification_call( &router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await?; diff --git a/crates/router/src/core/webhooks/recovery_incoming.rs b/crates/router/src/core/webhooks/recovery_incoming.rs index 89341614d9c..79994a48e85 100644 --- a/crates/router/src/core/webhooks/recovery_incoming.rs +++ b/crates/router/src/core/webhooks/recovery_incoming.rs @@ -433,6 +433,7 @@ impl RevenueRecoveryAttempt { force_sync: false, expand_attempts: true, param: None, + all_keys_required: None, }, payment_intent.payment_id.clone(), payments::CallConnectorAction::Avoid, @@ -811,6 +812,7 @@ impl BillingConnectorPaymentsSyncResponseData { &router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed) @@ -979,6 +981,7 @@ impl BillingConnectorInvoiceSyncResponseData { &router_data, payments::CallConnectorAction::Trigger, None, + None, ) .await .change_context(errors::RevenueRecoveryError::BillingConnectorInvoiceSyncFailed) diff --git a/crates/router/src/core/webhooks/utils.rs b/crates/router/src/core/webhooks/utils.rs index 155a21b4d25..4cf0d784a05 100644 --- a/crates/router/src/core/webhooks/utils.rs +++ b/crates/router/src/core/webhooks/utils.rs @@ -133,6 +133,7 @@ pub async fn construct_webhook_router_data( connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, + whole_connector_response: None, }; Ok(router_data) } diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 6af6a7af6e3..3ea5049742d 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -428,6 +428,7 @@ pub async fn payments_retrieve( client_secret: json_payload.client_secret.clone(), expand_attempts: json_payload.expand_attempts, expand_captures: json_payload.expand_captures, + all_keys_required: json_payload.all_keys_required, ..Default::default() }; let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { @@ -1903,10 +1904,11 @@ where merchant_context, profile_id, operation, - req, + req.clone(), auth_flow, payments::CallConnectorAction::Trigger, header_payload, + req.all_keys_required, ) .await } else { @@ -2812,6 +2814,7 @@ pub async fn proxy_confirm_intent( payment_id, payments::CallConnectorAction::Trigger, header_payload.clone(), + None, )) }, &auth::V2ApiKeyAuth { diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 4bc57cfdaa8..54384e107a2 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -140,6 +140,7 @@ pub async fn execute_connector_processing_step< req: &'b types::RouterData<T, Req, Resp>, call_connector_action: payments::CallConnectorAction, connector_request: Option<Request>, + all_keys_required: Option<bool>, ) -> CustomResult<types::RouterData<T, Req, Resp>, errors::ConnectorError> where T: Clone + Debug + 'static, @@ -272,7 +273,7 @@ where Ok(body) => { let connector_http_status_code = Some(body.status_code); let handle_response_result = connector_integration - .handle_response(req, Some(&mut connector_event), body) + .handle_response(req, Some(&mut connector_event), body.clone()) .inspect_err(|error| { if error.current_context() == &errors::ConnectorError::ResponseDeserializationFailed @@ -299,6 +300,16 @@ where val + external_latency }), ); + if all_keys_required == Some(true) { + let mut decoded = String::from_utf8(body.response.as_ref().to_vec()) + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + if decoded.starts_with('\u{feff}') { + decoded = decoded + .trim_start_matches('\u{feff}') + .to_string(); + } + data.whole_connector_response = Some(decoded); + } Ok(data) } Err(err) => { @@ -1061,13 +1072,26 @@ pub trait Authenticate { fn get_client_secret(&self) -> Option<&String> { None } + + fn get_all_keys_required(&self) -> Option<bool> { + None + } } +#[cfg(feature = "v2")] +impl Authenticate for api_models::payments::PaymentsConfirmIntentRequest {} +#[cfg(feature = "v2")] +impl Authenticate for api_models::payments::ProxyPaymentsRequest {} + #[cfg(feature = "v1")] impl Authenticate for api_models::payments::PaymentsRequest { fn get_client_secret(&self) -> Option<&String> { self.client_secret.as_ref() } + + fn get_all_keys_required(&self) -> Option<bool> { + self.all_keys_required + } } impl Authenticate for api_models::payment_methods::PaymentMethodListRequest { @@ -1095,7 +1119,11 @@ impl Authenticate for api_models::payments::PaymentsPostSessionTokensRequest { } impl Authenticate for api_models::payments::PaymentsUpdateMetadataRequest {} -impl Authenticate for api_models::payments::PaymentsRetrieveRequest {} +impl Authenticate for api_models::payments::PaymentsRetrieveRequest { + fn get_all_keys_required(&self) -> Option<bool> { + self.all_keys_required + } +} impl Authenticate for api_models::payments::PaymentsCancelRequest {} impl Authenticate for api_models::payments::PaymentsCaptureRequest {} impl Authenticate for api_models::payments::PaymentsIncrementalAuthorizationRequest {} diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index af5d983a48a..0c1255850a3 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -976,6 +976,7 @@ impl<F1, F2, T1, T2> ForeignFrom<(&RouterData<F1, T1, PaymentsResponseData>, T2) .clone(), authentication_id: data.authentication_id.clone(), psd2_sca_exemption_type: data.psd2_sca_exemption_type, + whole_connector_response: data.whole_connector_response.clone(), } } } @@ -1043,6 +1044,7 @@ impl<F1, F2> psd2_sca_exemption_type: None, additional_merchant_data: data.additional_merchant_data.clone(), connector_mandate_request_reference_id: None, + whole_connector_response: None, } } } diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs index 223c3e5638d..ad9a490398a 100644 --- a/crates/router/src/types/api/verify_connector.rs +++ b/crates/router/src/types/api/verify_connector.rs @@ -126,6 +126,7 @@ impl VerifyConnectorData { connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, + whole_connector_response: None, } } } diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index 3497a048a8a..61272a05877 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -133,6 +133,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, + whole_connector_response: None, } } @@ -205,6 +206,7 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { connector_mandate_request_reference_id: None, authentication_id: None, psd2_sca_exemption_type: None, + whole_connector_response: None, } } @@ -247,6 +249,7 @@ async fn payments_create_success() { &request, payments::CallConnectorAction::Trigger, None, + None, ) .await .unwrap(); @@ -312,6 +315,7 @@ async fn payments_create_failure() { &request, payments::CallConnectorAction::Trigger, None, + None, ) .await .is_err(); @@ -358,6 +362,7 @@ async fn refund_for_successful_payments() { &request, payments::CallConnectorAction::Trigger, None, + None, ) .await .unwrap(); @@ -383,6 +388,7 @@ async fn refund_for_successful_payments() { &refund_request, payments::CallConnectorAction::Trigger, None, + None, ) .await .unwrap(); @@ -433,6 +439,7 @@ async fn refunds_create_failure() { &request, payments::CallConnectorAction::Trigger, None, + None, ) .await .is_err(); diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index d6925ae1667..543d2451140 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -556,6 +556,7 @@ pub trait ConnectorActions: Connector { connector_mandate_request_reference_id: None, psd2_sca_exemption_type: None, authentication_id: None, + whole_connector_response: None, } } @@ -620,6 +621,7 @@ pub trait ConnectorActions: Connector { &request, payments::CallConnectorAction::Trigger, None, + None, ) .await?; Ok(res.response.unwrap()) @@ -664,6 +666,7 @@ pub trait ConnectorActions: Connector { &request, payments::CallConnectorAction::Trigger, None, + None, ) .await?; Ok(res.response.unwrap()) @@ -709,6 +712,7 @@ pub trait ConnectorActions: Connector { &request, payments::CallConnectorAction::Trigger, None, + None, ) .await?; Ok(res.response.unwrap()) @@ -753,6 +757,7 @@ pub trait ConnectorActions: Connector { &request, payments::CallConnectorAction::Trigger, None, + None, ) .await?; Ok(res.response.unwrap()) @@ -848,6 +853,7 @@ pub trait ConnectorActions: Connector { &request, payments::CallConnectorAction::Trigger, None, + None, ) .await?; Ok(res.response.unwrap()) @@ -889,6 +895,7 @@ async fn call_connector< &request, payments::CallConnectorAction::Trigger, None, + None, ) .await } diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs index 82296d2a83b..1879af550f1 100644 --- a/crates/router/tests/payments.rs +++ b/crates/router/tests/payments.rs @@ -464,6 +464,7 @@ async fn payments_create_core() { issuer_error_code: None, issuer_error_message: None, is_iframe_redirection_enabled: None, + whole_connector_response: None, }; let expected_response = services::ApplicationResponse::JsonWithHeaders((expected_response, vec![])); @@ -741,6 +742,7 @@ async fn payments_create_core_adyen_no_redirect() { issuer_error_code: None, issuer_error_message: None, is_iframe_redirection_enabled: None, + whole_connector_response: None, }, vec![], )); diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs index 1240d1c17a2..e7aaa09f5b8 100644 --- a/crates/router/tests/payments2.rs +++ b/crates/router/tests/payments2.rs @@ -226,6 +226,7 @@ async fn payments_create_core() { issuer_error_code: None, issuer_error_message: None, is_iframe_redirection_enabled: None, + whole_connector_response: None, }; let expected_response = @@ -511,6 +512,7 @@ async fn payments_create_core_adyen_no_redirect() { issuer_error_code: None, issuer_error_message: None, is_iframe_redirection_enabled: None, + whole_connector_response: None, }, vec![], ));
2025-05-09T13:20:44Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD closes this [issue](https://github.com/juspay/hyperswitch/issues/7997) ## Description <!-- Describe your changes in detail --> Added all_keys_required in confirm and psync payload. If all_keys_required is passed as true, we will send the whole connector response. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Postman Test Confirm call (with `all_keys_required` passed as `true`) Request (taking AuthorizeDotNet as connector) ``` curl --location 'http://localhost:8080/payments/pay_MsmPKoZNKAk0zpoBuA5Z/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'all_keys_required: true' \ --header 'api-key: ••••••' \ --data ' { "connector": ["authorizedotnet"], "all_keys_required": true, "capture_method": "automatic", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "370000000000002", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } } ' ``` Response: ``` { "payment_id": "pay_UHNVQh54xvuv97CixQVF", "merchant_id": "merchant_1746796056", "status": "succeeded", "amount": 35308, "net_amount": 35308, "shipping_cost": null, "amount_capturable": 0, "amount_received": 35308, "connector": "authorizedotnet", "client_secret": "pay_UHNVQh54xvuv97CixQVF_secret_aUvQnXDaU6Op4uFuWHC1", "created": "2025-05-09T13:08:19.469Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0000", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "491761", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": "token_xZJ3bAv0dVvWBWpuYRga", "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "80040892370", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80040892370", "payment_link": null, "profile_id": "pro_NLQkgFo4oL87ujOInwp1", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_Bjt7NDYXrZmazh9Tdavu", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-05-09T13:23:19.469Z", "fingerprint": null, "browser_info": { "os_type": null, "language": null, "time_zone": null, "ip_address": "::1", "os_version": null, "user_agent": null, "color_depth": null, "device_model": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "accept_language": "en", "java_script_enabled": null }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-05-09T13:18:33.486Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "whole_connector_response": "{\"transactionResponse\":{\"responseCode\":\"1\",\"authCode\":\"140GJ4\",\"avsResultCode\":\"Y\",\"cvvResultCode\":\"P\",\"cavvResultCode\":\"2\",\"transId\":\"80040892370\",\"refTransID\":\"\",\"transHash\":\"\",\"testRequest\":\"0\",\"accountNumber\":\"XXXX0000\",\"accountType\":\"Visa\",\"messages\":[{\"code\":\"1\",\"description\":\"This transaction has been approved.\"}],\"transHashSha2\":\"EDD14C10BDDBD427B768E42099F1AF0D089221FA13F9CA55D8B6323C8449585476AFEE55B4A054EE7FD26F73D4B85EF147B0552F0DB4EE17F4F60F8FB16CA2B9\",\"SupplementalDataQualificationIndicator\":0,\"networkTransId\":\"Z9TSL0XISGMU542D7Z5TF0A\"},\"refId\":\"\",\"messages\":{\"resultCode\":\"Ok\",\"message\":[{\"code\":\"I00001\",\"text\":\"Successful.\"}]}}" } ``` Psync: URL: ``` {{baseUrl}}/payments/:id?expand_captures=true&expand_attempts=true&all_keys_required=true ``` Response: ``` { "payment_id": "pay_UHNVQh54xvuv97CixQVF", "merchant_id": "merchant_1746796056", "status": "succeeded", "amount": 35308, "net_amount": 35308, "shipping_cost": null, "amount_capturable": 0, "amount_received": 35308, "connector": "authorizedotnet", "client_secret": "pay_UHNVQh54xvuv97CixQVF_secret_aUvQnXDaU6Op4uFuWHC1", "created": "2025-05-09T13:08:19.469Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": null, "refunds": null, "disputes": null, "attempts": [ { "attempt_id": "pay_UHNVQh54xvuv97CixQVF_1", "status": "charged", "amount": 35308, "order_tax_amount": null, "currency": "USD", "connector": "authorizedotnet", "error_message": null, "payment_method": "card", "connector_transaction_id": "80040892370", "capture_method": "automatic", "authentication_type": "three_ds", "created_at": "2025-05-09T13:08:19.470Z", "modified_at": "2025-05-09T13:18:33.485Z", "cancellation_reason": null, "mandate_id": null, "error_code": null, "payment_token": "token_xZJ3bAv0dVvWBWpuYRga", "connector_metadata": { "creditCard": { "cardNumber": "XXXX0000", "expirationDate": "XXXX" } }, "payment_experience": null, "payment_method_type": "credit", "reference_id": "80040892370", "unified_code": null, "unified_message": null, "client_source": null, "client_version": null } ], "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0000", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "491761", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": "token_xZJ3bAv0dVvWBWpuYRga", "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "80040892370", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "80040892370", "payment_link": null, "profile_id": "pro_NLQkgFo4oL87ujOInwp1", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_Bjt7NDYXrZmazh9Tdavu", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-05-09T13:23:19.469Z", "fingerprint": null, "browser_info": { "os_type": null, "language": null, "time_zone": null, "ip_address": "::1", "os_version": null, "user_agent": null, "color_depth": null, "device_model": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "accept_language": "en", "java_script_enabled": null }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-05-09T13:19:32.525Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "whole_connector_response": "{\"transaction\":{\"transId\":\"80040892370\",\"submitTimeUTC\":\"2025-05-09T13:18:33.043Z\",\"submitTimeLocal\":\"2025-05-09T06:18:33.043\",\"transactionType\":\"authCaptureTransaction\",\"transactionStatus\":\"capturedPendingSettlement\",\"responseCode\":1,\"responseReasonCode\":1,\"responseReasonDescription\":\"Approval\",\"authCode\":\"140GJ4\",\"AVSResponse\":\"Y\",\"cardCodeResponse\":\"P\",\"order\":{\"description\":\"pay_UHNVQh54xvuv97CixQVF_1\",\"discountAmount\":0.0,\"taxIsAfterDiscount\":false},\"authAmount\":353.08,\"settleAmount\":353.08,\"taxExempt\":false,\"payment\":{\"creditCard\":{\"cardNumber\":\"XXXX0000\",\"expirationDate\":\"XXXX\",\"cardType\":\"Visa\"}},\"billTo\":{\"firstName\":\"joseph\",\"lastName\":\"Doe\",\"address\":\"1467\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\"},\"recurringBilling\":false,\"customerIP\":\"110.227.219.118\",\"product\":\"Card Not Present\",\"marketType\":\"eCommerce\",\"networkTransId\":\"Z9TSL0XISGMU542D7Z5TF0A\",\"authorizationIndicator\":\"final\"},\"messages\":{\"resultCode\":\"Ok\",\"message\":[{\"code\":\"I00001\",\"text\":\"Successful.\"}]}}" } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
140d15bcbd0e74ddaacd8dbe074b5ff755879ffa
140d15bcbd0e74ddaacd8dbe074b5ff755879ffa
juspay/hyperswitch
juspay__hyperswitch-8015
Bug: [FEATURE] Barclaycard: Add template PR ### Feature Description Barclaycard: Add template PR ### Possible Implementation Barclaycard: Add template PR ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/config.example.toml b/config/config.example.toml index 6be49be237f..c735da47d89 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -188,6 +188,7 @@ authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api" bambora.base_url = "https://api.na.bambora.com" bamboraapac.base_url = "https://demo.ippayments.com.au/interface/api" bankofamerica.base_url = "https://apitest.merchant-services.bankofamerica.com/" +barclaycard.base_url = "https://api.smartpayfuse-test.barclaycard/pts/v2/" billwerk.base_url = "https://api.reepay.com/" billwerk.secondary_base_url = "https://card.reepay.com/" bitpay.base_url = "https://test.bitpay.com" diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index cb454b73731..ad39ee3ad19 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -32,6 +32,7 @@ authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api" bambora.base_url = "https://api.na.bambora.com" bamboraapac.base_url = "https://demo.ippayments.com.au/interface/api" bankofamerica.base_url = "https://apitest.merchant-services.bankofamerica.com/" +barclaycard.base_url = "https://api.smartpayfuse-test.barclaycard/pts/v2/" billwerk.base_url = "https://api.reepay.com/" billwerk.secondary_base_url = "https://card.reepay.com/" bitpay.base_url = "https://test.bitpay.com" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index efdce9d016c..f53e255253b 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -36,6 +36,7 @@ authorizedotnet.base_url = "https://api.authorize.net/xml/v1/request.api" bambora.base_url = "https://api.na.bambora.com" bamboraapac.base_url = "https://www.bambora.co.nz/interface/api/dts.asmx" bankofamerica.base_url = "https://api.merchant-services.bankofamerica.com/" +barclaycard.base_url = "https://api.smartpayfuse-test.barclaycard/pts/v2/" billwerk.base_url = "https://api.reepay.com/" billwerk.secondary_base_url = "https://card.reepay.com/" bitpay.base_url = "https://bitpay.com" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 3c3b5f5f403..c68c41ac7b8 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -36,6 +36,7 @@ authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api" bambora.base_url = "https://api.na.bambora.com" bamboraapac.base_url = "https://demo.ippayments.com.au/interface/api" bankofamerica.base_url = "https://apitest.merchant-services.bankofamerica.com/" +barclaycard.base_url = "https://api.smartpayfuse-test.barclaycard/pts/v2/" billwerk.base_url = "https://api.reepay.com/" billwerk.secondary_base_url = "https://card.reepay.com/" bitpay.base_url = "https://test.bitpay.com" diff --git a/config/development.toml b/config/development.toml index 2bdb4d6a806..c3da1fa04d4 100644 --- a/config/development.toml +++ b/config/development.toml @@ -123,6 +123,7 @@ cards = [ "bambora", "bamboraapac", "bankofamerica", + "barclaycard", "billwerk", "bitpay", "bluesnap", @@ -237,6 +238,7 @@ authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api" bambora.base_url = "https://api.na.bambora.com" bamboraapac.base_url = "https://demo.ippayments.com.au/interface/api" bankofamerica.base_url = "https://apitest.merchant-services.bankofamerica.com/" +barclaycard.base_url = "https://api.smartpayfuse-test.barclaycard/pts/v2/" billwerk.base_url = "https://api.reepay.com/" billwerk.secondary_base_url = "https://card.reepay.com/" bitpay.base_url = "https://test.bitpay.com" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 2f8ff2b2ab0..a617b928bab 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -119,6 +119,7 @@ authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api" bambora.base_url = "https://api.na.bambora.com" bamboraapac.base_url = "https://demo.ippayments.com.au/interface/api" bankofamerica.base_url = "https://apitest.merchant-services.bankofamerica.com/" +barclaycard.base_url = "https://api.smartpayfuse-test.barclaycard/pts/v2/" billwerk.base_url = "https://api.reepay.com/" billwerk.secondary_base_url = "https://card.reepay.com/" bitpay.base_url = "https://test.bitpay.com" @@ -243,6 +244,7 @@ cards = [ "bambora", "bamboraapac", "bankofamerica", + "barclaycard", "billwerk", "bitpay", "bluesnap", diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index a0ef01f4f11..76979d26d62 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -65,6 +65,7 @@ pub enum RoutableConnectors { Archipel, Authorizedotnet, Bankofamerica, + // Barclaycard, Billwerk, Bitpay, Bambora, @@ -217,6 +218,7 @@ pub enum Connector { Bambora, Bamboraapac, Bankofamerica, + // Barclaycard, Billwerk, Bitpay, Bluesnap, @@ -389,6 +391,7 @@ impl Connector { | Self::Bambora | Self::Bamboraapac | Self::Bankofamerica + // | Self::Barclaycard | Self::Billwerk | Self::Bitpay | Self::Bluesnap @@ -540,6 +543,7 @@ impl From<RoutableConnectors> for Connector { RoutableConnectors::Archipel => Self::Archipel, RoutableConnectors::Authorizedotnet => Self::Authorizedotnet, RoutableConnectors::Bankofamerica => Self::Bankofamerica, + // RoutableConnectors::Barclaycard => Self::Barclaycard, RoutableConnectors::Billwerk => Self::Billwerk, RoutableConnectors::Bitpay => Self::Bitpay, RoutableConnectors::Bambora => Self::Bambora, @@ -652,6 +656,7 @@ impl TryFrom<Connector> for RoutableConnectors { Connector::Archipel => Ok(Self::Archipel), Connector::Authorizedotnet => Ok(Self::Authorizedotnet), Connector::Bankofamerica => Ok(Self::Bankofamerica), + // Connector::Barclaycard => Ok(Self::Barclaycard), Connector::Billwerk => Ok(Self::Billwerk), Connector::Bitpay => Ok(Self::Bitpay), Connector::Bambora => Ok(Self::Bambora), diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index 61c9e1ca692..bfa63d59394 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -174,6 +174,7 @@ pub struct ConnectorConfig { pub authorizedotnet: Option<ConnectorTomlConfig>, pub bamboraapac: Option<ConnectorTomlConfig>, pub bankofamerica: Option<ConnectorTomlConfig>, + pub barclaycard: Option<ConnectorTomlConfig>, pub billwerk: Option<ConnectorTomlConfig>, pub bitpay: Option<ConnectorTomlConfig>, pub bluesnap: Option<ConnectorTomlConfig>, diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs index 283c6a9a3a4..b2f6bb1e708 100644 --- a/crates/hyperswitch_connectors/src/connectors.rs +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -8,6 +8,7 @@ pub mod authorizedotnet; pub mod bambora; pub mod bamboraapac; pub mod bankofamerica; +pub mod barclaycard; pub mod billwerk; pub mod bitpay; pub mod bluesnap; @@ -101,21 +102,22 @@ pub mod zsl; pub use self::{ aci::Aci, adyen::Adyen, adyenplatform::Adyenplatform, airwallex::Airwallex, amazonpay::Amazonpay, archipel::Archipel, authorizedotnet::Authorizedotnet, bambora::Bambora, - bamboraapac::Bamboraapac, bankofamerica::Bankofamerica, billwerk::Billwerk, bitpay::Bitpay, - bluesnap::Bluesnap, boku::Boku, braintree::Braintree, cashtocode::Cashtocode, - chargebee::Chargebee, checkout::Checkout, coinbase::Coinbase, coingate::Coingate, - cryptopay::Cryptopay, ctp_mastercard::CtpMastercard, cybersource::Cybersource, - datatrans::Datatrans, deutschebank::Deutschebank, digitalvirgo::Digitalvirgo, dlocal::Dlocal, - ebanx::Ebanx, elavon::Elavon, facilitapay::Facilitapay, fiserv::Fiserv, fiservemea::Fiservemea, - fiuu::Fiuu, forte::Forte, getnet::Getnet, globalpay::Globalpay, globepay::Globepay, - gocardless::Gocardless, gpayments::Gpayments, helcim::Helcim, hipay::Hipay, iatapay::Iatapay, - inespay::Inespay, itaubank::Itaubank, jpmorgan::Jpmorgan, - juspaythreedsserver::Juspaythreedsserver, klarna::Klarna, mifinity::Mifinity, mollie::Mollie, - moneris::Moneris, multisafepay::Multisafepay, netcetera::Netcetera, nexinets::Nexinets, - nexixpay::Nexixpay, nmi::Nmi, nomupay::Nomupay, noon::Noon, novalnet::Novalnet, nuvei::Nuvei, - opayo::Opayo, opennode::Opennode, paybox::Paybox, payeezy::Payeezy, payme::Payme, - payone::Payone, paypal::Paypal, paystack::Paystack, payu::Payu, placetopay::Placetopay, - plaid::Plaid, powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, + bamboraapac::Bamboraapac, bankofamerica::Bankofamerica, barclaycard::Barclaycard, + billwerk::Billwerk, bitpay::Bitpay, bluesnap::Bluesnap, boku::Boku, braintree::Braintree, + cashtocode::Cashtocode, chargebee::Chargebee, checkout::Checkout, coinbase::Coinbase, + coingate::Coingate, cryptopay::Cryptopay, ctp_mastercard::CtpMastercard, + cybersource::Cybersource, datatrans::Datatrans, deutschebank::Deutschebank, + digitalvirgo::Digitalvirgo, dlocal::Dlocal, ebanx::Ebanx, elavon::Elavon, + facilitapay::Facilitapay, fiserv::Fiserv, fiservemea::Fiservemea, fiuu::Fiuu, forte::Forte, + getnet::Getnet, globalpay::Globalpay, globepay::Globepay, gocardless::Gocardless, + gpayments::Gpayments, helcim::Helcim, hipay::Hipay, iatapay::Iatapay, inespay::Inespay, + itaubank::Itaubank, jpmorgan::Jpmorgan, juspaythreedsserver::Juspaythreedsserver, + klarna::Klarna, mifinity::Mifinity, mollie::Mollie, moneris::Moneris, + multisafepay::Multisafepay, netcetera::Netcetera, nexinets::Nexinets, nexixpay::Nexixpay, + nmi::Nmi, nomupay::Nomupay, noon::Noon, novalnet::Novalnet, nuvei::Nuvei, opayo::Opayo, + opennode::Opennode, paybox::Paybox, payeezy::Payeezy, payme::Payme, payone::Payone, + paypal::Paypal, paystack::Paystack, payu::Payu, placetopay::Placetopay, plaid::Plaid, + powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, recurly::Recurly, redsys::Redsys, riskified::Riskified, shift4::Shift4, signifyd::Signifyd, square::Square, stax::Stax, stripe::Stripe, stripebilling::Stripebilling, taxjar::Taxjar, threedsecureio::Threedsecureio, thunes::Thunes, trustpay::Trustpay, tsys::Tsys, diff --git a/crates/hyperswitch_connectors/src/connectors/barclaycard.rs b/crates/hyperswitch_connectors/src/connectors/barclaycard.rs new file mode 100644 index 00000000000..9397d063ff6 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/barclaycard.rs @@ -0,0 +1,573 @@ +pub mod transformers; + +use common_utils::{ + errors::CustomResult, + ext_traits::BytesExt, + request::{Method, Request, RequestBuilder, RequestContent}, + types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}, +}; +use error_stack::{report, ResultExt}; +use hyperswitch_domain_models::{ + router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, + router_flow_types::{ + access_token_auth::AccessTokenAuth, + payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, + refunds::{Execute, RSync}, + }, + router_request_types::{ + AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, + RefundsData, SetupMandateRequestData, + }, + router_response_types::{PaymentsResponseData, RefundsResponseData}, + types::{ + PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, + RefundSyncRouterData, RefundsRouterData, + }, +}; +use hyperswitch_interfaces::{ + api::{ + self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, + ConnectorValidation, + }, + configs::Connectors, + errors, + events::connector_api_logs::ConnectorEvent, + types::{self, Response}, + webhooks, +}; +use masking::{ExposeInterface, Mask}; +use transformers as barclaycard; + +use crate::{constants::headers, types::ResponseRouterData, utils}; + +#[derive(Clone)] +pub struct Barclaycard { + amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), +} + +impl Barclaycard { + pub fn new() -> &'static Self { + &Self { + amount_converter: &StringMinorUnitForConnector, + } + } +} + +impl api::Payment for Barclaycard {} +impl api::PaymentSession for Barclaycard {} +impl api::ConnectorAccessToken for Barclaycard {} +impl api::MandateSetup for Barclaycard {} +impl api::PaymentAuthorize for Barclaycard {} +impl api::PaymentSync for Barclaycard {} +impl api::PaymentCapture for Barclaycard {} +impl api::PaymentVoid for Barclaycard {} +impl api::Refund for Barclaycard {} +impl api::RefundExecute for Barclaycard {} +impl api::RefundSync for Barclaycard {} +impl api::PaymentToken for Barclaycard {} + +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Barclaycard +{ + // Not Implemented (R) +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Barclaycard +where + Self: ConnectorIntegration<Flow, Request, Response>, +{ + fn build_headers( + &self, + req: &RouterData<Flow, Request, Response>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let mut header = vec![( + headers::CONTENT_TYPE.to_string(), + self.get_content_type().to_string().into(), + )]; + let mut api_key = self.get_auth_header(&req.connector_auth_type)?; + header.append(&mut api_key); + Ok(header) + } +} + +impl ConnectorCommon for Barclaycard { + fn id(&self) -> &'static str { + "barclaycard" + } + + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Base + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { + connectors.barclaycard.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let auth = barclaycard::BarclaycardAuthType::try_from(auth_type) + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + Ok(vec![( + headers::AUTHORIZATION.to_string(), + auth.api_key.expose().into_masked(), + )]) + } + + fn build_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: barclaycard::BarclaycardErrorResponse = res + .response + .parse_struct("BarclaycardErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + + Ok(ErrorResponse { + status_code: res.status_code, + code: response.code, + message: response.message, + reason: response.reason, + attempt_status: None, + connector_transaction_id: None, + network_decline_code: None, + network_advice_code: None, + network_error_message: None, + }) + } +} + +impl ConnectorValidation for Barclaycard { + //TODO: implement functions when support enabled +} + +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Barclaycard { + //TODO: implement sessions flow +} + +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Barclaycard {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> + for Barclaycard +{ +} + +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Barclaycard { + fn get_headers( + &self, + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let amount = utils::convert_amount( + self.amount_converter, + req.request.minor_amount, + req.request.currency, + )?; + + let connector_router_data = barclaycard::BarclaycardRouterData::from((amount, req)); + let connector_req = + barclaycard::BarclaycardPaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::PaymentsAuthorizeType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsAuthorizeType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { + let response: barclaycard::BarclaycardPaymentsResponse = res + .response + .parse_struct("Barclaycard PaymentsAuthorizeResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Barclaycard { + fn get_headers( + &self, + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &PaymentsSyncRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn build_request( + &self, + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Get) + .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { + let response: barclaycard::BarclaycardPaymentsResponse = res + .response + .parse_struct("barclaycard PaymentsSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Barclaycard { + fn get_headers( + &self, + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &PaymentsCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + _req: &PaymentsCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) + } + + fn build_request( + &self, + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PaymentsCaptureType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsCaptureType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { + let response: barclaycard::BarclaycardPaymentsResponse = res + .response + .parse_struct("Barclaycard PaymentsCaptureResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Barclaycard {} + +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Barclaycard { + fn get_headers( + &self, + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &RefundsRouterData<Execute>, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + req: &RefundsRouterData<Execute>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let refund_amount = utils::convert_amount( + self.amount_converter, + req.request.minor_refund_amount, + req.request.currency, + )?; + + let connector_router_data = barclaycard::BarclaycardRouterData::from((refund_amount, req)); + let connector_req = + barclaycard::BarclaycardRefundRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&types::RefundExecuteType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::RefundExecuteType::get_headers( + self, req, connectors, + )?) + .set_body(types::RefundExecuteType::get_request_body( + self, req, connectors, + )?) + .build(); + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &RefundsRouterData<Execute>, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { + let response: barclaycard::RefundResponse = res + .response + .parse_struct("barclaycard RefundResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Barclaycard { + fn get_headers( + &self, + req: &RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &RefundSyncRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn build_request( + &self, + req: &RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Get) + .url(&types::RefundSyncType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::RefundSyncType::get_headers(self, req, connectors)?) + .set_body(types::RefundSyncType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { + let response: barclaycard::RefundResponse = res + .response + .parse_struct("barclaycard RefundSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +#[async_trait::async_trait] +impl webhooks::IncomingWebhook for Barclaycard { + fn get_webhook_object_reference_id( + &self, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } + + fn get_webhook_event_type( + &self, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } + + fn get_webhook_resource_object( + &self, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } +} + +impl ConnectorSpecifications for Barclaycard {} diff --git a/crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs b/crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs new file mode 100644 index 00000000000..1a994d3d2a0 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs @@ -0,0 +1,228 @@ +use common_enums::enums; +use common_utils::types::StringMinorUnit; +use hyperswitch_domain_models::{ + payment_method_data::PaymentMethodData, + router_data::{ConnectorAuthType, RouterData}, + router_flow_types::refunds::{Execute, RSync}, + router_request_types::ResponseId, + router_response_types::{PaymentsResponseData, RefundsResponseData}, + types::{PaymentsAuthorizeRouterData, RefundsRouterData}, +}; +use hyperswitch_interfaces::errors; +use masking::Secret; +use serde::{Deserialize, Serialize}; + +use crate::{ + types::{RefundsResponseRouterData, ResponseRouterData}, + utils::PaymentsAuthorizeRequestData, +}; + +//TODO: Fill the struct with respective fields +pub struct BarclaycardRouterData<T> { + pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. + pub router_data: T, +} + +impl<T> From<(StringMinorUnit, T)> for BarclaycardRouterData<T> { + fn from((amount, item): (StringMinorUnit, T)) -> Self { + //Todo : use utils to convert the amount to the type of amount that a connector accepts + Self { + amount, + router_data: item, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Serialize, PartialEq)] +pub struct BarclaycardPaymentsRequest { + amount: StringMinorUnit, + card: BarclaycardCard, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct BarclaycardCard { + number: cards::CardNumber, + expiry_month: Secret<String>, + expiry_year: Secret<String>, + cvc: Secret<String>, + complete: bool, +} + +impl TryFrom<&BarclaycardRouterData<&PaymentsAuthorizeRouterData>> for BarclaycardPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &BarclaycardRouterData<&PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + PaymentMethodData::Card(req_card) => { + let card = BarclaycardCard { + number: req_card.card_number, + expiry_month: req_card.card_exp_month, + expiry_year: req_card.card_exp_year, + cvc: req_card.card_cvc, + complete: item.router_data.request.is_auto_capture()?, + }; + Ok(Self { + amount: item.amount.clone(), + card, + }) + } + _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), + } + } +} + +//TODO: Fill the struct with respective fields +// Auth Struct +pub struct BarclaycardAuthType { + pub(super) api_key: Secret<String>, +} + +impl TryFrom<&ConnectorAuthType> for BarclaycardAuthType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { + match auth_type { + ConnectorAuthType::HeaderKey { api_key } => Ok(Self { + api_key: api_key.to_owned(), + }), + _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + } + } +} +// PaymentsResponse +//TODO: Append the remaining status flags +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum BarclaycardPaymentStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<BarclaycardPaymentStatus> for common_enums::AttemptStatus { + fn from(item: BarclaycardPaymentStatus) -> Self { + match item { + BarclaycardPaymentStatus::Succeeded => Self::Charged, + BarclaycardPaymentStatus::Failed => Self::Failure, + BarclaycardPaymentStatus::Processing => Self::Authorizing, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct BarclaycardPaymentsResponse { + status: BarclaycardPaymentStatus, + id: String, +} + +impl<F, T> TryFrom<ResponseRouterData<F, BarclaycardPaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData<F, BarclaycardPaymentsResponse, T, PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: common_enums::AttemptStatus::from(item.response.status), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.id), + redirection_data: Box::new(None), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: None, + incremental_authorization_allowed: None, + charges: None, + }), + ..item.data + }) + } +} + +//TODO: Fill the struct with respective fields +// REFUND : +// Type definition for RefundRequest +#[derive(Default, Debug, Serialize)] +pub struct BarclaycardRefundRequest { + pub amount: StringMinorUnit, +} + +impl<F> TryFrom<&BarclaycardRouterData<&RefundsRouterData<F>>> for BarclaycardRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &BarclaycardRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { + Ok(Self { + amount: item.amount.to_owned(), + }) + } +} + +// Type definition for Refund Response + +#[allow(dead_code)] +#[derive(Debug, Serialize, Default, Deserialize, Clone)] +pub enum RefundStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<RefundStatus> for enums::RefundStatus { + fn from(item: RefundStatus) -> Self { + match item { + RefundStatus::Succeeded => Self::Success, + RefundStatus::Failed => Self::Failure, + RefundStatus::Processing => Self::Pending, + //TODO: Review mapping + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize)] +pub struct RefundResponse { + id: String, + status: RefundStatus, +} + +impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: RefundsResponseRouterData<Execute, RefundResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(RefundsResponseData { + connector_refund_id: item.response.id.to_string(), + refund_status: enums::RefundStatus::from(item.response.status), + }), + ..item.data + }) + } +} + +impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: RefundsResponseRouterData<RSync, RefundResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(RefundsResponseData { + connector_refund_id: item.response.id.to_string(), + refund_status: enums::RefundStatus::from(item.response.status), + }), + ..item.data + }) + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +pub struct BarclaycardErrorResponse { + pub status_code: u16, + pub code: String, + pub message: String, + pub reason: Option<String>, +} diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index e8013933d6d..ed5f0135a65 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -127,6 +127,7 @@ default_imp_for_authorize_session_token!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -242,6 +243,7 @@ default_imp_for_calculate_tax!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -358,6 +360,7 @@ default_imp_for_session_update!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -474,6 +477,7 @@ default_imp_for_post_session_tokens!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Bitpay, connectors::Bluesnap, connectors::Braintree, @@ -589,6 +593,7 @@ default_imp_for_update_metadata!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Bitpay, connectors::Bluesnap, connectors::Braintree, @@ -705,6 +710,7 @@ default_imp_for_complete_authorize!( connectors::Archipel, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Boku, @@ -804,6 +810,7 @@ default_imp_for_incremental_authorization!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -920,6 +927,7 @@ default_imp_for_create_customer!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -1035,6 +1043,7 @@ default_imp_for_connector_redirect_response!( connectors::Bitpay, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Boku, connectors::Cashtocode, connectors::Chargebee, @@ -1130,6 +1139,7 @@ default_imp_for_pre_processing_steps!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -1237,6 +1247,7 @@ default_imp_for_post_processing_steps!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -1354,6 +1365,7 @@ default_imp_for_approve!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -1472,6 +1484,7 @@ default_imp_for_reject!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -1590,6 +1603,7 @@ default_imp_for_webhook_source_verification!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -1707,6 +1721,7 @@ default_imp_for_accept_dispute!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -1823,6 +1838,7 @@ default_imp_for_submit_evidence!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -1938,6 +1954,7 @@ default_imp_for_defend_dispute!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -2063,6 +2080,7 @@ default_imp_for_file_upload!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -2170,6 +2188,7 @@ default_imp_for_payouts!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -2281,6 +2300,7 @@ default_imp_for_payouts_create!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -2396,6 +2416,7 @@ default_imp_for_payouts_retrieve!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -2513,6 +2534,7 @@ default_imp_for_payouts_eligibility!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -2628,6 +2650,7 @@ default_imp_for_payouts_fulfill!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -2740,6 +2763,7 @@ default_imp_for_payouts_cancel!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -2856,6 +2880,7 @@ default_imp_for_payouts_quote!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -2973,6 +2998,7 @@ default_imp_for_payouts_recipient!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -3089,6 +3115,7 @@ default_imp_for_payouts_recipient_account!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -3207,6 +3234,7 @@ default_imp_for_frm_sale!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -3325,6 +3353,7 @@ default_imp_for_frm_checkout!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -3443,6 +3472,7 @@ default_imp_for_frm_transaction!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -3561,6 +3591,7 @@ default_imp_for_frm_fulfillment!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -3679,6 +3710,7 @@ default_imp_for_frm_record_return!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -3794,6 +3826,7 @@ default_imp_for_revoking_mandates!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -3907,6 +3940,7 @@ default_imp_for_uas_pre_authentication!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bluesnap, connectors::Bitpay, @@ -4022,6 +4056,7 @@ default_imp_for_uas_post_authentication!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -4138,6 +4173,7 @@ default_imp_for_uas_authentication_confirmation!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bluesnap, connectors::Bitpay, @@ -4246,6 +4282,7 @@ default_imp_for_connector_request_id!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bluesnap, connectors::Bitpay, @@ -4356,6 +4393,7 @@ default_imp_for_fraud_check!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bluesnap, connectors::Bitpay, @@ -4496,6 +4534,7 @@ default_imp_for_connector_authentication!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bluesnap, connectors::Bitpay, @@ -4609,6 +4648,7 @@ default_imp_for_uas_authentication!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -4717,6 +4757,7 @@ default_imp_for_revenue_recovery! { connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bluesnap, connectors::Bitpay, @@ -4836,6 +4877,7 @@ default_imp_for_billing_connector_payment_sync!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bluesnap, connectors::Bitpay, @@ -4954,6 +4996,7 @@ default_imp_for_revenue_recovery_record_back!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bluesnap, connectors::Bitpay, @@ -5070,6 +5113,7 @@ default_imp_for_billing_connector_invoice_sync!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bluesnap, connectors::Bitpay, diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index e6b0a24574f..9148bdb1135 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -248,6 +248,7 @@ default_imp_for_new_connector_integration_payment!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -366,6 +367,7 @@ default_imp_for_new_connector_integration_refund!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -479,6 +481,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -598,6 +601,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -715,6 +719,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -832,6 +837,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -960,6 +966,7 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -1080,6 +1087,7 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -1200,6 +1208,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -1320,6 +1329,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -1440,6 +1450,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -1560,6 +1571,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -1680,6 +1692,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -1800,6 +1813,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -1920,6 +1934,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -2038,6 +2053,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -2158,6 +2174,7 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -2278,6 +2295,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -2398,6 +2416,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -2518,6 +2537,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -2638,6 +2658,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -2755,6 +2776,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Bambora, connectors::Bamboraapac, connectors::Bankofamerica, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -2861,6 +2883,7 @@ default_imp_for_new_connector_integration_frm!( connectors::Amazonpay, connectors::Bambora, connectors::Bamboraapac, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -2978,6 +3001,7 @@ default_imp_for_new_connector_integration_connector_authentication!( connectors::Amazonpay, connectors::Bambora, connectors::Bamboraapac, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, @@ -3084,6 +3108,7 @@ default_imp_for_new_connector_integration_revenue_recovery!( connectors::Amazonpay, connectors::Bambora, connectors::Bamboraapac, + connectors::Barclaycard, connectors::Billwerk, connectors::Bitpay, connectors::Bluesnap, diff --git a/crates/hyperswitch_domain_models/src/configs.rs b/crates/hyperswitch_domain_models/src/configs.rs index d5d7f225150..7ce8b2cad01 100644 --- a/crates/hyperswitch_domain_models/src/configs.rs +++ b/crates/hyperswitch_domain_models/src/configs.rs @@ -22,6 +22,7 @@ pub struct Connectors { pub bambora: ConnectorParams, pub bamboraapac: ConnectorParams, pub bankofamerica: ConnectorParams, + pub barclaycard: ConnectorParams, pub billwerk: ConnectorParams, pub bitpay: ConnectorParams, pub bluesnap: ConnectorParamsWithSecondaryBaseUrl, diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index da49aaed74e..20f09c0ab9a 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -6,13 +6,13 @@ pub use hyperswitch_connectors::connectors::{ aci, aci::Aci, adyen, adyen::Adyen, adyenplatform, adyenplatform::Adyenplatform, airwallex, airwallex::Airwallex, amazonpay, amazonpay::Amazonpay, archipel, archipel::Archipel, authorizedotnet, authorizedotnet::Authorizedotnet, bambora, bambora::Bambora, bamboraapac, - bamboraapac::Bamboraapac, bankofamerica, bankofamerica::Bankofamerica, billwerk, - billwerk::Billwerk, bitpay, bitpay::Bitpay, bluesnap, bluesnap::Bluesnap, boku, boku::Boku, - braintree, braintree::Braintree, cashtocode, cashtocode::Cashtocode, chargebee, - chargebee::Chargebee, checkout, checkout::Checkout, coinbase, coinbase::Coinbase, coingate, - coingate::Coingate, cryptopay, cryptopay::Cryptopay, ctp_mastercard, - ctp_mastercard::CtpMastercard, cybersource, cybersource::Cybersource, datatrans, - datatrans::Datatrans, deutschebank, deutschebank::Deutschebank, digitalvirgo, + bamboraapac::Bamboraapac, bankofamerica, bankofamerica::Bankofamerica, barclaycard, + barclaycard::Barclaycard, billwerk, billwerk::Billwerk, bitpay, bitpay::Bitpay, bluesnap, + bluesnap::Bluesnap, boku, boku::Boku, braintree, braintree::Braintree, cashtocode, + cashtocode::Cashtocode, chargebee, chargebee::Chargebee, checkout, checkout::Checkout, + coinbase, coinbase::Coinbase, coingate, coingate::Coingate, cryptopay, cryptopay::Cryptopay, + ctp_mastercard, ctp_mastercard::CtpMastercard, cybersource, cybersource::Cybersource, + datatrans, datatrans::Datatrans, deutschebank, deutschebank::Deutschebank, digitalvirgo, digitalvirgo::Digitalvirgo, dlocal, dlocal::Dlocal, ebanx, ebanx::Ebanx, elavon, elavon::Elavon, facilitapay, facilitapay::Facilitapay, fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu, fiuu::Fiuu, forte, forte::Forte, getnet, getnet::Getnet, diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 14a6900693e..8abdc4216bc 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1340,6 +1340,10 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> { bankofamerica::transformers::BankOfAmericaAuthType::try_from(self.auth_type)?; Ok(()) } + // api_enums::Connector::Barclaycard => { + // barclaycard::transformers::BarclaycardAuthType::try_from(self.auth_type)?; + // Ok(()) + // }, api_enums::Connector::Billwerk => { billwerk::transformers::BillwerkAuthType::try_from(self.auth_type)?; Ok(()) diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 5009b993710..9296503c36e 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -329,6 +329,9 @@ impl ConnectorData { enums::Connector::Bankofamerica => { Ok(ConnectorEnum::Old(Box::new(&connector::Bankofamerica))) } + // enums::Connector::Barclaycard => { + // Ok(ConnectorEnum::Old(Box::new(connector::Barclaycard))) + // } enums::Connector::Billwerk => { Ok(ConnectorEnum::Old(Box::new(connector::Billwerk::new()))) } diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index ebdb0bfe1cd..e40456b7d98 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -219,6 +219,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { api_enums::Connector::Bambora => Self::Bambora, api_enums::Connector::Bamboraapac => Self::Bamboraapac, api_enums::Connector::Bankofamerica => Self::Bankofamerica, + // api_enums::Connector::Barclaycard => Self::Barclaycard, api_enums::Connector::Billwerk => Self::Billwerk, api_enums::Connector::Bitpay => Self::Bitpay, api_enums::Connector::Bluesnap => Self::Bluesnap, diff --git a/crates/router/tests/connectors/barclaycard.rs b/crates/router/tests/connectors/barclaycard.rs new file mode 100644 index 00000000000..2087131c4e6 --- /dev/null +++ b/crates/router/tests/connectors/barclaycard.rs @@ -0,0 +1,420 @@ +use masking::Secret; +use router::types::{self, api, domain, storage::enums}; +use test_utils::connector_auth; + +use crate::utils::{self, ConnectorActions}; + +#[derive(Clone, Copy)] +struct BarclaycardTest; +impl ConnectorActions for BarclaycardTest {} +impl utils::Connector for BarclaycardTest { + fn get_data(&self) -> api::ConnectorData { + use router::connector::Barclaycard; + utils::construct_connector_data_old( + Box::new(Barclaycard::new()), + types::Connector::DummyConnector1, + api::GetToken::Connector, + None, + ) + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + utils::to_connector_auth_type( + connector_auth::ConnectorAuthentication::new() + .barclaycard + .expect("Missing connector authentication configuration") + .into(), + ) + } + + fn get_name(&self) -> String { + "barclaycard".to_string() + } +} + +static CONNECTOR: BarclaycardTest = BarclaycardTest {}; + +fn get_default_payment_info() -> Option<utils::PaymentInfo> { + None +} + +fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { + None +} + +// Cards Positive Tests +// Creates a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_only_authorize_payment() { + let response = CONNECTOR + .authorize_payment(payment_method_details(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + assert_eq!(response.status, enums::AttemptStatus::Authorized); +} + +// Captures a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_capture_authorized_payment() { + let response = CONNECTOR + .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) + .await + .expect("Capture payment response"); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +// Partially captures a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_capture_authorized_payment() { + let response = CONNECTOR + .authorize_and_capture_payment( + payment_method_details(), + Some(types::PaymentsCaptureData { + amount_to_capture: 50, + ..utils::PaymentCaptureType::default().0 + }), + get_default_payment_info(), + ) + .await + .expect("Capture payment response"); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +// Synchronizes a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_authorized_payment() { + let authorize_response = CONNECTOR + .authorize_payment(payment_method_details(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: types::ResponseId::ConnectorTransactionId( + txn_id.unwrap(), + ), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .expect("PSync response"); + assert_eq!(response.status, enums::AttemptStatus::Authorized,); +} + +// Voids a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_void_authorized_payment() { + let response = CONNECTOR + .authorize_and_void_payment( + payment_method_details(), + Some(types::PaymentsCancelData { + connector_transaction_id: String::from(""), + cancellation_reason: Some("requested_by_customer".to_string()), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .expect("Void payment response"); + assert_eq!(response.status, enums::AttemptStatus::Voided); +} + +// Refunds a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_manually_captured_payment() { + let response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Partially refunds a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_refund_manually_captured_payment() { + let response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Synchronizes a refund using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_manually_captured_refund() { + let refund_response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + let response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Success, + refund_response.response.unwrap().connector_refund_id, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Creates a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_make_payment() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); +} + +// Synchronizes a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_auto_captured_payment() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + assert_ne!(txn_id, None, "Empty connector transaction id"); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Charged, + Some(types::PaymentsSyncData { + connector_transaction_id: types::ResponseId::ConnectorTransactionId( + txn_id.unwrap(), + ), + capture_method: Some(enums::CaptureMethod::Automatic), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::Charged,); +} + +// Refunds a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_auto_captured_payment() { + let response = CONNECTOR + .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Partially refunds a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_refund_succeeded_payment() { + let refund_response = CONNECTOR + .make_payment_and_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + refund_response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_succeeded_payment_multiple_times() { + CONNECTOR + .make_payment_and_multiple_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await; +} + +// Synchronizes a refund using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_refund() { + let refund_response = CONNECTOR + .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) + .await + .unwrap(); + let response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Success, + refund_response.response.unwrap().connector_refund_id, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Cards Negative scenarios +// Creates a payment with incorrect CVC. +#[actix_web::test] +async fn should_fail_payment_for_incorrect_cvc() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { + card_cvc: Secret::new("12345".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's security code is invalid.".to_string(), + ); +} + +// Creates a payment with incorrect expiry month. +#[actix_web::test] +async fn should_fail_payment_for_invalid_exp_month() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { + card_exp_month: Secret::new("20".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's expiration month is invalid.".to_string(), + ); +} + +// Creates a payment with incorrect expiry year. +#[actix_web::test] +async fn should_fail_payment_for_incorrect_expiry_year() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { + card_exp_year: Secret::new("2000".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's expiration year is invalid.".to_string(), + ); +} + +// Voids a payment using automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_fail_void_payment_for_auto_capture() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + assert_ne!(txn_id, None, "Empty connector transaction id"); + let void_response = CONNECTOR + .void_payment(txn_id.unwrap(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + void_response.response.unwrap_err().message, + "You cannot cancel this PaymentIntent because it has a status of succeeded." + ); +} + +// Captures a payment using invalid connector payment id. +#[actix_web::test] +async fn should_fail_capture_for_invalid_payment() { + let capture_response = CONNECTOR + .capture_payment("123456789".to_string(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + capture_response.response.unwrap_err().message, + String::from("No such payment_intent: '123456789'") + ); +} + +// Refunds a payment with refund amount higher than payment amount. +#[actix_web::test] +async fn should_fail_for_refund_amount_higher_than_payment_amount() { + let response = CONNECTOR + .make_payment_and_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 150, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Refund amount (₹1.50) is greater than charge amount (₹1.00)", + ); +} + +// Connector dependent test cases goes here + +// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 144f464b9db..2726363635e 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -16,6 +16,7 @@ mod bambora; mod bamboraapac; #[cfg(feature = "dummy_connector")] mod bankofamerica; +mod barclaycard; #[cfg(feature = "dummy_connector")] mod billwerk; mod bitpay; diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index 05a6060e8cb..7d208c5464e 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -329,4 +329,9 @@ api_key= "API Key" api_key = "API Key" [recurly] -api_key= "API Key" \ No newline at end of file +api_key= "API Key" + +[barclaycard] +api_key = "MyApiKey" +key1 = "Merchant id" +api_secret = "Secret key" \ No newline at end of file diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index 9b0a393fd8a..b9873776e09 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -23,6 +23,7 @@ pub struct ConnectorAuthentication { pub bambora: Option<BodyKey>, pub bamboraapac: Option<HeaderKey>, pub bankofamerica: Option<SignatureKey>, + pub barclaycard: Option<SignatureKey>, pub billwerk: Option<HeaderKey>, pub bitpay: Option<HeaderKey>, pub bluesnap: Option<BodyKey>, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index d682b5c3f8a..8ccb694a386 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -86,6 +86,7 @@ authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api" bambora.base_url = "https://api.na.bambora.com" bamboraapac.base_url = "https://demo.ippayments.com.au/interface/api" bankofamerica.base_url = "https://apitest.merchant-services.bankofamerica.com/" +barclaycard.base_url = "https://api.smartpayfuse-test.barclaycard/pts/v2/" billwerk.base_url = "https://api.reepay.com/" billwerk.secondary_base_url = "https://card.reepay.com/" bitpay.base_url = "https://test.bitpay.com" @@ -209,6 +210,7 @@ cards = [ "bambora", "bamboraapac", "bankofamerica", + "barclaycard", "billwerk", "bitpay", "bluesnap", diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index 3023c2e541e..bf27a84958c 100755 --- a/scripts/add_connector.sh +++ b/scripts/add_connector.sh @@ -6,7 +6,7 @@ function find_prev_connector() { git checkout $self cp $self $self.tmp # Add new connector to existing list and sort it - connectors=(aci adyen adyenplatform airwallex amazonpay applepay archipel authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode chargebee checkout coinbase cryptopay ctp_visa cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector ebanx elavon facilitapay fiserv fiservemea fiuu forte getnet globalpay globepay gocardless gpayments helcim hipay iatapay inespay itaubank jpmorgan juspaythreedsserver klarna mifinity mollie moneris multisafepay netcetera nexinets nexixpay nomupay noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal paystack payu placetopay plaid powertranz prophetpay rapyd razorpay recurly redsys shift4 square stax stripe stripebilling taxjar threedsecureio thunes trustpay tsys unified_authentication_service vgs volt wellsfargo wellsfargopayout wise worldline worldpay worldpayxml xendit zsl "$1") + connectors=(aci adyen adyenplatform airwallex amazonpay applepay archipel authorizedotnet bambora bamboraapac bankofamerica barclaycard billwerk bitpay bluesnap boku braintree cashtocode chargebee checkout coinbase cryptopay ctp_visa cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector ebanx elavon facilitapay fiserv fiservemea fiuu forte getnet globalpay globepay gocardless gpayments helcim hipay iatapay inespay itaubank jpmorgan juspaythreedsserver klarna mifinity mollie moneris multisafepay netcetera nexinets nexixpay nomupay noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal paystack payu placetopay plaid powertranz prophetpay rapyd razorpay recurly redsys shift4 square stax stripe stripebilling taxjar threedsecureio thunes trustpay tsys unified_authentication_service vgs volt wellsfargo wellsfargopayout wise worldline worldpay worldpayxml xendit zsl "$1") IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS res="$(echo ${sorted[@]})" sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp
2025-05-13T11:10:18Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD Closes this [issue](https://github.com/juspay/hyperswitch/issues/8015) ## Description <!-- Describe your changes in detail --> added barclaycard template code ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Added template code for barclaycard Docs Link: [https://developer.smartpayfuse.barclaycard/api-reference-assets/index.html](https://developer.smartpayfuse.barclaycard/api-reference-assets/index.html) ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Only template PR hence no testing required ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
e62f8ee8aba4ba05041b221e9af6f30100fdefcb
e62f8ee8aba4ba05041b221e9af6f30100fdefcb
juspay/hyperswitch
juspay__hyperswitch-8008
Bug: refactor(connector): move stripe connector from router crate to hyperswitch_connectors Move code related to stripe connector from router crate to hyperswitch_connectors
diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs index 009bec8c92a..b3b0f21b1b6 100644 --- a/crates/hyperswitch_connectors/src/connectors.rs +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -78,6 +78,7 @@ pub mod shift4; pub mod signifyd; pub mod square; pub mod stax; +pub mod stripe; pub mod stripebilling; pub mod taxjar; pub mod threedsecureio; @@ -115,7 +116,7 @@ pub use self::{ payone::Payone, paypal::Paypal, paystack::Paystack, payu::Payu, placetopay::Placetopay, plaid::Plaid, powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, recurly::Recurly, redsys::Redsys, riskified::Riskified, shift4::Shift4, signifyd::Signifyd, - square::Square, stax::Stax, stripebilling::Stripebilling, taxjar::Taxjar, + square::Square, stax::Stax, stripe::Stripe, stripebilling::Stripebilling, taxjar::Taxjar, threedsecureio::Threedsecureio, thunes::Thunes, trustpay::Trustpay, tsys::Tsys, unified_authentication_service::UnifiedAuthenticationService, vgs::Vgs, volt::Volt, wellsfargo::Wellsfargo, wellsfargopayout::Wellsfargopayout, wise::Wise, worldline::Worldline, diff --git a/crates/router/src/connector/stripe.rs b/crates/hyperswitch_connectors/src/connectors/stripe.rs similarity index 58% rename from crates/router/src/connector/stripe.rs rename to crates/hyperswitch_connectors/src/connectors/stripe.rs index 0fcddc5c342..be1777bac42 100644 --- a/crates/router/src/connector/stripe.rs +++ b/crates/hyperswitch_connectors/src/connectors/stripe.rs @@ -2,43 +2,91 @@ pub mod transformers; use std::collections::HashMap; +use api_models::webhooks::IncomingWebhookEvent; +use common_enums::{ + CallConnectorAction, CaptureMethod, PaymentAction, PaymentChargeType, PaymentMethodType, + PaymentResourceUpdateStatus, StripeChargeType, +}; use common_utils::{ - request::RequestContent, + crypto, + errors::CustomResult, + ext_traits::{ByteSliceExt as _, BytesExt, OptionExt as _}, + request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, }; -use diesel_models::enums; use error_stack::ResultExt; -use hyperswitch_domain_models::router_request_types::SplitRefundsRequest; -use masking::PeekInterface; +use hyperswitch_domain_models::{ + payment_method_data::PaymentMethodData, + router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, + router_flow_types::{ + AccessTokenAuth, Authorize, Capture, CreateConnectorCustomer, Evidence, Execute, PSync, + PaymentMethodToken, RSync, Retrieve, Session, SetupMandate, UpdateMetadata, Upload, Void, + }, + router_request_types::{ + AccessTokenRequestData, ConnectorCustomerData, PaymentMethodTokenizationData, + PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, + PaymentsSyncData, PaymentsUpdateMetadataData, RefundsData, RetrieveFileRequestData, + SetupMandateRequestData, SplitRefundsRequest, SubmitEvidenceRequestData, + UploadFileRequestData, + }, + router_response_types::{ + PaymentsResponseData, RefundsResponseData, RetrieveFileResponse, SubmitEvidenceResponse, + UploadFileResponse, + }, + types::{ + ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData, + PaymentsCaptureRouterData, PaymentsSyncRouterData, PaymentsUpdateMetadataRouterData, + RefundsRouterData, TokenizationRouterData, + }, +}; +#[cfg(feature = "payouts")] +use hyperswitch_domain_models::{ + router_flow_types::{PoCancel, PoCreate, PoFulfill, PoRecipient, PoRecipientAccount}, + types::{PayoutsData, PayoutsResponseData, PayoutsRouterData}, +}; +#[cfg(feature = "payouts")] +use hyperswitch_interfaces::types::{ + PayoutCancelType, PayoutCreateType, PayoutFulfillType, PayoutRecipientAccountType, + PayoutRecipientType, +}; +use hyperswitch_interfaces::{ + api::{ + self, + disputes::SubmitEvidence, + files::{FilePurpose, FileUpload, RetrieveFile, UploadFile}, + ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse, + ConnectorSpecifications, ConnectorValidation, + }, + configs::Connectors, + consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}, + disputes::DisputePayload, + errors::ConnectorError, + events::connector_api_logs::ConnectorEvent, + types::{ + ConnectorCustomerType, PaymentsAuthorizeType, PaymentsCaptureType, PaymentsSyncType, + PaymentsUpdateMetadataType, PaymentsVoidType, RefundExecuteType, RefundSyncType, Response, + RetrieveFileType, SubmitEvidenceType, TokenizationType, UploadFileType, + }, + webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, +}; +use masking::{Mask as _, Maskable, PeekInterface}; use router_env::{instrument, tracing}; use stripe::auth_headers; use self::transformers as stripe; -use super::utils::{self as connector_utils, PaymentMethodDataType, RefundsRequestData}; #[cfg(feature = "payouts")] -use super::utils::{PayoutsData, RouterData}; +use crate::utils::{PayoutsData as OtherPayoutsData, RouterData as OtherRouterData}; use crate::{ - configs::settings, - consts, - core::{ - errors::{self, CustomResult}, - payments, - }, - events::connector_api_logs::ConnectorEvent, - headers, - services::{ - self, - request::{self, Mask}, - ConnectorSpecifications, ConnectorValidation, - }, + constants::headers::{AUTHORIZATION, CONTENT_TYPE, STRIPE_COMPATIBLE_CONNECT_ACCOUNT}, types::{ - self, - api::{self, ConnectorCommon, ConnectorCommonExt}, - domain, + ResponseRouterData, RetrieveFileRouterData, SubmitEvidenceRouterData, UploadFileRouterData, + }, + utils::{ + self, get_authorise_integrity_object, get_capture_integrity_object, + get_refund_integrity_object, get_sync_integrity_object, PaymentMethodDataType, + RefundsRequestData as OtherRefundsRequestData, }, - utils::{crypto, ByteSliceExt, BytesExt, OptionExt}, }; - #[derive(Clone)] pub struct Stripe { amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), @@ -54,15 +102,15 @@ impl Stripe { impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Stripe where - Self: services::ConnectorIntegration<Flow, Request, Response>, + Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, - req: &types::RouterData<Flow, Request, Response>, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RouterData<Flow, Request, Response>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let mut header = vec![( - headers::CONTENT_TYPE.to_string(), + CONTENT_TYPE.to_string(), Self::common_get_content_type(self).to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; @@ -80,20 +128,20 @@ impl ConnectorCommon for Stripe { "application/x-www-form-urlencoded" } - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { // &self.base_url connectors.stripe.base_url.as_ref() } fn get_auth_header( &self, - auth_type: &types::ConnectorAuthType, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let auth = stripe::StripeAuthType::try_from(auth_type) - .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + .change_context(ConnectorError::FailedToObtainAuthType)?; Ok(vec![ ( - headers::AUTHORIZATION.to_string(), + AUTHORIZATION.to_string(), format!("Bearer {}", auth.api_key.peek()).into_masked(), ), ( @@ -106,25 +154,27 @@ impl ConnectorCommon for Stripe { #[cfg(feature = "payouts")] fn build_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { + use hyperswitch_interfaces::consts::NO_ERROR_CODE; + let response: stripe::StripeConnectErrorResponse = res .response .parse_struct("StripeConnectErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); - Ok(types::ErrorResponse { + Ok(ErrorResponse { status_code: res.status_code, code: response .error .code .clone() - .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: response .error .code - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: response.error.message, attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), @@ -138,26 +188,26 @@ impl ConnectorCommon for Stripe { impl ConnectorValidation for Stripe { fn validate_connector_against_payment_request( &self, - capture_method: Option<enums::CaptureMethod>, - _payment_method: enums::PaymentMethod, - _pmt: Option<enums::PaymentMethodType>, - ) -> CustomResult<(), errors::ConnectorError> { + capture_method: Option<CaptureMethod>, + _payment_method: common_enums::PaymentMethod, + _pmt: Option<PaymentMethodType>, + ) -> CustomResult<(), ConnectorError> { let capture_method = capture_method.unwrap_or_default(); match capture_method { - enums::CaptureMethod::SequentialAutomatic - | enums::CaptureMethod::Automatic - | enums::CaptureMethod::Manual => Ok(()), - enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( - connector_utils::construct_not_supported_error_report(capture_method, self.id()), + CaptureMethod::SequentialAutomatic + | CaptureMethod::Automatic + | CaptureMethod::Manual => Ok(()), + CaptureMethod::ManualMultiple | CaptureMethod::Scheduled => Err( + utils::construct_not_supported_error_report(capture_method, self.id()), ), } } fn validate_mandate_payment( &self, - pm_type: Option<types::storage::enums::PaymentMethodType>, - pm_data: domain::payments::PaymentMethodData, - ) -> CustomResult<(), errors::ConnectorError> { + pm_type: Option<PaymentMethodType>, + pm_data: PaymentMethodData, + ) -> CustomResult<(), ConnectorError> { let mandate_supported_pmd = std::collections::HashSet::from([ PaymentMethodDataType::Card, PaymentMethodDataType::ApplePay, @@ -170,7 +220,7 @@ impl ConnectorValidation for Stripe { PaymentMethodDataType::Ideal, PaymentMethodDataType::BancontactCard, ]); - connector_utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id()) + utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id()) } } @@ -184,43 +234,27 @@ impl api::PaymentCapture for Stripe {} impl api::PaymentSession for Stripe {} impl api::ConnectorAccessToken for Stripe {} -impl - services::ConnectorIntegration< - api::AccessTokenAuth, - types::AccessTokenRequestData, - types::AccessToken, - > for Stripe -{ +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Stripe { // Not Implemented (R) } -impl - services::ConnectorIntegration< - api::Session, - types::PaymentsSessionData, - types::PaymentsResponseData, - > for Stripe -{ +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Stripe { // Not Implemented (R) } impl api::ConnectorCustomer for Stripe {} -impl - services::ConnectorIntegration< - api::CreateConnectorCustomer, - types::ConnectorCustomerData, - types::PaymentsResponseData, - > for Stripe +impl ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData> + for Stripe { fn get_headers( &self, - req: &types::ConnectorCustomerRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &ConnectorCustomerRouterData, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - types::ConnectorCustomerType::get_content_type(self) + CONTENT_TYPE.to_string(), + ConnectorCustomerType::get_content_type(self) .to_string() .into(), )]; @@ -235,37 +269,33 @@ impl fn get_url( &self, - _req: &types::ConnectorCustomerRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &ConnectorCustomerRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!("{}{}", self.base_url(connectors), "v1/customers")) } fn get_request_body( &self, - req: &types::ConnectorCustomerRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &ConnectorCustomerRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let connector_req = stripe::CustomerRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - req: &types::ConnectorCustomerRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &ConnectorCustomerRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::ConnectorCustomerType::get_url( - self, req, connectors, - )?) + RequestBuilder::new() + .method(Method::Post) + .url(&ConnectorCustomerType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::ConnectorCustomerType::get_headers( - self, req, connectors, - )?) - .set_body(types::ConnectorCustomerType::get_request_body( + .headers(ConnectorCustomerType::get_headers(self, req, connectors)?) + .set_body(ConnectorCustomerType::get_request_body( self, req, connectors, )?) .build(), @@ -274,53 +304,53 @@ impl fn handle_response( &self, - data: &types::ConnectorCustomerRouterData, + data: &ConnectorCustomerRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::ConnectorCustomerRouterData, errors::ConnectorError> + res: Response, + ) -> CustomResult<ConnectorCustomerRouterData, ConnectorError> where - types::PaymentsResponseData: Clone, + PaymentsResponseData: Clone, { let response: stripe::StripeCustomerResponse = res .response .parse_struct("StripeCustomerResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) - .change_context(errors::ConnectorError::ResponseHandlingFailed) + .change_context(ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(types::ErrorResponse { + Ok(ErrorResponse { status_code: res.status_code, code: response .error .code .clone() - .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: response .error .code - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error @@ -342,23 +372,17 @@ impl impl api::PaymentToken for Stripe {} -impl - services::ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Stripe +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Stripe { fn get_headers( &self, - req: &types::TokenizationRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &TokenizationRouterData, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - types::TokenizationType::get_content_type(self) - .to_string() - .into(), + CONTENT_TYPE.to_string(), + TokenizationType::get_content_type(self).to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); @@ -371,88 +395,86 @@ impl fn get_url( &self, - _req: &types::TokenizationRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &TokenizationRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!("{}{}", self.base_url(connectors), "v1/tokens")) } fn get_request_body( &self, - req: &types::TokenizationRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &TokenizationRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let connector_req = stripe::TokenRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - req: &types::TokenizationRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &TokenizationRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::TokenizationType::get_url(self, req, connectors)?) + RequestBuilder::new() + .method(Method::Post) + .url(&TokenizationType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::TokenizationType::get_headers(self, req, connectors)?) - .set_body(types::TokenizationType::get_request_body( - self, req, connectors, - )?) + .headers(TokenizationType::get_headers(self, req, connectors)?) + .set_body(TokenizationType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, - data: &types::TokenizationRouterData, + data: &TokenizationRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::TokenizationRouterData, errors::ConnectorError> + res: Response, + ) -> CustomResult<TokenizationRouterData, ConnectorError> where - types::PaymentsResponseData: Clone, + PaymentsResponseData: Clone, { let response: stripe::StripeTokenResponse = res .response .parse_struct("StripeTokenResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) - .change_context(errors::ConnectorError::ResponseHandlingFailed) + .change_context(ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(types::ErrorResponse { + Ok(ErrorResponse { status_code: res.status_code, code: response .error .code .clone() - .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: response .error .code - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error @@ -474,20 +496,14 @@ impl impl api::MandateSetup for Stripe {} -impl - services::ConnectorIntegration< - api::Capture, - types::PaymentsCaptureData, - types::PaymentsResponseData, - > for Stripe -{ +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Stripe { fn get_headers( &self, - req: &types::PaymentsCaptureRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let mut header = vec![( - headers::CONTENT_TYPE.to_string(), + CONTENT_TYPE.to_string(), Self::common_get_content_type(self).to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; @@ -501,10 +517,9 @@ impl fn get_url( &self, - req: &types::PaymentsCaptureRouterData, - - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { let id = req.request.connector_transaction_id.as_str(); Ok(format!( @@ -517,10 +532,10 @@ impl fn get_request_body( &self, - req: &types::PaymentsCaptureRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let amount = connector_utils::convert_amount( + req: &PaymentsCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let amount = utils::convert_amount( self.amount_converter, req.request.minor_amount_to_capture, req.request.currency, @@ -531,18 +546,16 @@ impl fn build_request( &self, - req: &types::PaymentsCaptureRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PaymentsCaptureType::get_headers( - self, req, connectors, - )?) - .set_body(types::PaymentsCaptureType::get_request_body( + .headers(PaymentsCaptureType::get_headers(self, req, connectors)?) + .set_body(PaymentsCaptureType::get_request_body( self, req, connectors, )?) .build(), @@ -551,20 +564,20 @@ impl fn handle_response( &self, - data: &types::PaymentsCaptureRouterData, + data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> + res: Response, + ) -> CustomResult<PaymentsCaptureRouterData, ConnectorError> where - types::PaymentsCaptureData: Clone, - types::PaymentsResponseData: Clone, + PaymentsCaptureData: Clone, + PaymentsResponseData: Clone, { let response: stripe::PaymentIntentResponse = res .response .parse_struct("PaymentIntentResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; - let response_integrity_object = connector_utils::get_capture_integrity_object( + let response_integrity_object = get_capture_integrity_object( self.amount_converter, response.amount_received, response.currency.clone(), @@ -573,12 +586,12 @@ impl event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - let new_router_data = types::RouterData::try_from(types::ResponseRouterData { + let new_router_data = RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) - .change_context(errors::ConnectorError::ResponseHandlingFailed); + .change_context(ConnectorError::ResponseHandlingFailed); new_router_data.map(|mut router_data| { router_data.request.integrity_object = Some(response_integrity_object); @@ -588,28 +601,28 @@ impl fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(types::ErrorResponse { + Ok(ErrorResponse { status_code: res.status_code, code: response .error .code .clone() - .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: response .error .code - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error @@ -629,20 +642,15 @@ impl } } -impl - services::ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for Stripe -{ +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Stripe { fn get_headers( &self, - req: &types::PaymentsSyncRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - types::PaymentsSyncType::get_content_type(self) - .to_string() - .into(), + CONTENT_TYPE.to_string(), + PaymentsSyncType::get_content_type(self).to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); @@ -666,9 +674,9 @@ impl fn get_url( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { let id = req.request.connector_transaction_id.clone(); match id.get_connector_transaction_id() { @@ -685,33 +693,33 @@ impl x, "?expand[0]=latest_charge" //updated payment_id(if present) reside inside latest_charge field )), - x => x.change_context(errors::ConnectorError::MissingConnectorTransactionID), + x => x.change_context(ConnectorError::MissingConnectorTransactionID), } } fn build_request( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Get) - .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) + RequestBuilder::new() + .method(Method::Get) + .url(&PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) + .headers(PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, - data: &types::PaymentsSyncRouterData, + data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> + res: Response, + ) -> CustomResult<PaymentsSyncRouterData, ConnectorError> where - types::PaymentsResponseData: Clone, + PaymentsResponseData: Clone, { let id = data.request.connector_transaction_id.clone(); match id.get_connector_transaction_id() { @@ -719,12 +727,12 @@ impl let response: stripe::SetupIntentResponse = res .response .parse_struct("SetupIntentSyncResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -734,9 +742,9 @@ impl let response: stripe::PaymentIntentSyncResponse = res .response .parse_struct("PaymentIntentSyncResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; - let response_integrity_object = connector_utils::get_sync_integrity_object( + let response_integrity_object = get_sync_integrity_object( self.amount_converter, response.amount, response.currency.clone(), @@ -745,7 +753,7 @@ impl event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - let new_router_data = types::RouterData::try_from(types::ResponseRouterData { + let new_router_data = RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -755,35 +763,33 @@ impl router_data }) } - Err(err) => { - Err(err).change_context(errors::ConnectorError::MissingConnectorTransactionID) - } + Err(err) => Err(err).change_context(ConnectorError::MissingConnectorTransactionID), } } fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(types::ErrorResponse { + Ok(ErrorResponse { status_code: res.status_code, code: response .error .code .clone() - .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: response .error .code - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error @@ -804,21 +810,15 @@ impl } #[async_trait::async_trait] -impl - services::ConnectorIntegration< - api::Authorize, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, - > for Stripe -{ +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Stripe { fn get_headers( &self, - req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - types::PaymentsAuthorizeType::get_content_type(self) + CONTENT_TYPE.to_string(), + PaymentsAuthorizeType::get_content_type(self) .to_string() .into(), )]; @@ -830,10 +830,10 @@ impl )) = &req.request.split_payments { if stripe_split_payment.charge_type - == api::enums::PaymentChargeType::Stripe(api::enums::StripeChargeType::Direct) + == PaymentChargeType::Stripe(StripeChargeType::Direct) { let mut customer_account_header = vec![( - headers::STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(), + STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(), stripe_split_payment .transfer_account_id .clone() @@ -851,9 +851,9 @@ impl fn get_url( &self, - _req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!( "{}{}", self.base_url(connectors), @@ -863,10 +863,10 @@ impl fn get_request_body( &self, - req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let amount = connector_utils::convert_amount( + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let amount = utils::convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, @@ -878,20 +878,16 @@ impl fn build_request( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsAuthorizeType::get_url( - self, req, connectors, - )?) + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PaymentsAuthorizeType::get_headers( - self, req, connectors, - )?) - .set_body(types::PaymentsAuthorizeType::get_request_body( + .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?) + .set_body(PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), @@ -900,16 +896,16 @@ impl fn handle_response( &self, - data: &types::PaymentsAuthorizeRouterData, + data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + res: Response, + ) -> CustomResult<PaymentsAuthorizeRouterData, ConnectorError> { let response: stripe::PaymentIntentResponse = res .response .parse_struct("PaymentIntentResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; - let response_integrity_object = connector_utils::get_authorise_integrity_object( + let response_integrity_object = get_authorise_integrity_object( self.amount_converter, response.amount, response.currency.clone(), @@ -918,12 +914,12 @@ impl event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - let new_router_data = types::RouterData::try_from(types::ResponseRouterData { + let new_router_data = RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) - .change_context(errors::ConnectorError::ResponseHandlingFailed); + .change_context(ConnectorError::ResponseHandlingFailed); new_router_data.map(|mut router_data| { router_data.request.integrity_object = Some(response_integrity_object); @@ -933,26 +929,26 @@ impl fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(types::ErrorResponse { + Ok(ErrorResponse { status_code: res.status_code, code: response .error .code .clone() - .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: response .error .code - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error @@ -972,22 +968,14 @@ impl } } -impl - services::ConnectorIntegration< - api::UpdateMetadata, - types::PaymentsUpdateMetadataData, - types::PaymentsResponseData, - > for Stripe +impl ConnectorIntegration<UpdateMetadata, PaymentsUpdateMetadataData, PaymentsResponseData> + for Stripe { fn get_headers( &self, - req: &types::RouterData< - api::UpdateMetadata, - types::PaymentsUpdateMetadataData, - types::PaymentsResponseData, - >, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RouterData<UpdateMetadata, PaymentsUpdateMetadataData, PaymentsResponseData>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } @@ -997,9 +985,9 @@ impl fn get_url( &self, - req: &types::PaymentsUpdateMetadataRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + req: &PaymentsUpdateMetadataRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { let payment_id = &req.request.connector_transaction_id; Ok(format!( "{}v1/payment_intents/{}", @@ -1010,28 +998,26 @@ impl fn get_request_body( &self, - req: &types::PaymentsUpdateMetadataRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &PaymentsUpdateMetadataRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let connector_req = stripe::UpdateMetadataRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - req: &types::PaymentsUpdateMetadataRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsUpdateMetadataType::get_url( - self, req, connectors, - )?) + req: &PaymentsUpdateMetadataRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsUpdateMetadataType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PaymentsUpdateMetadataType::get_headers( + .headers(PaymentsUpdateMetadataType::get_headers( self, req, connectors, )?) - .set_body(types::PaymentsUpdateMetadataType::get_request_body( + .set_body(PaymentsUpdateMetadataType::get_request_body( self, req, connectors, )?) .build(); @@ -1040,49 +1026,41 @@ impl fn handle_response( &self, - data: &types::PaymentsUpdateMetadataRouterData, + data: &PaymentsUpdateMetadataRouterData, _event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PaymentsUpdateMetadataRouterData, errors::ConnectorError> { + res: Response, + ) -> CustomResult<PaymentsUpdateMetadataRouterData, ConnectorError> { router_env::logger::debug!("skipped parsing of the response"); // If 200 status code, then metadata was updated successfully. let status = if res.status_code == 200 { - enums::PaymentResourceUpdateStatus::Success + PaymentResourceUpdateStatus::Success } else { - enums::PaymentResourceUpdateStatus::Failure + PaymentResourceUpdateStatus::Failure }; - Ok(types::PaymentsUpdateMetadataRouterData { - response: Ok(types::PaymentsResponseData::PaymentResourceUpdateResponse { status }), + Ok(PaymentsUpdateMetadataRouterData { + response: Ok(PaymentsResponseData::PaymentResourceUpdateResponse { status }), ..data.clone() }) } fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } -impl - services::ConnectorIntegration< - api::Void, - types::PaymentsCancelData, - types::PaymentsResponseData, - > for Stripe -{ +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Stripe { fn get_headers( &self, - req: &types::PaymentsCancelRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsCancelRouterData, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - types::PaymentsVoidType::get_content_type(self) - .to_string() - .into(), + CONTENT_TYPE.to_string(), + PaymentsVoidType::get_content_type(self).to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); @@ -1095,9 +1073,9 @@ impl fn get_url( &self, - req: &types::PaymentsCancelRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + req: &PaymentsCancelRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { let payment_id = &req.request.connector_transaction_id; Ok(format!( "{}v1/payment_intents/{}/cancel", @@ -1108,76 +1086,74 @@ impl fn get_request_body( &self, - req: &types::PaymentsCancelRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &PaymentsCancelRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let connector_req = stripe::CancelRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - req: &types::PaymentsCancelRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) + req: &PaymentsCancelRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsVoidType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) - .set_body(types::PaymentsVoidType::get_request_body( - self, req, connectors, - )?) + .headers(PaymentsVoidType::get_headers(self, req, connectors)?) + .set_body(PaymentsVoidType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) } fn handle_response( &self, - data: &types::PaymentsCancelRouterData, + data: &PaymentsCancelRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { + res: Response, + ) -> CustomResult<PaymentsCancelRouterData, ConnectorError> { let response: stripe::PaymentIntentResponse = res .response .parse_struct("PaymentIntentResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) - .change_context(errors::ConnectorError::ResponseHandlingFailed) + .change_context(ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(types::ErrorResponse { + Ok(ErrorResponse { status_code: res.status_code, code: response .error .code .clone() - .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: response .error .code - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error @@ -1197,29 +1173,15 @@ impl } } -type Verify = dyn services::ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, ->; -impl - services::ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for Stripe -{ +type Verify = dyn ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>; +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Stripe { fn get_headers( &self, - req: &types::RouterData< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - >, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let mut header = vec![( - headers::CONTENT_TYPE.to_string(), + CONTENT_TYPE.to_string(), Verify::get_content_type(self).to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; @@ -1233,13 +1195,9 @@ impl fn get_url( &self, - _req: &types::RouterData< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - >, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!( "{}{}", self.base_url(connectors), @@ -1249,29 +1207,21 @@ impl fn get_request_body( &self, - req: &types::RouterData< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - >, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let connector_req = stripe::SetupIntentRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - req: &types::RouterData< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - >, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) + RequestBuilder::new() + .method(Method::Post) .url(&Verify::get_url(self, req, connectors)?) .attach_default_headers() .headers(Verify::get_headers(self, req, connectors)?) @@ -1282,66 +1232,58 @@ impl fn handle_response( &self, - data: &types::RouterData< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - >, + data: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, + res: Response, ) -> CustomResult< - types::RouterData< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - >, - errors::ConnectorError, + RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + ConnectorError, > where - api::SetupMandate: Clone, - types::SetupMandateRequestData: Clone, - types::PaymentsResponseData: Clone, + SetupMandate: Clone, + SetupMandateRequestData: Clone, + PaymentsResponseData: Clone, { let response: stripe::SetupIntentResponse = res .response .parse_struct("SetupIntentResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) - .change_context(errors::ConnectorError::ResponseHandlingFailed) + .change_context(ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(types::ErrorResponse { + Ok(ErrorResponse { status_code: res.status_code, code: response .error .code .clone() - .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: response .error .code - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error @@ -1365,19 +1307,15 @@ impl api::Refund for Stripe {} impl api::RefundExecute for Stripe {} impl api::RefundSync for Stripe {} -impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> - for Stripe -{ +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Stripe { fn get_headers( &self, - req: &types::RefundsRouterData<api::Execute>, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RefundsRouterData<Execute>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - types::RefundExecuteType::get_content_type(self) - .to_string() - .into(), + CONTENT_TYPE.to_string(), + RefundExecuteType::get_content_type(self).to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); @@ -1386,10 +1324,10 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref req.request.split_refunds.as_ref() { match &stripe_split_refund.charge_type { - api::enums::PaymentChargeType::Stripe(stripe_charge) => { - if stripe_charge == &api::enums::StripeChargeType::Direct { + PaymentChargeType::Stripe(stripe_charge) => { + if stripe_charge == &StripeChargeType::Direct { let mut customer_account_header = vec![( - headers::STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(), + STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(), stripe_split_refund .transfer_account_id .clone() @@ -1409,18 +1347,18 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref fn get_url( &self, - _req: &types::RefundsRouterData<api::Execute>, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!("{}{}", self.base_url(connectors), "v1/refunds")) } fn get_request_body( &self, - req: &types::RefundsRouterData<api::Execute>, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let refund_amount = connector_utils::convert_amount( + req: &RefundsRouterData<Execute>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let refund_amount = utils::convert_amount( self.amount_converter, req.request.minor_refund_amount, req.request.currency, @@ -1439,19 +1377,15 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref fn build_request( &self, - req: &types::RefundsRouterData<api::Execute>, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::RefundExecuteType::get_url(self, req, connectors)?) + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::RefundExecuteType::get_headers( - self, req, connectors, - )?) - .set_body(types::RefundExecuteType::get_request_body( - self, req, connectors, - )?) + .headers(RefundExecuteType::get_headers(self, req, connectors)?) + .set_body(RefundExecuteType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) } @@ -1459,16 +1393,16 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref #[instrument(skip_all)] fn handle_response( &self, - data: &types::RefundsRouterData<api::Execute>, + data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { + res: Response, + ) -> CustomResult<RefundsRouterData<Execute>, ConnectorError> { let response: stripe::RefundResponse = res.response .parse_struct("Stripe RefundResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; - let response_integrity_object = connector_utils::get_refund_integrity_object( + let response_integrity_object = get_refund_integrity_object( self.amount_converter, response.amount, response.currency.clone(), @@ -1477,7 +1411,7 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - let new_router_data = types::RouterData::try_from(types::ResponseRouterData { + let new_router_data = RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -1488,33 +1422,33 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref router_data.request.integrity_object = Some(response_integrity_object); router_data }) - .change_context(errors::ConnectorError::ResponseHandlingFailed) + .change_context(ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(types::ErrorResponse { + Ok(ErrorResponse { status_code: res.status_code, code: response .error .code .clone() - .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: response .error .code - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error @@ -1534,19 +1468,15 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref } } -impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> - for Stripe -{ +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Stripe { fn get_headers( &self, - req: &types::RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RouterData<RSync, RefundsData, RefundsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - types::RefundSyncType::get_content_type(self) - .to_string() - .into(), + CONTENT_TYPE.to_string(), + RefundSyncType::get_content_type(self).to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); @@ -1569,24 +1499,24 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun fn get_url( &self, - req: &types::RefundsRouterData<api::RSync>, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + req: &RefundsRouterData<RSync>, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { let id = req.request.get_connector_refund_id()?; Ok(format!("{}v1/refunds/{}", self.base_url(connectors), id)) } fn build_request( &self, - req: &types::RefundsRouterData<api::RSync>, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &RefundsRouterData<RSync>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::RefundSyncType::get_url(self, req, connectors)?) + RequestBuilder::new() + .method(Method::Post) + .url(&RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::RefundSyncType::get_headers(self, req, connectors)?) + .headers(RefundSyncType::get_headers(self, req, connectors)?) .build(), )) } @@ -1594,19 +1524,16 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun #[instrument(skip_all)] fn handle_response( &self, - data: &types::RefundsRouterData<api::RSync>, + data: &RefundsRouterData<RSync>, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult< - types::RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>, - errors::ConnectorError, - > { + res: Response, + ) -> CustomResult<RouterData<RSync, RefundsData, RefundsResponseData>, ConnectorError> { let response: stripe::RefundResponse = res.response .parse_struct("Stripe RefundResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; - let response_integrity_object = connector_utils::get_refund_integrity_object( + let response_integrity_object = get_refund_integrity_object( self.amount_converter, response.amount, response.currency.clone(), @@ -1615,7 +1542,7 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - let new_router_data = types::RouterData::try_from(types::ResponseRouterData { + let new_router_data = RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -1626,33 +1553,33 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun router_data.request.integrity_object = Some(response_integrity_object); router_data }) - .change_context(errors::ConnectorError::ResponseHandlingFailed) + .change_context(ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(types::ErrorResponse { + Ok(ErrorResponse { status_code: res.status_code, code: response .error .code .clone() - .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: response .error .code - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error @@ -1672,27 +1599,27 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun } } -impl api::UploadFile for Stripe {} +impl UploadFile for Stripe {} #[async_trait::async_trait] -impl api::FileUpload for Stripe { +impl FileUpload for Stripe { fn validate_file_upload( &self, - purpose: api::FilePurpose, + purpose: FilePurpose, file_size: i32, file_type: mime::Mime, - ) -> CustomResult<(), errors::ConnectorError> { + ) -> CustomResult<(), ConnectorError> { match purpose { - api::FilePurpose::DisputeEvidence => { + FilePurpose::DisputeEvidence => { let supported_file_types = ["image/jpeg", "image/png", "application/pdf"]; // 5 Megabytes (MB) if file_size > 5000000 { - Err(errors::ConnectorError::FileValidationFailed { + Err(ConnectorError::FileValidationFailed { reason: "file_size exceeded the max file size of 5MB".to_owned(), })? } if !supported_file_types.contains(&file_type.to_string().as_str()) { - Err(errors::ConnectorError::FileValidationFailed { + Err(ConnectorError::FileValidationFailed { reason: "file_type does not match JPEG, JPG, PNG, or PDF format".to_owned(), })? } @@ -1702,22 +1629,12 @@ impl api::FileUpload for Stripe { } } -impl - services::ConnectorIntegration< - api::Upload, - types::UploadFileRequestData, - types::UploadFileResponse, - > for Stripe -{ +impl ConnectorIntegration<Upload, UploadFileRequestData, UploadFileResponse> for Stripe { fn get_headers( &self, - req: &types::RouterData< - api::Upload, - types::UploadFileRequestData, - types::UploadFileResponse, - >, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RouterData<Upload, UploadFileRequestData, UploadFileResponse>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.get_auth_header(&req.connector_auth_type) } @@ -1727,9 +1644,9 @@ impl fn get_url( &self, - _req: &types::UploadFileRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &UploadFileRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!( "{}{}", connectors.stripe.base_url_file_upload, "v1/files" @@ -1738,27 +1655,25 @@ impl fn get_request_body( &self, - req: &types::UploadFileRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &UploadFileRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let connector_req = transformers::construct_file_upload_request(req.clone())?; Ok(RequestContent::FormData(connector_req)) } fn build_request( &self, - req: &types::UploadFileRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &UploadFileRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::UploadFileType::get_url(self, req, connectors)?) + RequestBuilder::new() + .method(Method::Post) + .url(&UploadFileType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::UploadFileType::get_headers(self, req, connectors)?) - .set_body(types::UploadFileType::get_request_body( - self, req, connectors, - )?) + .headers(UploadFileType::get_headers(self, req, connectors)?) + .set_body(UploadFileType::get_request_body(self, req, connectors)?) .build(), )) } @@ -1766,21 +1681,19 @@ impl #[instrument(skip_all)] fn handle_response( &self, - data: &types::UploadFileRouterData, + data: &UploadFileRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult< - types::RouterData<api::Upload, types::UploadFileRequestData, types::UploadFileResponse>, - errors::ConnectorError, - > { + res: Response, + ) -> CustomResult<RouterData<Upload, UploadFileRequestData, UploadFileResponse>, ConnectorError> + { let response: stripe::FileUploadResponse = res .response .parse_struct("Stripe FileUploadResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(types::UploadFileRouterData { - response: Ok(types::UploadFileResponse { + Ok(UploadFileRouterData { + response: Ok(UploadFileResponse { provider_file_id: response.file_id, }), ..data.clone() @@ -1789,28 +1702,28 @@ impl fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(types::ErrorResponse { + Ok(ErrorResponse { status_code: res.status_code, code: response .error .code .clone() - .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: response .error .code - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error @@ -1830,32 +1743,22 @@ impl } } -impl api::RetrieveFile for Stripe {} +impl RetrieveFile for Stripe {} -impl - services::ConnectorIntegration< - api::Retrieve, - types::RetrieveFileRequestData, - types::RetrieveFileResponse, - > for Stripe -{ +impl ConnectorIntegration<Retrieve, RetrieveFileRequestData, RetrieveFileResponse> for Stripe { fn get_headers( &self, - req: &types::RouterData< - api::Retrieve, - types::RetrieveFileRequestData, - types::RetrieveFileResponse, - >, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RouterData<Retrieve, RetrieveFileRequestData, RetrieveFileResponse>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.get_auth_header(&req.connector_auth_type) } fn get_url( &self, - req: &types::RetrieveFileRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + req: &RetrieveFileRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!( "{}v1/files/{}/contents", connectors.stripe.base_url_file_upload, req.request.provider_file_id @@ -1864,15 +1767,15 @@ impl fn build_request( &self, - req: &types::RetrieveFileRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &RetrieveFileRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Get) - .url(&types::RetrieveFileType::get_url(self, req, connectors)?) + RequestBuilder::new() + .method(Method::Get) + .url(&RetrieveFileType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::RetrieveFileType::get_headers(self, req, connectors)?) + .headers(RetrieveFileType::get_headers(self, req, connectors)?) .build(), )) } @@ -1880,24 +1783,17 @@ impl #[instrument(skip_all)] fn handle_response( &self, - data: &types::RetrieveFileRouterData, + data: &RetrieveFileRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult< - types::RouterData< - api::Retrieve, - types::RetrieveFileRequestData, - types::RetrieveFileResponse, - >, - errors::ConnectorError, - > { + res: Response, + ) -> CustomResult<RetrieveFileRouterData, ConnectorError> { let response = res.response; event_builder.map(|event| event.set_response_body(&serde_json::json!({"connector_response_type": "file", "status_code": res.status_code}))); router_env::logger::info!(connector_response_type=?"file"); - Ok(types::RetrieveFileRouterData { - response: Ok(types::RetrieveFileResponse { + Ok(RetrieveFileRouterData { + response: Ok(RetrieveFileResponse { file_data: response.to_vec(), }), ..data.clone() @@ -1906,28 +1802,28 @@ impl fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(types::ErrorResponse { + Ok(ErrorResponse { status_code: res.status_code, code: response .error .code .clone() - .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: response .error .code - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error @@ -1947,23 +1843,17 @@ impl } } -impl api::SubmitEvidence for Stripe {} +impl SubmitEvidence for Stripe {} -impl - services::ConnectorIntegration< - api::Evidence, - types::SubmitEvidenceRequestData, - types::SubmitEvidenceResponse, - > for Stripe -{ +impl ConnectorIntegration<Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse> for Stripe { fn get_headers( &self, - req: &types::SubmitEvidenceRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &SubmitEvidenceRouterData, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - types::SubmitEvidenceType::get_content_type(self) + CONTENT_TYPE.to_string(), + SubmitEvidenceType::get_content_type(self) .to_string() .into(), )]; @@ -1978,9 +1868,9 @@ impl fn get_url( &self, - req: &types::SubmitEvidenceRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + req: &SubmitEvidenceRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!( "{}{}{}", self.base_url(connectors), @@ -1991,28 +1881,24 @@ impl fn get_request_body( &self, - req: &types::SubmitEvidenceRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &SubmitEvidenceRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let connector_req = stripe::Evidence::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - req: &types::SubmitEvidenceRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::SubmitEvidenceType::get_url(self, req, connectors)?) + req: &SubmitEvidenceRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&SubmitEvidenceType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::SubmitEvidenceType::get_headers( - self, req, connectors, - )?) - .set_body(types::SubmitEvidenceType::get_request_body( - self, req, connectors, - )?) + .headers(SubmitEvidenceType::get_headers(self, req, connectors)?) + .set_body(SubmitEvidenceType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) } @@ -2020,18 +1906,18 @@ impl #[instrument(skip_all)] fn handle_response( &self, - data: &types::SubmitEvidenceRouterData, + data: &SubmitEvidenceRouterData, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::SubmitEvidenceRouterData, errors::ConnectorError> { + res: Response, + ) -> CustomResult<SubmitEvidenceRouterData, ConnectorError> { let response: stripe::DisputeObj = res .response .parse_struct("Stripe DisputeObj") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(types::SubmitEvidenceRouterData { - response: Ok(types::SubmitEvidenceResponse { + Ok(SubmitEvidenceRouterData { + response: Ok(SubmitEvidenceResponse { dispute_status: api_models::enums::DisputeStatus::DisputeChallenged, connector_status: Some(response.status), }), @@ -2041,28 +1927,28 @@ impl fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); - Ok(types::ErrorResponse { + Ok(ErrorResponse { status_code: res.status_code, code: response .error .code .clone() - .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + .unwrap_or_else(|| NO_ERROR_CODE.to_string()), message: response .error .code - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error @@ -2084,16 +1970,16 @@ impl fn get_signature_elements_from_header( headers: &actix_web::http::header::HeaderMap, -) -> CustomResult<HashMap<String, Vec<u8>>, errors::ConnectorError> { +) -> CustomResult<HashMap<String, Vec<u8>>, ConnectorError> { let security_header = headers .get("Stripe-Signature") .map(|header_value| { header_value .to_str() .map(String::from) - .map_err(|_| errors::ConnectorError::WebhookSignatureNotFound) + .map_err(|_| ConnectorError::WebhookSignatureNotFound) }) - .ok_or(errors::ConnectorError::WebhookSignatureNotFound)??; + .ok_or(ConnectorError::WebhookSignatureNotFound)??; let props = security_header.split(',').collect::<Vec<&str>>(); let mut security_header_kvs: HashMap<String, Vec<u8>> = HashMap::with_capacity(props.len()); @@ -2101,7 +1987,7 @@ fn get_signature_elements_from_header( for prop_str in &props { let (prop_key, prop_value) = prop_str .split_once('=') - .ok_or(errors::ConnectorError::WebhookSourceVerificationFailed)?; + .ok_or(ConnectorError::WebhookSourceVerificationFailed)?; security_header_kvs.insert(prop_key.to_string(), prop_value.bytes().collect()); } @@ -2110,39 +1996,39 @@ fn get_signature_elements_from_header( } #[async_trait::async_trait] -impl api::IncomingWebhook for Stripe { +impl IncomingWebhook for Stripe { fn get_webhook_source_verification_algorithm( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, ConnectorError> { Ok(Box::new(crypto::HmacSha256)) } fn get_webhook_source_verification_signature( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, - ) -> CustomResult<Vec<u8>, errors::ConnectorError> { + ) -> CustomResult<Vec<u8>, ConnectorError> { let mut security_header_kvs = get_signature_elements_from_header(request.headers)?; let signature = security_header_kvs .remove("v1") - .ok_or(errors::ConnectorError::WebhookSignatureNotFound)?; + .ok_or(ConnectorError::WebhookSignatureNotFound)?; - hex::decode(signature).change_context(errors::ConnectorError::WebhookSignatureNotFound) + hex::decode(signature).change_context(ConnectorError::WebhookSignatureNotFound) } fn get_webhook_source_verification_message( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, - ) -> CustomResult<Vec<u8>, errors::ConnectorError> { + ) -> CustomResult<Vec<u8>, ConnectorError> { let mut security_header_kvs = get_signature_elements_from_header(request.headers)?; let timestamp = security_header_kvs .remove("t") - .ok_or(errors::ConnectorError::WebhookSignatureNotFound)?; + .ok_or(ConnectorError::WebhookSignatureNotFound)?; Ok(format!( "{}.{}", @@ -2154,12 +2040,12 @@ impl api::IncomingWebhook for Stripe { fn get_webhook_object_reference_id( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::ObjectReferenceId, ConnectorError> { let details: stripe::WebhookEvent = request .body .parse_struct("WebhookEvent") - .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; + .change_context(ConnectorError::WebhookReferenceIdNotFound)?; Ok(match details.event_data.event_object.object { stripe::WebhookEventObjectType::PaymentIntent => { @@ -2199,7 +2085,7 @@ impl api::IncomingWebhook for Stripe { .event_data .event_object .payment_intent - .ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?, + .ok_or(ConnectorError::WebhookReferenceIdNotFound)?, ), ), } @@ -2211,7 +2097,7 @@ impl api::IncomingWebhook for Stripe { .event_data .event_object .payment_intent - .ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?, + .ok_or(ConnectorError::WebhookReferenceIdNotFound)?, ), ) } @@ -2265,25 +2151,25 @@ impl api::IncomingWebhook for Stripe { fn get_webhook_event_type( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<IncomingWebhookEvent, ConnectorError> { let details: stripe::WebhookEventTypeBody = request .body .parse_struct("WebhookEventTypeBody") - .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; + .change_context(ConnectorError::WebhookReferenceIdNotFound)?; Ok(match details.event_type { stripe::WebhookEventType::PaymentIntentFailed => { - api::IncomingWebhookEvent::PaymentIntentFailure + IncomingWebhookEvent::PaymentIntentFailure } stripe::WebhookEventType::PaymentIntentSucceed => { - api::IncomingWebhookEvent::PaymentIntentSuccess + IncomingWebhookEvent::PaymentIntentSuccess } stripe::WebhookEventType::PaymentIntentCanceled => { - api::IncomingWebhookEvent::PaymentIntentCancelled + IncomingWebhookEvent::PaymentIntentCancelled } stripe::WebhookEventType::PaymentIntentAmountCapturableUpdated => { - api::IncomingWebhookEvent::PaymentIntentAuthorizationSuccess + IncomingWebhookEvent::PaymentIntentAuthorizationSuccess } stripe::WebhookEventType::ChargeSucceeded => { if let Some(stripe::WebhookPaymentMethodDetails { @@ -2292,9 +2178,9 @@ impl api::IncomingWebhook for Stripe { | stripe::WebhookPaymentMethodType::MultibancoBankTransfers, }) = details.event_data.event_object.payment_method_details { - api::IncomingWebhookEvent::PaymentIntentSuccess + IncomingWebhookEvent::PaymentIntentSuccess } else { - api::IncomingWebhookEvent::EventNotSupported + IncomingWebhookEvent::EventNotSupported } } stripe::WebhookEventType::ChargeRefundUpdated => details @@ -2302,35 +2188,31 @@ impl api::IncomingWebhook for Stripe { .event_object .status .map(|status| match status { - stripe::WebhookEventStatus::Succeeded => { - api::IncomingWebhookEvent::RefundSuccess - } - stripe::WebhookEventStatus::Failed => api::IncomingWebhookEvent::RefundFailure, - _ => api::IncomingWebhookEvent::EventNotSupported, + stripe::WebhookEventStatus::Succeeded => IncomingWebhookEvent::RefundSuccess, + stripe::WebhookEventStatus::Failed => IncomingWebhookEvent::RefundFailure, + _ => IncomingWebhookEvent::EventNotSupported, }) - .unwrap_or(api::IncomingWebhookEvent::EventNotSupported), - stripe::WebhookEventType::SourceChargeable => { - api::IncomingWebhookEvent::SourceChargeable - } - stripe::WebhookEventType::DisputeCreated => api::IncomingWebhookEvent::DisputeOpened, - stripe::WebhookEventType::DisputeClosed => api::IncomingWebhookEvent::DisputeCancelled, + .unwrap_or(IncomingWebhookEvent::EventNotSupported), + stripe::WebhookEventType::SourceChargeable => IncomingWebhookEvent::SourceChargeable, + stripe::WebhookEventType::DisputeCreated => IncomingWebhookEvent::DisputeOpened, + stripe::WebhookEventType::DisputeClosed => IncomingWebhookEvent::DisputeCancelled, stripe::WebhookEventType::DisputeUpdated => details .event_data .event_object .status .map(Into::into) - .unwrap_or(api::IncomingWebhookEvent::EventNotSupported), + .unwrap_or(IncomingWebhookEvent::EventNotSupported), stripe::WebhookEventType::PaymentIntentPartiallyFunded => { - api::IncomingWebhookEvent::PaymentIntentPartiallyFunded + IncomingWebhookEvent::PaymentIntentPartiallyFunded } stripe::WebhookEventType::PaymentIntentRequiresAction => { - api::IncomingWebhookEvent::PaymentActionRequired + IncomingWebhookEvent::PaymentActionRequired } stripe::WebhookEventType::ChargeDisputeFundsWithdrawn => { - api::IncomingWebhookEvent::DisputeLost + IncomingWebhookEvent::DisputeLost } stripe::WebhookEventType::ChargeDisputeFundsReinstated => { - api::IncomingWebhookEvent::DisputeWon + IncomingWebhookEvent::DisputeWon } stripe::WebhookEventType::Unknown | stripe::WebhookEventType::ChargeCaptured @@ -2342,37 +2224,37 @@ impl api::IncomingWebhook for Stripe { | stripe::WebhookEventType::PaymentIntentCreated | stripe::WebhookEventType::PaymentIntentProcessing | stripe::WebhookEventType::SourceTransactionCreated => { - api::IncomingWebhookEvent::EventNotSupported + IncomingWebhookEvent::EventNotSupported } }) } fn get_webhook_resource_object( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> { let details: stripe::WebhookEvent = request .body .parse_struct("WebhookEvent") - .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + .change_context(ConnectorError::WebhookBodyDecodingFailed)?; Ok(Box::new(details.event_data.event_object)) } fn get_dispute_details( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::disputes::DisputePayload, errors::ConnectorError> { + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<DisputePayload, ConnectorError> { let details: stripe::WebhookEvent = request .body .parse_struct("WebhookEvent") - .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; - Ok(api::disputes::DisputePayload { + .change_context(ConnectorError::WebhookBodyDecodingFailed)?; + Ok(DisputePayload { amount: details .event_data .event_object .amount .get_required_value("amount") - .change_context(errors::ConnectorError::MissingRequiredField { + .change_context(ConnectorError::MissingRequiredField { field_name: "amount", })? .to_string(), @@ -2390,7 +2272,7 @@ impl api::IncomingWebhook for Stripe { .event_data .event_object .status - .ok_or(errors::ConnectorError::WebhookResourceObjectNotFound)? + .ok_or(ConnectorError::WebhookResourceObjectNotFound)? .to_string(), created_at: Some(details.event_data.event_object.created), updated_at: None, @@ -2398,18 +2280,18 @@ impl api::IncomingWebhook for Stripe { } } -impl services::ConnectorRedirectResponse for Stripe { +impl ConnectorRedirectResponse for Stripe { fn get_flow_type( &self, _query_params: &str, _json_payload: Option<serde_json::Value>, - action: services::PaymentAction, - ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> { + action: PaymentAction, + ) -> CustomResult<CallConnectorAction, ConnectorError> { match action { - services::PaymentAction::PSync - | services::PaymentAction::CompleteAuthorize - | services::PaymentAction::PaymentAuthenticateCompleteAuthorize => { - Ok(payments::CallConnectorAction::Trigger) + PaymentAction::PSync + | PaymentAction::CompleteAuthorize + | PaymentAction::PaymentAuthenticateCompleteAuthorize => { + Ok(CallConnectorAction::Trigger) } } } @@ -2428,18 +2310,16 @@ impl api::PayoutRecipient for Stripe {} impl api::PayoutRecipientAccount for Stripe {} #[cfg(feature = "payouts")] -impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::PayoutsResponseData> - for Stripe -{ +impl ConnectorIntegration<PoCancel, PayoutsData, PayoutsResponseData> for Stripe { fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, - req: &types::PayoutsRouterData<api::PoCancel>, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + req: &PayoutsRouterData<PoCancel>, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { let transfer_id = req.request.get_transfer_id()?; Ok(format!( "{}v1/transfers/{}/reversals", @@ -2449,34 +2329,32 @@ impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::Pa fn get_headers( &self, - req: &types::PayoutsRouterData<api::PoCancel>, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PayoutsRouterData<PoCancel>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, _connectors) } fn get_request_body( &self, - req: &types::RouterData<api::PoCancel, types::PayoutsData, types::PayoutsResponseData>, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &RouterData<PoCancel, PayoutsData, PayoutsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let connector_req = stripe::StripeConnectReversalRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - req: &types::PayoutsRouterData<api::PoCancel>, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PayoutCancelType::get_url(self, req, connectors)?) + req: &PayoutsRouterData<PoCancel>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&PayoutCancelType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PayoutCancelType::get_headers(self, req, connectors)?) - .set_body(types::PayoutCancelType::get_request_body( - self, req, connectors, - )?) + .headers(PayoutCancelType::get_headers(self, req, connectors)?) + .set_body(PayoutCancelType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) @@ -2484,16 +2362,16 @@ impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::Pa fn handle_response( &self, - data: &types::PayoutsRouterData<api::PoCancel>, + data: &PayoutsRouterData<PoCancel>, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PayoutsRouterData<api::PoCancel>, errors::ConnectorError> { + res: Response, + ) -> CustomResult<PayoutsRouterData<PoCancel>, ConnectorError> { let response: stripe::StripeConnectReversalResponse = res .response .parse_struct("StripeConnectReversalResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -2502,59 +2380,55 @@ impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::Pa fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "payouts")] -impl services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::PayoutsResponseData> - for Stripe -{ +impl ConnectorIntegration<PoCreate, PayoutsData, PayoutsResponseData> for Stripe { fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, - _req: &types::PayoutsRouterData<api::PoCreate>, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &PayoutsRouterData<PoCreate>, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!("{}v1/transfers", connectors.stripe.base_url)) } fn get_headers( &self, - req: &types::PayoutsRouterData<api::PoCreate>, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PayoutsRouterData<PoCreate>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_request_body( &self, - req: &types::PayoutsRouterData<api::PoCreate>, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &PayoutsRouterData<PoCreate>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let connector_req = stripe::StripeConnectPayoutCreateRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - req: &types::PayoutsRouterData<api::PoCreate>, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PayoutCreateType::get_url(self, req, connectors)?) + req: &PayoutsRouterData<PoCreate>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&PayoutCreateType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PayoutCreateType::get_headers(self, req, connectors)?) - .set_body(types::PayoutCreateType::get_request_body( - self, req, connectors, - )?) + .headers(PayoutCreateType::get_headers(self, req, connectors)?) + .set_body(PayoutCreateType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) @@ -2562,16 +2436,16 @@ impl services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::Pa fn handle_response( &self, - data: &types::PayoutsRouterData<api::PoCreate>, + data: &PayoutsRouterData<PoCreate>, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PayoutsRouterData<api::PoCreate>, errors::ConnectorError> { + res: Response, + ) -> CustomResult<PayoutsRouterData<PoCreate>, ConnectorError> { let response: stripe::StripeConnectPayoutCreateResponse = res .response .parse_struct("StripeConnectPayoutCreateResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -2580,38 +2454,36 @@ impl services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::Pa fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "payouts")] -impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResponseData> - for Stripe -{ +impl ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for Stripe { fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, - _req: &types::PayoutsRouterData<api::PoFulfill>, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &PayoutsRouterData<PoFulfill>, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!("{}v1/payouts", connectors.stripe.base_url,)) } fn get_headers( &self, - req: &types::PayoutsRouterData<api::PoFulfill>, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PayoutsRouterData<PoFulfill>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let mut headers = self.build_headers(req, connectors)?; let customer_account = req.get_connector_customer_id()?; let mut customer_account_header = vec![( - headers::STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(), + STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(), customer_account.into_masked(), )]; headers.append(&mut customer_account_header); @@ -2620,28 +2492,24 @@ impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::P fn get_request_body( &self, - req: &types::PayoutsRouterData<api::PoFulfill>, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &PayoutsRouterData<PoFulfill>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let connector_req = stripe::StripeConnectPayoutFulfillRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - req: &types::PayoutsRouterData<api::PoFulfill>, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PayoutFulfillType::get_url(self, req, connectors)?) + req: &PayoutsRouterData<PoFulfill>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&PayoutFulfillType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PayoutFulfillType::get_headers( - self, req, connectors, - )?) - .set_body(types::PayoutFulfillType::get_request_body( - self, req, connectors, - )?) + .headers(PayoutFulfillType::get_headers(self, req, connectors)?) + .set_body(PayoutFulfillType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) @@ -2649,16 +2517,16 @@ impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::P fn handle_response( &self, - data: &types::PayoutsRouterData<api::PoFulfill>, + data: &PayoutsRouterData<PoFulfill>, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PayoutsRouterData<api::PoFulfill>, errors::ConnectorError> { + res: Response, + ) -> CustomResult<PayoutsRouterData<PoFulfill>, ConnectorError> { let response: stripe::StripeConnectPayoutFulfillResponse = res .response .parse_struct("StripeConnectPayoutFulfillResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -2667,60 +2535,55 @@ impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::P fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "payouts")] -impl - services::ConnectorIntegration<api::PoRecipient, types::PayoutsData, types::PayoutsResponseData> - for Stripe -{ +impl ConnectorIntegration<PoRecipient, PayoutsData, PayoutsResponseData> for Stripe { fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, - _req: &types::PayoutsRouterData<api::PoRecipient>, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &PayoutsRouterData<PoRecipient>, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!("{}v1/accounts", connectors.stripe.base_url)) } fn get_headers( &self, - req: &types::PayoutsRouterData<api::PoRecipient>, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PayoutsRouterData<PoRecipient>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_request_body( &self, - req: &types::PayoutsRouterData<api::PoRecipient>, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &PayoutsRouterData<PoRecipient>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let connector_req = stripe::StripeConnectRecipientCreateRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - req: &types::PayoutsRouterData<api::PoRecipient>, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PayoutRecipientType::get_url(self, req, connectors)?) + req: &PayoutsRouterData<PoRecipient>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&PayoutRecipientType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PayoutRecipientType::get_headers( - self, req, connectors, - )?) - .set_body(types::PayoutRecipientType::get_request_body( + .headers(PayoutRecipientType::get_headers(self, req, connectors)?) + .set_body(PayoutRecipientType::get_request_body( self, req, connectors, )?) .build(); @@ -2730,16 +2593,16 @@ impl fn handle_response( &self, - data: &types::PayoutsRouterData<api::PoRecipient>, + data: &PayoutsRouterData<PoRecipient>, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PayoutsRouterData<api::PoRecipient>, errors::ConnectorError> { + res: Response, + ) -> CustomResult<PayoutsRouterData<PoRecipient>, ConnectorError> { let response: stripe::StripeConnectRecipientCreateResponse = res .response .parse_struct("StripeConnectRecipientCreateResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -2748,30 +2611,24 @@ impl fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "payouts")] -impl - services::ConnectorIntegration< - api::PoRecipientAccount, - types::PayoutsData, - types::PayoutsResponseData, - > for Stripe -{ +impl ConnectorIntegration<PoRecipientAccount, PayoutsData, PayoutsResponseData> for Stripe { fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, - req: &types::PayoutsRouterData<api::PoRecipientAccount>, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + req: &PayoutsRouterData<PoRecipientAccount>, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { let connector_customer_id = req.get_connector_customer_id()?; Ok(format!( "{}v1/accounts/{}/external_accounts", @@ -2781,36 +2638,34 @@ impl fn get_headers( &self, - req: &types::PayoutsRouterData<api::PoRecipientAccount>, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PayoutsRouterData<PoRecipientAccount>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_request_body( &self, - req: &types::PayoutsRouterData<api::PoRecipientAccount>, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &PayoutsRouterData<PoRecipientAccount>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let connector_req = stripe::StripeConnectRecipientAccountCreateRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, - req: &types::PayoutsRouterData<api::PoRecipientAccount>, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PayoutRecipientAccountType::get_url( - self, req, connectors, - )?) + req: &PayoutsRouterData<PoRecipientAccount>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&PayoutRecipientAccountType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PayoutRecipientAccountType::get_headers( + .headers(PayoutRecipientAccountType::get_headers( self, req, connectors, )?) - .set_body(types::PayoutRecipientAccountType::get_request_body( + .set_body(PayoutRecipientAccountType::get_request_body( self, req, connectors, )?) .build(); @@ -2820,17 +2675,16 @@ impl fn handle_response( &self, - data: &types::PayoutsRouterData<api::PoRecipientAccount>, + data: &PayoutsRouterData<PoRecipientAccount>, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PayoutsRouterData<api::PoRecipientAccount>, errors::ConnectorError> - { + res: Response, + ) -> CustomResult<PayoutsRouterData<PoRecipientAccount>, ConnectorError> { let response: stripe::StripeConnectRecipientAccountCreateResponse = res .response .parse_struct("StripeConnectRecipientAccountCreateResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -2839,9 +2693,9 @@ impl fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs similarity index 74% rename from crates/router/src/connector/stripe/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs index ad2e1d7e855..da6ec769363 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs @@ -1,38 +1,66 @@ use std::{collections::HashMap, ops::Deref}; use api_models::{self, enums as api_enums, payments}; +use common_enums::{enums, AttemptStatus, PaymentChargeType, StripeChargeType}; use common_utils::{ + collect_missing_value_keys, errors::CustomResult, - ext_traits::{ByteSliceExt, Encode}, + ext_traits::{ByteSliceExt, Encode, OptionExt as _}, pii::{self, Email}, - request::RequestContent, + request::{Method, RequestContent}, types::MinorUnit, }; use error_stack::ResultExt; -use hyperswitch_domain_models::mandates::AcceptanceType; -use masking::{ExposeInterface, ExposeOptionInterface, Mask, PeekInterface, Secret}; +use hyperswitch_domain_models::{ + mandates::AcceptanceType, + payment_method_data::{ + self, BankRedirectData, Card, CardRedirectData, GiftCardData, GooglePayWalletData, + PayLaterData, PaymentMethodData, VoucherData, WalletData, + }, + router_data::{ + AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData, + PaymentMethodToken, RouterData, + }, + router_flow_types::{Execute, RSync}, + router_request_types::{ + BrowserInformation, ChargeRefundsOptions, DestinationChargeRefund, DirectChargeRefund, + ResponseId, SplitRefundsRequest, + }, + router_response_types::{ + MandateReference, PaymentsResponseData, PreprocessingResponseId, RedirectForm, + RefundsResponseData, + }, + types::{ + ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData, + PaymentsUpdateMetadataRouterData, RefundsRouterData, SetupMandateRouterData, + TokenizationRouterData, + }, +}; +use hyperswitch_interfaces::{consts, errors::ConnectorError}; +use masking::{ExposeInterface, ExposeOptionInterface, Mask, Maskable, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use serde_json::Value; use time::PrimitiveDateTime; use url::Url; + +use crate::{ + constants::headers::STRIPE_COMPATIBLE_CONNECT_ACCOUNT, + utils::{convert_uppercase, ApplePay, ApplePayDecrypt, RouterData as OtherRouterData}, +}; #[cfg(feature = "payouts")] pub mod connect; #[cfg(feature = "payouts")] pub use self::connect::*; use crate::{ - collect_missing_value_keys, - connector::utils::{self as connector_util, ApplePay, ApplePayDecrypt, RouterData}, - consts, - core::errors, - headers, services, types::{ - self, api, domain, - storage::enums, - transformers::{ForeignFrom, ForeignTryFrom}, + RefundsResponseRouterData, ResponseRouterData, SubmitEvidenceRouterData, + UploadFileRouterData, + }, + utils::{ + get_unimplemented_payment_method_error_message, is_payment_failure, is_refund_failure, + PaymentsAuthorizeRequestData, SplitPaymentData, }, - utils::OptionExt, }; - pub mod auth_headers { pub const STRIPE_API_VERSION: &str = "stripe-version"; pub const STRIPE_VERSION: &str = "2022-11-15"; @@ -42,15 +70,15 @@ pub struct StripeAuthType { pub(super) api_key: Secret<String>, } -impl TryFrom<&types::ConnectorAuthType> for StripeAuthType { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::ConnectorAuthType) -> Result<Self, Self::Error> { - if let types::ConnectorAuthType::HeaderKey { api_key } = item { +impl TryFrom<&ConnectorAuthType> for StripeAuthType { + type Error = error_stack::Report<ConnectorError>; + fn try_from(item: &ConnectorAuthType) -> Result<Self, Self::Error> { + if let ConnectorAuthType::HeaderKey { api_key } = item { Ok(Self { api_key: api_key.to_owned(), }) } else { - Err(errors::ConnectorError::FailedToObtainAuthType.into()) + Err(ConnectorError::FailedToObtainAuthType.into()) } } } @@ -414,7 +442,7 @@ pub struct SepaBankTransferData { #[serde( rename = "payment_method_options[customer_balance][bank_transfer][eu_bank_transfer][country]" )] - pub country: api_models::enums::CountryAlpha2, + pub country: enums::CountryAlpha2, } #[derive(Debug, Eq, PartialEq, Serialize)] @@ -664,7 +692,7 @@ pub enum StripeCreditTransferTypes { } impl TryFrom<enums::PaymentMethodType> for StripePaymentMethodType { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from(value: enums::PaymentMethodType) -> Result<Self, Self::Error> { match value { enums::PaymentMethodType::Credit => Ok(Self::Card), @@ -701,8 +729,8 @@ impl TryFrom<enums::PaymentMethodType> for StripePaymentMethodType { | enums::PaymentMethodType::UpiCollect | enums::PaymentMethodType::UpiIntent | enums::PaymentMethodType::Cashapp - | enums::PaymentMethodType::Oxxo => Err(errors::ConnectorError::NotImplemented( - connector_util::get_unimplemented_payment_method_error_message("stripe"), + | enums::PaymentMethodType::Oxxo => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), ) .into()), enums::PaymentMethodType::AliPayHk @@ -771,8 +799,8 @@ impl TryFrom<enums::PaymentMethodType> for StripePaymentMethodType { | enums::PaymentMethodType::DuitNow | enums::PaymentMethodType::PromptPay | enums::PaymentMethodType::VietQr - | enums::PaymentMethodType::Mifinity => Err(errors::ConnectorError::NotImplemented( - connector_util::get_unimplemented_payment_method_error_message("stripe"), + | enums::PaymentMethodType::Mifinity => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), ) .into()), } @@ -880,87 +908,85 @@ impl From<WebhookEventStatus> for api_models::webhooks::IncomingWebhookEvent { } } -impl TryFrom<&common_enums::enums::BankNames> for StripeBankNames { - type Error = errors::ConnectorError; - fn try_from(bank: &common_enums::enums::BankNames) -> Result<Self, Self::Error> { +impl TryFrom<&enums::BankNames> for StripeBankNames { + type Error = ConnectorError; + fn try_from(bank: &enums::BankNames) -> Result<Self, Self::Error> { Ok(match bank { - common_enums::enums::BankNames::AbnAmro => Self::AbnAmro, - common_enums::enums::BankNames::ArzteUndApothekerBank => Self::ArzteUndApothekerBank, - common_enums::enums::BankNames::AsnBank => Self::AsnBank, - common_enums::enums::BankNames::AustrianAnadiBankAg => Self::AustrianAnadiBankAg, - common_enums::enums::BankNames::BankAustria => Self::BankAustria, - common_enums::enums::BankNames::BankhausCarlSpangler => Self::BankhausCarlSpangler, - common_enums::enums::BankNames::BankhausSchelhammerUndSchatteraAg => { + enums::BankNames::AbnAmro => Self::AbnAmro, + enums::BankNames::ArzteUndApothekerBank => Self::ArzteUndApothekerBank, + enums::BankNames::AsnBank => Self::AsnBank, + enums::BankNames::AustrianAnadiBankAg => Self::AustrianAnadiBankAg, + enums::BankNames::BankAustria => Self::BankAustria, + enums::BankNames::BankhausCarlSpangler => Self::BankhausCarlSpangler, + enums::BankNames::BankhausSchelhammerUndSchatteraAg => { Self::BankhausSchelhammerUndSchatteraAg } - common_enums::enums::BankNames::BawagPskAg => Self::BawagPskAg, - common_enums::enums::BankNames::BksBankAg => Self::BksBankAg, - common_enums::enums::BankNames::BrullKallmusBankAg => Self::BrullKallmusBankAg, - common_enums::enums::BankNames::BtvVierLanderBank => Self::BtvVierLanderBank, - common_enums::enums::BankNames::Bunq => Self::Bunq, - common_enums::enums::BankNames::CapitalBankGraweGruppeAg => { - Self::CapitalBankGraweGruppeAg - } - common_enums::enums::BankNames::Citi => Self::CitiHandlowy, - common_enums::enums::BankNames::Dolomitenbank => Self::Dolomitenbank, - common_enums::enums::BankNames::EasybankAg => Self::EasybankAg, - common_enums::enums::BankNames::ErsteBankUndSparkassen => Self::ErsteBankUndSparkassen, - common_enums::enums::BankNames::Handelsbanken => Self::Handelsbanken, - common_enums::enums::BankNames::HypoAlpeadriabankInternationalAg => { + enums::BankNames::BawagPskAg => Self::BawagPskAg, + enums::BankNames::BksBankAg => Self::BksBankAg, + enums::BankNames::BrullKallmusBankAg => Self::BrullKallmusBankAg, + enums::BankNames::BtvVierLanderBank => Self::BtvVierLanderBank, + enums::BankNames::Bunq => Self::Bunq, + enums::BankNames::CapitalBankGraweGruppeAg => Self::CapitalBankGraweGruppeAg, + enums::BankNames::Citi => Self::CitiHandlowy, + enums::BankNames::Dolomitenbank => Self::Dolomitenbank, + enums::BankNames::EasybankAg => Self::EasybankAg, + enums::BankNames::ErsteBankUndSparkassen => Self::ErsteBankUndSparkassen, + enums::BankNames::Handelsbanken => Self::Handelsbanken, + enums::BankNames::HypoAlpeadriabankInternationalAg => { Self::HypoAlpeadriabankInternationalAg } - common_enums::enums::BankNames::HypoNoeLbFurNiederosterreichUWien => { + enums::BankNames::HypoNoeLbFurNiederosterreichUWien => { Self::HypoNoeLbFurNiederosterreichUWien } - common_enums::enums::BankNames::HypoOberosterreichSalzburgSteiermark => { + enums::BankNames::HypoOberosterreichSalzburgSteiermark => { Self::HypoOberosterreichSalzburgSteiermark } - common_enums::enums::BankNames::HypoTirolBankAg => Self::HypoTirolBankAg, - common_enums::enums::BankNames::HypoVorarlbergBankAg => Self::HypoVorarlbergBankAg, - common_enums::enums::BankNames::HypoBankBurgenlandAktiengesellschaft => { + enums::BankNames::HypoTirolBankAg => Self::HypoTirolBankAg, + enums::BankNames::HypoVorarlbergBankAg => Self::HypoVorarlbergBankAg, + enums::BankNames::HypoBankBurgenlandAktiengesellschaft => { Self::HypoBankBurgenlandAktiengesellschaft } - common_enums::enums::BankNames::Ing => Self::Ing, - common_enums::enums::BankNames::Knab => Self::Knab, - common_enums::enums::BankNames::MarchfelderBank => Self::MarchfelderBank, - common_enums::enums::BankNames::OberbankAg => Self::OberbankAg, - common_enums::enums::BankNames::RaiffeisenBankengruppeOsterreich => { + enums::BankNames::Ing => Self::Ing, + enums::BankNames::Knab => Self::Knab, + enums::BankNames::MarchfelderBank => Self::MarchfelderBank, + enums::BankNames::OberbankAg => Self::OberbankAg, + enums::BankNames::RaiffeisenBankengruppeOsterreich => { Self::RaiffeisenBankengruppeOsterreich } - common_enums::enums::BankNames::Rabobank => Self::Rabobank, - common_enums::enums::BankNames::Regiobank => Self::Regiobank, - common_enums::enums::BankNames::Revolut => Self::Revolut, - common_enums::enums::BankNames::SnsBank => Self::SnsBank, - common_enums::enums::BankNames::TriodosBank => Self::TriodosBank, - common_enums::enums::BankNames::VanLanschot => Self::VanLanschot, - common_enums::enums::BankNames::Moneyou => Self::Moneyou, - common_enums::enums::BankNames::SchoellerbankAg => Self::SchoellerbankAg, - common_enums::enums::BankNames::SpardaBankWien => Self::SpardaBankWien, - common_enums::enums::BankNames::VolksbankGruppe => Self::VolksbankGruppe, - common_enums::enums::BankNames::VolkskreditbankAg => Self::VolkskreditbankAg, - common_enums::enums::BankNames::VrBankBraunau => Self::VrBankBraunau, - common_enums::enums::BankNames::PlusBank => Self::PlusBank, - common_enums::enums::BankNames::EtransferPocztowy24 => Self::EtransferPocztowy24, - common_enums::enums::BankNames::BankiSpbdzielcze => Self::BankiSpbdzielcze, - common_enums::enums::BankNames::BankNowyBfgSa => Self::BankNowyBfgSa, - common_enums::enums::BankNames::GetinBank => Self::GetinBank, - common_enums::enums::BankNames::Blik => Self::Blik, - common_enums::enums::BankNames::NoblePay => Self::NoblePay, - common_enums::enums::BankNames::IdeaBank => Self::IdeaBank, - common_enums::enums::BankNames::EnveloBank => Self::EnveloBank, - common_enums::enums::BankNames::NestPrzelew => Self::NestPrzelew, - common_enums::enums::BankNames::MbankMtransfer => Self::MbankMtransfer, - common_enums::enums::BankNames::Inteligo => Self::Inteligo, - common_enums::enums::BankNames::PbacZIpko => Self::PbacZIpko, - common_enums::enums::BankNames::BnpParibas => Self::BnpParibas, - common_enums::enums::BankNames::BankPekaoSa => Self::BankPekaoSa, - common_enums::enums::BankNames::VolkswagenBank => Self::VolkswagenBank, - common_enums::enums::BankNames::AliorBank => Self::AliorBank, - common_enums::enums::BankNames::Boz => Self::Boz, - - _ => Err(errors::ConnectorError::NotImplemented( - connector_util::get_unimplemented_payment_method_error_message("stripe"), + enums::BankNames::Rabobank => Self::Rabobank, + enums::BankNames::Regiobank => Self::Regiobank, + enums::BankNames::Revolut => Self::Revolut, + enums::BankNames::SnsBank => Self::SnsBank, + enums::BankNames::TriodosBank => Self::TriodosBank, + enums::BankNames::VanLanschot => Self::VanLanschot, + enums::BankNames::Moneyou => Self::Moneyou, + enums::BankNames::SchoellerbankAg => Self::SchoellerbankAg, + enums::BankNames::SpardaBankWien => Self::SpardaBankWien, + enums::BankNames::VolksbankGruppe => Self::VolksbankGruppe, + enums::BankNames::VolkskreditbankAg => Self::VolkskreditbankAg, + enums::BankNames::VrBankBraunau => Self::VrBankBraunau, + enums::BankNames::PlusBank => Self::PlusBank, + enums::BankNames::EtransferPocztowy24 => Self::EtransferPocztowy24, + enums::BankNames::BankiSpbdzielcze => Self::BankiSpbdzielcze, + enums::BankNames::BankNowyBfgSa => Self::BankNowyBfgSa, + enums::BankNames::GetinBank => Self::GetinBank, + enums::BankNames::Blik => Self::Blik, + enums::BankNames::NoblePay => Self::NoblePay, + enums::BankNames::IdeaBank => Self::IdeaBank, + enums::BankNames::EnveloBank => Self::EnveloBank, + enums::BankNames::NestPrzelew => Self::NestPrzelew, + enums::BankNames::MbankMtransfer => Self::MbankMtransfer, + enums::BankNames::Inteligo => Self::Inteligo, + enums::BankNames::PbacZIpko => Self::PbacZIpko, + enums::BankNames::BnpParibas => Self::BnpParibas, + enums::BankNames::BankPekaoSa => Self::BankPekaoSa, + enums::BankNames::VolkswagenBank => Self::VolkswagenBank, + enums::BankNames::AliorBank => Self::AliorBank, + enums::BankNames::Boz => Self::Boz, + + _ => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), ))?, }) } @@ -969,7 +995,7 @@ impl TryFrom<&common_enums::enums::BankNames> for StripeBankNames { fn validate_shipping_address_against_payment_method( shipping_address: &Option<StripeShippingAddress>, payment_method: Option<&StripePaymentMethodType>, -) -> Result<(), error_stack::Report<errors::ConnectorError>> { +) -> Result<(), error_stack::Report<ConnectorError>> { match payment_method { Some(StripePaymentMethodType::AfterpayClearpay) => match shipping_address { Some(address) => { @@ -980,14 +1006,14 @@ fn validate_shipping_address_against_payment_method( ); if !missing_fields.is_empty() { - return Err(errors::ConnectorError::MissingRequiredFields { + return Err(ConnectorError::MissingRequiredFields { field_names: missing_fields, } .into()); } Ok(()) } - None => Err(errors::ConnectorError::MissingRequiredField { + None => Err(ConnectorError::MissingRequiredField { field_name: "shipping.address", } .into()), @@ -996,125 +1022,112 @@ fn validate_shipping_address_against_payment_method( } } -impl TryFrom<&domain::payments::PayLaterData> for StripePaymentMethodType { - type Error = errors::ConnectorError; - fn try_from(pay_later_data: &domain::payments::PayLaterData) -> Result<Self, Self::Error> { +impl TryFrom<&PayLaterData> for StripePaymentMethodType { + type Error = ConnectorError; + fn try_from(pay_later_data: &PayLaterData) -> Result<Self, Self::Error> { match pay_later_data { - domain::payments::PayLaterData::KlarnaRedirect { .. } => Ok(Self::Klarna), - domain::payments::PayLaterData::AffirmRedirect {} => Ok(Self::Affirm), - domain::payments::PayLaterData::AfterpayClearpayRedirect { .. } => { - Ok(Self::AfterpayClearpay) - } - - domain::PayLaterData::KlarnaSdk { .. } - | domain::PayLaterData::PayBrightRedirect {} - | domain::PayLaterData::WalleyRedirect {} - | domain::PayLaterData::AlmaRedirect {} - | domain::PayLaterData::AtomeRedirect {} => { - Err(errors::ConnectorError::NotImplemented( - connector_util::get_unimplemented_payment_method_error_message("stripe"), - )) - } + PayLaterData::KlarnaRedirect { .. } => Ok(Self::Klarna), + PayLaterData::AffirmRedirect {} => Ok(Self::Affirm), + PayLaterData::AfterpayClearpayRedirect { .. } => Ok(Self::AfterpayClearpay), + + PayLaterData::KlarnaSdk { .. } + | PayLaterData::PayBrightRedirect {} + | PayLaterData::WalleyRedirect {} + | PayLaterData::AlmaRedirect {} + | PayLaterData::AtomeRedirect {} => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), + )), } } } -impl TryFrom<&domain::BankRedirectData> for StripePaymentMethodType { - type Error = errors::ConnectorError; - fn try_from(bank_redirect_data: &domain::BankRedirectData) -> Result<Self, Self::Error> { +impl TryFrom<&BankRedirectData> for StripePaymentMethodType { + type Error = ConnectorError; + fn try_from(bank_redirect_data: &BankRedirectData) -> Result<Self, Self::Error> { match bank_redirect_data { - domain::BankRedirectData::Giropay { .. } => Ok(Self::Giropay), - domain::BankRedirectData::Ideal { .. } => Ok(Self::Ideal), - domain::BankRedirectData::Sofort { .. } => Ok(Self::Sofort), - domain::BankRedirectData::BancontactCard { .. } => Ok(Self::Bancontact), - domain::BankRedirectData::Przelewy24 { .. } => Ok(Self::Przelewy24), - domain::BankRedirectData::Eps { .. } => Ok(Self::Eps), - domain::BankRedirectData::Blik { .. } => Ok(Self::Blik), - domain::BankRedirectData::OnlineBankingFpx { .. } => { - Err(errors::ConnectorError::NotImplemented( - connector_util::get_unimplemented_payment_method_error_message("stripe"), - )) - } - domain::BankRedirectData::Bizum {} - | domain::BankRedirectData::Interac { .. } - | domain::BankRedirectData::Eft { .. } - | domain::BankRedirectData::OnlineBankingCzechRepublic { .. } - | domain::BankRedirectData::OnlineBankingFinland { .. } - | domain::BankRedirectData::OnlineBankingPoland { .. } - | domain::BankRedirectData::OnlineBankingSlovakia { .. } - | domain::BankRedirectData::OnlineBankingThailand { .. } - | domain::BankRedirectData::OpenBankingUk { .. } - | domain::BankRedirectData::Trustly { .. } - | domain::BankRedirectData::LocalBankRedirect {} => { - Err(errors::ConnectorError::NotImplemented( - connector_util::get_unimplemented_payment_method_error_message("stripe"), - )) - } + BankRedirectData::Giropay { .. } => Ok(Self::Giropay), + BankRedirectData::Ideal { .. } => Ok(Self::Ideal), + BankRedirectData::Sofort { .. } => Ok(Self::Sofort), + BankRedirectData::BancontactCard { .. } => Ok(Self::Bancontact), + BankRedirectData::Przelewy24 { .. } => Ok(Self::Przelewy24), + BankRedirectData::Eps { .. } => Ok(Self::Eps), + BankRedirectData::Blik { .. } => Ok(Self::Blik), + BankRedirectData::OnlineBankingFpx { .. } => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), + )), + BankRedirectData::Bizum {} + | BankRedirectData::Interac { .. } + | BankRedirectData::Eft { .. } + | BankRedirectData::OnlineBankingCzechRepublic { .. } + | BankRedirectData::OnlineBankingFinland { .. } + | BankRedirectData::OnlineBankingPoland { .. } + | BankRedirectData::OnlineBankingSlovakia { .. } + | BankRedirectData::OnlineBankingThailand { .. } + | BankRedirectData::OpenBankingUk { .. } + | BankRedirectData::Trustly { .. } + | BankRedirectData::LocalBankRedirect {} => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), + )), } } } -impl ForeignTryFrom<&domain::WalletData> for Option<StripePaymentMethodType> { - type Error = errors::ConnectorError; - fn foreign_try_from(wallet_data: &domain::WalletData) -> Result<Self, Self::Error> { - match wallet_data { - domain::WalletData::AliPayRedirect(_) => Ok(Some(StripePaymentMethodType::Alipay)), - domain::WalletData::ApplePay(_) => Ok(None), - domain::WalletData::GooglePay(_) => Ok(Some(StripePaymentMethodType::Card)), - domain::WalletData::WeChatPayQr(_) => Ok(Some(StripePaymentMethodType::Wechatpay)), - domain::WalletData::CashappQr(_) => Ok(Some(StripePaymentMethodType::Cashapp)), - domain::WalletData::AmazonPayRedirect(_) => { - Ok(Some(StripePaymentMethodType::AmazonPay)) - } - domain::WalletData::MobilePayRedirect(_) => { - Err(errors::ConnectorError::NotImplemented( - connector_util::get_unimplemented_payment_method_error_message("stripe"), - )) - } - domain::WalletData::PaypalRedirect(_) - | domain::WalletData::AliPayQr(_) - | domain::WalletData::AliPayHkRedirect(_) - | domain::WalletData::MomoRedirect(_) - | domain::WalletData::KakaoPayRedirect(_) - | domain::WalletData::GoPayRedirect(_) - | domain::WalletData::GcashRedirect(_) - | domain::WalletData::ApplePayRedirect(_) - | domain::WalletData::ApplePayThirdPartySdk(_) - | domain::WalletData::DanaRedirect {} - | domain::WalletData::GooglePayRedirect(_) - | domain::WalletData::GooglePayThirdPartySdk(_) - | domain::WalletData::MbWayRedirect(_) - | domain::WalletData::PaypalSdk(_) - | domain::WalletData::Paze(_) - | domain::WalletData::SamsungPay(_) - | domain::WalletData::TwintRedirect {} - | domain::WalletData::VippsRedirect {} - | domain::WalletData::TouchNGoRedirect(_) - | domain::WalletData::SwishQr(_) - | domain::WalletData::WeChatPayRedirect(_) - | domain::WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( - connector_util::get_unimplemented_payment_method_error_message("stripe"), - )), - } +fn get_stripe_payment_method_type_from_wallet_data( + wallet_data: &WalletData, +) -> Result<Option<StripePaymentMethodType>, ConnectorError> { + match wallet_data { + WalletData::AliPayRedirect(_) => Ok(Some(StripePaymentMethodType::Alipay)), + WalletData::ApplePay(_) => Ok(None), + WalletData::GooglePay(_) => Ok(Some(StripePaymentMethodType::Card)), + WalletData::WeChatPayQr(_) => Ok(Some(StripePaymentMethodType::Wechatpay)), + WalletData::CashappQr(_) => Ok(Some(StripePaymentMethodType::Cashapp)), + WalletData::AmazonPayRedirect(_) => Ok(Some(StripePaymentMethodType::AmazonPay)), + WalletData::MobilePayRedirect(_) => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), + )), + WalletData::PaypalRedirect(_) + | WalletData::AliPayQr(_) + | WalletData::AliPayHkRedirect(_) + | WalletData::MomoRedirect(_) + | WalletData::KakaoPayRedirect(_) + | WalletData::GoPayRedirect(_) + | WalletData::GcashRedirect(_) + | WalletData::ApplePayRedirect(_) + | WalletData::ApplePayThirdPartySdk(_) + | WalletData::DanaRedirect {} + | WalletData::GooglePayRedirect(_) + | WalletData::GooglePayThirdPartySdk(_) + | WalletData::MbWayRedirect(_) + | WalletData::PaypalSdk(_) + | WalletData::Paze(_) + | WalletData::SamsungPay(_) + | WalletData::TwintRedirect {} + | WalletData::VippsRedirect {} + | WalletData::TouchNGoRedirect(_) + | WalletData::SwishQr(_) + | WalletData::WeChatPayRedirect(_) + | WalletData::Mifinity(_) => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), + )), } } -impl From<&domain::BankDebitData> for StripePaymentMethodType { - fn from(bank_debit_data: &domain::BankDebitData) -> Self { +impl From<&payment_method_data::BankDebitData> for StripePaymentMethodType { + fn from(bank_debit_data: &payment_method_data::BankDebitData) -> Self { match bank_debit_data { - domain::BankDebitData::AchBankDebit { .. } => Self::Ach, - domain::BankDebitData::SepaBankDebit { .. } => Self::Sepa, - domain::BankDebitData::BecsBankDebit { .. } => Self::Becs, - domain::BankDebitData::BacsBankDebit { .. } => Self::Bacs, + payment_method_data::BankDebitData::AchBankDebit { .. } => Self::Ach, + payment_method_data::BankDebitData::SepaBankDebit { .. } => Self::Sepa, + payment_method_data::BankDebitData::BecsBankDebit { .. } => Self::Becs, + payment_method_data::BankDebitData::BacsBankDebit { .. } => Self::Bacs, } } } fn get_bank_debit_data( - bank_debit_data: &domain::BankDebitData, + bank_debit_data: &payment_method_data::BankDebitData, ) -> (StripePaymentMethodType, BankDebitData) { match bank_debit_data { - domain::BankDebitData::AchBankDebit { + payment_method_data::BankDebitData::AchBankDebit { account_number, routing_number, .. @@ -1126,13 +1139,13 @@ fn get_bank_debit_data( }; (StripePaymentMethodType::Ach, ach_data) } - domain::BankDebitData::SepaBankDebit { iban, .. } => { + payment_method_data::BankDebitData::SepaBankDebit { iban, .. } => { let sepa_data: BankDebitData = BankDebitData::Sepa { iban: iban.to_owned(), }; (StripePaymentMethodType::Sepa, sepa_data) } - domain::BankDebitData::BecsBankDebit { + payment_method_data::BankDebitData::BecsBankDebit { account_number, bsb_number, .. @@ -1143,7 +1156,7 @@ fn get_bank_debit_data( }; (StripePaymentMethodType::Becs, becs_data) } - domain::BankDebitData::BacsBankDebit { + payment_method_data::BankDebitData::BacsBankDebit { account_number, sort_code, .. @@ -1158,9 +1171,9 @@ fn get_bank_debit_data( } fn create_stripe_payment_method( - payment_method_data: &domain::PaymentMethodData, + payment_method_data: &PaymentMethodData, auth_type: enums::AuthenticationType, - payment_method_token: Option<types::PaymentMethodToken>, + payment_method_token: Option<PaymentMethodToken>, is_customer_initiated_mandate_payment: Option<bool>, billing_address: StripeBillingAddress, ) -> Result< @@ -1169,10 +1182,10 @@ fn create_stripe_payment_method( Option<StripePaymentMethodType>, StripeBillingAddress, ), - error_stack::Report<errors::ConnectorError>, + error_stack::Report<ConnectorError>, > { match payment_method_data { - domain::PaymentMethodData::Card(card_details) => { + PaymentMethodData::Card(card_details) => { let payment_method_auth_type = match auth_type { enums::AuthenticationType::ThreeDs => Auth3ds::Any, enums::AuthenticationType::NoThreeDs => Auth3ds::Automatic, @@ -1183,7 +1196,7 @@ fn create_stripe_payment_method( billing_address, )) } - domain::PaymentMethodData::PayLater(pay_later_data) => { + PaymentMethodData::PayLater(pay_later_data) => { let stripe_pm_type = StripePaymentMethodType::try_from(pay_later_data)?; Ok(( @@ -1194,7 +1207,7 @@ fn create_stripe_payment_method( billing_address, )) } - domain::PaymentMethodData::BankRedirect(bank_redirect_data) => { + PaymentMethodData::BankRedirect(bank_redirect_data) => { let billing_address = if is_customer_initiated_mandate_payment == Some(true) { mandatory_parameters_for_sepa_bank_debit_mandates( &Some(billing_address.to_owned()), @@ -1208,8 +1221,8 @@ fn create_stripe_payment_method( Ok((bank_redirect_data, Some(pm_type), billing_address)) } - domain::PaymentMethodData::Wallet(wallet_data) => { - let pm_type = ForeignTryFrom::foreign_try_from(wallet_data)?; + PaymentMethodData::Wallet(wallet_data) => { + let pm_type = get_stripe_payment_method_type_from_wallet_data(wallet_data)?; let wallet_specific_data = StripePaymentMethodData::try_from((wallet_data, payment_method_token))?; Ok(( @@ -1218,7 +1231,7 @@ fn create_stripe_payment_method( StripeBillingAddress::default(), )) } - domain::PaymentMethodData::BankDebit(bank_debit_data) => { + PaymentMethodData::BankDebit(bank_debit_data) => { let (pm_type, bank_debit_data) = get_bank_debit_data(bank_debit_data); let pm_data = StripePaymentMethodData::BankDebit(StripeBankDebitData { @@ -1227,155 +1240,149 @@ fn create_stripe_payment_method( Ok((pm_data, Some(pm_type), billing_address)) } - domain::PaymentMethodData::BankTransfer(bank_transfer_data) => { - match bank_transfer_data.deref() { - domain::BankTransferData::AchBankTransfer {} => Ok(( - StripePaymentMethodData::BankTransfer(StripeBankTransferData::AchBankTransfer( - Box::new(AchTransferData { - payment_method_data_type: StripePaymentMethodType::CustomerBalance, - bank_transfer_type: StripeCreditTransferTypes::AchCreditTransfer, - payment_method_type: StripePaymentMethodType::CustomerBalance, - balance_funding_type: BankTransferType::BankTransfers, - }), - )), - None, - StripeBillingAddress::default(), - )), - domain::BankTransferData::MultibancoBankTransfer {} => Ok(( - StripePaymentMethodData::BankTransfer( - StripeBankTransferData::MultibancoBankTransfers(Box::new( - MultibancoTransferData { - payment_method_data_type: StripeCreditTransferTypes::Multibanco, - payment_method_type: StripeCreditTransferTypes::Multibanco, - email: billing_address.email.ok_or( - errors::ConnectorError::MissingRequiredField { - field_name: "billing_address.email", - }, - )?, - }, - )), - ), - None, - StripeBillingAddress::default(), + PaymentMethodData::BankTransfer(bank_transfer_data) => match bank_transfer_data.deref() { + payment_method_data::BankTransferData::AchBankTransfer {} => Ok(( + StripePaymentMethodData::BankTransfer(StripeBankTransferData::AchBankTransfer( + Box::new(AchTransferData { + payment_method_data_type: StripePaymentMethodType::CustomerBalance, + bank_transfer_type: StripeCreditTransferTypes::AchCreditTransfer, + payment_method_type: StripePaymentMethodType::CustomerBalance, + balance_funding_type: BankTransferType::BankTransfers, + }), )), - domain::BankTransferData::SepaBankTransfer {} => Ok(( - StripePaymentMethodData::BankTransfer( - StripeBankTransferData::SepaBankTransfer(Box::new(SepaBankTransferData { - payment_method_data_type: StripePaymentMethodType::CustomerBalance, - bank_transfer_type: BankTransferType::EuBankTransfer, - balance_funding_type: BankTransferType::BankTransfers, - payment_method_type: StripePaymentMethodType::CustomerBalance, - country: billing_address.country.ok_or( - errors::ConnectorError::MissingRequiredField { - field_name: "billing_address.country", + None, + StripeBillingAddress::default(), + )), + payment_method_data::BankTransferData::MultibancoBankTransfer {} => Ok(( + StripePaymentMethodData::BankTransfer( + StripeBankTransferData::MultibancoBankTransfers(Box::new( + MultibancoTransferData { + payment_method_data_type: StripeCreditTransferTypes::Multibanco, + payment_method_type: StripeCreditTransferTypes::Multibanco, + email: billing_address.email.ok_or( + ConnectorError::MissingRequiredField { + field_name: "billing_address.email", }, )?, - })), - ), - Some(StripePaymentMethodType::CustomerBalance), - billing_address, + }, + )), + ), + None, + StripeBillingAddress::default(), + )), + payment_method_data::BankTransferData::SepaBankTransfer {} => Ok(( + StripePaymentMethodData::BankTransfer(StripeBankTransferData::SepaBankTransfer( + Box::new(SepaBankTransferData { + payment_method_data_type: StripePaymentMethodType::CustomerBalance, + bank_transfer_type: BankTransferType::EuBankTransfer, + balance_funding_type: BankTransferType::BankTransfers, + payment_method_type: StripePaymentMethodType::CustomerBalance, + country: billing_address.country.ok_or( + ConnectorError::MissingRequiredField { + field_name: "billing_address.country", + }, + )?, + }), )), - domain::BankTransferData::BacsBankTransfer {} => Ok(( - StripePaymentMethodData::BankTransfer( - StripeBankTransferData::BacsBankTransfers(Box::new(BacsBankTransferData { - payment_method_data_type: StripePaymentMethodType::CustomerBalance, - bank_transfer_type: BankTransferType::GbBankTransfer, - balance_funding_type: BankTransferType::BankTransfers, - payment_method_type: StripePaymentMethodType::CustomerBalance, - })), - ), - Some(StripePaymentMethodType::CustomerBalance), - billing_address, + Some(StripePaymentMethodType::CustomerBalance), + billing_address, + )), + payment_method_data::BankTransferData::BacsBankTransfer {} => Ok(( + StripePaymentMethodData::BankTransfer(StripeBankTransferData::BacsBankTransfers( + Box::new(BacsBankTransferData { + payment_method_data_type: StripePaymentMethodType::CustomerBalance, + bank_transfer_type: BankTransferType::GbBankTransfer, + balance_funding_type: BankTransferType::BankTransfers, + payment_method_type: StripePaymentMethodType::CustomerBalance, + }), )), - domain::BankTransferData::Pix { .. } => { - Err(errors::ConnectorError::NotImplemented( - connector_util::get_unimplemented_payment_method_error_message("stripe"), - ) - .into()) - } - domain::BankTransferData::Pse {} - | domain::BankTransferData::LocalBankTransfer { .. } - | domain::BankTransferData::InstantBankTransfer {} - | domain::BankTransferData::PermataBankTransfer { .. } - | domain::BankTransferData::BcaBankTransfer { .. } - | domain::BankTransferData::BniVaBankTransfer { .. } - | domain::BankTransferData::BriVaBankTransfer { .. } - | domain::BankTransferData::CimbVaBankTransfer { .. } - | domain::BankTransferData::DanamonVaBankTransfer { .. } - | domain::BankTransferData::MandiriVaBankTransfer { .. } => { - Err(errors::ConnectorError::NotImplemented( - connector_util::get_unimplemented_payment_method_error_message("stripe"), - ) - .into()) - } - } - } - domain::PaymentMethodData::Crypto(_) => Err(errors::ConnectorError::NotImplemented( - connector_util::get_unimplemented_payment_method_error_message("stripe"), + Some(StripePaymentMethodType::CustomerBalance), + billing_address, + )), + payment_method_data::BankTransferData::Pix { .. } => Err( + ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message( + "stripe", + )) + .into(), + ), + payment_method_data::BankTransferData::Pse {} + | payment_method_data::BankTransferData::LocalBankTransfer { .. } + | payment_method_data::BankTransferData::InstantBankTransfer {} + | payment_method_data::BankTransferData::PermataBankTransfer { .. } + | payment_method_data::BankTransferData::BcaBankTransfer { .. } + | payment_method_data::BankTransferData::BniVaBankTransfer { .. } + | payment_method_data::BankTransferData::BriVaBankTransfer { .. } + | payment_method_data::BankTransferData::CimbVaBankTransfer { .. } + | payment_method_data::BankTransferData::DanamonVaBankTransfer { .. } + | payment_method_data::BankTransferData::MandiriVaBankTransfer { .. } => Err( + ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message( + "stripe", + )) + .into(), + ), + }, + PaymentMethodData::Crypto(_) => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), ) .into()), - domain::PaymentMethodData::GiftCard(giftcard_data) => match giftcard_data.deref() { - domain::GiftCardData::Givex(_) | domain::GiftCardData::PaySafeCard {} => { - Err(errors::ConnectorError::NotImplemented( - connector_util::get_unimplemented_payment_method_error_message("stripe"), - ) - .into()) - } + PaymentMethodData::GiftCard(giftcard_data) => match giftcard_data.deref() { + GiftCardData::Givex(_) | GiftCardData::PaySafeCard {} => Err( + ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message( + "stripe", + )) + .into(), + ), }, - domain::PaymentMethodData::CardRedirect(cardredirect_data) => match cardredirect_data { - domain::CardRedirectData::Knet {} - | domain::CardRedirectData::Benefit {} - | domain::CardRedirectData::MomoAtm {} - | domain::CardRedirectData::CardRedirect {} => { - Err(errors::ConnectorError::NotImplemented( - connector_util::get_unimplemented_payment_method_error_message("stripe"), - ) - .into()) - } + PaymentMethodData::CardRedirect(cardredirect_data) => match cardredirect_data { + CardRedirectData::Knet {} + | CardRedirectData::Benefit {} + | CardRedirectData::MomoAtm {} + | CardRedirectData::CardRedirect {} => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), + ) + .into()), }, - domain::PaymentMethodData::Reward => Err(errors::ConnectorError::NotImplemented( - connector_util::get_unimplemented_payment_method_error_message("stripe"), + PaymentMethodData::Reward => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), ) .into()), - domain::PaymentMethodData::Voucher(voucher_data) => match voucher_data { - domain::VoucherData::Boleto(_) | domain::VoucherData::Oxxo => { - Err(errors::ConnectorError::NotImplemented( - connector_util::get_unimplemented_payment_method_error_message("stripe"), - ) - .into()) - } - domain::VoucherData::Alfamart(_) - | domain::VoucherData::Efecty - | domain::VoucherData::PagoEfectivo - | domain::VoucherData::RedCompra - | domain::VoucherData::RedPagos - | domain::VoucherData::Indomaret(_) - | domain::VoucherData::SevenEleven(_) - | domain::VoucherData::Lawson(_) - | domain::VoucherData::MiniStop(_) - | domain::VoucherData::FamilyMart(_) - | domain::VoucherData::Seicomart(_) - | domain::VoucherData::PayEasy(_) => Err(errors::ConnectorError::NotImplemented( - connector_util::get_unimplemented_payment_method_error_message("stripe"), + PaymentMethodData::Voucher(voucher_data) => match voucher_data { + VoucherData::Boleto(_) | VoucherData::Oxxo => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), + ) + .into()), + VoucherData::Alfamart(_) + | VoucherData::Efecty + | VoucherData::PagoEfectivo + | VoucherData::RedCompra + | VoucherData::RedPagos + | VoucherData::Indomaret(_) + | VoucherData::SevenEleven(_) + | VoucherData::Lawson(_) + | VoucherData::MiniStop(_) + | VoucherData::FamilyMart(_) + | VoucherData::Seicomart(_) + | VoucherData::PayEasy(_) => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), ) .into()), }, - domain::PaymentMethodData::Upi(_) - | domain::PaymentMethodData::RealTimePayment(_) - | domain::PaymentMethodData::MobilePayment(_) - | domain::PaymentMethodData::MandatePayment - | domain::PaymentMethodData::OpenBanking(_) - | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) - | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { - Err(errors::ConnectorError::NotImplemented( - connector_util::get_unimplemented_payment_method_error_message("stripe"), - ) - .into()) - } + PaymentMethodData::Upi(_) + | PaymentMethodData::RealTimePayment(_) + | PaymentMethodData::MobilePayment(_) + | PaymentMethodData::MandatePayment + | PaymentMethodData::OpenBanking(_) + | PaymentMethodData::CardToken(_) + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => Err( + ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message( + "stripe", + )) + .into(), + ), } } @@ -1395,11 +1402,9 @@ fn get_stripe_card_network(card_network: common_enums::CardNetwork) -> Option<St } } -impl TryFrom<(&domain::Card, Auth3ds)> for StripePaymentMethodData { - type Error = errors::ConnectorError; - fn try_from( - (card, payment_method_auth_type): (&domain::Card, Auth3ds), - ) -> Result<Self, Self::Error> { +impl TryFrom<(&Card, Auth3ds)> for StripePaymentMethodData { + type Error = ConnectorError; + fn try_from((card, payment_method_auth_type): (&Card, Auth3ds)) -> Result<Self, Self::Error> { Ok(Self::Card(StripeCardData { payment_method_data_type: StripePaymentMethodType::Card, payment_method_data_card_number: card.card_number.clone(), @@ -1415,18 +1420,15 @@ impl TryFrom<(&domain::Card, Auth3ds)> for StripePaymentMethodData { } } -impl TryFrom<(&domain::WalletData, Option<types::PaymentMethodToken>)> for StripePaymentMethodData { - type Error = error_stack::Report<errors::ConnectorError>; +impl TryFrom<(&WalletData, Option<PaymentMethodToken>)> for StripePaymentMethodData { + type Error = error_stack::Report<ConnectorError>; fn try_from( - (wallet_data, payment_method_token): ( - &domain::WalletData, - Option<types::PaymentMethodToken>, - ), + (wallet_data, payment_method_token): (&WalletData, Option<PaymentMethodToken>), ) -> Result<Self, Self::Error> { match wallet_data { - domain::WalletData::ApplePay(applepay_data) => { + WalletData::ApplePay(applepay_data) => { let mut apple_pay_decrypt_data = - if let Some(types::PaymentMethodToken::ApplePayDecrypt(decrypt_data)) = + if let Some(PaymentMethodToken::ApplePayDecrypt(decrypt_data)) = payment_method_token { let expiry_year_4_digit = decrypt_data.get_four_digit_expiry_year()?; @@ -1463,87 +1465,84 @@ impl TryFrom<(&domain::WalletData, Option<types::PaymentMethodToken>)> for Strip ), }))); }; - let pmd = apple_pay_decrypt_data - .ok_or(errors::ConnectorError::MissingApplePayTokenData)?; + let pmd = apple_pay_decrypt_data.ok_or(ConnectorError::MissingApplePayTokenData)?; Ok(pmd) } - domain::WalletData::WeChatPayQr(_) => Ok(Self::Wallet(StripeWallet::WechatpayPayment( + WalletData::WeChatPayQr(_) => Ok(Self::Wallet(StripeWallet::WechatpayPayment( WechatpayPayment { client: WechatClient::Web, payment_method_data_type: StripePaymentMethodType::Wechatpay, }, ))), - domain::WalletData::AliPayRedirect(_) => { + WalletData::AliPayRedirect(_) => { Ok(Self::Wallet(StripeWallet::AlipayPayment(AlipayPayment { payment_method_data_type: StripePaymentMethodType::Alipay, }))) } - domain::WalletData::CashappQr(_) => { - Ok(Self::Wallet(StripeWallet::Cashapp(CashappPayment { - payment_method_data_type: StripePaymentMethodType::Cashapp, - }))) - } - domain::WalletData::AmazonPayRedirect(_) => Ok(Self::Wallet( - StripeWallet::AmazonpayPayment(AmazonpayPayment { + WalletData::CashappQr(_) => Ok(Self::Wallet(StripeWallet::Cashapp(CashappPayment { + payment_method_data_type: StripePaymentMethodType::Cashapp, + }))), + WalletData::AmazonPayRedirect(_) => Ok(Self::Wallet(StripeWallet::AmazonpayPayment( + AmazonpayPayment { payment_method_types: StripePaymentMethodType::AmazonPay, - }), - )), - domain::WalletData::GooglePay(gpay_data) => Ok(Self::try_from(gpay_data)?), - domain::WalletData::PaypalRedirect(_) | domain::WalletData::MobilePayRedirect(_) => { - Err(errors::ConnectorError::NotImplemented( - connector_util::get_unimplemented_payment_method_error_message("stripe"), - ) - .into()) - } - domain::WalletData::AliPayQr(_) - | domain::WalletData::AliPayHkRedirect(_) - | domain::WalletData::MomoRedirect(_) - | domain::WalletData::KakaoPayRedirect(_) - | domain::WalletData::GoPayRedirect(_) - | domain::WalletData::GcashRedirect(_) - | domain::WalletData::ApplePayRedirect(_) - | domain::WalletData::ApplePayThirdPartySdk(_) - | domain::WalletData::DanaRedirect {} - | domain::WalletData::GooglePayRedirect(_) - | domain::WalletData::GooglePayThirdPartySdk(_) - | domain::WalletData::MbWayRedirect(_) - | domain::WalletData::PaypalSdk(_) - | domain::WalletData::Paze(_) - | domain::WalletData::SamsungPay(_) - | domain::WalletData::TwintRedirect {} - | domain::WalletData::VippsRedirect {} - | domain::WalletData::TouchNGoRedirect(_) - | domain::WalletData::SwishQr(_) - | domain::WalletData::WeChatPayRedirect(_) - | domain::WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( - connector_util::get_unimplemented_payment_method_error_message("stripe"), + }, + ))), + WalletData::GooglePay(gpay_data) => Ok(Self::try_from(gpay_data)?), + WalletData::PaypalRedirect(_) | WalletData::MobilePayRedirect(_) => Err( + ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message( + "stripe", + )) + .into(), + ), + WalletData::AliPayQr(_) + | WalletData::AliPayHkRedirect(_) + | WalletData::MomoRedirect(_) + | WalletData::KakaoPayRedirect(_) + | WalletData::GoPayRedirect(_) + | WalletData::GcashRedirect(_) + | WalletData::ApplePayRedirect(_) + | WalletData::ApplePayThirdPartySdk(_) + | WalletData::DanaRedirect {} + | WalletData::GooglePayRedirect(_) + | WalletData::GooglePayThirdPartySdk(_) + | WalletData::MbWayRedirect(_) + | WalletData::PaypalSdk(_) + | WalletData::Paze(_) + | WalletData::SamsungPay(_) + | WalletData::TwintRedirect {} + | WalletData::VippsRedirect {} + | WalletData::TouchNGoRedirect(_) + | WalletData::SwishQr(_) + | WalletData::WeChatPayRedirect(_) + | WalletData::Mifinity(_) => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), ) .into()), } } } -impl TryFrom<&domain::BankRedirectData> for StripePaymentMethodData { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(bank_redirect_data: &domain::BankRedirectData) -> Result<Self, Self::Error> { +impl TryFrom<&BankRedirectData> for StripePaymentMethodData { + type Error = error_stack::Report<ConnectorError>; + fn try_from(bank_redirect_data: &BankRedirectData) -> Result<Self, Self::Error> { let payment_method_data_type = StripePaymentMethodType::try_from(bank_redirect_data)?; match bank_redirect_data { - domain::BankRedirectData::BancontactCard { .. } => Ok(Self::BankRedirect( + BankRedirectData::BancontactCard { .. } => Ok(Self::BankRedirect( StripeBankRedirectData::StripeBancontactCard(Box::new(StripeBancontactCard { payment_method_data_type, })), )), - domain::BankRedirectData::Blik { blik_code } => Ok(Self::BankRedirect( + BankRedirectData::Blik { blik_code } => Ok(Self::BankRedirect( StripeBankRedirectData::StripeBlik(Box::new(StripeBlik { payment_method_data_type, code: Secret::new(blik_code.clone().ok_or( - errors::ConnectorError::MissingRequiredField { + ConnectorError::MissingRequiredField { field_name: "blik_code", }, )?), })), )), - domain::BankRedirectData::Eps { bank_name, .. } => Ok(Self::BankRedirect( + BankRedirectData::Eps { bank_name, .. } => Ok(Self::BankRedirect( StripeBankRedirectData::StripeEps(Box::new(StripeEps { payment_method_data_type, bank_name: bank_name @@ -1551,12 +1550,12 @@ impl TryFrom<&domain::BankRedirectData> for StripePaymentMethodData { .transpose()?, })), )), - domain::BankRedirectData::Giropay { .. } => Ok(Self::BankRedirect( + BankRedirectData::Giropay { .. } => Ok(Self::BankRedirect( StripeBankRedirectData::StripeGiropay(Box::new(StripeGiropay { payment_method_data_type, })), )), - domain::BankRedirectData::Ideal { bank_name, .. } => { + BankRedirectData::Ideal { bank_name, .. } => { let bank_name = bank_name .map(|bank_name| StripeBankNames::try_from(&bank_name)) .transpose()?; @@ -1567,7 +1566,7 @@ impl TryFrom<&domain::BankRedirectData> for StripePaymentMethodData { }), ))) } - domain::BankRedirectData::Przelewy24 { bank_name, .. } => { + BankRedirectData::Przelewy24 { bank_name, .. } => { let bank_name = bank_name .map(|bank_name| StripeBankNames::try_from(&bank_name)) .transpose()?; @@ -1578,36 +1577,32 @@ impl TryFrom<&domain::BankRedirectData> for StripePaymentMethodData { })), )) } - domain::BankRedirectData::OnlineBankingFpx { .. } => { - Err(errors::ConnectorError::NotImplemented( - connector_util::get_unimplemented_payment_method_error_message("stripe"), - ) - .into()) - } - domain::BankRedirectData::Bizum {} - | domain::BankRedirectData::Eft { .. } - | domain::BankRedirectData::Interac { .. } - | domain::BankRedirectData::OnlineBankingCzechRepublic { .. } - | domain::BankRedirectData::OnlineBankingFinland { .. } - | domain::BankRedirectData::OnlineBankingPoland { .. } - | domain::BankRedirectData::OnlineBankingSlovakia { .. } - | domain::BankRedirectData::OnlineBankingThailand { .. } - | domain::BankRedirectData::OpenBankingUk { .. } - | domain::BankRedirectData::Sofort { .. } - | domain::BankRedirectData::Trustly { .. } - | domain::BankRedirectData::LocalBankRedirect {} => { - Err(errors::ConnectorError::NotImplemented( - connector_util::get_unimplemented_payment_method_error_message("stripe"), - ) - .into()) - } + BankRedirectData::OnlineBankingFpx { .. } => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), + ) + .into()), + BankRedirectData::Bizum {} + | BankRedirectData::Eft { .. } + | BankRedirectData::Interac { .. } + | BankRedirectData::OnlineBankingCzechRepublic { .. } + | BankRedirectData::OnlineBankingFinland { .. } + | BankRedirectData::OnlineBankingPoland { .. } + | BankRedirectData::OnlineBankingSlovakia { .. } + | BankRedirectData::OnlineBankingThailand { .. } + | BankRedirectData::OpenBankingUk { .. } + | BankRedirectData::Sofort { .. } + | BankRedirectData::Trustly { .. } + | BankRedirectData::LocalBankRedirect {} => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), + ) + .into()), } } } -impl TryFrom<&domain::GooglePayWalletData> for StripePaymentMethodData { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(gpay_data: &domain::GooglePayWalletData) -> Result<Self, Self::Error> { +impl TryFrom<&GooglePayWalletData> for StripePaymentMethodData { + type Error = error_stack::Report<ConnectorError>; + fn try_from(gpay_data: &GooglePayWalletData) -> Result<Self, Self::Error> { Ok(Self::Wallet(StripeWallet::GooglepayToken(GooglePayToken { token: Secret::new( gpay_data @@ -1615,7 +1610,7 @@ impl TryFrom<&domain::GooglePayWalletData> for StripePaymentMethodData { .token .as_bytes() .parse_struct::<StripeGpayToken>("StripeGpayToken") - .change_context(errors::ConnectorError::InvalidWalletToken { + .change_context(ConnectorError::InvalidWalletToken { wallet_name: "Google Pay".to_string(), })? .id, @@ -1625,11 +1620,9 @@ impl TryFrom<&domain::GooglePayWalletData> for StripePaymentMethodData { } } -impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntentRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - data: (&types::PaymentsAuthorizeRouterData, MinorUnit), - ) -> Result<Self, Self::Error> { +impl TryFrom<(&PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntentRequest { + type Error = error_stack::Report<ConnectorError>; + fn try_from(data: (&PaymentsAuthorizeRouterData, MinorUnit)) -> Result<Self, Self::Error> { let item = data.0; let amount = data.1; let order_id = item.connector_request_reference_id.clone(); @@ -1737,7 +1730,7 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntent }); let payment_data = match item.request.payment_method_data { - domain::payments::PaymentMethodData::CardDetailsForNetworkTransactionId( + PaymentMethodData::CardDetailsForNetworkTransactionId( ref card_details_for_network_transaction_id, ) => StripePaymentMethodData::Card(StripeCardData { payment_method_data_type: StripePaymentMethodType::Card, @@ -1759,29 +1752,27 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntent .clone() .and_then(get_stripe_card_network), }), - domain::payments::PaymentMethodData::CardRedirect(_) - | domain::payments::PaymentMethodData::Wallet(_) - | domain::payments::PaymentMethodData::PayLater(_) - | domain::payments::PaymentMethodData::BankRedirect(_) - | domain::payments::PaymentMethodData::BankDebit(_) - | domain::payments::PaymentMethodData::BankTransfer(_) - | domain::payments::PaymentMethodData::Crypto(_) - | domain::payments::PaymentMethodData::MandatePayment - | domain::payments::PaymentMethodData::Reward - | domain::payments::PaymentMethodData::RealTimePayment(_) - | domain::payments::PaymentMethodData::MobilePayment(_) - | domain::payments::PaymentMethodData::Upi(_) - | domain::payments::PaymentMethodData::Voucher(_) - | domain::payments::PaymentMethodData::GiftCard(_) - | domain::payments::PaymentMethodData::OpenBanking(_) - | domain::payments::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) - | domain::PaymentMethodData::Card(_) => { - Err(errors::ConnectorError::NotSupported { - message: "Network tokenization for payment method".to_string(), - connector: "Stripe", - })? - } + PaymentMethodData::CardRedirect(_) + | PaymentMethodData::Wallet(_) + | PaymentMethodData::PayLater(_) + | PaymentMethodData::BankRedirect(_) + | PaymentMethodData::BankDebit(_) + | PaymentMethodData::BankTransfer(_) + | PaymentMethodData::Crypto(_) + | PaymentMethodData::MandatePayment + | PaymentMethodData::Reward + | PaymentMethodData::RealTimePayment(_) + | PaymentMethodData::MobilePayment(_) + | PaymentMethodData::Upi(_) + | PaymentMethodData::Voucher(_) + | PaymentMethodData::GiftCard(_) + | PaymentMethodData::OpenBanking(_) + | PaymentMethodData::CardToken(_) + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::Card(_) => Err(ConnectorError::NotSupported { + message: "Network tokenization for payment method".to_string(), + connector: "Stripe", + })?, }; ( @@ -1798,10 +1789,12 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntent &item.request.payment_method_data, item.auth_type, item.payment_method_token.clone(), - Some(connector_util::PaymentsAuthorizeRequestData::is_customer_initiated_mandate_payment( - &item.request, - )), - billing_address + Some( + PaymentsAuthorizeRequestData::is_customer_initiated_mandate_payment( + &item.request, + ), + ), + billing_address, )?; validate_shipping_address_against_payment_method( @@ -1821,26 +1814,26 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntent }; payment_data = match item.request.payment_method_data { - domain::PaymentMethodData::Wallet(domain::WalletData::ApplePay(_)) => { + PaymentMethodData::Wallet(WalletData::ApplePay(_)) => { let payment_method_token = item .payment_method_token .to_owned() .get_required_value("payment_token") - .change_context(errors::ConnectorError::InvalidWalletToken { + .change_context(ConnectorError::InvalidWalletToken { wallet_name: "Apple Pay".to_string(), })?; let payment_method_token = match payment_method_token { - types::PaymentMethodToken::Token(payment_method_token) => payment_method_token, - types::PaymentMethodToken::ApplePayDecrypt(_) => { - Err(errors::ConnectorError::InvalidWalletToken { + PaymentMethodToken::Token(payment_method_token) => payment_method_token, + PaymentMethodToken::ApplePayDecrypt(_) => { + Err(ConnectorError::InvalidWalletToken { wallet_name: "Apple Pay".to_string(), })? } - types::PaymentMethodToken::PazeDecrypt(_) => { + PaymentMethodToken::PazeDecrypt(_) => { Err(crate::unimplemented_payment_method!("Paze", "Stripe"))? } - types::PaymentMethodToken::GooglePayDecrypt(_) => { + PaymentMethodToken::GooglePayDecrypt(_) => { Err(crate::unimplemented_payment_method!("Google Pay", "Stripe"))? } }; @@ -1863,25 +1856,23 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntent .customer_acceptance .as_ref() .map(|customer_acceptance| { - Ok::<_, error_stack::Report<errors::ConnectorError>>( + Ok::<_, error_stack::Report<ConnectorError>>( match customer_acceptance.acceptance_type { AcceptanceType::Online => { let online_mandate = customer_acceptance .online .clone() .get_required_value("online") - .change_context( - errors::ConnectorError::MissingRequiredField { - field_name: "online", - }, - )?; + .change_context(ConnectorError::MissingRequiredField { + field_name: "online", + })?; StripeMandateRequest { mandate_type: StripeMandateType::Online { ip_address: online_mandate .ip_address .get_required_value("ip_address") .change_context( - errors::ConnectorError::MissingRequiredField { + ConnectorError::MissingRequiredField { field_name: "ip_address", }, )?, @@ -1937,22 +1928,18 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntent stripe_split_payment, )) => { let charges = match &stripe_split_payment.charge_type { - api_models::enums::PaymentChargeType::Stripe(charge_type) => { - match charge_type { - api_models::enums::StripeChargeType::Direct => Some(IntentCharges { - application_fee_amount: stripe_split_payment.application_fees, - destination_account_id: None, - }), - api_models::enums::StripeChargeType::Destination => { - Some(IntentCharges { - application_fee_amount: stripe_split_payment.application_fees, - destination_account_id: Some( - stripe_split_payment.transfer_account_id.clone(), - ), - }) - } - } - } + PaymentChargeType::Stripe(charge_type) => match charge_type { + StripeChargeType::Direct => Some(IntentCharges { + application_fee_amount: stripe_split_payment.application_fees, + destination_account_id: None, + }), + StripeChargeType::Destination => Some(IntentCharges { + application_fee_amount: stripe_split_payment.application_fees, + destination_account_id: Some( + stripe_split_payment.transfer_account_id.clone(), + ), + }), + }, }; (charges, None) } @@ -1993,8 +1980,8 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntent } fn get_payment_method_type_for_saved_payment_method_payment( - item: &types::PaymentsAuthorizeRouterData, -) -> Result<Option<StripePaymentMethodType>, error_stack::Report<errors::ConnectorError>> { + item: &PaymentsAuthorizeRouterData, +) -> Result<Option<StripePaymentMethodType>, error_stack::Report<ConnectorError>> { if item.payment_method == api_enums::PaymentMethod::Card { Ok(Some(StripePaymentMethodType::Card)) //stripe takes ["Card"] as default } else { @@ -2004,13 +1991,13 @@ fn get_payment_method_type_for_saved_payment_method_payment( Some(payment_method_type) => { StripePaymentMethodType::try_from(payment_method_type) } - None => Err(errors::ConnectorError::MissingRequiredField { + None => Err(ConnectorError::MissingRequiredField { field_name: "payment_method_type", } .into()), } } - None => Err(errors::ConnectorError::MissingRequiredField { + None => Err(ConnectorError::MissingRequiredField { field_name: "recurring_mandate_payment_data", } .into()), @@ -2025,8 +2012,8 @@ fn get_payment_method_type_for_saved_payment_method_payment( } } -impl From<types::BrowserInformation> for StripeBrowserInformation { - fn from(item: types::BrowserInformation) -> Self { +impl From<BrowserInformation> for StripeBrowserInformation { + fn from(item: BrowserInformation) -> Self { Self { ip_address: item.ip_address.map(|ip| Secret::new(ip.to_string())), user_agent: item.user_agent, @@ -2034,9 +2021,9 @@ impl From<types::BrowserInformation> for StripeBrowserInformation { } } -impl TryFrom<&types::SetupMandateRouterData> for SetupIntentRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> { +impl TryFrom<&SetupMandateRouterData> for SetupIntentRequest { + type Error = error_stack::Report<ConnectorError>; + fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> { //Only cards supported for mandates let pm_type = StripePaymentMethodType::Card; let payment_data = StripePaymentMethodData::try_from((item, item.auth_type, pm_type))?; @@ -2068,12 +2055,12 @@ impl TryFrom<&types::SetupMandateRouterData> for SetupIntentRequest { } } -impl TryFrom<&types::TokenizationRouterData> for TokenRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> { +impl TryFrom<&TokenizationRouterData> for TokenRequest { + type Error = error_stack::Report<ConnectorError>; + fn try_from(item: &TokenizationRouterData) -> Result<Self, Self::Error> { // Card flow for tokenization is handled separately because of API contact difference let request_payment_data = match &item.request.payment_method_data { - domain::PaymentMethodData::Card(card_details) => { + PaymentMethodData::Card(card_details) => { StripePaymentMethodData::CardToken(StripeCardToken { token_card_number: card_details.card_number.clone(), token_card_exp_month: card_details.card_exp_month.clone(), @@ -2099,9 +2086,9 @@ impl TryFrom<&types::TokenizationRouterData> for TokenRequest { } } -impl TryFrom<&types::ConnectorCustomerRouterData> for CustomerRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::ConnectorCustomerRouterData) -> Result<Self, Self::Error> { +impl TryFrom<&ConnectorCustomerRouterData> for CustomerRequest { + type Error = error_stack::Report<ConnectorError>; + fn try_from(item: &ConnectorCustomerRouterData) -> Result<Self, Self::Error> { Ok(Self { description: item.request.description.to_owned(), email: item.request.email.to_owned(), @@ -2131,7 +2118,7 @@ pub enum StripePaymentStatus { Pending, } -impl From<StripePaymentStatus> for enums::AttemptStatus { +impl From<StripePaymentStatus> for AttemptStatus { fn from(item: StripePaymentStatus) -> Self { match item { StripePaymentStatus::Succeeded => Self::Charged, @@ -2336,7 +2323,7 @@ pub struct AdditionalPaymentMethodDetails { pub authentication_details: Option<Value>, } -impl From<AdditionalPaymentMethodDetails> for types::AdditionalPaymentMethodConnectorResponse { +impl From<AdditionalPaymentMethodDetails> for AdditionalPaymentMethodConnectorResponse { fn from(item: AdditionalPaymentMethodDetails) -> Self { Self::Card { authentication_data: item.authentication_details, @@ -2440,7 +2427,7 @@ pub struct SetupIntentResponse { fn extract_payment_method_connector_response_from_latest_charge( stripe_charge_enum: &StripeChargeEnum, -) -> Option<types::ConnectorResponseData> { +) -> Option<ConnectorResponseData> { if let StripeChargeEnum::ChargeObject(charge_object) = stripe_charge_enum { charge_object .payment_method_details @@ -2449,13 +2436,13 @@ fn extract_payment_method_connector_response_from_latest_charge( } else { None } - .map(types::AdditionalPaymentMethodConnectorResponse::from) - .map(types::ConnectorResponseData::with_additional_payment_method_data) + .map(AdditionalPaymentMethodConnectorResponse::from) + .map(ConnectorResponseData::with_additional_payment_method_data) } fn extract_payment_method_connector_response_from_latest_attempt( stripe_latest_attempt: &LatestAttempt, -) -> Option<types::ConnectorResponseData> { +) -> Option<ConnectorResponseData> { if let LatestAttempt::PaymentIntentAttempt(intent_attempt) = stripe_latest_attempt { intent_attempt .payment_method_details @@ -2464,26 +2451,23 @@ fn extract_payment_method_connector_response_from_latest_attempt( } else { None } - .map(types::AdditionalPaymentMethodConnectorResponse::from) - .map(types::ConnectorResponseData::with_additional_payment_method_data) + .map(AdditionalPaymentMethodConnectorResponse::from) + .map(ConnectorResponseData::with_additional_payment_method_data) } -impl<F, T> - TryFrom<types::ResponseRouterData<F, PaymentIntentResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, PaymentIntentResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> where - T: connector_util::SplitPaymentData, + T: SplitPaymentData, { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: types::ResponseRouterData<F, PaymentIntentResponse, T, types::PaymentsResponseData>, + item: ResponseRouterData<F, PaymentIntentResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let redirect_data = item.response.next_action.clone(); let redirection_data = redirect_data .and_then(|redirection_data| redirection_data.get_url()) - .map(|redirection_url| { - services::RedirectForm::from((redirection_url, services::Method::Get)) - }); + .map(|redirection_url| RedirectForm::from((redirection_url, Method::Get))); let mandate_reference = item.response.payment_method.map(|payment_method_id| { // Implemented Save and re-use payment information for recurring charges @@ -2491,7 +2475,7 @@ where // For backward compatibility payment_method_id & connector_mandate_id is being populated with the same value let connector_mandate_id = Some(payment_method_id.clone().expose()); let payment_method_id = Some(payment_method_id.expose()); - types::MandateReference { + MandateReference { connector_mandate_id, payment_method_id, mandate_metadata: None, @@ -2517,14 +2501,14 @@ where let connector_metadata = get_connector_metadata(item.response.next_action.as_ref(), item.response.amount)?; - let status = enums::AttemptStatus::from(item.response.status); + let status = AttemptStatus::from(item.response.status); - let response = if connector_util::is_payment_failure(status) { - types::PaymentsResponseData::foreign_try_from(( + let response = if is_payment_failure(status) { + *get_stripe_payments_response_data( &item.response.last_payment_error, item.http_code, item.response.id.clone(), - )) + ) } else { let charges = item .response @@ -2536,8 +2520,8 @@ where }) .and_then(|charge_id| construct_charge_response(charge_id, &item.data.request)); - Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(redirection_data), mandate_reference: Box::new(mandate_reference), connector_metadata, @@ -2575,7 +2559,7 @@ where pub fn get_connector_metadata( next_action: Option<&StripeNextActionResponse>, amount: MinorUnit, -) -> CustomResult<Option<Value>, errors::ConnectorError> { +) -> CustomResult<Option<Value>, ConnectorError> { let next_action_response = next_action .and_then(|next_action_response| match next_action_response { StripeNextActionResponse::DisplayBankTransferInstructions(response) => { @@ -2679,7 +2663,7 @@ pub fn get_connector_metadata( _ => None, }) .transpose() - .change_context(errors::ConnectorError::ResponseHandlingFailed)?; + .change_context(ConnectorError::ResponseHandlingFailed)?; Ok(next_action_response) } @@ -2722,27 +2706,19 @@ pub fn get_payment_method_id( } } -impl<F, T> - TryFrom<types::ResponseRouterData<F, PaymentIntentSyncResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, PaymentIntentSyncResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> where - T: connector_util::SplitPaymentData, + T: SplitPaymentData, { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: types::ResponseRouterData< - F, - PaymentIntentSyncResponse, - T, - types::PaymentsResponseData, - >, + item: ResponseRouterData<F, PaymentIntentSyncResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let redirect_data = item.response.next_action.clone(); let redirection_data = redirect_data .and_then(|redirection_data| redirection_data.get_url()) - .map(|redirection_url| { - services::RedirectForm::from((redirection_url, services::Method::Get)) - }); + .map(|redirection_url| RedirectForm::from((redirection_url, Method::Get))); let mandate_reference = item .response @@ -2755,7 +2731,7 @@ where let payment_method_id = get_payment_method_id(item.response.latest_charge.clone(), payment_method_id); - types::MandateReference { + MandateReference { connector_mandate_id: Some(payment_method_id.clone()), payment_method_id: Some(payment_method_id), mandate_metadata: None, @@ -2766,7 +2742,7 @@ where let connector_metadata = get_connector_metadata(item.response.next_action.as_ref(), item.response.amount)?; - let status = enums::AttemptStatus::from(item.response.status.to_owned()); + let status = AttemptStatus::from(item.response.status.to_owned()); let connector_response_data = item .response @@ -2774,12 +2750,12 @@ where .as_ref() .and_then(extract_payment_method_connector_response_from_latest_charge); - let response = if connector_util::is_payment_failure(status) { - types::PaymentsResponseData::foreign_try_from(( + let response = if is_payment_failure(status) { + *get_stripe_payments_response_data( &item.response.payment_intent_fields.last_payment_error, item.http_code, item.response.id.clone(), - )) + ) } else { let network_transaction_id = match item.response.latest_charge.clone() { Some(StripeChargeEnum::ChargeObject(charge_object)) => charge_object @@ -2802,8 +2778,8 @@ where }) .and_then(|charge_id| construct_charge_response(charge_id, &item.data.request)); - Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(redirection_data), mandate_reference: Box::new(mandate_reference), connector_metadata, @@ -2815,7 +2791,7 @@ where }; Ok(Self { - status: enums::AttemptStatus::from(item.response.status.to_owned()), + status: AttemptStatus::from(item.response.status.to_owned()), response, amount_captured: item .response @@ -2828,20 +2804,17 @@ where } } -impl<F, T> - TryFrom<types::ResponseRouterData<F, SetupIntentResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, SetupIntentResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: types::ResponseRouterData<F, SetupIntentResponse, T, types::PaymentsResponseData>, + item: ResponseRouterData<F, SetupIntentResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let redirect_data = item.response.next_action.clone(); let redirection_data = redirect_data .and_then(|redirection_data| redirection_data.get_url()) - .map(|redirection_url| { - services::RedirectForm::from((redirection_url, services::Method::Get)) - }); + .map(|redirection_url| RedirectForm::from((redirection_url, Method::Get))); let mandate_reference = item.response.payment_method.map(|payment_method_id| { // Implemented Save and re-use payment information for recurring charges @@ -2849,26 +2822,26 @@ impl<F, T> // For backward compatibility payment_method_id & connector_mandate_id is being populated with the same value let connector_mandate_id = Some(payment_method_id.clone()); let payment_method_id = Some(payment_method_id); - types::MandateReference { + MandateReference { connector_mandate_id, payment_method_id, mandate_metadata: None, connector_mandate_request_reference_id: None, } }); - let status = enums::AttemptStatus::from(item.response.status); + let status = AttemptStatus::from(item.response.status); let connector_response_data = item .response .latest_attempt .as_ref() .and_then(extract_payment_method_connector_response_from_latest_attempt); - let response = if connector_util::is_payment_failure(status) { - types::PaymentsResponseData::foreign_try_from(( + let response = if is_payment_failure(status) { + *get_stripe_payments_response_data( &item.response.last_setup_error, item.http_code, item.response.id.clone(), - )) + ) } else { let network_transaction_id = match item.response.latest_attempt { Some(LatestAttempt::PaymentIntentAttempt(attempt)) => attempt @@ -2882,8 +2855,8 @@ impl<F, T> _ => None, }; - Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(redirection_data), mandate_reference: Box::new(mandate_reference), connector_metadata: None, @@ -2903,20 +2876,20 @@ impl<F, T> } } -impl ForeignFrom<Option<LatestAttempt>> for Option<String> { - fn foreign_from(latest_attempt: Option<LatestAttempt>) -> Self { - match latest_attempt { - Some(LatestAttempt::PaymentIntentAttempt(attempt)) => attempt - .payment_method_options - .and_then(|payment_method_options| match payment_method_options { - StripePaymentMethodOptions::Card { - network_transaction_id, - .. - } => network_transaction_id.map(|network_id| network_id.expose()), - _ => None, - }), - _ => None, - } +pub fn stripe_opt_latest_attempt_to_opt_string( + latest_attempt: Option<LatestAttempt>, +) -> Option<String> { + match latest_attempt { + Some(LatestAttempt::PaymentIntentAttempt(attempt)) => attempt + .payment_method_options + .and_then(|payment_method_options| match payment_method_options { + StripePaymentMethodOptions::Card { + network_transaction_id, + .. + } => network_transaction_id.map(|network_id| network_id.expose()), + _ => None, + }), + _ => None, } } @@ -3119,10 +3092,10 @@ pub struct RefundRequest { pub meta_data: StripeMetadata, } -impl<F> TryFrom<(&types::RefundsRouterData<F>, MinorUnit)> for RefundRequest { - type Error = error_stack::Report<errors::ConnectorError>; +impl<F> TryFrom<(&RefundsRouterData<F>, MinorUnit)> for RefundRequest { + type Error = error_stack::Report<ConnectorError>; fn try_from( - (item, refund_amount): (&types::RefundsRouterData<F>, MinorUnit), + (item, refund_amount): (&RefundsRouterData<F>, MinorUnit), ) -> Result<Self, Self::Error> { let payment_intent = item.request.connector_transaction_id.clone(); Ok(Self { @@ -3146,28 +3119,26 @@ pub struct ChargeRefundRequest { pub meta_data: StripeMetadata, } -impl<F> TryFrom<&types::RefundsRouterData<F>> for ChargeRefundRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { +impl<F> TryFrom<&RefundsRouterData<F>> for ChargeRefundRequest { + type Error = error_stack::Report<ConnectorError>; + fn try_from(item: &RefundsRouterData<F>) -> Result<Self, Self::Error> { let amount = item.request.minor_refund_amount; match item.request.split_refunds.as_ref() { - None => Err(errors::ConnectorError::MissingRequiredField { + None => Err(ConnectorError::MissingRequiredField { field_name: "split_refunds", } .into()), Some(split_refunds) => match split_refunds { - types::SplitRefundsRequest::StripeSplitRefund(stripe_refund) => { + SplitRefundsRequest::StripeSplitRefund(stripe_refund) => { let (refund_application_fee, reverse_transfer) = match &stripe_refund.options { - types::ChargeRefundsOptions::Direct(types::DirectChargeRefund { + ChargeRefundsOptions::Direct(DirectChargeRefund { revert_platform_fee, }) => (Some(*revert_platform_fee), None), - types::ChargeRefundsOptions::Destination( - types::DestinationChargeRefund { - revert_platform_fee, - revert_transfer, - }, - ) => (Some(*revert_platform_fee), Some(*revert_transfer)), + ChargeRefundsOptions::Destination(DestinationChargeRefund { + revert_platform_fee, + revert_transfer, + }) => (Some(*revert_platform_fee), Some(*revert_transfer)), }; Ok(Self { @@ -3181,7 +3152,7 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for ChargeRefundRequest { }, }) } - _ => Err(errors::ConnectorError::MissingRequiredField { + _ => Err(ConnectorError::MissingRequiredField { field_name: "stripe_split_refund", })?, }, @@ -3224,16 +3195,14 @@ pub struct RefundResponse { pub failure_reason: Option<String>, } -impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> - for types::RefundsRouterData<api::Execute> -{ - type Error = error_stack::Report<errors::ConnectorError>; +impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, + item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { let refund_status = enums::RefundStatus::from(item.response.status); - let response = if connector_util::is_refund_failure(refund_status) { - Err(types::ErrorResponse { + let response = if is_refund_failure(refund_status) { + Err(hyperswitch_domain_models::router_data::ErrorResponse { code: consts::NO_ERROR_CODE.to_string(), message: item .response @@ -3249,7 +3218,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> network_error_message: None, }) } else { - Ok(types::RefundsResponseData { + Ok(RefundsResponseData { connector_refund_id: item.response.id, refund_status, }) @@ -3262,16 +3231,14 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> } } -impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> - for types::RefundsRouterData<api::RSync> -{ - type Error = error_stack::Report<errors::ConnectorError>; +impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: types::RefundsResponseRouterData<api::RSync, RefundResponse>, + item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { let refund_status = enums::RefundStatus::from(item.response.status); - let response = if connector_util::is_refund_failure(refund_status) { - Err(types::ErrorResponse { + let response = if is_refund_failure(refund_status) { + Err(hyperswitch_domain_models::router_data::ErrorResponse { code: consts::NO_ERROR_CODE.to_string(), message: item .response @@ -3287,7 +3254,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> network_error_message: None, }) } else { - Ok(types::RefundsResponseData { + Ok(RefundsResponseData { connector_refund_id: item.response.id, refund_status, }) @@ -3380,9 +3347,9 @@ pub struct CancelRequest { cancellation_reason: Option<String>, } -impl TryFrom<&types::PaymentsCancelRouterData> for CancelRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> { +impl TryFrom<&PaymentsCancelRouterData> for CancelRequest { + type Error = error_stack::Report<ConnectorError>; + fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> { Ok(Self { cancellation_reason: item.request.cancellation_reason.clone(), }) @@ -3395,9 +3362,9 @@ pub struct UpdateMetadataRequest { pub metadata: HashMap<String, String>, } -impl TryFrom<&types::PaymentsUpdateMetadataRouterData> for UpdateMetadataRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsUpdateMetadataRouterData) -> Result<Self, Self::Error> { +impl TryFrom<&PaymentsUpdateMetadataRouterData> for UpdateMetadataRequest { + type Error = error_stack::Report<ConnectorError>; + fn try_from(item: &PaymentsUpdateMetadataRouterData) -> Result<Self, Self::Error> { let metadata = format_metadata_for_request(item.request.metadata.clone()); Ok(Self { metadata }) } @@ -3484,7 +3451,7 @@ pub struct CaptureRequest { } impl TryFrom<MinorUnit> for CaptureRequest { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from(capture_amount: MinorUnit) -> Result<Self, Self::Error> { Ok(Self { amount_to_capture: Some(capture_amount), @@ -3492,31 +3459,26 @@ impl TryFrom<MinorUnit> for CaptureRequest { } } -impl<F, T> - TryFrom<types::ResponseRouterData<F, StripeSourceResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, StripeSourceResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: types::ResponseRouterData<F, StripeSourceResponse, T, types::PaymentsResponseData>, + item: ResponseRouterData<F, StripeSourceResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let connector_source_response = item.response.to_owned(); let connector_metadata = connector_source_response .encode_to_value() - .change_context(errors::ConnectorError::ResponseHandlingFailed)?; + .change_context(ConnectorError::ResponseHandlingFailed)?; // We get pending as the status from stripe, but hyperswitch should give it as requires_customer_action as // customer has to make payment to the virtual account number given in the source response let status = match connector_source_response.status.clone().into() { - diesel_models::enums::AttemptStatus::Pending => { - diesel_models::enums::AttemptStatus::AuthenticationPending - } + AttemptStatus::Pending => AttemptStatus::AuthenticationPending, _ => connector_source_response.status.into(), }; Ok(Self { - response: Ok(types::PaymentsResponseData::PreProcessingResponse { - pre_processing_id: types::PreprocessingResponseId::PreProcessingId( - item.response.id, - ), + response: Ok(PaymentsResponseData::PreProcessingResponse { + pre_processing_id: PreprocessingResponseId::PreProcessingId(item.response.id), connector_metadata: Some(connector_metadata), session_token: None, connector_response_reference_id: None, @@ -3527,12 +3489,10 @@ impl<F, T> } } -impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for ChargesRequest { - type Error = error_stack::Report<errors::ConnectorError>; +impl TryFrom<(&PaymentsAuthorizeRouterData, MinorUnit)> for ChargesRequest { + type Error = error_stack::Report<ConnectorError>; - fn try_from( - data: (&types::PaymentsAuthorizeRouterData, MinorUnit), - ) -> Result<Self, Self::Error> { + fn try_from(data: (&PaymentsAuthorizeRouterData, MinorUnit)) -> Result<Self, Self::Error> { { let value = data.0; let amount = data.1; @@ -3552,21 +3512,21 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for ChargesReques } } -impl<F, T> TryFrom<types::ResponseRouterData<F, ChargesResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, ChargesResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: types::ResponseRouterData<F, ChargesResponse, T, types::PaymentsResponseData>, + item: ResponseRouterData<F, ChargesResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let connector_source_response = item.response.to_owned(); let connector_metadata = connector_source_response .source .encode_to_value() - .change_context(errors::ConnectorError::ResponseHandlingFailed)?; - let status = enums::AttemptStatus::from(item.response.status); - let response = if connector_util::is_payment_failure(status) { - Err(types::ErrorResponse { + .change_context(ConnectorError::ResponseHandlingFailed)?; + let status = AttemptStatus::from(item.response.status); + let response = if is_payment_failure(status) { + Err(hyperswitch_domain_models::router_data::ErrorResponse { code: item .response .failure_code @@ -3585,8 +3545,8 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, ChargesResponse, T, types::Payme network_error_message: None, }) } else { - Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: Some(connector_metadata), @@ -3605,16 +3565,15 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, ChargesResponse, T, types::Payme } } -impl<F, T> - TryFrom<types::ResponseRouterData<F, StripeTokenResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, StripeTokenResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: types::ResponseRouterData<F, StripeTokenResponse, T, types::PaymentsResponseData>, + item: ResponseRouterData<F, StripeTokenResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(types::PaymentsResponseData::TokenizationResponse { + response: Ok(PaymentsResponseData::TokenizationResponse { token: item.response.id.expose(), }), ..item.data @@ -3622,16 +3581,15 @@ impl<F, T> } } -impl<F, T> - TryFrom<types::ResponseRouterData<F, StripeCustomerResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, StripeCustomerResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: types::ResponseRouterData<F, StripeCustomerResponse, T, types::PaymentsResponseData>, + item: ResponseRouterData<F, StripeCustomerResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(types::PaymentsResponseData::ConnectorCustomerResponse { + response: Ok(PaymentsResponseData::ConnectorCustomerResponse { connector_customer_id: item.response.id, }), ..item.data @@ -3740,7 +3698,7 @@ pub struct WebhookEventObjectData { pub id: String, pub object: WebhookEventObjectType, pub amount: Option<i32>, - #[serde(default, deserialize_with = "connector_util::convert_uppercase")] + #[serde(default, deserialize_with = "convert_uppercase")] pub currency: enums::Currency, pub payment_intent: Option<String>, pub client_secret: Option<Secret<String>>, @@ -3847,113 +3805,116 @@ pub struct EvidenceDetails { impl TryFrom<( - &types::SetupMandateRouterData, + &SetupMandateRouterData, enums::AuthenticationType, StripePaymentMethodType, )> for StripePaymentMethodData { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from( (item, auth_type, pm_type): ( - &types::SetupMandateRouterData, + &SetupMandateRouterData, enums::AuthenticationType, StripePaymentMethodType, ), ) -> Result<Self, Self::Error> { let pm_data = &item.request.payment_method_data; match pm_data { - domain::PaymentMethodData::Card(ref ccard) => { + PaymentMethodData::Card(ref ccard) => { let payment_method_auth_type = match auth_type { enums::AuthenticationType::ThreeDs => Auth3ds::Any, enums::AuthenticationType::NoThreeDs => Auth3ds::Automatic, }; Ok(Self::try_from((ccard, payment_method_auth_type))?) } - domain::PaymentMethodData::PayLater(_) => Ok(Self::PayLater(StripePayLaterData { + PaymentMethodData::PayLater(_) => Ok(Self::PayLater(StripePayLaterData { payment_method_data_type: pm_type, })), - domain::PaymentMethodData::BankRedirect(ref bank_redirect_data) => { + PaymentMethodData::BankRedirect(ref bank_redirect_data) => { Ok(Self::try_from(bank_redirect_data)?) } - domain::PaymentMethodData::Wallet(ref wallet_data) => { - Ok(Self::try_from((wallet_data, None))?) - } - domain::PaymentMethodData::BankDebit(bank_debit_data) => { + PaymentMethodData::Wallet(ref wallet_data) => Ok(Self::try_from((wallet_data, None))?), + PaymentMethodData::BankDebit(bank_debit_data) => { let (_pm_type, bank_data) = get_bank_debit_data(bank_debit_data); Ok(Self::BankDebit(StripeBankDebitData { bank_specific_data: bank_data, })) } - domain::PaymentMethodData::BankTransfer(bank_transfer_data) => match bank_transfer_data - .deref() + PaymentMethodData::BankTransfer(bank_transfer_data) => match bank_transfer_data.deref() { - domain::BankTransferData::AchBankTransfer {} => Ok(Self::BankTransfer( - StripeBankTransferData::AchBankTransfer(Box::new(AchTransferData { - payment_method_data_type: StripePaymentMethodType::CustomerBalance, - bank_transfer_type: StripeCreditTransferTypes::AchCreditTransfer, - payment_method_type: StripePaymentMethodType::CustomerBalance, - balance_funding_type: BankTransferType::BankTransfers, - })), - )), - domain::BankTransferData::MultibancoBankTransfer {} => Ok(Self::BankTransfer( - StripeBankTransferData::MultibancoBankTransfers(Box::new( + payment_method_data::BankTransferData::AchBankTransfer {} => { + Ok(Self::BankTransfer(StripeBankTransferData::AchBankTransfer( + Box::new(AchTransferData { + payment_method_data_type: StripePaymentMethodType::CustomerBalance, + bank_transfer_type: StripeCreditTransferTypes::AchCreditTransfer, + payment_method_type: StripePaymentMethodType::CustomerBalance, + balance_funding_type: BankTransferType::BankTransfers, + }), + ))) + } + payment_method_data::BankTransferData::MultibancoBankTransfer {} => Ok( + Self::BankTransfer(StripeBankTransferData::MultibancoBankTransfers(Box::new( MultibancoTransferData { payment_method_data_type: StripeCreditTransferTypes::Multibanco, payment_method_type: StripeCreditTransferTypes::Multibanco, email: item.get_billing_email()?, }, - )), - )), - domain::BankTransferData::SepaBankTransfer {} => Ok(Self::BankTransfer( - StripeBankTransferData::SepaBankTransfer(Box::new(SepaBankTransferData { - payment_method_data_type: StripePaymentMethodType::CustomerBalance, - bank_transfer_type: BankTransferType::EuBankTransfer, - balance_funding_type: BankTransferType::BankTransfers, - payment_method_type: StripePaymentMethodType::CustomerBalance, - country: item.get_billing_country()?, - })), - )), - domain::BankTransferData::BacsBankTransfer { .. } => Ok(Self::BankTransfer( - StripeBankTransferData::BacsBankTransfers(Box::new(BacsBankTransferData { - payment_method_data_type: StripePaymentMethodType::CustomerBalance, - bank_transfer_type: BankTransferType::GbBankTransfer, - balance_funding_type: BankTransferType::BankTransfers, - payment_method_type: StripePaymentMethodType::CustomerBalance, - })), - )), - domain::BankTransferData::Pix { .. } - | domain::BankTransferData::Pse {} - | domain::BankTransferData::PermataBankTransfer { .. } - | domain::BankTransferData::BcaBankTransfer { .. } - | domain::BankTransferData::BniVaBankTransfer { .. } - | domain::BankTransferData::BriVaBankTransfer { .. } - | domain::BankTransferData::CimbVaBankTransfer { .. } - | domain::BankTransferData::DanamonVaBankTransfer { .. } - | domain::BankTransferData::LocalBankTransfer { .. } - | domain::BankTransferData::InstantBankTransfer {} - | domain::BankTransferData::MandiriVaBankTransfer { .. } => { - Err(errors::ConnectorError::NotImplemented( - connector_util::get_unimplemented_payment_method_error_message("stripe"), + ))), + ), + payment_method_data::BankTransferData::SepaBankTransfer {} => { + Ok(Self::BankTransfer( + StripeBankTransferData::SepaBankTransfer(Box::new(SepaBankTransferData { + payment_method_data_type: StripePaymentMethodType::CustomerBalance, + bank_transfer_type: BankTransferType::EuBankTransfer, + balance_funding_type: BankTransferType::BankTransfers, + payment_method_type: StripePaymentMethodType::CustomerBalance, + country: item.get_billing_country()?, + })), + )) + } + payment_method_data::BankTransferData::BacsBankTransfer { .. } => { + Ok(Self::BankTransfer( + StripeBankTransferData::BacsBankTransfers(Box::new(BacsBankTransferData { + payment_method_data_type: StripePaymentMethodType::CustomerBalance, + bank_transfer_type: BankTransferType::GbBankTransfer, + balance_funding_type: BankTransferType::BankTransfers, + payment_method_type: StripePaymentMethodType::CustomerBalance, + })), + )) + } + payment_method_data::BankTransferData::Pix { .. } + | payment_method_data::BankTransferData::Pse {} + | payment_method_data::BankTransferData::PermataBankTransfer { .. } + | payment_method_data::BankTransferData::BcaBankTransfer { .. } + | payment_method_data::BankTransferData::BniVaBankTransfer { .. } + | payment_method_data::BankTransferData::BriVaBankTransfer { .. } + | payment_method_data::BankTransferData::CimbVaBankTransfer { .. } + | payment_method_data::BankTransferData::DanamonVaBankTransfer { .. } + | payment_method_data::BankTransferData::LocalBankTransfer { .. } + | payment_method_data::BankTransferData::InstantBankTransfer {} + | payment_method_data::BankTransferData::MandiriVaBankTransfer { .. } => { + Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), ) .into()) } }, - domain::PaymentMethodData::MandatePayment - | domain::PaymentMethodData::Crypto(_) - | domain::PaymentMethodData::Reward - | domain::PaymentMethodData::RealTimePayment(_) - | domain::PaymentMethodData::MobilePayment(_) - | domain::PaymentMethodData::GiftCard(_) - | domain::PaymentMethodData::Upi(_) - | domain::PaymentMethodData::CardRedirect(_) - | domain::PaymentMethodData::Voucher(_) - | domain::PaymentMethodData::OpenBanking(_) - | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) - | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { - Err(errors::ConnectorError::NotImplemented( - connector_util::get_unimplemented_payment_method_error_message("stripe"), + PaymentMethodData::MandatePayment + | PaymentMethodData::Crypto(_) + | PaymentMethodData::Reward + | PaymentMethodData::RealTimePayment(_) + | PaymentMethodData::MobilePayment(_) + | PaymentMethodData::GiftCard(_) + | PaymentMethodData::Upi(_) + | PaymentMethodData::CardRedirect(_) + | PaymentMethodData::Voucher(_) + | PaymentMethodData::OpenBanking(_) + | PaymentMethodData::CardToken(_) + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { + Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("stripe"), ))? } } @@ -3966,13 +3927,13 @@ pub struct StripeGpayToken { } pub fn get_bank_transfer_request_data( - req: &types::PaymentsAuthorizeRouterData, - bank_transfer_data: &domain::BankTransferData, + req: &PaymentsAuthorizeRouterData, + bank_transfer_data: &payment_method_data::BankTransferData, amount: MinorUnit, -) -> CustomResult<RequestContent, errors::ConnectorError> { +) -> CustomResult<RequestContent, ConnectorError> { match bank_transfer_data { - domain::BankTransferData::AchBankTransfer { .. } - | domain::BankTransferData::MultibancoBankTransfer { .. } => { + payment_method_data::BankTransferData::AchBankTransfer { .. } + | payment_method_data::BankTransferData::MultibancoBankTransfer { .. } => { let req = ChargesRequest::try_from((req, amount))?; Ok(RequestContent::FormUrlEncoded(Box::new(req))) } @@ -3984,15 +3945,15 @@ pub fn get_bank_transfer_request_data( } pub fn construct_file_upload_request( - file_upload_router_data: types::UploadFileRouterData, -) -> CustomResult<reqwest::multipart::Form, errors::ConnectorError> { + file_upload_router_data: UploadFileRouterData, +) -> CustomResult<reqwest::multipart::Form, ConnectorError> { let request = file_upload_router_data.request; let mut multipart = reqwest::multipart::Form::new(); multipart = multipart.text("purpose", "dispute_evidence"); let file_data = reqwest::multipart::Part::bytes(request.file) .file_name(request.file_key) .mime_str(request.file_type.as_ref()) - .map_err(|_| errors::ConnectorError::RequestEncodingFailed)?; + .map_err(|_| ConnectorError::RequestEncodingFailed)?; multipart = multipart.part("file", file_data); Ok(multipart) } @@ -4060,7 +4021,7 @@ pub struct Evidence { fn mandatory_parameters_for_sepa_bank_debit_mandates( billing_details: &Option<StripeBillingAddress>, is_customer_initiated_mandate_payment: Option<bool>, -) -> Result<StripeBillingAddress, errors::ConnectorError> { +) -> Result<StripeBillingAddress, ConnectorError> { let billing_name = billing_details .clone() .and_then(|billing_data| billing_data.name.clone()); @@ -4070,17 +4031,13 @@ fn mandatory_parameters_for_sepa_bank_debit_mandates( .and_then(|billing_data| billing_data.email.clone()); match is_customer_initiated_mandate_payment { Some(true) => Ok(StripeBillingAddress { - name: Some( - billing_name.ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "billing_name", - })?, - ), + name: Some(billing_name.ok_or(ConnectorError::MissingRequiredField { + field_name: "billing_name", + })?), - email: Some( - billing_email.ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "billing_email", - })?, - ), + email: Some(billing_email.ok_or(ConnectorError::MissingRequiredField { + field_name: "billing_email", + })?), ..StripeBillingAddress::default() }), Some(false) | None => Ok(StripeBillingAddress { @@ -4091,9 +4048,9 @@ fn mandatory_parameters_for_sepa_bank_debit_mandates( } } -impl TryFrom<&types::SubmitEvidenceRouterData> for Evidence { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::SubmitEvidenceRouterData) -> Result<Self, Self::Error> { +impl TryFrom<&SubmitEvidenceRouterData> for Evidence { + type Error = error_stack::Report<ConnectorError>; + fn try_from(item: &SubmitEvidenceRouterData) -> Result<Self, Self::Error> { let submit_evidence_request_data = item.request.clone(); Ok(Self { access_activity_log: submit_evidence_request_data.access_activity_log, @@ -4171,67 +4128,65 @@ fn get_transaction_metadata( meta_data } -impl ForeignTryFrom<(&Option<ErrorDetails>, u16, String)> for types::PaymentsResponseData { - type Error = types::ErrorResponse; - fn foreign_try_from( - (response, http_code, response_id): (&Option<ErrorDetails>, u16, String), - ) -> Result<Self, Self::Error> { - let (code, error_message) = match response { - Some(error_details) => ( - error_details - .code - .to_owned() - .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), - error_details - .message - .to_owned() - .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), - ), - None => ( - consts::NO_ERROR_CODE.to_string(), - consts::NO_ERROR_MESSAGE.to_string(), - ), - }; +fn get_stripe_payments_response_data( + response: &Option<ErrorDetails>, + http_code: u16, + response_id: String, +) -> Box<Result<PaymentsResponseData, hyperswitch_domain_models::router_data::ErrorResponse>> { + let (code, error_message) = match response { + Some(error_details) => ( + error_details + .code + .to_owned() + .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + error_details + .message + .to_owned() + .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + ), + None => ( + consts::NO_ERROR_CODE.to_string(), + consts::NO_ERROR_MESSAGE.to_string(), + ), + }; - Err(types::ErrorResponse { - code, - message: error_message.clone(), - reason: response.clone().and_then(|res| { - res.decline_code - .clone() - .map(|decline_code| { - format!( - "message - {}, decline_code - {}", - error_message, decline_code - ) - }) - .or(Some(error_message.clone())) - }), - status_code: http_code, - attempt_status: None, - connector_transaction_id: Some(response_id), - network_advice_code: response - .as_ref() - .and_then(|res| res.network_advice_code.clone()), - network_decline_code: response - .as_ref() - .and_then(|res| res.network_decline_code.clone()), - network_error_message: response - .as_ref() - .and_then(|res| res.decline_code.clone().or(res.advice_code.clone())), - }) - } + Box::new(Err(hyperswitch_domain_models::router_data::ErrorResponse { + code, + message: error_message.clone(), + reason: response.clone().and_then(|res| { + res.decline_code + .clone() + .map(|decline_code| { + format!( + "message - {}, decline_code - {}", + error_message, decline_code + ) + }) + .or(Some(error_message.clone())) + }), + status_code: http_code, + attempt_status: None, + connector_transaction_id: Some(response_id), + network_advice_code: response + .as_ref() + .and_then(|res| res.network_advice_code.clone()), + network_decline_code: response + .as_ref() + .and_then(|res| res.network_decline_code.clone()), + network_error_message: response + .as_ref() + .and_then(|res| res.decline_code.clone().or(res.advice_code.clone())), + })) } pub(super) fn transform_headers_for_connect_platform( - charge_type: api::enums::PaymentChargeType, + charge_type: PaymentChargeType, transfer_account_id: String, - header: &mut Vec<(String, services::request::Maskable<String>)>, + header: &mut Vec<(String, Maskable<String>)>, ) { - if let api::enums::PaymentChargeType::Stripe(api::enums::StripeChargeType::Direct) = charge_type - { + if let PaymentChargeType::Stripe(StripeChargeType::Direct) = charge_type { let mut customer_account_header = vec![( - headers::STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(), + STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(), transfer_account_id.into_masked(), )]; header.append(&mut customer_account_header); @@ -4243,7 +4198,7 @@ pub fn construct_charge_response<T>( request: &T, ) -> Option<common_types::payments::ConnectorChargeResponseData> where - T: connector_util::SplitPaymentData, + T: SplitPaymentData, { let charge_request = request.get_split_payment_data(); if let Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment( @@ -4269,15 +4224,13 @@ where #[cfg(test)] mod test_validate_shipping_address_against_payment_method { #![allow(clippy::unwrap_used)] - use api_models::enums::CountryAlpha2; + use common_enums::CountryAlpha2; + use hyperswitch_interfaces::errors::ConnectorError; use masking::Secret; - use crate::{ - connector::stripe::transformers::{ - validate_shipping_address_against_payment_method, StripePaymentMethodType, - StripeShippingAddress, - }, - core::errors, + use crate::connectors::stripe::transformers::{ + validate_shipping_address_against_payment_method, StripePaymentMethodType, + StripeShippingAddress, }; #[test] @@ -4403,8 +4356,8 @@ mod test_validate_shipping_address_against_payment_method { } } - fn get_missing_fields(connector_error: &errors::ConnectorError) -> Vec<&'static str> { - if let errors::ConnectorError::MissingRequiredFields { field_names } = connector_error { + fn get_missing_fields(connector_error: &ConnectorError) -> Vec<&'static str> { + if let ConnectorError::MissingRequiredFields { field_names } = connector_error { return field_names.to_vec(); } diff --git a/crates/router/src/connector/stripe/transformers/connect.rs b/crates/hyperswitch_connectors/src/connectors/stripe/transformers/connect.rs similarity index 86% rename from crates/router/src/connector/stripe/transformers/connect.rs rename to crates/hyperswitch_connectors/src/connectors/stripe/transformers/connect.rs index 9852338038c..bb8d4509dac 100644 --- a/crates/router/src/connector/stripe/transformers/connect.rs +++ b/crates/hyperswitch_connectors/src/connectors/stripe/transformers/connect.rs @@ -1,17 +1,17 @@ use api_models; -use common_utils::pii::Email; +use common_enums::{enums, Currency}; +use common_utils::{ext_traits::OptionExt as _, pii::Email}; use error_stack::ResultExt; +use hyperswitch_domain_models::types::{PayoutsResponseData, PayoutsRouterData}; +use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; use super::ErrorDetails; use crate::{ - connector::utils::{PayoutsData, RouterData}, - core::{errors, payments::CustomerDetailsExt}, - types::{self, storage::enums, PayoutIndividualDetailsExt}, - utils::OptionExt, + types::{PayoutIndividualDetailsExt as _, PayoutsResponseRouterData}, + utils::{CustomerDetails as _, PayoutsData as _, RouterData}, }; - type Error = error_stack::Report<errors::ConnectorError>; #[derive(Clone, Debug, Deserialize, Serialize)] @@ -33,7 +33,7 @@ pub struct StripeConnectErrorResponse { #[derive(Clone, Debug, Serialize)] pub struct StripeConnectPayoutCreateRequest { amount: i64, - currency: enums::Currency, + currency: Currency, destination: String, transfer_group: String, } @@ -56,7 +56,7 @@ pub struct TransferReversals { #[derive(Clone, Debug, Serialize)] pub struct StripeConnectPayoutFulfillRequest { amount: i64, - currency: enums::Currency, + currency: Currency, } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -190,7 +190,7 @@ pub struct RecipientBankAccountRequest { #[serde(rename = "external_account[country]")] external_account_country: enums::CountryAlpha2, #[serde(rename = "external_account[currency]")] - external_account_currency: enums::Currency, + external_account_currency: Currency, #[serde(rename = "external_account[account_holder_name]")] external_account_account_holder_name: Secret<String>, #[serde(rename = "external_account[account_number]")] @@ -207,9 +207,9 @@ pub struct StripeConnectRecipientAccountCreateResponse { } // Payouts create/transfer request transform -impl<F> TryFrom<&types::PayoutsRouterData<F>> for StripeConnectPayoutCreateRequest { +impl<F> TryFrom<&PayoutsRouterData<F>> for StripeConnectPayoutCreateRequest { type Error = Error; - fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> { + fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> { let request = item.request.to_owned(); let connector_customer_id = item.get_connector_customer_id()?; Ok(Self { @@ -222,17 +222,17 @@ impl<F> TryFrom<&types::PayoutsRouterData<F>> for StripeConnectPayoutCreateReque } // Payouts create response transform -impl<F> TryFrom<types::PayoutsResponseRouterData<F, StripeConnectPayoutCreateResponse>> - for types::PayoutsRouterData<F> +impl<F> TryFrom<PayoutsResponseRouterData<F, StripeConnectPayoutCreateResponse>> + for PayoutsRouterData<F> { type Error = Error; fn try_from( - item: types::PayoutsResponseRouterData<F, StripeConnectPayoutCreateResponse>, + item: PayoutsResponseRouterData<F, StripeConnectPayoutCreateResponse>, ) -> Result<Self, Self::Error> { let response: StripeConnectPayoutCreateResponse = item.response; Ok(Self { - response: Ok(types::PayoutsResponseData { + response: Ok(PayoutsResponseData { status: Some(enums::PayoutStatus::RequiresFulfillment), connector_payout_id: Some(response.id), payout_eligible: None, @@ -246,9 +246,9 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, StripeConnectPayoutCreateRes } // Payouts fulfill request transform -impl<F> TryFrom<&types::PayoutsRouterData<F>> for StripeConnectPayoutFulfillRequest { +impl<F> TryFrom<&PayoutsRouterData<F>> for StripeConnectPayoutFulfillRequest { type Error = Error; - fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> { + fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> { let request = item.request.to_owned(); Ok(Self { amount: request.amount, @@ -258,17 +258,17 @@ impl<F> TryFrom<&types::PayoutsRouterData<F>> for StripeConnectPayoutFulfillRequ } // Payouts fulfill response transform -impl<F> TryFrom<types::PayoutsResponseRouterData<F, StripeConnectPayoutFulfillResponse>> - for types::PayoutsRouterData<F> +impl<F> TryFrom<PayoutsResponseRouterData<F, StripeConnectPayoutFulfillResponse>> + for PayoutsRouterData<F> { type Error = Error; fn try_from( - item: types::PayoutsResponseRouterData<F, StripeConnectPayoutFulfillResponse>, + item: PayoutsResponseRouterData<F, StripeConnectPayoutFulfillResponse>, ) -> Result<Self, Self::Error> { let response: StripeConnectPayoutFulfillResponse = item.response; Ok(Self { - response: Ok(types::PayoutsResponseData { + response: Ok(PayoutsResponseData { status: Some(enums::PayoutStatus::from(response.status)), connector_payout_id: Some(response.id), payout_eligible: None, @@ -282,9 +282,9 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, StripeConnectPayoutFulfillRe } // Payouts reversal request transform -impl<F> TryFrom<&types::PayoutsRouterData<F>> for StripeConnectReversalRequest { +impl<F> TryFrom<&PayoutsRouterData<F>> for StripeConnectReversalRequest { type Error = Error; - fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> { + fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> { Ok(Self { amount: item.request.amount, }) @@ -292,15 +292,15 @@ impl<F> TryFrom<&types::PayoutsRouterData<F>> for StripeConnectReversalRequest { } // Payouts reversal response transform -impl<F> TryFrom<types::PayoutsResponseRouterData<F, StripeConnectReversalResponse>> - for types::PayoutsRouterData<F> +impl<F> TryFrom<PayoutsResponseRouterData<F, StripeConnectReversalResponse>> + for PayoutsRouterData<F> { type Error = Error; fn try_from( - item: types::PayoutsResponseRouterData<F, StripeConnectReversalResponse>, + item: PayoutsResponseRouterData<F, StripeConnectReversalResponse>, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(types::PayoutsResponseData { + response: Ok(PayoutsResponseData { status: Some(enums::PayoutStatus::Cancelled), connector_payout_id: item.data.request.connector_payout_id.clone(), payout_eligible: None, @@ -314,12 +314,12 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, StripeConnectReversalRespons } // Recipient creation request transform -impl<F> TryFrom<&types::PayoutsRouterData<F>> for StripeConnectRecipientCreateRequest { +impl<F> TryFrom<&PayoutsRouterData<F>> for StripeConnectRecipientCreateRequest { type Error = Error; - fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> { + fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> { let request = item.request.to_owned(); let customer_details = request.get_customer_details()?; - let customer_email = customer_details.get_email()?; + let customer_email = customer_details.get_customer_email()?; let address = item.get_billing_address()?.clone(); let payout_vendor_details = request.get_vendor_details()?; let (vendor_details, individual_details) = ( @@ -366,16 +366,16 @@ impl<F> TryFrom<&types::PayoutsRouterData<F>> for StripeConnectRecipientCreateRe } // Recipient creation response transform -impl<F> TryFrom<types::PayoutsResponseRouterData<F, StripeConnectRecipientCreateResponse>> - for types::PayoutsRouterData<F> +impl<F> TryFrom<PayoutsResponseRouterData<F, StripeConnectRecipientCreateResponse>> + for PayoutsRouterData<F> { type Error = Error; fn try_from( - item: types::PayoutsResponseRouterData<F, StripeConnectRecipientCreateResponse>, + item: PayoutsResponseRouterData<F, StripeConnectRecipientCreateResponse>, ) -> Result<Self, Self::Error> { let response: StripeConnectRecipientCreateResponse = item.response; Ok(Self { - response: Ok(types::PayoutsResponseData { + response: Ok(PayoutsResponseData { status: Some(enums::PayoutStatus::RequiresVendorAccountCreation), connector_payout_id: Some(response.id), payout_eligible: None, @@ -389,13 +389,13 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, StripeConnectRecipientCreate } // Recipient account's creation request -impl<F> TryFrom<&types::PayoutsRouterData<F>> for StripeConnectRecipientAccountCreateRequest { +impl<F> TryFrom<&PayoutsRouterData<F>> for StripeConnectRecipientAccountCreateRequest { type Error = Error; - fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> { + fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> { let request = item.request.to_owned(); let payout_method_data = item.get_payout_method_data()?; let customer_details = request.get_customer_details()?; - let customer_name = customer_details.get_name()?; + let customer_name = customer_details.get_customer_name()?; let payout_vendor_details = request.get_vendor_details()?; match payout_method_data { api_models::payouts::PayoutMethodData::Card(_) => { @@ -450,15 +450,15 @@ impl<F> TryFrom<&types::PayoutsRouterData<F>> for StripeConnectRecipientAccountC } // Recipient account's creation response -impl<F> TryFrom<types::PayoutsResponseRouterData<F, StripeConnectRecipientAccountCreateResponse>> - for types::PayoutsRouterData<F> +impl<F> TryFrom<PayoutsResponseRouterData<F, StripeConnectRecipientAccountCreateResponse>> + for PayoutsRouterData<F> { type Error = Error; fn try_from( - item: types::PayoutsResponseRouterData<F, StripeConnectRecipientAccountCreateResponse>, + item: PayoutsResponseRouterData<F, StripeConnectRecipientAccountCreateResponse>, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(types::PayoutsResponseData { + response: Ok(PayoutsResponseData { status: Some(enums::PayoutStatus::RequiresCreation), connector_payout_id: item.data.request.connector_payout_id.clone(), payout_eligible: None, diff --git a/crates/hyperswitch_connectors/src/constants.rs b/crates/hyperswitch_connectors/src/constants.rs index 47ef0be4ec3..faeb9e2c0a5 100644 --- a/crates/hyperswitch_connectors/src/constants.rs +++ b/crates/hyperswitch_connectors/src/constants.rs @@ -27,6 +27,7 @@ pub(crate) mod headers { pub(crate) const X_API_KEY: &str = "X-Api-Key"; pub(crate) const CORRELATION_ID: &str = "Correlation-Id"; pub(crate) const WP_API_VERSION: &str = "WP-Api-Version"; + pub(crate) const STRIPE_COMPATIBLE_CONNECT_ACCOUNT: &str = "Stripe-Account"; pub(crate) const SOURCE: &str = "Source"; pub(crate) const USER_AGENT: &str = "User-Agent"; pub(crate) const KEY: &str = "key"; diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 3708e02cdc3..c6d50f7eda5 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -194,6 +194,7 @@ default_imp_for_authorize_session_token!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::UnifiedAuthenticationService, @@ -309,6 +310,7 @@ default_imp_for_calculate_tax!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Threedsecureio, connectors::Thunes, @@ -389,6 +391,7 @@ default_imp_for_session_update!( connectors::Riskified, connectors::Shift4, connectors::Signifyd, + connectors::Stripe, connectors::Stax, connectors::Square, connectors::Stripebilling, @@ -505,6 +508,7 @@ default_imp_for_post_session_tokens!( connectors::Signifyd, connectors::Square, connectors::Stax, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Mifinity, @@ -748,6 +752,7 @@ default_imp_for_complete_authorize!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -862,6 +867,7 @@ default_imp_for_incremental_authorization!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -1176,6 +1182,7 @@ default_imp_for_pre_processing_steps!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -1289,6 +1296,7 @@ default_imp_for_post_processing_steps!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -1405,6 +1413,7 @@ default_imp_for_approve!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -1521,6 +1530,7 @@ default_imp_for_reject!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -1636,6 +1646,7 @@ default_imp_for_webhook_source_verification!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -1751,6 +1762,7 @@ default_imp_for_accept_dispute!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -1979,6 +1991,7 @@ default_imp_for_defend_dispute!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -2431,6 +2444,7 @@ default_imp_for_payouts_retrieve!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -2546,6 +2560,7 @@ default_imp_for_payouts_eligibility!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -2885,6 +2900,7 @@ default_imp_for_payouts_quote!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -3232,6 +3248,7 @@ default_imp_for_frm_sale!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -3348,6 +3365,7 @@ default_imp_for_frm_checkout!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -3464,6 +3482,7 @@ default_imp_for_frm_transaction!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -3580,6 +3599,7 @@ default_imp_for_frm_fulfillment!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -3694,6 +3714,7 @@ default_imp_for_frm_record_return!( connectors::Recurly, connectors::Redsys, connectors::Shift4, + connectors::Stripe, connectors::Stax, connectors::Square, connectors::Stripebilling, @@ -3808,6 +3829,7 @@ default_imp_for_revoking_mandates!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -3920,6 +3942,7 @@ default_imp_for_uas_pre_authentication!( connectors::Riskified, connectors::Shift4, connectors::Signifyd, + connectors::Stripe, connectors::Stax, connectors::Square, connectors::Stripebilling, @@ -4033,6 +4056,7 @@ default_imp_for_uas_post_authentication!( connectors::Riskified, connectors::Shift4, connectors::Signifyd, + connectors::Stripe, connectors::Stax, connectors::Square, connectors::Stripebilling, @@ -4149,6 +4173,7 @@ default_imp_for_uas_authentication_confirmation!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -4254,6 +4279,7 @@ default_imp_for_connector_request_id!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -4362,6 +4388,7 @@ default_imp_for_fraud_check!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -4500,6 +4527,7 @@ default_imp_for_connector_authentication!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, @@ -4612,6 +4640,7 @@ default_imp_for_uas_authentication!( connectors::Signifyd, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Taxjar, connectors::Threedsecureio, @@ -4718,6 +4747,7 @@ default_imp_for_revenue_recovery! { connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -4834,6 +4864,7 @@ default_imp_for_billing_connector_payment_sync!( connectors::Riskified, connectors::Shift4, connectors::Signifyd, + connectors::Stripe, connectors::Stax, connectors::Square, connectors::Taxjar, @@ -4949,6 +4980,7 @@ default_imp_for_revenue_recovery_record_back!( connectors::Riskified, connectors::Shift4, connectors::Signifyd, + connectors::Stripe, connectors::Stax, connectors::Square, connectors::Taxjar, @@ -5066,6 +5098,7 @@ default_imp_for_billing_connector_invoice_sync!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripe, connectors::Stripebilling, connectors::Threedsecureio, connectors::Taxjar, diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index 3e5d37a44e4..e6b0a24574f 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -318,6 +318,7 @@ default_imp_for_new_connector_integration_payment!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -435,6 +436,7 @@ default_imp_for_new_connector_integration_refund!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -547,6 +549,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -664,6 +667,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -780,6 +784,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -897,6 +902,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -1024,6 +1030,7 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -1143,6 +1150,7 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -1262,6 +1270,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -1381,6 +1390,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -1500,6 +1510,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -1619,6 +1630,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -1738,6 +1750,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -1857,6 +1870,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -1976,6 +1990,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -2093,6 +2108,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -2212,6 +2228,7 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -2331,6 +2348,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -2450,6 +2468,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -2569,6 +2588,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -2688,6 +2708,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -2803,6 +2824,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Stripebilling, connectors::Taxjar, @@ -2890,6 +2912,7 @@ default_imp_for_new_connector_integration_frm!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Taxjar, connectors::Threedsecureio, @@ -3004,6 +3027,7 @@ default_imp_for_new_connector_integration_connector_authentication!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Taxjar, connectors::Threedsecureio, @@ -3110,6 +3134,7 @@ default_imp_for_new_connector_integration_revenue_recovery!( connectors::Shift4, connectors::Signifyd, connectors::Stax, + connectors::Stripe, connectors::Square, connectors::Taxjar, connectors::Threedsecureio, diff --git a/crates/hyperswitch_connectors/src/types.rs b/crates/hyperswitch_connectors/src/types.rs index a072317ea70..f6673e7dc4c 100644 --- a/crates/hyperswitch_connectors/src/types.rs +++ b/crates/hyperswitch_connectors/src/types.rs @@ -9,7 +9,7 @@ use hyperswitch_domain_models::{ Authentication, PostAuthentication, PreAuthentication, PreAuthenticationVersionCall, }, Accept, AccessTokenAuth, Authorize, Capture, Defend, Evidence, PSync, PostProcessing, - PreProcessing, Session, Upload, Void, + PreProcessing, Retrieve, Session, Upload, Void, }, router_request_types::{ authentication::{ @@ -19,11 +19,12 @@ use hyperswitch_domain_models::{ AcceptDisputeRequestData, AccessTokenRequestData, DefendDisputeRequestData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsPostProcessingData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, RefundsData, - SubmitEvidenceRequestData, UploadFileRequestData, + RetrieveFileRequestData, SubmitEvidenceRequestData, UploadFileRequestData, }, router_response_types::{ AcceptDisputeResponse, AuthenticationResponseData, DefendDisputeResponse, - PaymentsResponseData, RefundsResponseData, SubmitEvidenceResponse, UploadFileResponse, + PaymentsResponseData, RefundsResponseData, RetrieveFileResponse, SubmitEvidenceResponse, + UploadFileResponse, }, }; #[cfg(feature = "frm")] @@ -141,3 +142,24 @@ pub(crate) type FrmRecordReturnType = #[cfg(feature = "frm")] pub(crate) type FrmSaleType = dyn ConnectorIntegration<Sale, FraudCheckSaleData, FraudCheckResponseData>; + +pub(crate) type RetrieveFileRouterData = + RouterData<Retrieve, RetrieveFileRequestData, RetrieveFileResponse>; + +#[cfg(feature = "payouts")] +pub(crate) trait PayoutIndividualDetailsExt { + type Error; + fn get_external_account_account_holder_type(&self) -> Result<String, Self::Error>; +} + +#[cfg(feature = "payouts")] +impl PayoutIndividualDetailsExt for api_models::payouts::PayoutIndividualDetails { + type Error = error_stack::Report<hyperswitch_interfaces::errors::ConnectorError>; + fn get_external_account_account_holder_type(&self) -> Result<String, Self::Error> { + self.external_account_account_holder_type + .clone() + .ok_or_else(crate::utils::missing_field_err( + "external_account_account_holder_type", + )) + } +} diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index 5a1b320ea14..0f336df390b 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -53,11 +53,12 @@ use hyperswitch_domain_models::{ RouterData as ConnectorRouterData, }, router_request_types::{ - AuthenticationData, BrowserInformation, CompleteAuthorizeData, ConnectorCustomerData, - MandateRevokeRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, - PaymentsCancelData, PaymentsCaptureData, PaymentsPostSessionTokensData, - PaymentsPreProcessingData, PaymentsSyncData, RefundsData, ResponseId, - SetupMandateRequestData, + AuthenticationData, AuthoriseIntegrityObject, BrowserInformation, CaptureIntegrityObject, + CompleteAuthorizeData, ConnectorCustomerData, MandateRevokeRequestData, + PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, + PaymentsCaptureData, PaymentsPostSessionTokensData, PaymentsPreProcessingData, + PaymentsSyncData, RefundIntegrityObject, RefundsData, ResponseId, SetupMandateRequestData, + SyncIntegrityObject, }, router_response_types::{CaptureSyncResponse, PaymentsResponseData}, types::{OrderDetailsWithAmount, SetupMandateRouterData}, @@ -2503,13 +2504,13 @@ macro_rules! get_formatted_date_time { #[macro_export] macro_rules! unimplemented_payment_method { ($payment_method:expr, $connector:expr) => { - errors::ConnectorError::NotImplemented(format!( + hyperswitch_interfaces::errors::ConnectorError::NotImplemented(format!( "{} through {}", $payment_method, $connector )) }; ($payment_method:expr, $flow:expr, $connector:expr) => { - errors::ConnectorError::NotImplemented(format!( + hyperswitch_interfaces::errors::ConnectorError::NotImplemented(format!( "{} {} through {}", $payment_method, $flow, $connector )) @@ -6317,3 +6318,105 @@ impl FraudCheckRecordReturnRequest for FraudCheckRecordReturnData { self.currency.ok_or_else(missing_field_err("currency")) } } + +pub trait SplitPaymentData { + fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest>; +} + +impl SplitPaymentData for PaymentsCaptureData { + fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> { + None + } +} + +impl SplitPaymentData for PaymentsAuthorizeData { + fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> { + self.split_payments.clone() + } +} + +impl SplitPaymentData for PaymentsSyncData { + fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> { + self.split_payments.clone() + } +} + +impl SplitPaymentData for PaymentsCancelData { + fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> { + None + } +} + +impl SplitPaymentData for SetupMandateRequestData { + fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> { + None + } +} + +pub fn get_refund_integrity_object<T>( + amount_convertor: &dyn AmountConvertor<Output = T>, + refund_amount: T, + currency: String, +) -> Result<RefundIntegrityObject, error_stack::Report<errors::ConnectorError>> { + let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str()) + .change_context(errors::ConnectorError::ParsingFailed)?; + + let refund_amount_in_minor_unit = + convert_back_amount_to_minor_units(amount_convertor, refund_amount, currency_enum)?; + + Ok(RefundIntegrityObject { + currency: currency_enum, + refund_amount: refund_amount_in_minor_unit, + }) +} + +pub fn get_capture_integrity_object<T>( + amount_convertor: &dyn AmountConvertor<Output = T>, + capture_amount: Option<T>, + currency: String, +) -> Result<CaptureIntegrityObject, error_stack::Report<errors::ConnectorError>> { + let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str()) + .change_context(errors::ConnectorError::ParsingFailed)?; + + let capture_amount_in_minor_unit = capture_amount + .map(|amount| convert_back_amount_to_minor_units(amount_convertor, amount, currency_enum)) + .transpose()?; + + Ok(CaptureIntegrityObject { + capture_amount: capture_amount_in_minor_unit, + currency: currency_enum, + }) +} + +pub fn get_sync_integrity_object<T>( + amount_convertor: &dyn AmountConvertor<Output = T>, + amount: T, + currency: String, +) -> Result<SyncIntegrityObject, error_stack::Report<errors::ConnectorError>> { + let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str()) + .change_context(errors::ConnectorError::ParsingFailed)?; + let amount_in_minor_unit = + convert_back_amount_to_minor_units(amount_convertor, amount, currency_enum)?; + + Ok(SyncIntegrityObject { + amount: Some(amount_in_minor_unit), + currency: Some(currency_enum), + }) +} + +pub fn get_authorise_integrity_object<T>( + amount_convertor: &dyn AmountConvertor<Output = T>, + amount: T, + currency: String, +) -> Result<AuthoriseIntegrityObject, error_stack::Report<errors::ConnectorError>> { + let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str()) + .change_context(errors::ConnectorError::ParsingFailed)?; + + let amount_in_minor_unit = + convert_back_amount_to_minor_units(amount_convertor, amount, currency_enum)?; + + Ok(AuthoriseIntegrityObject { + amount: amount_in_minor_unit, + currency: currency_enum, + }) +} diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index 51482cb09a1..1006b0ded37 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -1,6 +1,5 @@ #[cfg(feature = "dummy_connector")] pub mod dummyconnector; -pub mod stripe; pub mod utils; pub use hyperswitch_connectors::connectors::{ @@ -31,9 +30,10 @@ pub use hyperswitch_connectors::connectors::{ plaid::Plaid, powertranz, powertranz::Powertranz, prophetpay, prophetpay::Prophetpay, rapyd, rapyd::Rapyd, razorpay, razorpay::Razorpay, recurly, recurly::Recurly, redsys, redsys::Redsys, riskified, riskified::Riskified, shift4, shift4::Shift4, signifyd, signifyd::Signifyd, square, - square::Square, stax, stax::Stax, stripebilling, stripebilling::Stripebilling, taxjar, - taxjar::Taxjar, threedsecureio, threedsecureio::Threedsecureio, thunes, thunes::Thunes, - trustpay, trustpay::Trustpay, tsys, tsys::Tsys, unified_authentication_service, + square::Square, stax, stax::Stax, stripe, stripe::Stripe, stripebilling, + stripebilling::Stripebilling, taxjar, taxjar::Taxjar, threedsecureio, + threedsecureio::Threedsecureio, thunes, thunes::Thunes, trustpay, trustpay::Trustpay, tsys, + tsys::Tsys, unified_authentication_service, unified_authentication_service::UnifiedAuthenticationService, vgs, vgs::Vgs, volt, volt::Volt, wellsfargo, wellsfargo::Wellsfargo, wellsfargopayout, wellsfargopayout::Wellsfargopayout, wise, wise::Wise, worldline, worldline::Worldline, worldpay, worldpay::Worldpay, worldpayxml, @@ -42,4 +42,3 @@ pub use hyperswitch_connectors::connectors::{ #[cfg(feature = "dummy_connector")] pub use self::dummyconnector::DummyConnector; -pub use self::stripe::Stripe; diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index f06433c545e..9a64dfdaa6a 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -21,12 +21,7 @@ use common_utils::{ use diesel_models::{enums, types::OrderDetailsWithAmount}; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ - network_tokenization::NetworkTokenNumber, - payments::payment_attempt::PaymentAttempt, - router_request_types::{ - AuthoriseIntegrityObject, CaptureIntegrityObject, RefundIntegrityObject, - SyncIntegrityObject, - }, + network_tokenization::NetworkTokenNumber, payments::payment_attempt::PaymentAttempt, }; use masking::{Deserialize, ExposeInterface, Secret}; use once_cell::sync::Lazy; @@ -750,7 +745,6 @@ impl PaymentsCaptureRequestData for types::PaymentsCaptureData { self.capture_method.to_owned() } } - pub trait SplitPaymentData { fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest>; } @@ -2755,73 +2749,6 @@ pub fn convert_back_amount_to_minor_units<T>( .change_context(errors::ConnectorError::AmountConversionFailed) } -pub fn get_authorise_integrity_object<T>( - amount_convertor: &dyn AmountConvertor<Output = T>, - amount: T, - currency: String, -) -> Result<AuthoriseIntegrityObject, error_stack::Report<errors::ConnectorError>> { - let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str()) - .change_context(errors::ConnectorError::ParsingFailed)?; - - let amount_in_minor_unit = - convert_back_amount_to_minor_units(amount_convertor, amount, currency_enum)?; - - Ok(AuthoriseIntegrityObject { - amount: amount_in_minor_unit, - currency: currency_enum, - }) -} - -pub fn get_sync_integrity_object<T>( - amount_convertor: &dyn AmountConvertor<Output = T>, - amount: T, - currency: String, -) -> Result<SyncIntegrityObject, error_stack::Report<errors::ConnectorError>> { - let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str()) - .change_context(errors::ConnectorError::ParsingFailed)?; - let amount_in_minor_unit = - convert_back_amount_to_minor_units(amount_convertor, amount, currency_enum)?; - - Ok(SyncIntegrityObject { - amount: Some(amount_in_minor_unit), - currency: Some(currency_enum), - }) -} - -pub fn get_capture_integrity_object<T>( - amount_convertor: &dyn AmountConvertor<Output = T>, - capture_amount: Option<T>, - currency: String, -) -> Result<CaptureIntegrityObject, error_stack::Report<errors::ConnectorError>> { - let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str()) - .change_context(errors::ConnectorError::ParsingFailed)?; - - let capture_amount_in_minor_unit = capture_amount - .map(|amount| convert_back_amount_to_minor_units(amount_convertor, amount, currency_enum)) - .transpose()?; - - Ok(CaptureIntegrityObject { - capture_amount: capture_amount_in_minor_unit, - currency: currency_enum, - }) -} - -pub fn get_refund_integrity_object<T>( - amount_convertor: &dyn AmountConvertor<Output = T>, - refund_amount: T, - currency: String, -) -> Result<RefundIntegrityObject, error_stack::Report<errors::ConnectorError>> { - let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str()) - .change_context(errors::ConnectorError::ParsingFailed)?; - - let refund_amount_in_minor_unit = - convert_back_amount_to_minor_units(amount_convertor, refund_amount, currency_enum)?; - - Ok(RefundIntegrityObject { - currency: currency_enum, - refund_amount: refund_amount_in_minor_unit, - }) -} pub trait NetworkTokenData { fn get_card_issuer(&self) -> Result<CardIssuer, Error>; fn get_expiry_year_4_digit(&self) -> Secret<String>; diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index f5350e81d5f..d166bc41a24 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -96,7 +96,6 @@ use crate::core::routing::helpers as routing_helpers; use crate::types::api::convert_connector_data_to_routable_connectors; use crate::{ configs::settings::{ApplePayPreDecryptFlow, PaymentMethodTypeTokenFilter}, - connector::utils::missing_field_err, consts, core::{ errors::{self, CustomResult, RouterResponse, RouterResult}, @@ -5503,22 +5502,6 @@ pub struct IncrementalAuthorizationDetails { pub authorization_id: Option<String>, } -pub trait CustomerDetailsExt { - type Error; - fn get_name(&self) -> Result<Secret<String, masking::WithType>, Self::Error>; - fn get_email(&self) -> Result<pii::Email, Self::Error>; -} - -impl CustomerDetailsExt for CustomerDetails { - type Error = error_stack::Report<errors::ConnectorError>; - fn get_name(&self) -> Result<Secret<String, masking::WithType>, Self::Error> { - self.name.clone().ok_or_else(missing_field_err("name")) - } - fn get_email(&self) -> Result<pii::Email, Self::Error> { - self.email.clone().ok_or_else(missing_field_err("email")) - } -} - pub async fn get_payment_link_response_from_id( state: &SessionState, payment_link_id: &str, diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index ff52833cd49..2e4864c80ca 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -190,21 +190,6 @@ pub trait Feature<F, T> { } } -macro_rules! default_imp_for_complete_authorize { - ($($path:ident::$connector:ident),*) => { - $( - impl api::PaymentsCompleteAuthorize for $path::$connector {} - impl - services::ConnectorIntegration< - api::CompleteAuthorize, - types::CompleteAuthorizeData, - types::PaymentsResponseData, - > for $path::$connector - {} - )* - }; -} - #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PaymentsCompleteAuthorize for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] @@ -217,22 +202,6 @@ impl<const T: u8> { } -default_imp_for_complete_authorize!(connector::Stripe); -macro_rules! default_imp_for_webhook_source_verification { - ($($path:ident::$connector:ident),*) => { - $( - impl api::ConnectorVerifyWebhookSource for $path::$connector {} - impl - services::ConnectorIntegration< - api::VerifyWebhookSource, - types::VerifyWebhookSourceRequestData, - types::VerifyWebhookSourceResponseData, - > for $path::$connector - {} - )* - }; -} - #[cfg(feature = "dummy_connector")] impl<const T: u8> api::ConnectorVerifyWebhookSource for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] @@ -244,22 +213,6 @@ impl<const T: u8> > for connector::DummyConnector<T> { } -default_imp_for_webhook_source_verification!(connector::Stripe); - -macro_rules! default_imp_for_create_customer { - ($($path:ident::$connector:ident),*) => { - $( - impl api::ConnectorCustomer for $path::$connector {} - impl - services::ConnectorIntegration< - api::CreateConnectorCustomer, - types::ConnectorCustomerData, - types::PaymentsResponseData, - > for $path::$connector - {} - )* - }; -} #[cfg(feature = "dummy_connector")] impl<const T: u8> api::ConnectorCustomer for connector::DummyConnector<T> {} @@ -273,25 +226,6 @@ impl<const T: u8> { } -default_imp_for_create_customer!(); - -macro_rules! default_imp_for_connector_redirect_response { - ($($path:ident::$connector:ident),*) => { - $( - impl services::ConnectorRedirectResponse for $path::$connector { - fn get_flow_type( - &self, - _query_params: &str, - _json_payload: Option<serde_json::Value>, - _action: services::PaymentAction - ) -> CustomResult<payments::CallConnectorAction, ConnectorError> { - Ok(payments::CallConnectorAction::Trigger) - } - } - )* - }; -} - #[cfg(feature = "dummy_connector")] impl<const T: u8> services::ConnectorRedirectResponse for connector::DummyConnector<T> { fn get_flow_type( @@ -304,37 +238,9 @@ impl<const T: u8> services::ConnectorRedirectResponse for connector::DummyConnec } } -default_imp_for_connector_redirect_response!(); - -macro_rules! default_imp_for_connector_request_id { - ($($path:ident::$connector:ident),*) => { - $( - impl api::ConnectorTransactionId for $path::$connector {} - )* - }; -} - #[cfg(feature = "dummy_connector")] impl<const T: u8> api::ConnectorTransactionId for connector::DummyConnector<T> {} -default_imp_for_connector_request_id!(connector::Stripe); - -macro_rules! default_imp_for_accept_dispute { - ($($path:ident::$connector:ident),*) => { - $( - impl api::Dispute for $path::$connector {} - impl api::AcceptDispute for $path::$connector {} - impl - services::ConnectorIntegration< - api::Accept, - types::AcceptDisputeRequestData, - types::AcceptDisputeResponse, - > for $path::$connector - {} - )* - }; -} - #[cfg(feature = "dummy_connector")] impl<const T: u8> api::Dispute for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] @@ -349,32 +255,6 @@ impl<const T: u8> { } -default_imp_for_accept_dispute!(connector::Stripe); - -macro_rules! default_imp_for_file_upload { - ($($path:ident::$connector:ident),*) => { - $( - impl api::FileUpload for $path::$connector {} - impl api::UploadFile for $path::$connector {} - impl - services::ConnectorIntegration< - api::Upload, - types::UploadFileRequestData, - types::UploadFileResponse, - > for $path::$connector - {} - impl api::RetrieveFile for $path::$connector {} - impl - services::ConnectorIntegration< - api::Retrieve, - types::RetrieveFileRequestData, - types::RetrieveFileResponse, - > for $path::$connector - {} - )* - }; -} - #[cfg(feature = "dummy_connector")] impl<const T: u8> api::FileUpload for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] @@ -400,23 +280,6 @@ impl<const T: u8> { } -default_imp_for_file_upload!(); - -macro_rules! default_imp_for_submit_evidence { - ($($path:ident::$connector:ident),*) => { - $( - impl api::SubmitEvidence for $path::$connector {} - impl - services::ConnectorIntegration< - api::Evidence, - types::SubmitEvidenceRequestData, - types::SubmitEvidenceResponse, - > for $path::$connector - {} - )* - }; -} - #[cfg(feature = "dummy_connector")] impl<const T: u8> api::SubmitEvidence for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] @@ -429,23 +292,6 @@ impl<const T: u8> { } -default_imp_for_submit_evidence!(); - -macro_rules! default_imp_for_defend_dispute { - ($($path:ident::$connector:ident),*) => { - $( - impl api::DefendDispute for $path::$connector {} - impl - services::ConnectorIntegration< - api::Defend, - types::DefendDisputeRequestData, - types::DefendDisputeResponse, - > for $path::$connector - {} - )* - }; -} - #[cfg(feature = "dummy_connector")] impl<const T: u8> api::DefendDispute for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] @@ -458,38 +304,6 @@ impl<const T: u8> { } -default_imp_for_defend_dispute!(connector::Stripe); - -macro_rules! default_imp_for_pre_processing_steps{ - ($($path:ident::$connector:ident),*)=> { - $( - impl api::PaymentsPreProcessing for $path::$connector {} - impl - services::ConnectorIntegration< - api::PreProcessing, - types::PaymentsPreProcessingData, - types::PaymentsResponseData, - > for $path::$connector - {} - )* - }; -} - -macro_rules! default_imp_for_post_processing_steps{ - ($($path:ident::$connector:ident),*)=> { - $( - impl api::PaymentsPostProcessing for $path::$connector {} - impl - services::ConnectorIntegration< - api::PostProcessing, - types::PaymentsPostProcessingData, - types::PaymentsResponseData, - > for $path::$connector - {} - )* - }; -} - #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PaymentsPreProcessing for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] @@ -502,8 +316,6 @@ impl<const T: u8> { } -default_imp_for_pre_processing_steps!(connector::Stripe); - #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PaymentsPostProcessing for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] @@ -516,37 +328,9 @@ impl<const T: u8> { } -default_imp_for_post_processing_steps!(connector::Stripe); - -macro_rules! default_imp_for_payouts { - ($($path:ident::$connector:ident),*) => { - $( - impl Payouts for $path::$connector {} - )* - }; -} - #[cfg(feature = "dummy_connector")] impl<const T: u8> Payouts for connector::DummyConnector<T> {} -default_imp_for_payouts!(); - -#[cfg(feature = "payouts")] -macro_rules! default_imp_for_payouts_create { - ($($path:ident::$connector:ident),*) => { - $( - impl api::PayoutCreate for $path::$connector {} - impl - services::ConnectorIntegration< - api::PoCreate, - types::PayoutsData, - types::PayoutsResponseData, - > for $path::$connector - {} - )* - }; -} - #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PayoutCreate for connector::DummyConnector<T> {} @@ -558,25 +342,6 @@ impl<const T: u8> { } -#[cfg(feature = "payouts")] -default_imp_for_payouts_create!(); - -#[cfg(feature = "payouts")] -macro_rules! default_imp_for_payouts_retrieve { - ($($path:ident::$connector:ident),*) => { - $( - impl api::PayoutSync for $path::$connector {} - impl - services::ConnectorIntegration< - api::PoSync, - types::PayoutsData, - types::PayoutsResponseData, - > for $path::$connector - {} - )* - }; -} - #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PayoutSync for connector::DummyConnector<T> {} @@ -588,25 +353,6 @@ impl<const T: u8> { } -#[cfg(feature = "payouts")] -default_imp_for_payouts_retrieve!(connector::Stripe); - -#[cfg(feature = "payouts")] -macro_rules! default_imp_for_payouts_eligibility { - ($($path:ident::$connector:ident),*) => { - $( - impl api::PayoutEligibility for $path::$connector {} - impl - services::ConnectorIntegration< - api::PoEligibility, - types::PayoutsData, - types::PayoutsResponseData, - > for $path::$connector - {} - )* - }; -} - #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PayoutEligibility for connector::DummyConnector<T> {} @@ -621,25 +367,6 @@ impl<const T: u8> { } -#[cfg(feature = "payouts")] -default_imp_for_payouts_eligibility!(connector::Stripe); - -#[cfg(feature = "payouts")] -macro_rules! default_imp_for_payouts_fulfill { - ($($path:ident::$connector:ident),*) => { - $( - impl api::PayoutFulfill for $path::$connector {} - impl - services::ConnectorIntegration< - api::PoFulfill, - types::PayoutsData, - types::PayoutsResponseData, - > for $path::$connector - {} - )* - }; -} - #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PayoutFulfill for connector::DummyConnector<T> {} @@ -651,25 +378,6 @@ impl<const T: u8> { } -#[cfg(feature = "payouts")] -default_imp_for_payouts_fulfill!(); - -#[cfg(feature = "payouts")] -macro_rules! default_imp_for_payouts_cancel { - ($($path:ident::$connector:ident),*) => { - $( - impl api::PayoutCancel for $path::$connector {} - impl - services::ConnectorIntegration< - api::PoCancel, - types::PayoutsData, - types::PayoutsResponseData, - > for $path::$connector - {} - )* - }; -} - #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PayoutCancel for connector::DummyConnector<T> {} @@ -681,25 +389,6 @@ impl<const T: u8> { } -#[cfg(feature = "payouts")] -default_imp_for_payouts_cancel!(); - -#[cfg(feature = "payouts")] -macro_rules! default_imp_for_payouts_quote { - ($($path:ident::$connector:ident),*) => { - $( - impl api::PayoutQuote for $path::$connector {} - impl - services::ConnectorIntegration< - api::PoQuote, - types::PayoutsData, - types::PayoutsResponseData, - > for $path::$connector - {} - )* - }; -} - #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PayoutQuote for connector::DummyConnector<T> {} @@ -711,25 +400,6 @@ impl<const T: u8> { } -#[cfg(feature = "payouts")] -default_imp_for_payouts_quote!(connector::Stripe); - -#[cfg(feature = "payouts")] -macro_rules! default_imp_for_payouts_recipient { - ($($path:ident::$connector:ident),*) => { - $( - impl api::PayoutRecipient for $path::$connector {} - impl - services::ConnectorIntegration< - api::PoRecipient, - types::PayoutsData, - types::PayoutsResponseData, - > for $path::$connector - {} - )* - }; -} - #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PayoutRecipient for connector::DummyConnector<T> {} @@ -741,25 +411,6 @@ impl<const T: u8> { } -#[cfg(feature = "payouts")] -default_imp_for_payouts_recipient!(); - -#[cfg(feature = "payouts")] -macro_rules! default_imp_for_payouts_recipient_account { - ($($path:ident::$connector:ident),*) => { - $( - impl api::PayoutRecipientAccount for $path::$connector {} - impl - services::ConnectorIntegration< - api::PoRecipientAccount, - types::PayoutsData, - types::PayoutsResponseData, - > for $path::$connector - {} - )* - }; -} - #[cfg(feature = "payouts")] #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PayoutRecipientAccount for connector::DummyConnector<T> {} @@ -774,24 +425,6 @@ impl<const T: u8> { } -#[cfg(feature = "payouts")] -default_imp_for_payouts_recipient_account!(); - -macro_rules! default_imp_for_approve { - ($($path:ident::$connector:ident),*) => { - $( - impl api::PaymentApprove for $path::$connector {} - impl - services::ConnectorIntegration< - api::Approve, - types::PaymentsApproveData, - types::PaymentsResponseData, - > for $path::$connector - {} - )* - }; -} - #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PaymentApprove for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] @@ -804,23 +437,6 @@ impl<const T: u8> { } -default_imp_for_approve!(connector::Stripe); - -macro_rules! default_imp_for_reject { - ($($path:ident::$connector:ident),*) => { - $( - impl api::PaymentReject for $path::$connector {} - impl - services::ConnectorIntegration< - api::Reject, - types::PaymentsRejectData, - types::PaymentsResponseData, - > for $path::$connector - {} - )* - }; -} - #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PaymentReject for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] @@ -833,39 +449,9 @@ impl<const T: u8> { } -default_imp_for_reject!(connector::Stripe); - -#[cfg(feature = "frm")] -macro_rules! default_imp_for_fraud_check { - ($($path:ident::$connector:ident),*) => { - $( - impl api::FraudCheck for $path::$connector {} - )* - }; -} - #[cfg(feature = "dummy_connector")] impl<const T: u8> api::FraudCheck for connector::DummyConnector<T> {} -#[cfg(feature = "frm")] -default_imp_for_fraud_check!(connector::Stripe); - -#[cfg(feature = "frm")] -macro_rules! default_imp_for_frm_sale { - ($($path:ident::$connector:ident),*) => { - $( - impl api::FraudCheckSale for $path::$connector {} - impl - services::ConnectorIntegration< - api::Sale, - frm_types::FraudCheckSaleData, - frm_types::FraudCheckResponseData, - > for $path::$connector - {} - )* - }; -} - #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> api::FraudCheckSale for connector::DummyConnector<T> {} #[cfg(all(feature = "frm", feature = "dummy_connector"))] @@ -878,25 +464,6 @@ impl<const T: u8> { } -#[cfg(feature = "frm")] -default_imp_for_frm_sale!(connector::Stripe); - -#[cfg(feature = "frm")] -macro_rules! default_imp_for_frm_checkout { - ($($path:ident::$connector:ident),*) => { - $( - impl api::FraudCheckCheckout for $path::$connector {} - impl - services::ConnectorIntegration< - api::Checkout, - frm_types::FraudCheckCheckoutData, - frm_types::FraudCheckResponseData, - > for $path::$connector - {} - )* - }; -} - #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> api::FraudCheckCheckout for connector::DummyConnector<T> {} #[cfg(all(feature = "frm", feature = "dummy_connector"))] @@ -909,25 +476,6 @@ impl<const T: u8> { } -#[cfg(feature = "frm")] -default_imp_for_frm_checkout!(connector::Stripe); - -#[cfg(feature = "frm")] -macro_rules! default_imp_for_frm_transaction { - ($($path:ident::$connector:ident),*) => { - $( - impl api::FraudCheckTransaction for $path::$connector {} - impl - services::ConnectorIntegration< - api::Transaction, - frm_types::FraudCheckTransactionData, - frm_types::FraudCheckResponseData, - > for $path::$connector - {} - )* - }; -} - #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> api::FraudCheckTransaction for connector::DummyConnector<T> {} #[cfg(all(feature = "frm", feature = "dummy_connector"))] @@ -940,25 +488,6 @@ impl<const T: u8> { } -#[cfg(feature = "frm")] -default_imp_for_frm_transaction!(connector::Stripe); - -#[cfg(feature = "frm")] -macro_rules! default_imp_for_frm_fulfillment { - ($($path:ident::$connector:ident),*) => { - $( - impl api::FraudCheckFulfillment for $path::$connector {} - impl - services::ConnectorIntegration< - api::Fulfillment, - frm_types::FraudCheckFulfillmentData, - frm_types::FraudCheckResponseData, - > for $path::$connector - {} - )* - }; -} - #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> api::FraudCheckFulfillment for connector::DummyConnector<T> {} #[cfg(all(feature = "frm", feature = "dummy_connector"))] @@ -971,25 +500,6 @@ impl<const T: u8> { } -#[cfg(feature = "frm")] -default_imp_for_frm_fulfillment!(connector::Stripe); - -#[cfg(feature = "frm")] -macro_rules! default_imp_for_frm_record_return { - ($($path:ident::$connector:ident),*) => { - $( - impl api::FraudCheckRecordReturn for $path::$connector {} - impl - services::ConnectorIntegration< - api::RecordReturn, - frm_types::FraudCheckRecordReturnData, - frm_types::FraudCheckResponseData, - > for $path::$connector - {} - )* - }; -} - #[cfg(all(feature = "frm", feature = "dummy_connector"))] impl<const T: u8> api::FraudCheckRecordReturn for connector::DummyConnector<T> {} #[cfg(all(feature = "frm", feature = "dummy_connector"))] @@ -1002,24 +512,6 @@ impl<const T: u8> { } -#[cfg(feature = "frm")] -default_imp_for_frm_record_return!(connector::Stripe); - -macro_rules! default_imp_for_incremental_authorization { - ($($path:ident::$connector:ident),*) => { - $( - impl api::PaymentIncrementalAuthorization for $path::$connector {} - impl - services::ConnectorIntegration< - api::IncrementalAuthorization, - types::PaymentsIncrementalAuthorizationData, - types::PaymentsResponseData, - > for $path::$connector - {} - )* - }; -} - #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PaymentIncrementalAuthorization for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] @@ -1032,22 +524,6 @@ impl<const T: u8> { } -default_imp_for_incremental_authorization!(connector::Stripe); - -macro_rules! default_imp_for_revoking_mandates { - ($($path:ident::$connector:ident),*) => { - $( impl api::ConnectorMandateRevoke for $path::$connector {} - impl - services::ConnectorIntegration< - api::MandateRevoke, - types::MandateRevokeRequestData, - types::MandateRevokeResponseData, - > for $path::$connector - {} - )* - }; -} - #[cfg(feature = "dummy_connector")] impl<const T: u8> api::ConnectorMandateRevoke for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] @@ -1059,46 +535,6 @@ impl<const T: u8> > for connector::DummyConnector<T> { } -default_imp_for_revoking_mandates!(connector::Stripe); - -macro_rules! default_imp_for_connector_authentication { - ($($path:ident::$connector:ident),*) => { - $( impl api::ExternalAuthentication for $path::$connector {} - impl api::ConnectorAuthentication for $path::$connector {} - impl api::ConnectorPreAuthentication for $path::$connector {} - impl api::ConnectorPreAuthenticationVersionCall for $path::$connector {} - impl api::ConnectorPostAuthentication for $path::$connector {} - impl - services::ConnectorIntegration< - api::Authentication, - types::authentication::ConnectorAuthenticationRequestData, - types::authentication::AuthenticationResponseData, - > for $path::$connector - {} - impl - services::ConnectorIntegration< - api::PreAuthentication, - types::authentication::PreAuthNRequestData, - types::authentication::AuthenticationResponseData, - > for $path::$connector - {} - impl - services::ConnectorIntegration< - api::PreAuthenticationVersionCall, - types::authentication::PreAuthNRequestData, - types::authentication::AuthenticationResponseData, - > for $path::$connector - {} - impl - services::ConnectorIntegration< - api::PostAuthentication, - types::authentication::ConnectorPostAuthenticationRequestData, - types::authentication::AuthenticationResponseData, - > for $path::$connector - {} - )* - }; -} #[cfg(feature = "dummy_connector")] impl<const T: u8> api::ExternalAuthentication for connector::DummyConnector<T> {} @@ -1147,21 +583,7 @@ impl<const T: u8> > for connector::DummyConnector<T> { } -default_imp_for_connector_authentication!(connector::Stripe); -macro_rules! default_imp_for_authorize_session_token { - ($($path:ident::$connector:ident),*) => { - $( impl api::PaymentAuthorizeSessionToken for $path::$connector {} - impl - services::ConnectorIntegration< - api::AuthorizeSessionToken, - types::AuthorizeSessionTokenData, - types::PaymentsResponseData - > for $path::$connector - {} - )* - }; -} #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PaymentAuthorizeSessionToken for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] @@ -1173,21 +595,7 @@ impl<const T: u8> > for connector::DummyConnector<T> { } -default_imp_for_authorize_session_token!(connector::Stripe); -macro_rules! default_imp_for_calculate_tax { - ($($path:ident::$connector:ident),*) => { - $( impl api::TaxCalculation for $path::$connector {} - impl - services::ConnectorIntegration< - api::CalculateTax, - types::PaymentsTaxCalculationData, - types::TaxCalculationResponseData - > for $path::$connector - {} - )* - }; -} #[cfg(feature = "dummy_connector")] impl<const T: u8> api::TaxCalculation for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] @@ -1200,21 +608,6 @@ impl<const T: u8> { } -default_imp_for_calculate_tax!(connector::Stripe); - -macro_rules! default_imp_for_session_update { - ($($path:ident::$connector:ident),*) => { - $( impl api::PaymentSessionUpdate for $path::$connector {} - impl - services::ConnectorIntegration< - api::SdkSessionUpdate, - types::SdkPaymentsSessionUpdateData, - types::PaymentsResponseData - > for $path::$connector - {} - )* - }; -} #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PaymentSessionUpdate for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] @@ -1227,21 +620,6 @@ impl<const T: u8> { } -default_imp_for_session_update!(connector::Stripe); - -macro_rules! default_imp_for_post_session_tokens { - ($($path:ident::$connector:ident),*) => { - $( impl api::PaymentPostSessionTokens for $path::$connector {} - impl - services::ConnectorIntegration< - api::PostSessionTokens, - types::PaymentsPostSessionTokensData, - types::PaymentsResponseData - > for $path::$connector - {} - )* - }; -} #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PaymentPostSessionTokens for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] @@ -1254,21 +632,6 @@ impl<const T: u8> { } -default_imp_for_post_session_tokens!(connector::Stripe); - -macro_rules! default_imp_for_update_metadata { - ($($path:ident::$connector:ident),*) => { - $( impl api::PaymentUpdateMetadata for $path::$connector {} - impl - services::ConnectorIntegration< - api::UpdateMetadata, - types::PaymentsUpdateMetadataData, - types::PaymentsResponseData - > for $path::$connector - {} - )* - }; -} #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PaymentUpdateMetadata for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] @@ -1281,22 +644,6 @@ impl<const T: u8> { } -default_imp_for_update_metadata!(); - -macro_rules! default_imp_for_uas_pre_authentication { - ($($path:ident::$connector:ident),*) => { - $( impl UnifiedAuthenticationService for $path::$connector {} - impl UasPreAuthentication for $path::$connector {} - impl - services::ConnectorIntegration< - PreAuthenticate, - types::UasPreAuthenticationRequestData, - types::UasAuthenticationResponseData - > for $path::$connector - {} - )* - }; -} #[cfg(feature = "dummy_connector")] impl<const T: u8> UasPreAuthentication for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] @@ -1311,21 +658,6 @@ impl<const T: u8> { } -default_imp_for_uas_pre_authentication!(connector::Stripe); - -macro_rules! default_imp_for_uas_post_authentication { - ($($path:ident::$connector:ident),*) => { - $( impl UasPostAuthentication for $path::$connector {} - impl - services::ConnectorIntegration< - PostAuthenticate, - types::UasPostAuthenticationRequestData, - types::UasAuthenticationResponseData - > for $path::$connector - {} - )* - }; -} #[cfg(feature = "dummy_connector")] impl<const T: u8> UasPostAuthentication for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] @@ -1338,24 +670,6 @@ impl<const T: u8> { } -default_imp_for_uas_post_authentication!(connector::Stripe); - -macro_rules! default_imp_for_uas_authentication_confirmation { - ($($path:ident::$connector:ident),*) => { - $( impl UasAuthenticationConfirmation for $path::$connector {} - impl - services::ConnectorIntegration< - AuthenticationConfirmation, - types::UasConfirmationRequestData, - types::UasAuthenticationResponseData - > for $path::$connector - {} - )* - }; -} - -default_imp_for_uas_authentication_confirmation!(connector::Stripe); - #[cfg(feature = "dummy_connector")] impl<const T: u8> UasAuthenticationConfirmation for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] @@ -1368,20 +682,6 @@ impl<const T: u8> { } -macro_rules! default_imp_for_uas_authentication { - ($($path:ident::$connector:ident),*) => { - $( impl UasAuthentication for $path::$connector {} - impl - services::ConnectorIntegration< - Authenticate, - types::UasAuthenticationRequestData, - types::UasAuthenticationResponseData - > for $path::$connector - {} - )* - }; -} - #[cfg(feature = "dummy_connector")] impl<const T: u8> UasAuthentication for connector::DummyConnector<T> {} #[cfg(feature = "dummy_connector")] @@ -1394,8 +694,6 @@ impl<const T: u8> { } -default_imp_for_uas_authentication!(connector::Stripe); - /// Determines whether a capture API call should be made for a payment attempt /// This function evaluates whether an authorized payment should proceed with a capture API call /// based on various payment parameters. It's primarily used in two-step (auth + capture) payment flows for CaptureMethod SequentialAutomatic @@ -1506,38 +804,9 @@ fn handle_post_capture_response( } } -macro_rules! default_imp_for_revenue_recovery { - ($($path:ident::$connector:ident),*) => { - $( impl api::RevenueRecovery for $path::$connector {} - )* - }; -} - #[cfg(feature = "dummy_connector")] impl<const T: u8> api::RevenueRecovery for connector::DummyConnector<T> {} -default_imp_for_revenue_recovery! { - - connector::Stripe - - - -} - -#[cfg(all(feature = "v2", feature = "revenue_recovery"))] -macro_rules! default_imp_for_billing_connector_payment_sync { - ($($path:ident::$connector:ident),*) => { - $( impl api::BillingConnectorPaymentsSyncIntegration for $path::$connector {} - impl - services::ConnectorIntegration< - BillingConnectorPaymentsSync, - types::BillingConnectorPaymentsSyncRequest, - types::BillingConnectorPaymentsSyncResponse, - > for $path::$connector - {} - )* - }; -} #[cfg(all(feature = "v2", feature = "revenue_recovery"))] #[cfg(feature = "dummy_connector")] impl<const T: u8> api::BillingConnectorPaymentsSyncIntegration for connector::DummyConnector<T> {} @@ -1552,24 +821,6 @@ impl<const T: u8> { } -#[cfg(all(feature = "v2", feature = "revenue_recovery"))] -default_imp_for_billing_connector_payment_sync!(connector::Stripe); - -#[cfg(all(feature = "v2", feature = "revenue_recovery"))] -macro_rules! default_imp_for_revenue_recovery_record_back { - ($($path:ident::$connector:ident),*) => { - $( - impl api::RevenueRecoveryRecordBack for $path::$connector {} - impl - services::ConnectorIntegration< - RecoveryRecordBack, - types::RevenueRecoveryRecordBackRequest, - types::RevenueRecoveryRecordBackResponse, - > for $path::$connector - {} - )* - }; -} #[cfg(all(feature = "v2", feature = "revenue_recovery"))] #[cfg(feature = "dummy_connector")] impl<const T: u8> api::RevenueRecoveryRecordBack for connector::DummyConnector<T> {} @@ -1583,24 +834,7 @@ impl<const T: u8> > for connector::DummyConnector<T> { } -#[cfg(all(feature = "v2", feature = "revenue_recovery"))] -default_imp_for_revenue_recovery_record_back!(connector::Stripe); -#[cfg(all(feature = "v2", feature = "revenue_recovery"))] -macro_rules! default_imp_for_billing_connector_invoice_sync { - ($($path:ident::$connector:ident),*) => { - $( - impl api::BillingConnectorInvoiceSyncIntegration for $path::$connector {} - impl - services::ConnectorIntegration< - BillingConnectorInvoiceSync, - types::BillingConnectorInvoiceSyncRequest, - types::BillingConnectorInvoiceSyncResponse, - > for $path::$connector - {} - )* - }; -} #[cfg(all(feature = "v2", feature = "revenue_recovery"))] #[cfg(feature = "dummy_connector")] impl<const T: u8> api::BillingConnectorInvoiceSyncIntegration for connector::DummyConnector<T> {} @@ -1614,5 +848,3 @@ impl<const T: u8> > for connector::DummyConnector<T> { } -#[cfg(all(feature = "v2", feature = "revenue_recovery"))] -default_imp_for_billing_connector_invoice_sync!(connector::Stripe); diff --git a/crates/router/src/macros.rs b/crates/router/src/macros.rs index c6de30c8d0f..21c89342fbd 100644 --- a/crates/router/src/macros.rs +++ b/crates/router/src/macros.rs @@ -1,4 +1,4 @@ -pub use common_utils::{collect_missing_value_keys, newtype}; +pub use common_utils::newtype; #[macro_export] macro_rules! get_payment_link_config_value_based_on_priority { diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 22a84c66d14..af5d983a48a 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -115,10 +115,7 @@ pub use hyperswitch_interfaces::types::{ pub use crate::core::payments::CustomerDetails; #[cfg(feature = "payouts")] -use crate::{ - connector::utils::missing_field_err, - core::utils::IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_PAYOUTS_FLOW, -}; +use crate::core::utils::IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_PAYOUTS_FLOW; use crate::{ consts, core::{ @@ -252,16 +249,6 @@ pub trait PayoutIndividualDetailsExt { fn get_external_account_account_holder_type(&self) -> Result<String, Self::Error>; } -#[cfg(feature = "payouts")] -impl PayoutIndividualDetailsExt for api_models::payouts::PayoutIndividualDetails { - type Error = error_stack::Report<errors::ConnectorError>; - fn get_external_account_account_holder_type(&self) -> Result<String, Self::Error> { - self.external_account_account_holder_type - .clone() - .ok_or_else(missing_field_err("external_account_account_holder_type")) - } -} - pub trait Capturable { fn get_captured_amount<F>(&self, _payment_data: &PaymentData<F>) -> Option<i64> where
2025-05-13T05:06:47Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Move stripe connector code form `router` crate to `hyperswitch_connectors` crate - issue : https://github.com/juspay/hyperswitch/issues/8008 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - Create a stripe Connector account ```sh curl --location 'http://localhost:8080/account/merchant_1747113313/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-feature: integ-custom' \ --header 'api-key: ******* ' \ --data '{ "connector_type": "payment_processor", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "************" }, "connector_name": "stripe", "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "city": "NY", "unit": "245" }, "connector_webhook_details": { "merchant_secret": "MyWebhookSecret" }, "business_country": "US", "business_label": "default" }' ``` Response : ```json { "connector_type": "payment_processor", "connector_name": "stripe", "connector_label": "stripe_US_default", "merchant_connector_id": "mca_8qleoiztV9FBwkaNf0Rm", "profile_id": "pro_t33gfLUkrUO76eylTYK4", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "****************************************************************************************" }, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "connector_webhook_details": { "merchant_secret": "MyWebhookSecret", "additional_secret": null }, "metadata": { "city": "NY", "unit": "245" }, "test_mode": false, "disabled": false, "frm_configs": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "applepay_verified_domains": null, "pm_auth_config": null, "status": "active", "additional_merchant_data": null, "connector_wallets_details": null } ``` ### make successful payment ```sh curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_Li4eaVL1tG5lV2lVmj3vP6BBwvxQ19KIWwp7V2zbw1rhithkA5HxCr02paARBlCz' \ --data-raw '{ "amount": 10000000, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "CustomerX", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "HK", "first_name": "John", "last_name": "Doe" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "13.232.74.226" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "HK", "first_name": "John", "last_name": "Doe" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "connector_metadata": { "noon": { "order_category": "pay" } }, "setup_future_usage": "off_session", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "13.232.74.226", "user_agent": "amet irure esse" } } }' ``` response ```json { "payment_id": "pay_q6e0Q412V5XBmVTfFvoe", "merchant_id": "merchant_1747113313", "status": "succeeded", "amount": 10000000, "net_amount": 10000000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 10000000, "connector": "stripe", "client_secret": "pay_q6e0Q412V5XBmVTfFvoe_secret_EbWpc8loQOn0naXMfEgZ", "created": "2025-05-13T05:15:28.338Z", "currency": "USD", "customer_id": "CustomerX", "customer": { "id": "CustomerX", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": { "cvc_check": "pass", "address_line1_check": "pass", "address_postal_code_check": "pass" }, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "HK", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "HK", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "CustomerX", "created_at": 1747113328, "expires": 1747116928, "secret": "epk_2f16f9167ee34c60a28130b51275b9d3" }, "manual_retry_allowed": false, "connector_transaction_id": "pi_3ROBBdD5R7gDAGff02wZ2nM2", "frm_message": null, "metadata": null, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "pay" }, "braintree": null, "adyen": null }, "feature_metadata": null, "reference_id": "pi_3ROBBdD5R7gDAGff02wZ2nM2", "payment_link": null, "profile_id": "pro_t33gfLUkrUO76eylTYK4", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_8qleoiztV9FBwkaNf0Rm", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-05-13T05:30:28.338Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "13.232.74.226", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-05-13T05:15:30.957Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
9d78c583f6c299ab9f63e551b887d1cb080106b4
9d78c583f6c299ab9f63e551b887d1cb080106b4
juspay/hyperswitch
juspay__hyperswitch-8000
Bug: Feat(euclid): Hyperswitch integration with decision engine ## Description This PR integrates the Euclid-based decision engine with Hyperswitch’s dynamic routing infrastructure. It enables dual routing logic: legacy DSL-based evaluation and decision-engine-backed configurations. The integration ensures routing algorithms can be authored, activated, and evaluated via Euclid and linked seamlessly to merchant profiles. ## Outcomes - Adds support for storing and linking decision-engine routing IDs (`decision_engine_routing_id`) in the existing `routing_algorithm` table. - Enables creation and linking of Euclid routing configurations during algorithm creation and configuration linking flows. - Enhances observability with logging and tracing of decision engine interactions. - Preserves backward compatibility with existing static/dynamic routing mechanisms. ## Diff Hunk Explanation ### `crates/api_models/src/routing.rs` - Added `decision_engine_routing_id` to `RoutingDictionaryRecord` to expose the DE mapping in API responses. - Updated `RoutingAlgorithmKind` with `PartialEq` to aid in logic branching. ### `crates/diesel_models/src/routing_algorithm.rs` - Included new optional field `decision_engine_routing_id` to map to Euclid's algorithm record. ### `crates/diesel_models/src/schema.rs` - Altered `routing_algorithm` schema to include `decision_engine_routing_id VARCHAR(64)`. ### `crates/router/src/core/payments/routing.rs` - Imported `perform_decision_euclid_routing` into static routing flow for test execution and future use. ### `crates/router/src/core/routing.rs` - On routing creation, checks if the algorithm is a Euclid (Advanced) type, then creates it in the decision engine and stores the returned ID. - On routing configuration linking, activates the respective routing config in the decision engine using `ActivateRoutingConfigRequest`. - Enhances `retrieve_merchant_routing_dictionary` to fetch and append decision engine routing configs by profile ID. ### `crates/router/src/core/routing/transformers.rs` - Ensures `decision_engine_routing_id` is preserved and transformed when converting between internal and API models. ### `migrations/2025-05-08-102850_add_de_euclid_id_in_routing_algorithm_table/*.sql` - Adds and removes the `decision_engine_routing_id` column in the `routing_algorithm` table via Diesel migrations. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Here is the complete testing [guidelines](https://docs.google.com/document/d/11Xr_KWA5ire4qBXLcALSe7JeHeRjn8_dzvW7HBh91rY/edit?tab=t.0).
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 12c30cc61f0..197f9fdbda8 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -21668,6 +21668,10 @@ } ], "nullable": true + }, + "decision_engine_routing_id": { + "type": "string", + "nullable": true } } }, diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index e5f3cfbbe79..cda884f9de3 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -25900,6 +25900,10 @@ } ], "nullable": true + }, + "decision_engine_routing_id": { + "type": "string", + "nullable": true } } }, diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index 90cce48574b..c929bb3ea5d 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -269,7 +269,9 @@ impl RoutableConnectorChoiceWithStatus { } } -#[derive(Debug, Copy, Clone, serde::Serialize, serde::Deserialize, strum::Display, ToSchema)] +#[derive( + Debug, Copy, Clone, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, ToSchema, +)] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RoutingAlgorithmKind { @@ -484,6 +486,7 @@ pub struct RoutingDictionaryRecord { pub created_at: i64, pub modified_at: i64, pub algorithm_for: Option<TransactionType>, + pub decision_engine_routing_id: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] diff --git a/crates/diesel_models/src/routing_algorithm.rs b/crates/diesel_models/src/routing_algorithm.rs index 5f5a0560811..4e6e9212885 100644 --- a/crates/diesel_models/src/routing_algorithm.rs +++ b/crates/diesel_models/src/routing_algorithm.rs @@ -17,6 +17,7 @@ pub struct RoutingAlgorithm { pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub algorithm_for: enums::TransactionType, + pub decision_engine_routing_id: Option<String>, } pub struct RoutingAlgorithmMetadata { diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 6f978a7afec..50474dd9491 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -1407,6 +1407,8 @@ diesel::table! { created_at -> Timestamp, modified_at -> Timestamp, algorithm_for -> TransactionType, + #[max_length = 64] + decision_engine_routing_id -> Nullable<Varchar>, } } diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 0b5b7003c07..9280415412d 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -1,4 +1,5 @@ mod transformers; +pub mod utils; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use std::collections::hash_map; @@ -50,6 +51,7 @@ use rand::SeedableRng; use router_env::{instrument, tracing}; use rustc_hash::FxHashMap; use storage_impl::redis::cache::{CacheKey, CGRAPH_CACHE, ROUTING_CACHE}; +use utils::perform_decision_euclid_routing; #[cfg(feature = "v2")] use crate::core::admin; @@ -466,7 +468,27 @@ pub async fn perform_static_routing_v1( } }; - execute_dsl_and_get_connector_v1(backend_input, interpreter)? + let de_euclid_connectors = perform_decision_euclid_routing( + state, + backend_input.clone(), + business_profile.get_id().get_string_repr().to_string(), + ) + .await + .map_err(|e| + // errors are ignored as this is just for diff checking as of now (optional flow). + logger::error!(decision_engine_euclid_evaluate_error=?e, "decision_engine_euclid: error in evaluation of rule") + ).unwrap_or_default(); + let routable_connectors = execute_dsl_and_get_connector_v1(backend_input, interpreter)?; + let connectors = routable_connectors + .iter() + .map(|c| c.connector.to_string()) + .collect::<Vec<String>>(); + utils::compare_and_log_result( + de_euclid_connectors, + connectors, + "evaluate_routing".to_string(), + ); + routable_connectors } }) } diff --git a/crates/router/src/core/payments/routing/utils.rs b/crates/router/src/core/payments/routing/utils.rs new file mode 100644 index 00000000000..551694a0aaf --- /dev/null +++ b/crates/router/src/core/payments/routing/utils.rs @@ -0,0 +1,736 @@ +use std::collections::{HashMap, HashSet}; + +use api_models::routing as api_routing; +use async_trait::async_trait; +use common_utils::id_type; +use diesel_models::{enums, routing_algorithm}; +use error_stack::ResultExt; +use euclid::{backend::BackendInput, frontend::ast}; +use serde::{Deserialize, Serialize}; + +use super::RoutingResult; +use crate::{ + core::errors, + routes::SessionState, + services::{self, logger}, + types::transformers::ForeignInto, +}; + +// New Trait for handling Euclid API calls +#[async_trait] +pub trait EuclidApiHandler { + async fn send_euclid_request<Req, Res>( + state: &SessionState, + http_method: services::Method, + path: &str, + request_body: Option<Req>, // Option to handle GET/DELETE requests without body + timeout: Option<u64>, + ) -> RoutingResult<Res> + where + Req: Serialize + Send + Sync + 'static, + Res: serde::de::DeserializeOwned + Send + 'static + std::fmt::Debug; + + async fn send_euclid_request_without_response_parsing<Req>( + state: &SessionState, + http_method: services::Method, + path: &str, + request_body: Option<Req>, + timeout: Option<u64>, + ) -> RoutingResult<()> + where + Req: Serialize + Send + Sync + 'static; +} + +// Struct to implement the EuclidApiHandler trait +pub struct EuclidApiClient; + +impl EuclidApiClient { + async fn build_and_send_euclid_http_request<Req>( + state: &SessionState, + http_method: services::Method, + path: &str, + request_body: Option<Req>, + timeout: Option<u64>, + context_message: &str, + ) -> RoutingResult<reqwest::Response> + where + Req: Serialize + Send + Sync + 'static, + { + let euclid_base_url = &state.conf.open_router.url; + let url = format!("{}/{}", euclid_base_url, path); + logger::debug!(euclid_api_call_url = %url, euclid_request_path = %path, http_method = ?http_method, "decision_engine_euclid: Initiating Euclid API call ({})", context_message); + + let mut request_builder = services::RequestBuilder::new() + .method(http_method) + .url(&url); + + if let Some(body_content) = request_body { + let body = common_utils::request::RequestContent::Json(Box::new(body_content)); + request_builder = request_builder.set_body(body); + } + + let http_request = request_builder.build(); + logger::info!(?http_request, euclid_request_path = %path, "decision_engine_euclid: Constructed Euclid API request details ({})", context_message); + + state + .api_client + .send_request(state, http_request, timeout, false) + .await + .change_context(errors::RoutingError::DslExecutionError) + .attach_printable_lazy(|| { + format!( + "Euclid API call to path '{}' unresponsive ({})", + path, context_message + ) + }) + } +} + +#[async_trait] +impl EuclidApiHandler for EuclidApiClient { + async fn send_euclid_request<Req, Res>( + state: &SessionState, + http_method: services::Method, + path: &str, + request_body: Option<Req>, // Option to handle GET/DELETE requests without body + timeout: Option<u64>, + ) -> RoutingResult<Res> + where + Req: Serialize + Send + Sync + 'static, + Res: serde::de::DeserializeOwned + Send + 'static + std::fmt::Debug, + { + let response = Self::build_and_send_euclid_http_request( + state, + http_method, + path, + request_body, + timeout, + "parsing response", + ) + .await?; + logger::debug!(euclid_response = ?response, euclid_request_path = %path, "decision_engine_euclid: Received raw response from Euclid API"); + + let parsed_response = response + .json::<Res>() + .await + .change_context(errors::RoutingError::GenericConversionError { + from: "ApiResponse".to_string(), + to: std::any::type_name::<Res>().to_string(), + }) + .attach_printable_lazy(|| { + format!( + "Unable to parse response of type '{}' received from Euclid API path: {}", + std::any::type_name::<Res>(), + path + ) + })?; + logger::debug!(parsed_response = ?parsed_response, response_type = %std::any::type_name::<Res>(), euclid_request_path = %path, "decision_engine_euclid: Successfully parsed response from Euclid API"); + Ok(parsed_response) + } + + async fn send_euclid_request_without_response_parsing<Req>( + state: &SessionState, + http_method: services::Method, + path: &str, + request_body: Option<Req>, + timeout: Option<u64>, + ) -> RoutingResult<()> + where + Req: Serialize + Send + Sync + 'static, + { + let response = Self::build_and_send_euclid_http_request( + state, + http_method, + path, + request_body, + timeout, + "not parsing response", + ) + .await?; + + logger::debug!(euclid_response = ?response, euclid_request_path = %path, "decision_engine_routing: Received raw response from Euclid API"); + Ok(()) + } +} + +const EUCLID_API_TIMEOUT: u64 = 5; + +pub async fn perform_decision_euclid_routing( + state: &SessionState, + input: BackendInput, + created_by: String, +) -> RoutingResult<Vec<String>> { + logger::debug!("decision_engine_euclid: evaluate api call for euclid routing evaluation"); + + let routing_request = convert_backend_input_to_routing_eval(created_by, input)?; + + let euclid_response: RoutingEvaluateResponse = EuclidApiClient::send_euclid_request( + state, + services::Method::Post, + "routing/evaluate", + Some(routing_request), + Some(EUCLID_API_TIMEOUT), + ) + .await?; + + logger::debug!(decision_engine_euclid_response=?euclid_response,"decision_engine_euclid"); + logger::debug!(decision_engine_euclid_selected_connector=?euclid_response.evaluated_output,"decision_engine_euclid"); + + Ok(euclid_response.evaluated_output) +} + +pub async fn create_de_euclid_routing_algo( + state: &SessionState, + routing_request: &RoutingRule, +) -> RoutingResult<String> { + logger::debug!("decision_engine_euclid: create api call for euclid routing rule creation"); + + logger::debug!(decision_engine_euclid_request=?routing_request,"decision_engine_euclid"); + let euclid_response: RoutingDictionaryRecord = EuclidApiClient::send_euclid_request( + state, + services::Method::Post, + "routing/create", + Some(routing_request.clone()), + Some(EUCLID_API_TIMEOUT), + ) + .await?; + + logger::debug!(decision_engine_euclid_parsed_response=?euclid_response,"decision_engine_euclid"); + Ok(euclid_response.rule_id) +} + +pub async fn link_de_euclid_routing_algorithm( + state: &SessionState, + routing_request: ActivateRoutingConfigRequest, +) -> RoutingResult<()> { + logger::debug!("decision_engine_euclid: link api call for euclid routing algorithm"); + + EuclidApiClient::send_euclid_request_without_response_parsing( + state, + services::Method::Post, + "routing/activate", + Some(routing_request.clone()), + Some(EUCLID_API_TIMEOUT), + ) + .await?; + + logger::debug!(decision_engine_euclid_activated=?routing_request, "decision_engine_euclid: link_de_euclid_routing_algorithm completed"); + Ok(()) +} + +pub async fn list_de_euclid_routing_algorithms( + state: &SessionState, + routing_list_request: ListRountingAlgorithmsRequest, +) -> RoutingResult<Vec<api_routing::RoutingDictionaryRecord>> { + logger::debug!("decision_engine_euclid: list api call for euclid routing algorithms"); + let created_by = routing_list_request.created_by; + let response: Vec<RoutingAlgorithmRecord> = EuclidApiClient::send_euclid_request( + state, + services::Method::Post, + format!("routing/list/{created_by}").as_str(), + None::<()>, + Some(EUCLID_API_TIMEOUT), + ) + .await?; + + Ok(response + .into_iter() + .map(routing_algorithm::RoutingProfileMetadata::from) + .map(ForeignInto::foreign_into) + .collect::<Vec<_>>()) +} + +pub fn compare_and_log_result<T: RoutingEq<T> + Serialize>( + de_result: Vec<T>, + result: Vec<T>, + flow: String, +) { + let is_equal = de_result.len() == result.len() + && de_result + .iter() + .zip(result.iter()) + .all(|(a, b)| T::is_equal(a, b)); + + if is_equal { + router_env::logger::info!(routing_flow=?flow, is_equal=?is_equal, "decision_engine_euclid"); + } else { + router_env::logger::debug!(routing_flow=?flow, is_equal=?is_equal, de_response=?to_json_string(&de_result), hs_response=?to_json_string(&result), "decision_engine_euclid"); + } +} + +pub trait RoutingEq<T> { + fn is_equal(a: &T, b: &T) -> bool; +} + +impl RoutingEq<Self> for api_routing::RoutingDictionaryRecord { + fn is_equal(a: &Self, b: &Self) -> bool { + a.name == b.name + && a.profile_id == b.profile_id + && a.description == b.description + && a.kind == b.kind + && a.algorithm_for == b.algorithm_for + } +} + +impl RoutingEq<Self> for String { + fn is_equal(a: &Self, b: &Self) -> bool { + a.to_lowercase() == b.to_lowercase() + } +} + +pub fn to_json_string<T: Serialize>(value: &T) -> String { + serde_json::to_string(value) + .map_err(|_| errors::RoutingError::GenericConversionError { + from: "T".to_string(), + to: "JsonValue".to_string(), + }) + .unwrap_or_default() +} + +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct ActivateRoutingConfigRequest { + pub created_by: String, + pub routing_algorithm_id: String, +} + +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct ListRountingAlgorithmsRequest { + pub created_by: String, +} + +// Maps Hyperswitch `BackendInput` to a `RoutingEvaluateRequest` compatible with Decision Engine +pub fn convert_backend_input_to_routing_eval( + created_by: String, + input: BackendInput, +) -> RoutingResult<RoutingEvaluateRequest> { + let mut params: HashMap<String, Option<ValueType>> = HashMap::new(); + + // Payment + params.insert( + "amount".to_string(), + Some(ValueType::Number( + input + .payment + .amount + .get_amount_as_i64() + .try_into() + .unwrap_or_default(), + )), + ); + params.insert( + "currency".to_string(), + Some(ValueType::EnumVariant(input.payment.currency.to_string())), + ); + + if let Some(auth_type) = input.payment.authentication_type { + params.insert( + "authentication_type".to_string(), + Some(ValueType::EnumVariant(auth_type.to_string())), + ); + } + if let Some(bin) = input.payment.card_bin { + params.insert("card_bin".to_string(), Some(ValueType::StrValue(bin))); + } + if let Some(capture_method) = input.payment.capture_method { + params.insert( + "capture_method".to_string(), + Some(ValueType::EnumVariant(capture_method.to_string())), + ); + } + if let Some(country) = input.payment.business_country { + params.insert( + "business_country".to_string(), + Some(ValueType::EnumVariant(country.to_string())), + ); + } + if let Some(country) = input.payment.billing_country { + params.insert( + "billing_country".to_string(), + Some(ValueType::EnumVariant(country.to_string())), + ); + } + if let Some(label) = input.payment.business_label { + params.insert( + "business_label".to_string(), + Some(ValueType::StrValue(label)), + ); + } + if let Some(sfu) = input.payment.setup_future_usage { + params.insert( + "setup_future_usage".to_string(), + Some(ValueType::EnumVariant(sfu.to_string())), + ); + } + + // PaymentMethod + if let Some(pm) = input.payment_method.payment_method { + params.insert( + "payment_method".to_string(), + Some(ValueType::EnumVariant(pm.to_string())), + ); + } + if let Some(pmt) = input.payment_method.payment_method_type { + params.insert( + "payment_method_type".to_string(), + Some(ValueType::EnumVariant(pmt.to_string())), + ); + } + if let Some(network) = input.payment_method.card_network { + params.insert( + "card_network".to_string(), + Some(ValueType::EnumVariant(network.to_string())), + ); + } + + // Mandate + if let Some(pt) = input.mandate.payment_type { + params.insert( + "payment_type".to_string(), + Some(ValueType::EnumVariant(pt.to_string())), + ); + } + if let Some(mt) = input.mandate.mandate_type { + params.insert( + "mandate_type".to_string(), + Some(ValueType::EnumVariant(mt.to_string())), + ); + } + if let Some(mat) = input.mandate.mandate_acceptance_type { + params.insert( + "mandate_acceptance_type".to_string(), + Some(ValueType::EnumVariant(mat.to_string())), + ); + } + + // Metadata + if let Some(meta) = input.metadata { + for (k, v) in meta.into_iter() { + params.insert( + k.clone(), + Some(ValueType::MetadataVariant(MetadataValue { + key: k, + value: v, + })), + ); + } + } + + Ok(RoutingEvaluateRequest { + created_by, + parameters: params, + }) +} + +//TODO: temporary change will be refactored afterwards +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq)] +pub struct RoutingEvaluateRequest { + pub created_by: String, + pub parameters: HashMap<String, Option<ValueType>>, +} + +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub struct RoutingEvaluateResponse { + pub status: String, + pub output: serde_json::Value, + pub evaluated_output: Vec<String>, + pub eligible_connectors: Vec<String>, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct MetadataValue { + pub key: String, + pub value: String, +} + +/// Represents a value in the DSL +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(tag = "type", content = "value", rename_all = "snake_case")] +pub enum ValueType { + /// Represents a number literal + Number(u64), + /// Represents an enum variant + EnumVariant(String), + /// Represents a Metadata variant + MetadataVariant(MetadataValue), + /// Represents a arbitrary String value + StrValue(String), + GlobalRef(String), +} + +pub type Metadata = HashMap<String, serde_json::Value>; +/// Represents a number comparison for "NumberComparisonArrayValue" +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct NumberComparison { + pub comparison_type: ComparisonType, + pub number: u64, +} + +/// Conditional comparison type +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ComparisonType { + Equal, + NotEqual, + LessThan, + LessThanEqual, + GreaterThan, + GreaterThanEqual, +} + +/// Represents a single comparison condition. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct Comparison { + /// The left hand side which will always be a domain input identifier like "payment.method.cardtype" + pub lhs: String, + /// The comparison operator + pub comparison: ComparisonType, + /// The value to compare against + pub value: ValueType, + /// Additional metadata that the Static Analyzer and Backend does not touch. + /// This can be used to store useful information for the frontend and is required for communication + /// between the static analyzer and the frontend. + // #[schema(value_type=HashMap<String, serde_json::Value>)] + pub metadata: Metadata, +} + +/// Represents all the conditions of an IF statement +/// eg: +/// +/// ```text +/// payment.method = card & payment.method.cardtype = debit & payment.method.network = diners +/// ``` +pub type IfCondition = Vec<Comparison>; + +/// Represents an IF statement with conditions and optional nested IF statements +/// +/// ```text +/// payment.method = card { +/// payment.method.cardtype = (credit, debit) { +/// payment.method.network = (amex, rupay, diners) +/// } +/// } +/// ``` +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct IfStatement { + // #[schema(value_type=Vec<Comparison>)] + pub condition: IfCondition, + pub nested: Option<Vec<IfStatement>>, +} + +/// Represents a rule +/// +/// ```text +/// rule_name: [stripe, adyen, checkout] +/// { +/// payment.method = card { +/// payment.method.cardtype = (credit, debit) { +/// payment.method.network = (amex, rupay, diners) +/// } +/// +/// payment.method.cardtype = credit +/// } +/// } +/// ``` +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +// #[aliases(RuleConnectorSelection = Rule<ConnectorSelection>)] +pub struct Rule { + pub name: String, + #[serde(alias = "routingType")] + pub routing_type: RoutingType, + #[serde(alias = "routingOutput")] + pub output: Output, + pub statements: Vec<IfStatement>, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum RoutingType { + Priority, + VolumeSplit, + VolumeSplitPriority, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct VolumeSplit<T> { + pub split: u8, + pub output: T, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Output { + Priority(Vec<String>), + VolumeSplit(Vec<VolumeSplit<String>>), + VolumeSplitPriority(Vec<VolumeSplit<Vec<String>>>), +} + +pub type Globals = HashMap<String, HashSet<ValueType>>; + +/// The program, having a default connector selection and +/// a bunch of rules. Also can hold arbitrary metadata. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +// #[aliases(ProgramConnectorSelection = Program<ConnectorSelection>)] +pub struct Program { + pub globals: Globals, + pub default_selection: Output, + // #[schema(value_type=RuleConnectorSelection)] + pub rules: Vec<Rule>, + // #[schema(value_type=HashMap<String, serde_json::Value>)] + pub metadata: Option<Metadata>, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct RoutingRule { + pub name: String, + pub description: Option<String>, + pub metadata: Option<RoutingMetadata>, + pub created_by: String, + pub algorithm: Program, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct RoutingMetadata { + pub kind: enums::RoutingAlgorithmKind, + pub algorithm_for: enums::TransactionType, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct RoutingDictionaryRecord { + pub rule_id: String, + pub name: String, + pub created_at: time::PrimitiveDateTime, + pub modified_at: time::PrimitiveDateTime, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct RoutingAlgorithmRecord { + pub id: id_type::RoutingId, + pub name: String, + pub description: Option<String>, + pub created_by: id_type::ProfileId, + pub algorithm_data: Program, + pub metadata: Option<RoutingMetadata>, + pub created_at: time::PrimitiveDateTime, + pub modified_at: time::PrimitiveDateTime, +} + +impl From<RoutingAlgorithmRecord> for routing_algorithm::RoutingProfileMetadata { + fn from(record: RoutingAlgorithmRecord) -> Self { + let (kind, algorithm_for) = match record.metadata { + Some(metadata) => (metadata.kind, metadata.algorithm_for), + None => ( + enums::RoutingAlgorithmKind::Advanced, + enums::TransactionType::default(), + ), + }; + Self { + profile_id: record.created_by, + algorithm_id: record.id, + name: record.name, + description: record.description, + kind, + created_at: record.created_at, + modified_at: record.modified_at, + algorithm_for, + } + } +} +use api_models::routing::{ConnectorSelection, RoutableConnectorChoice}; +impl From<ast::Program<ConnectorSelection>> for Program { + fn from(p: ast::Program<ConnectorSelection>) -> Self { + Self { + globals: HashMap::new(), + default_selection: convert_output(p.default_selection), + rules: p.rules.into_iter().map(convert_rule).collect(), + metadata: Some(p.metadata), + } + } +} + +fn convert_rule(rule: ast::Rule<ConnectorSelection>) -> Rule { + let routing_type = match &rule.connector_selection { + ConnectorSelection::Priority(_) => RoutingType::Priority, + ConnectorSelection::VolumeSplit(_) => RoutingType::VolumeSplit, + }; + + Rule { + name: rule.name, + routing_type, + output: convert_output(rule.connector_selection), + statements: rule.statements.into_iter().map(convert_if_stmt).collect(), + } +} + +fn convert_if_stmt(stmt: ast::IfStatement) -> IfStatement { + IfStatement { + condition: stmt.condition.into_iter().map(convert_comparison).collect(), + nested: stmt + .nested + .map(|v| v.into_iter().map(convert_if_stmt).collect()), + } +} + +fn convert_comparison(c: ast::Comparison) -> Comparison { + Comparison { + lhs: c.lhs, + comparison: convert_comparison_type(c.comparison), + value: convert_value(c.value), + metadata: c.metadata, + } +} + +fn convert_comparison_type(ct: ast::ComparisonType) -> ComparisonType { + match ct { + ast::ComparisonType::Equal => ComparisonType::Equal, + ast::ComparisonType::NotEqual => ComparisonType::NotEqual, + ast::ComparisonType::LessThan => ComparisonType::LessThan, + ast::ComparisonType::LessThanEqual => ComparisonType::LessThanEqual, + ast::ComparisonType::GreaterThan => ComparisonType::GreaterThan, + ast::ComparisonType::GreaterThanEqual => ComparisonType::GreaterThanEqual, + } +} + +#[allow(clippy::unimplemented)] +fn convert_value(v: ast::ValueType) -> ValueType { + use ast::ValueType::*; + match v { + Number(n) => ValueType::Number(n.get_amount_as_i64().try_into().unwrap_or_default()), + EnumVariant(e) => ValueType::EnumVariant(e), + MetadataVariant(m) => ValueType::MetadataVariant(MetadataValue { + key: m.key, + value: m.value, + }), + StrValue(s) => ValueType::StrValue(s), + _ => unimplemented!(), // GlobalRef(r) => ValueType::GlobalRef(r), + } +} + +fn convert_output(sel: ConnectorSelection) -> Output { + match sel { + ConnectorSelection::Priority(choices) => { + Output::Priority(choices.into_iter().map(stringify_choice).collect()) + } + ConnectorSelection::VolumeSplit(vs) => Output::VolumeSplit( + vs.into_iter() + .map(|v| VolumeSplit { + split: v.split, + output: stringify_choice(v.connector), + }) + .collect(), + ), + } +} + +fn stringify_choice(c: RoutableConnectorChoice) -> String { + c.connector.to_string() +} diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs index 25a1838e95e..6b86bb83f54 100644 --- a/crates/router/src/core/routing.rs +++ b/crates/router/src/core/routing.rs @@ -31,7 +31,10 @@ use super::payouts; use super::{ errors::RouterResult, payments::{ - routing::{self as payments_routing}, + routing::{ + utils::*, + {self as payments_routing}, + }, OperationSessionGetters, }, }; @@ -118,6 +121,7 @@ impl RoutingAlgorithmUpdate { created_at: timestamp, modified_at: timestamp, algorithm_for: transaction_type, + decision_engine_routing_id: None, }; Self(algo) } @@ -153,14 +157,34 @@ pub async fn retrieve_merchant_routing_dictionary( ) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; - let routing_metadata = - super::utils::filter_objects_based_on_profile_id_list(profile_id_list, routing_metadata); + let routing_metadata = super::utils::filter_objects_based_on_profile_id_list( + profile_id_list.clone(), + routing_metadata, + ); let result = routing_metadata .into_iter() .map(ForeignInto::foreign_into) .collect::<Vec<_>>(); + if let Some(profile_ids) = profile_id_list { + let mut de_result: Vec<routing_types::RoutingDictionaryRecord> = vec![]; + // DE_TODO: need to replace this with batch API call to reduce the number of network calls + for profile_id in profile_ids { + let list_request = ListRountingAlgorithmsRequest { + created_by: profile_id.get_string_repr().to_string(), + }; + list_de_euclid_routing_algorithms(&state, list_request) + .await + .map_err(|e| { + router_env::logger::error!(decision_engine_error=?e, "decision_engine_euclid"); + }) + .ok() // Avoid throwing error if Decision Engine is not available or other errors + .map(|mut de_routing| de_result.append(&mut de_routing)); + } + compare_and_log_result(de_result, result.clone(), "list_routing".to_string()); + } + metrics::ROUTING_MERCHANT_DICTIONARY_RETRIEVE_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json( routing_types::RoutingKind::RoutingAlgorithm(result), @@ -249,6 +273,10 @@ pub async fn create_routing_algorithm_under_profile( request: routing_types::RoutingConfigRequest, transaction_type: enums::TransactionType, ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { + use api_models::routing::RoutingAlgorithm as EuclidAlgorithm; + + use crate::services::logger; + metrics::ROUTING_CREATE_REQUEST_RECEIVED.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); @@ -269,6 +297,7 @@ pub async fn create_routing_algorithm_under_profile( let algorithm = request .algorithm + .clone() .get_required_value("algorithm") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "algorithm", @@ -306,6 +335,37 @@ pub async fn create_routing_algorithm_under_profile( ) .await?; + let mut decision_engine_routing_id: Option<String> = None; + + if let Some(EuclidAlgorithm::Advanced(program)) = request.algorithm.clone() { + let internal_program: Program = program.into(); + let routing_rule = RoutingRule { + name: name.clone(), + description: Some(description.clone()), + created_by: profile_id.get_string_repr().to_string(), + algorithm: internal_program, + metadata: Some(RoutingMetadata { + kind: algorithm.get_kind().foreign_into(), + algorithm_for: transaction_type.to_owned(), + }), + }; + + decision_engine_routing_id = create_de_euclid_routing_algo(&state, &routing_rule) + .await + .map_err(|e| { + // errors are ignored as this is just for diff checking as of now (optional flow). + logger::error!(decision_engine_error=?e, "decision_engine_euclid"); + logger::debug!(decision_engine_request=?routing_rule, "decision_engine_euclid"); + }) + .ok(); + } + + if decision_engine_routing_id.is_some() { + logger::info!(routing_flow=?"create_euclid_routing_algorithm", is_equal=?"true", "decision_engine_euclid"); + } else { + logger::info!(routing_flow=?"create_euclid_routing_algorithm", is_equal=?"false", "decision_engine_euclid"); + } + let timestamp = common_utils::date_time::now(); let algo = RoutingAlgorithm { algorithm_id: algorithm_id.clone(), @@ -318,6 +378,7 @@ pub async fn create_routing_algorithm_under_profile( created_at: timestamp, modified_at: timestamp, algorithm_for: transaction_type.to_owned(), + decision_engine_routing_id, }; let record = db .insert_routing_algorithm(algo) @@ -536,7 +597,7 @@ pub async fn link_routing_config( db, key_manager_state, merchant_context.get_merchant_key_store(), - business_profile, + business_profile.clone(), dynamic_routing_ref, ) .await?; @@ -578,14 +639,37 @@ pub async fn link_routing_config( db, key_manager_state, merchant_context.get_merchant_key_store(), - business_profile, + business_profile.clone(), routing_ref, transaction_type, ) .await?; } }; - + if let Some(euclid_routing_id) = routing_algorithm.decision_engine_routing_id.clone() { + let routing_algo = ActivateRoutingConfigRequest { + created_by: business_profile.get_id().get_string_repr().to_string(), + routing_algorithm_id: euclid_routing_id, + }; + let link_result = link_de_euclid_routing_algorithm(&state, routing_algo).await; + match link_result { + Ok(_) => { + router_env::logger::info!( + routing_flow=?"link_routing_algorithm", + is_equal=?true, + "decision_engine_euclid" + ); + } + Err(e) => { + router_env::logger::info!( + routing_flow=?"link_routing_algorithm", + is_equal=?false, + error=?e, + "decision_engine_euclid" + ); + } + } + } metrics::ROUTING_LINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json( routing_algorithm.foreign_into(), @@ -1436,6 +1520,7 @@ pub async fn success_based_routing_update_configs( created_at: timestamp, modified_at: timestamp, algorithm_for: dynamic_routing_algo_to_update.algorithm_for, + decision_engine_routing_id: None, }; let record = db .insert_routing_algorithm(algo) @@ -1535,6 +1620,7 @@ pub async fn elimination_routing_update_configs( created_at: timestamp, modified_at: timestamp, algorithm_for: dynamic_routing_algo_to_update.algorithm_for, + decision_engine_routing_id: None, }; let record = db @@ -1680,6 +1766,7 @@ pub async fn contract_based_dynamic_routing_setup( created_at: timestamp, modified_at: timestamp, algorithm_for: common_enums::TransactionType::Payment, + decision_engine_routing_id: None, }; // 1. if dynamic_routing_algo_ref already present, insert contract based algo and disable success based @@ -1867,6 +1954,7 @@ pub async fn contract_based_routing_update_configs( created_at: timestamp, modified_at: timestamp, algorithm_for: dynamic_routing_algo_to_update.algorithm_for, + decision_engine_routing_id: None, }; let record = db .insert_routing_algorithm(algo) diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index dc594180e70..39b601ed296 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -1761,6 +1761,7 @@ pub async fn default_specific_dynamic_routing_setup( created_at: timestamp, modified_at: timestamp, algorithm_for: common_enums::TransactionType::Payment, + decision_engine_routing_id: None, } } routing_types::DynamicRoutingType::EliminationRouting => { @@ -1777,6 +1778,7 @@ pub async fn default_specific_dynamic_routing_setup( created_at: timestamp, modified_at: timestamp, algorithm_for: common_enums::TransactionType::Payment, + decision_engine_routing_id: None, } } diff --git a/crates/router/src/core/routing/transformers.rs b/crates/router/src/core/routing/transformers.rs index 85b6e5832a8..e9088ded2e7 100644 --- a/crates/router/src/core/routing/transformers.rs +++ b/crates/router/src/core/routing/transformers.rs @@ -32,6 +32,7 @@ impl ForeignFrom<RoutingProfileMetadata> for RoutingDictionaryRecord { created_at: value.created_at.assume_utc().unix_timestamp(), modified_at: value.modified_at.assume_utc().unix_timestamp(), algorithm_for: Some(value.algorithm_for), + decision_engine_routing_id: None, } } } @@ -48,6 +49,7 @@ impl ForeignFrom<RoutingAlgorithm> for RoutingDictionaryRecord { created_at: value.created_at.assume_utc().unix_timestamp(), modified_at: value.modified_at.assume_utc().unix_timestamp(), algorithm_for: Some(value.algorithm_for), + decision_engine_routing_id: value.decision_engine_routing_id, } } } diff --git a/migrations/2025-05-08-102850_add_de_euclid_id_in_routing_algorithm_table/down.sql b/migrations/2025-05-08-102850_add_de_euclid_id_in_routing_algorithm_table/down.sql new file mode 100644 index 00000000000..e0b2631d03b --- /dev/null +++ b/migrations/2025-05-08-102850_add_de_euclid_id_in_routing_algorithm_table/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE routing_algorithm +DROP COLUMN IF EXISTS decision_engine_routing_id; diff --git a/migrations/2025-05-08-102850_add_de_euclid_id_in_routing_algorithm_table/up.sql b/migrations/2025-05-08-102850_add_de_euclid_id_in_routing_algorithm_table/up.sql new file mode 100644 index 00000000000..b768b2a3070 --- /dev/null +++ b/migrations/2025-05-08-102850_add_de_euclid_id_in_routing_algorithm_table/up.sql @@ -0,0 +1,3 @@ +-- Your SQL goes here +ALTER TABLE routing_algorithm +ADD COLUMN decision_engine_routing_id VARCHAR(64); diff --git a/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql b/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql index 1140974d7c7..0e086500cc1 100644 --- a/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql +++ b/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql @@ -128,3 +128,7 @@ ALTER TABLE refund DROP COLUMN IF EXISTS internal_reference_id, DROP COLUMN IF EXISTS refund_id, DROP COLUMN IF EXISTS merchant_connector_id; + +-- Run below queries only when V1 is deprecated +ALTER TABLE routing_algorithm + DROP COLUMN IF EXISTS decision_engine_routing_id;
2025-04-29T10:13:40Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR integrates the Euclid-based decision engine with Hyperswitch’s dynamic routing infrastructure. It enables dual routing logic: legacy DSL-based evaluation and decision-engine-backed configurations. The integration ensures routing algorithms can be authored, activated, and evaluated via Euclid and linked seamlessly to merchant profiles. ## Outcomes - Adds support for storing and linking decision-engine routing IDs (`decision_engine_routing_id`) in the existing `routing_algorithm` table. - Enables creation and linking of Euclid routing configurations during algorithm creation and configuration linking flows. - Enhances observability with logging and tracing of decision engine interactions. - Preserves backward compatibility with existing static/dynamic routing mechanisms. ## Diff Hunk Explanation ### `crates/api_models/src/routing.rs` - Added `decision_engine_routing_id` to `RoutingDictionaryRecord` to expose the DE mapping in API responses. - Updated `RoutingAlgorithmKind` with `PartialEq` to aid in logic branching. ### `crates/diesel_models/src/routing_algorithm.rs` - Included new optional field `decision_engine_routing_id` to map to Euclid's algorithm record. ### `crates/diesel_models/src/schema.rs` - Altered `routing_algorithm` schema to include `decision_engine_routing_id VARCHAR(64)`. ### `crates/router/src/core/payments/routing.rs` - Imported `perform_decision_euclid_routing` into static routing flow for test execution and future use. ### `crates/router/src/core/routing.rs` - On routing creation, checks if the algorithm is a Euclid (Advanced) type, then creates it in the decision engine and stores the returned ID. - On routing configuration linking, activates the respective routing config in the decision engine using `ActivateRoutingConfigRequest`. - Enhances `retrieve_merchant_routing_dictionary` to fetch and append decision engine routing configs by profile ID. ### `crates/router/src/core/routing/transformers.rs` - Ensures `decision_engine_routing_id` is preserved and transformed when converting between internal and API models. ### `migrations/2025-05-08-102850_add_de_euclid_id_in_routing_algorithm_table/*.sql` - Adds and removes the `decision_engine_routing_id` column in the `routing_algorithm` table via Diesel migrations. ### Additional Changes - [ ] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Here is the complete testing [guidelines](https://docs.google.com/document/d/1xL3EJdMoCLXP5epOeqNsNYvqFqlJyhxss3LahQQ5xGU/edit?usp=sharing). ## Migrations ``` ALTER TABLE routing_algorithm ADD COLUMN decision_engine_routing_id VARCHAR(64); ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
04dc14a93022d03d74b02ae244ee8bb8afa50c27
04dc14a93022d03d74b02ae244ee8bb8afa50c27
juspay/hyperswitch
juspay__hyperswitch-7995
Bug: [FEATURE]: Add coingate, paystack connector specifications ### Feature Description Add coingate, paystack connector specifications ### Possible Implementation Add coingate, paystack connector specifications ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 17d346b9518..42f9a1abeec 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -673,6 +673,12 @@ apple_pay = { country = "AD,AE,AG,AL,AM,AO,AR,AT,AU,AZ,BA,BB,BD,BE,BG,BH,BI,BJ,B credit = {country = "AU,NZ,CN,HK,IN,LK,KR,MY,SG,GB,BE,FR,DE,IT,ME,NL,PL,ES,ZA,AR,BR,CO,MX,PA,UY,US,CA", currency = "AFN,ALL,DZD,AOA,ARS,AMD,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BYN,BZD,BMD,BTN,BOB,VES,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XAF,CLP,CNY,COP,KMF,CDF,CRC,HRK,CUP,CZK,DKK,DJF,DOP,XCD,EGP,ERN,ETB,EUR,FKP,FJD,XPF,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KGS,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,ANG,NZD,NIO,NGN,VUV,KPW,NOK,OMR,PKR,PAB,PGK,PYG,PEN,PHP,PLN,GBP,QAR,RON,RUB,RWF,SHP,SVC,WST,STN,SAR,RSD,SCR,SLL,SGD,SBD,SOS,ZAR,KRW,SSP,LKR,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,UGX,UAH,AED,USD,UYU,UZS,VND,XOF,YER,ZMW,ZWL"} debit = {country = "AU,NZ,CN,HK,IN,LK,KR,MY,SG,GB,BE,FR,DE,IT,ME,NL,PL,ES,ZA,AR,BR,CO,MX,PA,UY,US,CA", currency = "AFN,ALL,DZD,AOA,ARS,AMD,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BYN,BZD,BMD,BTN,BOB,VES,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XAF,CLP,CNY,COP,KMF,CDF,CRC,HRK,CUP,CZK,DKK,DJF,DOP,XCD,EGP,ERN,ETB,EUR,FKP,FJD,XPF,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KGS,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,ANG,NZD,NIO,NGN,VUV,KPW,NOK,OMR,PKR,PAB,PGK,PYG,PEN,PHP,PLN,GBP,QAR,RON,RUB,RWF,SHP,SVC,WST,STN,SAR,RSD,SCR,SLL,SGD,SBD,SOS,ZAR,KRW,SSP,LKR,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,UGX,UAH,AED,USD,UYU,UZS,VND,XOF,YER,ZMW,ZWL"} +[pm_filters.coingate] +crypto_currency = { country = "AL, AD, AT, BE, BA, BG, HR, CZ, DK, EE, FI, FR, DE, GR, HU, IS, IE, IT, LV, LT, LU, MT, MD, NL, NO, PL, PT, RO, RS, SK, SI, ES, SE, CH, UA, GB, AR, BR, CL, CO, CR, DO, SV, GD, MX, PE, LC, AU, NZ, CY, HK, IN, IL, JP, KR, QA, SA, SG, EG", currency = "EUR, USD, GBP" } + +[pm_filters.paystack] +eft = { country = "NG, ZA, GH, KE, CI", currency = "NGN, GHS, ZAR, KES, USD" } + [temp_locker_enable_config] bluesnap.payment_method = "card" nuvei.payment_method = "card" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index a79a21af9ae..60e87c35e1c 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -682,6 +682,12 @@ przelewy24 = { country = "PL", currency = "CZK,EUR,GBP,PLN" } trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NL,NZ,NO,PL,PT,ES,SE,CH,GB,US", currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" } +[pm_filters.coingate] +crypto_currency = { country = "AL, AD, AT, BE, BA, BG, HR, CZ, DK, EE, FI, FR, DE, GR, HU, IS, IE, IT, LV, LT, LU, MT, MD, NL, NO, PL, PT, RO, RS, SK, SI, ES, SE, CH, UA, GB, AR, BR, CL, CO, CR, DO, SV, GD, MX, PE, LC, AU, NZ, CY, HK, IN, IL, JP, KR, QA, SA, SG, EG", currency = "EUR, USD, GBP" } + +[pm_filters.paystack] +eft = { country = "NG, ZA, GH, KE, CI", currency = "NGN, GHS, ZAR, KES, USD" } + [payout_method_filters.adyenplatform] sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT,CZ,DE,HU,NO,PL,SE,GB,CH" , currency = "EUR,CZK,DKK,HUF,NOK,PLN,SEK,GBP,CHF" } diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 6862f7abebb..39b9013f21c 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -684,6 +684,12 @@ przelewy24 = { country = "PL", currency = "CZK,EUR,GBP,PLN" } trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NL,NZ,NO,PL,PT,ES,SE,CH,GB,US", currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" } +[pm_filters.coingate] +crypto_currency = { country = "AL, AD, AT, BE, BA, BG, HR, CZ, DK, EE, FI, FR, DE, GR, HU, IS, IE, IT, LV, LT, LU, MT, MD, NL, NO, PL, PT, RO, RS, SK, SI, ES, SE, CH, UA, GB, AR, BR, CL, CO, CR, DO, SV, GD, MX, PE, LC, AU, NZ, CY, HK, IN, IL, JP, KR, QA, SA, SG, EG", currency = "EUR, USD, GBP" } + +[pm_filters.paystack] +eft = { country = "NG, ZA, GH, KE, CI", currency = "NGN, GHS, ZAR, KES, USD" } + [payout_method_filters.stripe] ach = { country = "US", currency = "USD" } diff --git a/config/development.toml b/config/development.toml index debfebc8110..08275b720a0 100644 --- a/config/development.toml +++ b/config/development.toml @@ -841,6 +841,12 @@ debit = { country = "AD,AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,BE credit = { country = "BE,CH,CO,CR,EC,HN,MX,PA,PR,UY", currency = "CLP,COP,USD"} debit = { country = "BE,CH,CO,CR,EC,HN,MX,PA,PR,UY", currency = "CLP,COP,USD"} +[pm_filters.coingate] +crypto_currency = { country = "AL, AD, AT, BE, BA, BG, HR, CZ, DK, EE, FI, FR, DE, GR, HU, IS, IE, IT, LV, LT, LU, MT, MD, NL, NO, PL, PT, RO, RS, SK, SI, ES, SE, CH, UA, GB, AR, BR, CL, CO, CR, DO, SV, GD, MX, PE, LC, AU, NZ, CY, HK, IN, IL, JP, KR, QA, SA, SG, EG", currency = "EUR, USD, GBP" } + +[pm_filters.paystack] +eft = { country = "NG, ZA, GH, KE, CI", currency = "NGN, GHS, ZAR, KES, USD" } + [tokenization] stripe = { long_lived_token = false, payment_method = "wallet", payment_method_type = { type = "disable_only", list = "google_pay" } } checkout = { long_lived_token = false, payment_method = "wallet", apple_pay_pre_decrypt_flow = "network_tokenization" } diff --git a/config/docker_compose.toml b/config/docker_compose.toml index a5d0aeff9e9..bd7192700cf 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -802,6 +802,12 @@ przelewy24 = { country = "PL", currency = "CZK,EUR,GBP,PLN" } trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NL,NZ,NO,PL,PT,ES,SE,CH,GB,US", currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" } +[pm_filters.coingate] +crypto_currency = { country = "AL, AD, AT, BE, BA, BG, HR, CZ, DK, EE, FI, FR, DE, GR, HU, IS, IE, IT, LV, LT, LU, MT, MD, NL, NO, PL, PT, RO, RS, SK, SI, ES, SE, CH, UA, GB, AR, BR, CL, CO, CR, DO, SV, GD, MX, PE, LC, AU, NZ, CY, HK, IN, IL, JP, KR, QA, SA, SG, EG", currency = "EUR, USD, GBP" } + +[pm_filters.paystack] +eft = { country = "NG, ZA, GH, KE, CI", currency = "NGN, GHS, ZAR, KES, USD" } + [bank_config.online_banking_fpx] adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" fiuu.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_of_china,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" diff --git a/crates/hyperswitch_connectors/src/connectors/coingate.rs b/crates/hyperswitch_connectors/src/connectors/coingate.rs index d6cbe50e449..e6a4e06f47e 100644 --- a/crates/hyperswitch_connectors/src/connectors/coingate.rs +++ b/crates/hyperswitch_connectors/src/connectors/coingate.rs @@ -1,6 +1,7 @@ pub mod transformers; +use std::sync::LazyLock; -use common_enums::{CaptureMethod, PaymentMethod, PaymentMethodType}; +use common_enums::{enums, CaptureMethod, PaymentMethod, PaymentMethodType}; use common_utils::{ crypto, errors::CustomResult, @@ -21,7 +22,10 @@ use hyperswitch_domain_models::{ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, + }, types::{ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, @@ -517,25 +521,7 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Coingate } } -impl ConnectorValidation for Coingate { - fn validate_connector_against_payment_request( - &self, - capture_method: Option<CaptureMethod>, - _payment_method: PaymentMethod, - _pmt: Option<PaymentMethodType>, - ) -> CustomResult<(), errors::ConnectorError> { - let capture_method = capture_method.unwrap_or_default(); - match capture_method { - CaptureMethod::Automatic | CaptureMethod::SequentialAutomatic => Ok(()), - CaptureMethod::ManualMultiple | CaptureMethod::Scheduled | CaptureMethod::Manual => { - Err(utils::construct_not_supported_error_report( - capture_method, - self.id(), - )) - } - } - } -} +impl ConnectorValidation for Coingate {} #[async_trait::async_trait] impl webhooks::IncomingWebhook for Coingate { @@ -630,4 +616,45 @@ impl webhooks::IncomingWebhook for Coingate { } } -impl ConnectorSpecifications for Coingate {} +static COINGATE_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(|| { + let supported_capture_methods = + vec![CaptureMethod::Automatic, CaptureMethod::SequentialAutomatic]; + + let mut coingate_supported_payment_methods = SupportedPaymentMethods::new(); + + coingate_supported_payment_methods.add( + PaymentMethod::Crypto, + PaymentMethodType::CryptoCurrency, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods, + specific_features: None, + }, + ); + + coingate_supported_payment_methods + }); + +static COINGATE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Coingate", + description: "CoinGate's online payment solution makes it easy for businesses to accept Bitcoin, Ethereum, stablecoins and other cryptocurrencies for payments on any website.", + connector_type: enums::PaymentConnectorCategory::AlternativePaymentMethod, +}; + +static COINGATE_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payments]; + +impl ConnectorSpecifications for Coingate { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&COINGATE_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*COINGATE_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&COINGATE_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/paystack.rs b/crates/hyperswitch_connectors/src/connectors/paystack.rs index e613298d071..aabccbef50d 100644 --- a/crates/hyperswitch_connectors/src/connectors/paystack.rs +++ b/crates/hyperswitch_connectors/src/connectors/paystack.rs @@ -1,5 +1,7 @@ pub mod transformers; +use std::sync::LazyLock; +use common_enums::enums; use common_utils::{ crypto, errors::CustomResult, @@ -20,7 +22,10 @@ use hyperswitch_domain_models::{ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{ + ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, + SupportedPaymentMethods, SupportedPaymentMethodsExt, + }, types::{ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, @@ -652,4 +657,48 @@ impl webhooks::IncomingWebhook for Paystack { } } -impl ConnectorSpecifications for Paystack {} +static PAYSTACK_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = + LazyLock::new(|| { + let supported_capture_methods = vec![ + enums::CaptureMethod::Automatic, + enums::CaptureMethod::SequentialAutomatic, + ]; + + let mut paystack_supported_payment_methods = SupportedPaymentMethods::new(); + + paystack_supported_payment_methods.add( + enums::PaymentMethod::BankRedirect, + enums::PaymentMethodType::Eft, + PaymentMethodDetails { + mandates: enums::FeatureStatus::NotSupported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods, + specific_features: None, + }, + ); + + paystack_supported_payment_methods + }); + +static PAYSTACK_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { + display_name: "Paystack", + description: "Paystack is a Nigerian financial technology company that provides online and offline payment solutions to businesses across Africa.", + connector_type: enums::PaymentConnectorCategory::PaymentGateway, +}; + +static PAYSTACK_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 2] = + [enums::EventClass::Payments, enums::EventClass::Refunds]; + +impl ConnectorSpecifications for Paystack { + fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { + Some(&PAYSTACK_CONNECTOR_INFO) + } + + fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { + Some(&*PAYSTACK_SUPPORTED_PAYMENT_METHODS) + } + + fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { + Some(&PAYSTACK_SUPPORTED_WEBHOOK_FLOWS) + } +} diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 4dff7cedbe9..e4111d85236 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -532,6 +532,12 @@ debit = { country = "CN,HK,ID,MY,PH,SG,TH,TW,VN", currency = "CNY,HKD,IDR,MYR,PH credit = { country = "BE,CH,CO,CR,EC,HN,MX,PA,PR,UY", currency = "CLP,COP,USD"} debit = { country = "BE,CH,CO,CR,EC,HN,MX,PA,PR,UY", currency = "CLP,COP,USD"} +[pm_filters.coingate] +crypto_currency = { country = "AL, AD, AT, BE, BA, BG, HR, CZ, DK, EE, FI, FR, DE, GR, HU, IS, IE, IT, LV, LT, LU, MT, MD, NL, NO, PL, PT, RO, RS, SK, SI, ES, SE, CH, UA, GB, AR, BR, CL, CO, CR, DO, SV, GD, MX, PE, LC, AU, NZ, CY, HK, IN, IL, JP, KR, QA, SA, SG, EG", currency = "EUR, USD, GBP" } + +[pm_filters.paystack] +eft = { country = "NG, ZA, GH, KE, CI", currency = "NGN, GHS, ZAR, KES, USD" } + #tokenization configuration which describe token lifetime and payment method for specific connector [tokenization] stripe = { long_lived_token = false, payment_method = "wallet", payment_method_type = { type = "disable_only", list = "google_pay" } }
2025-05-09T11:30:58Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD Closes this [issue](https://github.com/juspay/hyperswitch/issues/7995) ## Description <!-- Describe your changes in detail --> Added coingate, paystack connector specifications ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Postman Test Request: ``` curl --location 'http://localhost:8080/feature_matrix' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: ***' ``` Response: ``` { "connector_count": 2, "connectors": [ { "name": "COINGATE", "display_name": "Coingate", "description": "CoinGate's online payment solution makes it easy for businesses to accept Bitcoin, Ethereum, stablecoins and other cryptocurrencies for payments on any website.", "category": "alternative_payment_method", "supported_payment_methods": [ { "payment_method": "crypto", "payment_method_type": "crypto_currency", "payment_method_type_display_name": "Crypto", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "sequential_automatic" ], "supported_countries": [ "POL", "CRI", "ARG", "FRA", "DEU", "HKG", "SVN", "ESP", "SRB", "ISR", "MLT", "JPN", "CHL", "UKR", "ALB", "LUX", "ITA", "HUN", "IRL", "KOR", "CHE", "CZE", "FIN", "AUS", "COL", "SVK", "HRV", "LCA", "EGY", "GRC", "MDA", "CYP", "PER", "GRD", "LVA", "PRT", "ROU", "DNK", "QAT", "AND", "NLD", "LTU", "SGP", "SAU", "AUT", "BRA", "NZL", "ISL", "NOR", "BGR", "MEX", "BEL", "BIH", "DOM", "GBR", "SWE", "EST", "IND", "SLV" ], "supported_currencies": [ "GBP", "EUR", "USD" ] } ], "supported_webhook_flows": [ "payments" ] }, { "name": "PAYSTACK", "display_name": "Paystack", "description": "Paystack is a Nigerian financial technology company that provides online and offline payment solutions to businesses across Africa.", "category": "payment_gateway", "supported_payment_methods": [ { "payment_method": "bank_redirect", "payment_method_type": "eft", "payment_method_type_display_name": "EFT", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "sequential_automatic" ], "supported_countries": [ "ZAF", "CIV", "NGA", "KEN", "GHA" ], "supported_currencies": [ "GHS", "USD", "KES", "NGN", "ZAR" ] } ], "supported_webhook_flows": [ "payments", "refunds" ] } ] } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
40fd473989b04f70c1dc78025a555a972ffe2596
40fd473989b04f70c1dc78025a555a972ffe2596
juspay/hyperswitch
juspay__hyperswitch-7989
Bug: [BUG] recurring mandate through bancontact card bank redirect via stripe fails connector throws below error: ``` "The provided bancontact PaymentMethod cannot be used again. It was used in a previous PaymentIntent or SetupIntent to set up a sepa_debit PaymentMethod, which can be used for multiple payments. To find the ID of the sepa_debit PaymentMethod, list the sepa_debit PaymentMethods associated with the Customer used to set up this PaymentMethod." ``` this is because we're just passing bancontact card payment method id instead of sepa direct debit payment method id. check: - https://docs.stripe.com/payments/bancontact - https://docs.stripe.com/payments/bancontact/save-during-payment?platform=web#web-charge-sepa-pm
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 9d372a5415c..ad2e1d7e855 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -2071,7 +2071,7 @@ impl TryFrom<&types::SetupMandateRouterData> for SetupIntentRequest { impl TryFrom<&types::TokenizationRouterData> for TokenRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> { - // Card flow for tokenization is handled seperately because of API contact difference + // Card flow for tokenization is handled separately because of API contact difference let request_payment_data = match &item.request.payment_method_data { domain::PaymentMethodData::Card(card_details) => { StripePaymentMethodData::CardToken(StripeCardToken { @@ -2683,6 +2683,45 @@ pub fn get_connector_metadata( Ok(next_action_response) } +pub fn get_payment_method_id( + latest_charge: Option<StripeChargeEnum>, + payment_method_id_from_intent_root: Secret<String>, +) -> String { + match latest_charge { + Some(StripeChargeEnum::ChargeObject(charge)) => match charge.payment_method_details { + Some(StripePaymentMethodDetailsResponse::Bancontact { bancontact }) => bancontact + .attached_payment_method + .map(|attached_payment_method| attached_payment_method.expose()) + .unwrap_or(payment_method_id_from_intent_root.expose()), + Some(StripePaymentMethodDetailsResponse::Ideal { ideal }) => ideal + .attached_payment_method + .map(|attached_payment_method| attached_payment_method.expose()) + .unwrap_or(payment_method_id_from_intent_root.expose()), + Some(StripePaymentMethodDetailsResponse::Blik) + | Some(StripePaymentMethodDetailsResponse::Eps) + | Some(StripePaymentMethodDetailsResponse::Fpx) + | Some(StripePaymentMethodDetailsResponse::Giropay) + | Some(StripePaymentMethodDetailsResponse::Przelewy24) + | Some(StripePaymentMethodDetailsResponse::Card { .. }) + | Some(StripePaymentMethodDetailsResponse::Klarna) + | Some(StripePaymentMethodDetailsResponse::Affirm) + | Some(StripePaymentMethodDetailsResponse::AfterpayClearpay) + | Some(StripePaymentMethodDetailsResponse::AmazonPay) + | Some(StripePaymentMethodDetailsResponse::ApplePay) + | Some(StripePaymentMethodDetailsResponse::Ach) + | Some(StripePaymentMethodDetailsResponse::Sepa) + | Some(StripePaymentMethodDetailsResponse::Becs) + | Some(StripePaymentMethodDetailsResponse::Bacs) + | Some(StripePaymentMethodDetailsResponse::Wechatpay) + | Some(StripePaymentMethodDetailsResponse::Alipay) + | Some(StripePaymentMethodDetailsResponse::CustomerBalance) + | Some(StripePaymentMethodDetailsResponse::Cashapp { .. }) + | None => payment_method_id_from_intent_root.expose(), + }, + Some(StripeChargeEnum::ChargeId(_)) | None => payment_method_id_from_intent_root.expose(), + } +} + impl<F, T> TryFrom<types::ResponseRouterData<F, PaymentIntentSyncResponse, T, types::PaymentsResponseData>> for types::RouterData<F, T, types::PaymentsResponseData> @@ -2713,46 +2752,11 @@ where // Implemented Save and re-use payment information for recurring charges // For more info: https://docs.stripe.com/recurring-payments#accept-recurring-payments // For backward compatibility payment_method_id & connector_mandate_id is being populated with the same value - let connector_mandate_id = Some(payment_method_id.clone().expose()); - let payment_method_id = match item.response.latest_charge.clone() { - Some(StripeChargeEnum::ChargeObject(charge)) => { - match charge.payment_method_details { - Some(StripePaymentMethodDetailsResponse::Bancontact { bancontact }) => { - bancontact - .attached_payment_method - .map(|attached_payment_method| attached_payment_method.expose()) - .unwrap_or(payment_method_id.expose()) - } - Some(StripePaymentMethodDetailsResponse::Ideal { ideal }) => ideal - .attached_payment_method - .map(|attached_payment_method| attached_payment_method.expose()) - .unwrap_or(payment_method_id.expose()), - Some(StripePaymentMethodDetailsResponse::Blik) - | Some(StripePaymentMethodDetailsResponse::Eps) - | Some(StripePaymentMethodDetailsResponse::Fpx) - | Some(StripePaymentMethodDetailsResponse::Giropay) - | Some(StripePaymentMethodDetailsResponse::Przelewy24) - | Some(StripePaymentMethodDetailsResponse::Card { .. }) - | Some(StripePaymentMethodDetailsResponse::Klarna) - | Some(StripePaymentMethodDetailsResponse::Affirm) - | Some(StripePaymentMethodDetailsResponse::AfterpayClearpay) - | Some(StripePaymentMethodDetailsResponse::AmazonPay) - | Some(StripePaymentMethodDetailsResponse::ApplePay) - | Some(StripePaymentMethodDetailsResponse::Ach) - | Some(StripePaymentMethodDetailsResponse::Sepa) - | Some(StripePaymentMethodDetailsResponse::Becs) - | Some(StripePaymentMethodDetailsResponse::Bacs) - | Some(StripePaymentMethodDetailsResponse::Wechatpay) - | Some(StripePaymentMethodDetailsResponse::Alipay) - | Some(StripePaymentMethodDetailsResponse::CustomerBalance) - | Some(StripePaymentMethodDetailsResponse::Cashapp { .. }) - | None => payment_method_id.expose(), - } - } - Some(StripeChargeEnum::ChargeId(_)) | None => payment_method_id.expose(), - }; + let payment_method_id = + get_payment_method_id(item.response.latest_charge.clone(), payment_method_id); + types::MandateReference { - connector_mandate_id, + connector_mandate_id: Some(payment_method_id.clone()), payment_method_id: Some(payment_method_id), mandate_metadata: None, connector_mandate_request_reference_id: None,
2025-05-08T11:33:59Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> this pr aims to fix the stripe bank redirect recurring mandate. for context, `bancontact` recurring mandates happen via `sepa direct debit` and hence, stripe sends 2 connector mandate ids as shown below: ```json { "payment_method": "pm_somevalue_1", "payment_method_details": { "bancontact": { "generated_sepa_debit": "pm_somevalue_2", "generated_sepa_debit_mandate": "mandate_somevalue", }, } ``` in order to do a recurring mandate, we are expected to pass the second connector mandate id. at the moment of me writing this, what is happening is that we pass the first connector mandate id that results in the recurring transaction to fail with error message provided in `motivation and context` section. the fix is to pass second connector mandte id for the payment methods that requires it. area of impact: - stripe recurring payments. ideally, this shouldn't affect any other payment method since this pr have no logic change. also, we fallback to using first connector mandate id if we do not get second connector mandate id. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> bancontact card bank redirect recurring mandates were failing with below message: ``` "The provided bancontact PaymentMethod cannot be used again. It was used in a previous PaymentIntent or SetupIntent to set up a sepa_debit PaymentMethod, which can be used for multiple payments. To find the ID of the sepa_debit PaymentMethod, list the sepa_debit PaymentMethods associated with the Customer used to set up this PaymentMethod." ``` this is not intended and should be fixed since the connector is live on production. closes #7989 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ### bancontact_card <details> <summary>create payment intent</summary> request: ```curl curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Accept-Language: ja' \ --header 'api-key: dev_12v5OB2ziszoDZL6Nl9nxIG65eJoFm4PtRKPayOZWpsCy74L5XTztLZX5N71VJ71' \ --data-raw '{ "amount": 6500, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 6500 } ], "currency": "EUR", "confirm": false, "capture_method": "automatic", "authentication_type": "three_ds", "setup_future_usage": "off_session", "request_external_three_ds_authentication": false, "email": "[email protected]", "description": "Hello this is description", "shipping": { "address": { "state": "California", "city": "Banglore", "country": "US", "line1": "sdsdfsdf", "line2": "hsgdbhd", "line3": "alsksoe", "zip": "571201", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "123456789", "country_code": "+1" } }, "connector_metadata": { "noon": { "order_category": "applepay" } }, "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "email": "[email protected]", "phone": { "number": "8056594427", "country_code": "+91" } }, "customer_id": "new" }' ``` response: ```json { "payment_id": "pay_46PJnwYjtyblbSWEEMH5", "merchant_id": "spriteMerchantBornAt1746687723", "status": "requires_payment_method", "amount": 6500, "net_amount": 6500, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_46PJnwYjtyblbSWEEMH5_secret_hy4q23J6YdCNB1WXw5tD", "created": "2025-05-08T11:00:41.266Z", "currency": "EUR", "customer_id": "new", "customer": { "id": "new", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": "Hello this is description", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": { "address": { "city": "Banglore", "country": "US", "line1": "sdsdfsdf", "line2": "hsgdbhd", "line3": "alsksoe", "zip": "571201", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "123456789", "country_code": "+1" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "order_details": [ { "brand": null, "amount": 6500, "category": null, "quantity": 1, "tax_rate": null, "product_id": null, "product_name": "Apple iphone 15", "product_type": null, "sub_category": null, "product_img_link": null, "product_tax_code": null, "total_tax_amount": null, "requires_shipping": null } ], "email": "[email protected]", "name": null, "phone": null, "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "new", "created_at": 1746702041, "expires": 1746705641, "secret": "epk_8f136979577f4053accd518f3b11fd29" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "applepay" }, "braintree": null, "adyen": null }, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_HJPiTC1q4eKhHsitqxTn", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-05-08T11:15:41.266Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-05-08T11:00:41.298Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` </details> <details> <summary>confirm payment intent</summary> request: ```curl curl --location 'http://localhost:8080/payments/pay_46PJnwYjtyblbSWEEMH5/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_12v5OB2ziszoDZL6Nl9nxIG65eJoFm4PtRKPayOZWpsCy74L5XTztLZX5N71VJ71' \ --data '{ "payment_id": "pay_46PJnwYjtyblbSWEEMH5", "payment_method_data": { "bank_redirect": { "bancontact_card": { "card_number": null, "card_exp_month": null, "card_exp_year": null, "card_holder_name": null, "billing_details": null } } }, "payment_method": "bank_redirect", "mandate_data": { "update_mandate_id": null, "customer_acceptance": { "acceptance_type": "online", "accepted_at": "2025-05-07T09:30:52.779Z", "online": { "ip_address": "103.23.45.1", "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:138.0) Gecko/20100101 Firefox/138.0" } }, "mandate_type": { "multi_use": { "amount": 1000, "currency": "USD", "start_date": "2023-04-21T00:00:00Z", "end_date": "2023-05-21T00:00:00Z", "metadata": { "frequency": "13" } } } }, "browser_info": { "color_depth": 24, "java_enabled": true, "java_script_enabled": true, "language": "en-US", "screen_height": 1117, "screen_width": 1728, "time_zone": -330, "ip_address": "103.159.11.202", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:138.0) Gecko/20100101 Firefox/138.0", "os_type": "macOS", "os_version": "10.15", "device_model": "Macintosh", "accept_language": "en" }, "payment_method_type": "bancontact_card", "payment_type": "new_mandate" }' ``` response: ```json { "payment_id": "pay_46PJnwYjtyblbSWEEMH5", "merchant_id": "spriteMerchantBornAt1746687723", "status": "requires_customer_action", "amount": 6500, "net_amount": 6500, "shipping_cost": null, "amount_capturable": 6500, "amount_received": 0, "connector": "stripe", "client_secret": "pay_46PJnwYjtyblbSWEEMH5_secret_hy4q23J6YdCNB1WXw5tD", "created": "2025-05-08T11:00:41.266Z", "currency": "EUR", "customer_id": "new", "customer": { "id": "new", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": "Hello this is description", "refunds": null, "disputes": null, "mandate_id": "man_GRW76jmrxiK7Cs8FDIJr", "mandate_data": { "update_mandate_id": null, "customer_acceptance": { "acceptance_type": "online", "accepted_at": "2025-05-07T09:30:52.779Z", "online": { "ip_address": "103.23.45.1", "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:138.0) Gecko/20100101 Firefox/138.0" } }, "mandate_type": { "multi_use": { "amount": 1000, "currency": "USD", "start_date": "2023-04-21T00:00:00.000Z", "end_date": "2023-05-21T00:00:00.000Z", "metadata": { "frequency": "13" } } } }, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "bank_redirect", "payment_method_data": { "bank_redirect": { "type": "BankRedirectResponse", "bank_name": null, "BancontactCard": { "last4": null, "card_exp_month": null, "card_exp_year": null, "card_holder_name": null } }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "Banglore", "country": "US", "line1": "sdsdfsdf", "line2": "hsgdbhd", "line3": "alsksoe", "zip": "571201", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "123456789", "country_code": "+1" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "order_details": [ { "brand": null, "amount": 6500, "category": null, "quantity": 1, "tax_rate": null, "product_id": null, "product_name": "Apple iphone 15", "product_type": null, "sub_category": null, "product_img_link": null, "product_tax_code": null, "total_tax_amount": null, "requires_shipping": null } ], "email": "[email protected]", "name": null, "phone": null, "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_46PJnwYjtyblbSWEEMH5/spriteMerchantBornAt1746687723/pay_46PJnwYjtyblbSWEEMH5_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "bancontact_card", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "pi_3RMSCKD5R7gDAGff0e5Xcr6s", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "applepay" }, "braintree": null, "adyen": null }, "feature_metadata": null, "reference_id": "pi_3RMSCKD5R7gDAGff0e5Xcr6s", "payment_link": null, "profile_id": "pro_HJPiTC1q4eKhHsitqxTn", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_nRFLCSCqPa4judlbaHUi", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-05-08T11:15:41.266Z", "fingerprint": null, "browser_info": { "os_type": "macOS", "language": "en-US", "time_zone": -330, "ip_address": "103.159.11.202", "os_version": "10.15", "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:138.0) Gecko/20100101 Firefox/138.0", "color_depth": 24, "device_model": "Macintosh", "java_enabled": true, "screen_width": 1728, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 1117, "accept_language": "en", "java_script_enabled": true }, "payment_method_id": "pm_gtwOpqeWWinhXFQIDNol", "payment_method_status": null, "updated": "2025-05-08T11:01:05.114Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` </details> <details> <summary>redirection</summary> |image| |-| |<img width="1707" alt="image" src="https://github.com/user-attachments/assets/b810dd24-52d2-4eae-9da1-218a7f6d263e" />| |<img width="873" alt="image" src="https://github.com/user-attachments/assets/85a8c5ef-317d-4e7c-baca-b437457f57e7" />| </details> <details> <summary>retrieve payment</summary> request: ```curl curl --location 'http://localhost:8080/payments/pay_46PJnwYjtyblbSWEEMH5?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_12v5OB2ziszoDZL6Nl9nxIG65eJoFm4PtRKPayOZWpsCy74L5XTztLZX5N71VJ71' ``` response: ```json { "payment_id": "pay_46PJnwYjtyblbSWEEMH5", "merchant_id": "spriteMerchantBornAt1746687723", "status": "succeeded", "amount": 6500, "net_amount": 6500, "shipping_cost": null, "amount_capturable": 0, "amount_received": 6500, "connector": "stripe", "client_secret": "pay_46PJnwYjtyblbSWEEMH5_secret_hy4q23J6YdCNB1WXw5tD", "created": "2025-05-08T11:00:41.266Z", "currency": "EUR", "customer_id": "new", "customer": { "id": "new", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": "Hello this is description", "refunds": null, "disputes": null, "mandate_id": "man_GRW76jmrxiK7Cs8FDIJr", "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "bank_redirect", "payment_method_data": { "bank_redirect": { "type": "BankRedirectResponse", "bank_name": null, "BancontactCard": { "last4": null, "card_exp_month": null, "card_exp_year": null, "card_holder_name": null } }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "Banglore", "country": "US", "line1": "sdsdfsdf", "line2": "hsgdbhd", "line3": "alsksoe", "zip": "571201", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "123456789", "country_code": "+1" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "order_details": [ { "brand": null, "amount": 6500, "category": null, "quantity": 1, "tax_rate": null, "product_id": null, "product_name": "Apple iphone 15", "product_type": null, "sub_category": null, "product_img_link": null, "product_tax_code": null, "total_tax_amount": null, "requires_shipping": null } ], "email": "[email protected]", "name": null, "phone": null, "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "bancontact_card", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "pi_3RMSCKD5R7gDAGff0e5Xcr6s", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "applepay" }, "braintree": null, "adyen": null }, "feature_metadata": null, "reference_id": "pi_3RMSCKD5R7gDAGff0e5Xcr6s", "payment_link": null, "profile_id": "pro_HJPiTC1q4eKhHsitqxTn", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_nRFLCSCqPa4judlbaHUi", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-05-08T11:15:41.266Z", "fingerprint": null, "browser_info": { "os_type": "macOS", "language": "en-US", "time_zone": -330, "ip_address": "103.159.11.202", "os_version": "10.15", "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:138.0) Gecko/20100101 Firefox/138.0", "color_depth": 24, "device_model": "Macintosh", "java_enabled": true, "screen_width": 1728, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 1117, "accept_language": "en", "java_script_enabled": true }, "payment_method_id": "pm_gtwOpqeWWinhXFQIDNol", "payment_method_status": "active", "updated": "2025-05-08T11:01:46.108Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` </details> <details> <summary>recurring payment</summary> request: ```curl curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_12v5OB2ziszoDZL6Nl9nxIG65eJoFm4PtRKPayOZWpsCy74L5XTztLZX5N71VJ71' \ --data '{ "amount": 999, "currency": "EUR", "capture_method": "automatic", "authentication_type": "no_three_ds", "confirm": true, "customer_id": "new", "off_session": true, "description": "Hello this is description", "recurring_details": { "type": "payment_method_id", "data": "pm_gtwOpqeWWinhXFQIDNol" } }' ``` response: ```json { "payment_id": "pay_9mzLCnix44o1qsG7iqQk", "merchant_id": "spriteMerchantBornAt1746687723", "status": "processing", "amount": 999, "net_amount": 999, "shipping_cost": null, "amount_capturable": 0, "amount_received": 0, "connector": "stripe", "client_secret": "pay_9mzLCnix44o1qsG7iqQk_secret_VIhPpAB29hISqbDVRk5d", "created": "2025-05-08T11:04:06.681Z", "currency": "EUR", "customer_id": "new", "customer": { "id": "new", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": "Hello this is description", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": true, "capture_on": null, "capture_method": "automatic", "payment_method": "bank_redirect", "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "[email protected]", "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "bancontact_card", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "new", "created_at": 1746702246, "expires": 1746705846, "secret": "epk_d600fbfd15cb48ea8c172d73aafe95d5" }, "manual_retry_allowed": false, "connector_transaction_id": "pi_3RMSFHD5R7gDAGff1bbPj0tS", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pi_3RMSFHD5R7gDAGff1bbPj0tS", "payment_link": null, "profile_id": "pro_HJPiTC1q4eKhHsitqxTn", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_nRFLCSCqPa4judlbaHUi", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-05-08T11:19:06.681Z", "fingerprint": null, "browser_info": null, "payment_method_id": "pm_gtwOpqeWWinhXFQIDNol", "payment_method_status": "active", "updated": "2025-05-08T11:04:08.011Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": "pm_1RMSCyD5R7gDAGffKy7iS7J8", "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` </details> <details> <summary>retrieve payment</summary> it takes a few seconds for the payment to get `succeeded`. since scheduler has not been set up locally, i had to manually do a force sync. process tracker should take care of this. request: ```curl curl --location 'http://localhost:8080/payments/pay_9mzLCnix44o1qsG7iqQk?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_12v5OB2ziszoDZL6Nl9nxIG65eJoFm4PtRKPayOZWpsCy74L5XTztLZX5N71VJ71' ``` response: ```json { "payment_id": "pay_9mzLCnix44o1qsG7iqQk", "merchant_id": "spriteMerchantBornAt1746687723", "status": "succeeded", "amount": 999, "net_amount": 999, "shipping_cost": null, "amount_capturable": 0, "amount_received": 999, "connector": "stripe", "client_secret": "pay_9mzLCnix44o1qsG7iqQk_secret_VIhPpAB29hISqbDVRk5d", "created": "2025-05-08T11:04:06.681Z", "currency": "EUR", "customer_id": "new", "customer": { "id": "new", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": "Hello this is description", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": true, "capture_on": null, "capture_method": "automatic", "payment_method": "bank_redirect", "payment_method_data": { "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" } }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "[email protected]", "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "bancontact_card", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "pi_3RMSFHD5R7gDAGff1bbPj0tS", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pi_3RMSFHD5R7gDAGff1bbPj0tS", "payment_link": null, "profile_id": "pro_HJPiTC1q4eKhHsitqxTn", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_nRFLCSCqPa4judlbaHUi", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-05-08T11:19:06.681Z", "fingerprint": null, "browser_info": null, "payment_method_id": "pm_gtwOpqeWWinhXFQIDNol", "payment_method_status": "active", "updated": "2025-05-08T11:04:24.246Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": "pm_1RMSCyD5R7gDAGffKy7iS7J8", "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` </details> ### cards just to be safe, tested cards as well (no other payment methods should be affected with this change other than bancontact and ideal): <details> <summary>create payment intent</summary> request: ```curl curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Accept-Language: ja' \ --header 'api-key: dev_12v5OB2ziszoDZL6Nl9nxIG65eJoFm4PtRKPayOZWpsCy74L5XTztLZX5N71VJ71' \ --data-raw '{ "amount": 6500, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 6500 } ], "currency": "EUR", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "setup_future_usage": "off_session", "request_external_three_ds_authentication": false, "email": "[email protected]", "description": "Hello this is description", "shipping": { "address": { "state": "California", "city": "Banglore", "country": "US", "line1": "sdsdfsdf", "line2": "hsgdbhd", "line3": "alsksoe", "zip": "571201", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "123456789", "country_code": "+1" } }, "connector_metadata": { "noon": { "order_category": "applepay" } }, "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "email": "[email protected]", "phone": { "number": "8056594427", "country_code": "+91" } }, "customer_id": "new" }' ``` response: ```json { "payment_id": "pay_HBBoIetDibOlU7NZd1Qv", "merchant_id": "spriteMerchantBornAt1746687723", "status": "requires_payment_method", "amount": 6500, "net_amount": 6500, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_HBBoIetDibOlU7NZd1Qv_secret_0wbaBIpByiAF96MgiX9l", "created": "2025-05-08T11:31:34.614Z", "currency": "EUR", "customer_id": "new", "customer": { "id": "new", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": "Hello this is description", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": { "address": { "city": "Banglore", "country": "US", "line1": "sdsdfsdf", "line2": "hsgdbhd", "line3": "alsksoe", "zip": "571201", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "123456789", "country_code": "+1" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "order_details": [ { "brand": null, "amount": 6500, "category": null, "quantity": 1, "tax_rate": null, "product_id": null, "product_name": "Apple iphone 15", "product_type": null, "sub_category": null, "product_img_link": null, "product_tax_code": null, "total_tax_amount": null, "requires_shipping": null } ], "email": "[email protected]", "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "new", "created_at": 1746703894, "expires": 1746707494, "secret": "epk_c491860832564ff5bd1561fe0715c809" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "applepay" }, "braintree": null, "adyen": null }, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_HJPiTC1q4eKhHsitqxTn", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-05-08T11:46:34.614Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-05-08T11:31:34.628Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` </details> <details> <summary>confirm payment intent</summary> request: ```curl curl --location 'http://localhost:8080/payments/pay_HBBoIetDibOlU7NZd1Qv/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_12v5OB2ziszoDZL6Nl9nxIG65eJoFm4PtRKPayOZWpsCy74L5XTztLZX5N71VJ71' \ --data '{ "payment_id": "pay_HBBoIetDibOlU7NZd1Qv", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "01", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "100" } }, "customer_acceptance": { "acceptance_type": "online", "accepted_at": "2025-05-07T09:30:52.779Z", "online": { "ip_address": "103.23.45.1", "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:138.0) Gecko/20100101 Firefox/138.0" } }, "browser_info": { "color_depth": 24, "java_enabled": true, "java_script_enabled": true, "language": "en-US", "screen_height": 1117, "screen_width": 1728, "time_zone": -330, "ip_address": "103.159.11.202", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:138.0) Gecko/20100101 Firefox/138.0", "os_type": "macOS", "os_version": "10.15", "device_model": "Macintosh", "accept_language": "en" }, "payment_type": "new_mandate" }' ``` response: ```json { "payment_id": "pay_HBBoIetDibOlU7NZd1Qv", "merchant_id": "spriteMerchantBornAt1746687723", "status": "succeeded", "amount": 6500, "net_amount": 6500, "shipping_cost": null, "amount_capturable": 0, "amount_received": 6500, "connector": "stripe", "client_secret": "pay_HBBoIetDibOlU7NZd1Qv_secret_0wbaBIpByiAF96MgiX9l", "created": "2025-05-08T11:31:34.614Z", "currency": "EUR", "customer_id": "new", "customer": { "id": "new", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": "Hello this is description", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "JP Morgan", "card_issuing_country": "INDIA", "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": { "cvc_check": "pass", "address_line1_check": "pass", "address_postal_code_check": "pass" }, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "Banglore", "country": "US", "line1": "sdsdfsdf", "line2": "hsgdbhd", "line3": "alsksoe", "zip": "571201", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "123456789", "country_code": "+1" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "order_details": [ { "brand": null, "amount": 6500, "category": null, "quantity": 1, "tax_rate": null, "product_id": null, "product_name": "Apple iphone 15", "product_type": null, "sub_category": null, "product_img_link": null, "product_tax_code": null, "total_tax_amount": null, "requires_shipping": null } ], "email": "[email protected]", "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "pi_3RMShLD5R7gDAGff0J19UjFK", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "applepay" }, "braintree": null, "adyen": null }, "feature_metadata": null, "reference_id": "pi_3RMShLD5R7gDAGff0J19UjFK", "payment_link": null, "profile_id": "pro_HJPiTC1q4eKhHsitqxTn", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_nRFLCSCqPa4judlbaHUi", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-05-08T11:46:34.614Z", "fingerprint": null, "browser_info": { "os_type": "macOS", "language": "en-US", "time_zone": -330, "ip_address": "103.159.11.202", "os_version": "10.15", "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:138.0) Gecko/20100101 Firefox/138.0", "color_depth": 24, "device_model": "Macintosh", "java_enabled": true, "screen_width": 1728, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 1117, "accept_language": "en", "java_script_enabled": true }, "payment_method_id": "pm_zRfLjuiAL44Uxnk817X1", "payment_method_status": "active", "updated": "2025-05-08T11:33:08.445Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": "pm_1RMShLD5R7gDAGffHkC1jRTH", "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` </details> <details> <summary>retrieve payment</summary> request: ```curl curl --location 'http://localhost:8080/payments/pay_HBBoIetDibOlU7NZd1Qv?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_12v5OB2ziszoDZL6Nl9nxIG65eJoFm4PtRKPayOZWpsCy74L5XTztLZX5N71VJ71' ``` response: ```json { "payment_id": "pay_HBBoIetDibOlU7NZd1Qv", "merchant_id": "spriteMerchantBornAt1746687723", "status": "succeeded", "amount": 6500, "net_amount": 6500, "shipping_cost": null, "amount_capturable": 0, "amount_received": 6500, "connector": "stripe", "client_secret": "pay_HBBoIetDibOlU7NZd1Qv_secret_0wbaBIpByiAF96MgiX9l", "created": "2025-05-08T11:31:34.614Z", "currency": "EUR", "customer_id": "new", "customer": { "id": "new", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": "Hello this is description", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "JP Morgan", "card_issuing_country": "INDIA", "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": { "cvc_check": "pass", "address_line1_check": "pass", "address_postal_code_check": "pass" }, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "Banglore", "country": "US", "line1": "sdsdfsdf", "line2": "hsgdbhd", "line3": "alsksoe", "zip": "571201", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "123456789", "country_code": "+1" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "order_details": [ { "brand": null, "amount": 6500, "category": null, "quantity": 1, "tax_rate": null, "product_id": null, "product_name": "Apple iphone 15", "product_type": null, "sub_category": null, "product_img_link": null, "product_tax_code": null, "total_tax_amount": null, "requires_shipping": null } ], "email": "[email protected]", "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "pi_3RMShLD5R7gDAGff0J19UjFK", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "applepay" }, "braintree": null, "adyen": null }, "feature_metadata": null, "reference_id": "pi_3RMShLD5R7gDAGff0J19UjFK", "payment_link": null, "profile_id": "pro_HJPiTC1q4eKhHsitqxTn", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_nRFLCSCqPa4judlbaHUi", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-05-08T11:46:34.614Z", "fingerprint": null, "browser_info": { "os_type": "macOS", "language": "en-US", "time_zone": -330, "ip_address": "103.159.11.202", "os_version": "10.15", "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:138.0) Gecko/20100101 Firefox/138.0", "color_depth": 24, "device_model": "Macintosh", "java_enabled": true, "screen_width": 1728, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 1117, "accept_language": "en", "java_script_enabled": true }, "payment_method_id": "pm_zRfLjuiAL44Uxnk817X1", "payment_method_status": "active", "updated": "2025-05-08T11:33:08.445Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` </details> <details> <summary>recurring payment</summary> request: ```curl curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_12v5OB2ziszoDZL6Nl9nxIG65eJoFm4PtRKPayOZWpsCy74L5XTztLZX5N71VJ71' \ --data '{ "amount": 999, "currency": "EUR", "capture_method": "automatic", "authentication_type": "no_three_ds", "confirm": true, "customer_id": "new", "off_session": true, "description": "Hello this is description", "recurring_details": { "type": "payment_method_id", "data": "pm_zRfLjuiAL44Uxnk817X1" } }' ``` response: ```json { "payment_id": "pay_G1ksB3bXcirAt7CtsYP9", "merchant_id": "spriteMerchantBornAt1746687723", "status": "succeeded", "amount": 999, "net_amount": 999, "shipping_cost": null, "amount_capturable": 0, "amount_received": 999, "connector": "stripe", "client_secret": "pay_G1ksB3bXcirAt7CtsYP9_secret_JJMUdSp6SpS7jpMq49XJ", "created": "2025-05-08T11:33:31.891Z", "currency": "EUR", "customer_id": "new", "customer": { "id": "new", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": "Hello this is description", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": true, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "JP Morgan", "card_issuing_country": "INDIA", "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "[email protected]", "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "new", "created_at": 1746704011, "expires": 1746707611, "secret": "epk_500bb0e95274419294502e0009d42a7a" }, "manual_retry_allowed": false, "connector_transaction_id": "pi_3RMShkD5R7gDAGff0wXmhdaI", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pi_3RMShkD5R7gDAGff0wXmhdaI", "payment_link": null, "profile_id": "pro_HJPiTC1q4eKhHsitqxTn", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_nRFLCSCqPa4judlbaHUi", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-05-08T11:48:31.891Z", "fingerprint": null, "browser_info": null, "payment_method_id": "pm_zRfLjuiAL44Uxnk817X1", "payment_method_status": "active", "updated": "2025-05-08T11:33:33.085Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": "pm_1RMShLD5R7gDAGffHkC1jRTH", "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` </details> <details> <summary>retrieve payment</summary> request: ```curl curl --location 'http://localhost:8080/payments/pay_G1ksB3bXcirAt7CtsYP9?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_12v5OB2ziszoDZL6Nl9nxIG65eJoFm4PtRKPayOZWpsCy74L5XTztLZX5N71VJ71' ``` response: ```json { "payment_id": "pay_G1ksB3bXcirAt7CtsYP9", "merchant_id": "spriteMerchantBornAt1746687723", "status": "succeeded", "amount": 999, "net_amount": 999, "shipping_cost": null, "amount_capturable": 0, "amount_received": 999, "connector": "stripe", "client_secret": "pay_G1ksB3bXcirAt7CtsYP9_secret_JJMUdSp6SpS7jpMq49XJ", "created": "2025-05-08T11:33:31.891Z", "currency": "EUR", "customer_id": "new", "customer": { "id": "new", "name": null, "email": "[email protected]", "phone": null, "phone_country_code": null }, "description": "Hello this is description", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": true, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "JP Morgan", "card_issuing_country": "INDIA", "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" } }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "[email protected]", "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "pi_3RMShkD5R7gDAGff0wXmhdaI", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pi_3RMShkD5R7gDAGff0wXmhdaI", "payment_link": null, "profile_id": "pro_HJPiTC1q4eKhHsitqxTn", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_nRFLCSCqPa4judlbaHUi", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-05-08T11:48:31.891Z", "fingerprint": null, "browser_info": null, "payment_method_id": "pm_zRfLjuiAL44Uxnk817X1", "payment_method_status": "active", "updated": "2025-05-08T11:33:33.085Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` </details> ### sepa bank debit <details> <summary>create payment intent</summary> request: ```curl curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_XUootVtd5tq25XA9K0SB0i4RO3pTTnpbWHebsUNfRig5WL5tSfBOneCjirenpAbP' \ --data-raw '{ "amount": 1800, "currency": "USD", "confirm": false, "capture_method": "automatic", "customer_id": "new", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "return_url": "https://duck.com", "setup_future_usage": "off_session", "business_country": "US", "billing": { "address": { "line1": "1467", "line2": "HarrisonStreet", "line3": "HarrisonStreet", "city": "SanFransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Swangi", "last_name": "Kumari" } }, "metadata": { "order_details": { "product_name": "Apple iphone 15", "quantity": 1, "amount": 1800, "account_name": "transaction_processing" } } }' ``` response: ```json { "payment_id": "pay_D33h9y1S7XIksb1w2QgY", "merchant_id": "spriteMerchantBornAt1746713671", "status": "requires_payment_method", "amount": 1800, "net_amount": 1800, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_D33h9y1S7XIksb1w2QgY_secret_d8ZcBuLS0GFvx41fzBC7", "created": "2025-05-08T14:55:42.337Z", "currency": "USD", "customer_id": "new", "customer": { "id": "new", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": { "address": { "city": "SanFransico", "country": "US", "line1": "1467", "line2": "HarrisonStreet", "line3": "HarrisonStreet", "zip": "94122", "state": "California", "first_name": "Swangi", "last_name": "Kumari" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "new", "created_at": 1746716142, "expires": 1746719742, "secret": "epk_6373b3d1a39548e1abdde6e0ae993a13" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": { "order_details": { "amount": 1800, "quantity": 1, "account_name": "transaction_processing", "product_name": "Apple iphone 15" } }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_Vy4QgpvAOgLLqtMSro11", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-05-08T15:10:42.337Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-05-08T14:55:42.346Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` </details> <details> <summary>confirm payment intent</summary> request: ```curl curl --location 'http://localhost:8080/payments/pay_1lAtqj68APg0Lzz1RBZ7/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_XUootVtd5tq25XA9K0SB0i4RO3pTTnpbWHebsUNfRig5WL5tSfBOneCjirenpAbP' \ --data-raw '{ "payment_id": "pay_1lAtqj68APg0Lzz1RBZ7", "payment_method": "bank_debit", "payment_method_type": "ach", "payment_method_data": { "bank_debit": { "ach_bank_debit": { "billing_details": { "name": "John Doe", "email": "[email protected]" }, "account_number": "000123456789", "routing_number": "110000000" } } }, "mandate_data": { "customer_acceptance": { "acceptance_type": "online", "accepted_at": "2022-09-10T10:11:12Z", "online": { "ip_address": "123.32.25.123", "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" } }, "mandate_type": { "single_use": { "amount": 6540, "currency": "USD" } } }, "browser_info": { "color_depth": 24, "java_enabled": true, "java_script_enabled": true, "language": "en-US", "screen_height": 1117, "screen_width": 1728, "time_zone": -330, "ip_address": "103.159.11.202", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:138.0) Gecko/20100101 Firefox/138.0", "os_type": "macOS", "os_version": "10.15", "device_model": "Macintosh", "accept_language": "en" }, "payment_type": "new_mandate" }' ``` response: ```json { "payment_id": "pay_D33h9y1S7XIksb1w2QgY", "merchant_id": "spriteMerchantBornAt1746713671", "status": "requires_customer_action", "amount": 1800, "net_amount": 1800, "shipping_cost": null, "amount_capturable": 1800, "amount_received": 0, "connector": "stripe", "client_secret": "pay_D33h9y1S7XIksb1w2QgY_secret_d8ZcBuLS0GFvx41fzBC7", "created": "2025-05-08T14:55:42.337Z", "currency": "USD", "customer_id": "new", "customer": { "id": "new", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": "man_a9rhLB6kISXVyJiI90UO", "mandate_data": { "update_mandate_id": null, "customer_acceptance": { "acceptance_type": "online", "accepted_at": "2022-09-10T10:11:12.000Z", "online": { "ip_address": "123.32.25.123", "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36" } }, "mandate_type": { "single_use": { "amount": 6540, "currency": "USD", "start_date": null, "end_date": null, "metadata": null } } }, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "bank_debit", "payment_method_data": { "bank_debit": { "ach": { "account_number": "0001****6789", "routing_number": "110***000", "card_holder_name": null, "bank_account_holder_name": null, "bank_name": null, "bank_type": null, "bank_holder_type": null } }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "SanFransico", "country": "US", "line1": "1467", "line2": "HarrisonStreet", "line3": "HarrisonStreet", "zip": "94122", "state": "California", "first_name": "Swangi", "last_name": "Kumari" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_D33h9y1S7XIksb1w2QgY/spriteMerchantBornAt1746713671/pay_D33h9y1S7XIksb1w2QgY_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "ach", "connector_label": "stripe_US_default", "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "pi_3RMVrQD5R7gDAGff0m8bN954", "frm_message": null, "metadata": { "order_details": { "amount": 1800, "quantity": 1, "account_name": "transaction_processing", "product_name": "Apple iphone 15" } }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pi_3RMVrQD5R7gDAGff0m8bN954", "payment_link": null, "profile_id": "pro_Vy4QgpvAOgLLqtMSro11", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_YjqGIfO85PF6xZnG3Ouq", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-05-08T15:10:42.337Z", "fingerprint": null, "browser_info": { "os_type": "macOS", "language": "en-US", "time_zone": -330, "ip_address": "103.159.11.202", "os_version": "10.15", "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:138.0) Gecko/20100101 Firefox/138.0", "color_depth": 24, "device_model": "Macintosh", "java_enabled": true, "screen_width": 1728, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 1117, "accept_language": "en", "java_script_enabled": true }, "payment_method_id": "pm_FS5SzbT7bfiigu9uBFYb", "payment_method_status": null, "updated": "2025-05-08T14:55:44.926Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` </details> <details> <summary>retrieve payment</summary> request: ```curl curl --location 'http://localhost:8080/payments/pay_1lAtqj68APg0Lzz1RBZ7?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_XUootVtd5tq25XA9K0SB0i4RO3pTTnpbWHebsUNfRig5WL5tSfBOneCjirenpAbP' ``` response: ```json { "payment_id": "pay_D33h9y1S7XIksb1w2QgY", "merchant_id": "spriteMerchantBornAt1746713671", "status": "succeeded", "amount": 1800, "net_amount": 1800, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1800, "connector": "stripe", "client_secret": "pay_D33h9y1S7XIksb1w2QgY_secret_d8ZcBuLS0GFvx41fzBC7", "created": "2025-05-08T14:55:42.337Z", "currency": "USD", "customer_id": "new", "customer": { "id": "new", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": "man_a9rhLB6kISXVyJiI90UO", "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "bank_debit", "payment_method_data": { "bank_debit": { "ach": { "account_number": "0001****6789", "routing_number": "110***000", "card_holder_name": null, "bank_account_holder_name": null, "bank_name": null, "bank_type": null, "bank_holder_type": null } }, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "SanFransico", "country": "US", "line1": "1467", "line2": "HarrisonStreet", "line3": "HarrisonStreet", "zip": "94122", "state": "California", "first_name": "Swangi", "last_name": "Kumari" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "ach", "connector_label": "stripe_US_default", "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "pi_3RMVrQD5R7gDAGff0m8bN954", "frm_message": null, "metadata": { "order_details": { "amount": 1800, "quantity": 1, "account_name": "transaction_processing", "product_name": "Apple iphone 15" } }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pi_3RMVrQD5R7gDAGff0m8bN954", "payment_link": null, "profile_id": "pro_Vy4QgpvAOgLLqtMSro11", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_YjqGIfO85PF6xZnG3Ouq", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-05-08T15:10:42.337Z", "fingerprint": null, "browser_info": { "os_type": "macOS", "language": "en-US", "time_zone": -330, "ip_address": "103.159.11.202", "os_version": "10.15", "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:138.0) Gecko/20100101 Firefox/138.0", "color_depth": 24, "device_model": "Macintosh", "java_enabled": true, "screen_width": 1728, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 1117, "accept_language": "en", "java_script_enabled": true }, "payment_method_id": "pm_FS5SzbT7bfiigu9uBFYb", "payment_method_status": "active", "updated": "2025-05-08T14:56:21.244Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` </details> <details> <summary>recurring payment</summary> request: ```curl curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_XUootVtd5tq25XA9K0SB0i4RO3pTTnpbWHebsUNfRig5WL5tSfBOneCjirenpAbP' \ --data '{ "amount": 999, "currency": "USD", "capture_method": "automatic", "authentication_type": "no_three_ds", "confirm": true, "customer_id": "new", "off_session": true, "description": "Hello this is description" , "recurring_details": { "type": "mandate_id", "data": "man_a9rhLB6kISXVyJiI90UO" } }' ``` response: ```json { "payment_id": "pay_1lAtqj68APg0Lzz1RBZ7", "merchant_id": "spriteMerchantBornAt1746713671", "status": "processing", "amount": 999, "net_amount": 999, "shipping_cost": null, "amount_capturable": 0, "amount_received": 0, "connector": "stripe", "client_secret": "pay_1lAtqj68APg0Lzz1RBZ7_secret_qXpuGLVGCrCAQgfRWj6y", "created": "2025-05-08T14:59:41.984Z", "currency": "USD", "customer_id": "new", "customer": { "id": "new", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": "Hello this is description", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": true, "capture_on": null, "capture_method": "automatic", "payment_method": "bank_debit", "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "ach", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "new", "created_at": 1746716381, "expires": 1746719981, "secret": "epk_6ae53619f23e479aaa49fe78ff0ad42b" }, "manual_retry_allowed": false, "connector_transaction_id": "pi_3RMVvGD5R7gDAGff0gI0w0fr", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pi_3RMVvGD5R7gDAGff0gI0w0fr", "payment_link": null, "profile_id": "pro_Vy4QgpvAOgLLqtMSro11", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_YjqGIfO85PF6xZnG3Ouq", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-05-08T15:14:41.984Z", "fingerprint": null, "browser_info": null, "payment_method_id": "pm_FS5SzbT7bfiigu9uBFYb", "payment_method_status": "active", "updated": "2025-05-08T14:59:42.837Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": "pm_1RMVrQD5R7gDAGffic9TPCEG", "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` </details> <details> <summary>retrieve payment</summary> request: ```curl curl --location 'http://localhost:8080/payments/pay_1lAtqj68APg0Lzz1RBZ7?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_XUootVtd5tq25XA9K0SB0i4RO3pTTnpbWHebsUNfRig5WL5tSfBOneCjirenpAbP' ``` response: ```json { "payment_id": "pay_1lAtqj68APg0Lzz1RBZ7", "merchant_id": "spriteMerchantBornAt1746713671", "status": "succeeded", "amount": 999, "net_amount": 999, "shipping_cost": null, "amount_capturable": 0, "amount_received": 999, "connector": "stripe", "client_secret": "pay_1lAtqj68APg0Lzz1RBZ7_secret_qXpuGLVGCrCAQgfRWj6y", "created": "2025-05-08T14:59:41.984Z", "currency": "USD", "customer_id": "new", "customer": { "id": "new", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": "Hello this is description", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": true, "capture_on": null, "capture_method": "automatic", "payment_method": "bank_debit", "payment_method_data": { "billing": { "address": { "city": "SanFransico", "country": "US", "line1": "1467", "line2": "HarrisonStreet", "line3": "HarrisonStreet", "zip": "94122", "state": "California", "first_name": "John Doe", "last_name": null }, "phone": null, "email": "[email protected]" } }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "ach", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "pi_3RMVvGD5R7gDAGff0gI0w0fr", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pi_3RMVvGD5R7gDAGff0gI0w0fr", "payment_link": null, "profile_id": "pro_Vy4QgpvAOgLLqtMSro11", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_YjqGIfO85PF6xZnG3Ouq", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-05-08T15:14:41.984Z", "fingerprint": null, "browser_info": null, "payment_method_id": "pm_FS5SzbT7bfiigu9uBFYb", "payment_method_status": "active", "updated": "2025-05-08T15:00:06.980Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": "pm_1RMVrQD5R7gDAGffic9TPCEG", "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
fafe4d99286f4aaf3965b23a9e06648f3a43b108
fafe4d99286f4aaf3965b23a9e06648f3a43b108
juspay/hyperswitch
juspay__hyperswitch-7988
Bug: [BUG] Add feature flags and db methods for refunds v2 to non kv config Add feature flags and db methods for refunds v2 to non kv config. Currently the compilation fails if we disable the `kv_store` feature flag
diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs index 7d9a8703169..eead49c12da 100644 --- a/crates/router/src/db/refund.rs +++ b/crates/router/src/db/refund.rs @@ -91,7 +91,7 @@ pub trait RefundInterface { offset: i64, ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError>; - #[cfg(all(feature = "v2", feature = "refunds_v2"))] + #[cfg(all(feature = "v2", feature = "refunds_v2", feature = "olap"))] async fn filter_refund_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, @@ -138,7 +138,7 @@ pub trait RefundInterface { storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError>; - #[cfg(all(feature = "v2", feature = "refunds_v2"))] + #[cfg(all(feature = "v2", feature = "refunds_v2", feature = "olap"))] async fn get_total_count_of_refunds( &self, merchant_id: &common_utils::id_type::MerchantId, @@ -150,6 +150,7 @@ pub trait RefundInterface { #[cfg(not(feature = "kv_store"))] mod storage { use error_stack::report; + use hyperswitch_domain_models::refunds; use router_env::{instrument, tracing}; use super::RefundInterface; @@ -162,6 +163,7 @@ mod storage { #[async_trait::async_trait] impl RefundInterface for Store { + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[instrument(skip_all)] async fn find_refund_by_internal_reference_id_merchant_id( &self, @@ -208,6 +210,19 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) } + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + async fn find_refund_by_id( + &self, + id: &common_utils::id_type::GlobalRefundId, + storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<storage_types::Refund, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + storage_types::Refund::find_by_global_id(&conn, id) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } + + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[instrument(skip_all)] async fn update_refund( &self, @@ -221,6 +236,21 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) } + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + #[instrument(skip_all)] + async fn update_refund( + &self, + this: storage_types::Refund, + refund: storage_types::RefundUpdate, + _storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<storage_types::Refund, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + this.update_with_id(&conn, refund) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } + + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[instrument(skip_all)] async fn find_refund_by_merchant_id_refund_id( &self, @@ -234,6 +264,7 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[instrument(skip_all)] async fn find_refund_by_merchant_id_connector_refund_id_connector( &self, @@ -253,6 +284,7 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[instrument(skip_all)] async fn find_refund_by_payment_id_merchant_id( &self, @@ -266,7 +298,11 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) } - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] #[instrument(skip_all)] async fn filter_refund_by_constraints( &self, @@ -288,7 +324,33 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) } - #[cfg(feature = "olap")] + #[cfg(all(feature = "v2", feature = "refunds_v2", feature = "olap"))] + #[instrument(skip_all)] + async fn filter_refund_by_constraints( + &self, + merchant_id: &common_utils::id_type::MerchantId, + refund_details: refunds::RefundListConstraints, + _storage_scheme: enums::MerchantStorageScheme, + limit: i64, + offset: i64, + ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + <diesel_models::refund::Refund as storage_types::RefundDbExt>::filter_by_constraints( + &conn, + merchant_id, + refund_details, + limit, + offset, + ) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } + + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] #[instrument(skip_all)] async fn filter_refund_by_meta_constraints( &self, @@ -306,7 +368,11 @@ mod storage { .map_err(|error|report!(errors::StorageError::from(error))) } - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] #[instrument(skip_all)] async fn get_refund_status_with_count( &self, @@ -321,7 +387,11 @@ mod storage { .map_err(|error|report!(errors::StorageError::from(error))) } - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "refunds_v2"), + feature = "olap" + ))] #[instrument(skip_all)] async fn get_total_count_of_refunds( &self, @@ -338,6 +408,24 @@ mod storage { .await .map_err(|error| report!(errors::StorageError::from(error))) } + + #[cfg(all(feature = "v2", feature = "refunds_v2", feature = "olap"))] + #[instrument(skip_all)] + async fn get_total_count_of_refunds( + &self, + merchant_id: &common_utils::id_type::MerchantId, + refund_details: refunds::RefundListConstraints, + _storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<i64, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + <diesel_models::refund::Refund as storage_types::RefundDbExt>::get_refunds_count( + &conn, + merchant_id, + refund_details, + ) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } } } @@ -943,7 +1031,7 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) } - #[cfg(all(feature = "v2", feature = "refunds_v2"))] + #[cfg(all(feature = "v2", feature = "refunds_v2", feature = "olap"))] #[instrument(skip_all)] async fn filter_refund_by_constraints( &self, @@ -1024,7 +1112,7 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) } - #[cfg(all(feature = "v2", feature = "refunds_v2"))] + #[cfg(all(feature = "v2", feature = "refunds_v2", feature = "olap"))] #[instrument(skip_all)] async fn get_total_count_of_refunds( &self,
2025-05-08T10:19:43Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR contains support for db calls that are used in refunds v2 core flows for non kv config. There are 2 ways that HS use to interact with DB, using KV and without KV. In code we represent it by `kv_store` feature flag. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Since KV is default in HyperSwitch, if some opensource merchant wants to use our product without this kv feature, the refunds v2 flow will still be supported through postgres DB calls. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - Go to router crate's `Cargo.toml`, in default_common under features, remove `kv_store` - Use `just run_v2` to run the app. - Create Refund API Call ``` curl --location 'http://localhost:8080/v2/refunds' \ --header 'X-Profile-Id: pro_qxkJLjzL3XeuzDKGsp1S' \ --header 'Content-Type: application/json' \ --header 'Authorization: api-key=dev_R1HetQC825xDVj4cT8Pjj5EARrN86R1hBluyhMbXqMVQcJC1JvUHQKrIzaKzPCZt' \ --data '{ "payment_id":"12345_pay_019734bc76567f31ae472001903e2185", "merchant_reference_id":"1748936520", "reason":"Paid by mistake", "metadata":{ "foo":"bar" } }' ``` - Response from the above call ``` { "id": "12345_ref_019734bcee6c76a3bd9f37fb0a57a062", "payment_id": "12345_pay_019734bc76567f31ae472001903e2185", "merchant_reference_id": "1748936487", "amount": 70, "currency": "EUR", "status": "succeeded", "reason": "Paid by mistake", "metadata": { "foo": "bar" }, "error_details": { "code": "", "message": "" }, "created_at": "2025-06-03T07:41:26.559Z", "updated_at": "2025-06-03T07:41:27.758Z", "connector": "stripe", "profile_id": "pro_qxkJLjzL3XeuzDKGsp1S", "merchant_connector_id": "mca_tgPFo4p9Yhg6COBKqVLF", "connector_refund_reference_id": null } ``` - Refunds Retrieve API Call ``` curl --location 'http://localhost:8080/v2/refunds/12345_ref_019734bcee6c76a3bd9f37fb0a57a062' \ --header 'x-profile-id: pro_qxkJLjzL3XeuzDKGsp1S' \ --header 'Authorization: api-key=dev_R1HetQC825xDVj4cT8Pjj5EARrN86R1hBluyhMbXqMVQcJC1JvUHQKrIzaKzPCZt' ``` - Response from the above call ``` { "id": "12345_ref_019734bcee6c76a3bd9f37fb0a57a062", "payment_id": "12345_pay_019734bc76567f31ae472001903e2185", "merchant_reference_id": "1748936487", "amount": 70, "currency": "EUR", "status": "succeeded", "reason": "Paid by mistake", "metadata": { "foo": "bar" }, "error_details": { "code": "", "message": "" }, "created_at": "2025-06-03T07:41:26.559Z", "updated_at": "2025-06-03T07:41:27.758Z", "connector": "stripe", "profile_id": "pro_qxkJLjzL3XeuzDKGsp1S", "merchant_connector_id": "mca_tgPFo4p9Yhg6COBKqVLF", "connector_refund_reference_id": null } ``` - Screenshot of DB record of this refund <img width="586" alt="Screenshot 2025-06-03 at 1 14 30 PM" src="https://github.com/user-attachments/assets/e875aa2c-fb32-4cf7-8530-f70532d21046" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
06c5215c0edf0ed47cc55fd5216c4642cc515f37
06c5215c0edf0ed47cc55fd5216c4642cc515f37
juspay/hyperswitch
juspay__hyperswitch-7985
Bug: [BUG] Update Metadata for connectors other than stripe throws 500 ### Bug Description Update metadata gives 500 error for other connectors than stripe Need to change this to 400 ```sh curl --location 'http://localhost:8080/payments/pay_fvWhpXtZwWZSE1JfTUI4/update_metadata' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_HIEBRxKrtikKM4GesRs3p2yo2syIYQyx0KmoDPcHKQersYRTfdfEBYWRslkq1XK4' \ --data '{ "metadata": { "order_id": "999999897989", "dbehcb": "2324", "abb": "efe" } }' ``` this gets `500` error response. ### Expected Behavior Give 4xx error ### Actual Behavior Gives 500 for any connectors other than stripe ### Steps To Reproduce - Create a successful payment via any connector - call update_metadata for that payment ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/router/src/core/payments/flows/update_metadata_flow.rs b/crates/router/src/core/payments/flows/update_metadata_flow.rs index 9281775e393..f9a6790356a 100644 --- a/crates/router/src/core/payments/flows/update_metadata_flow.rs +++ b/crates/router/src/core/payments/flows/update_metadata_flow.rs @@ -30,19 +30,18 @@ impl merchant_recipient_data: Option<types::MerchantRecipientData>, header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>, ) -> RouterResult<types::PaymentsUpdateMetadataRouterData> { - Box::pin(transformers::construct_payment_router_data::< - api::UpdateMetadata, - types::PaymentsUpdateMetadataData, - >( - state, - self.clone(), - connector_id, - merchant_context, - customer, - merchant_connector_account, - merchant_recipient_data, - header_payload, - )) + Box::pin( + transformers::construct_payment_router_data_for_update_metadata( + state, + self.clone(), + connector_id, + merchant_context, + customer, + merchant_connector_account, + merchant_recipient_data, + header_payload, + ), + ) .await } diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index ac7b4cb00b1..211be32ce9f 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -1247,6 +1247,195 @@ where Ok(router_data) } +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] +#[instrument(skip_all)] +#[allow(clippy::too_many_arguments)] +pub async fn construct_payment_router_data_for_update_metadata<'a>( + state: &'a SessionState, + payment_data: PaymentData<api::UpdateMetadata>, + connector_id: &str, + merchant_context: &domain::MerchantContext, + customer: &'a Option<domain::Customer>, + merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, + header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>, +) -> RouterResult< + types::RouterData< + api::UpdateMetadata, + types::PaymentsUpdateMetadataData, + types::PaymentsResponseData, + >, +> { + let (payment_method, router_data); + + fp_utils::when(merchant_connector_account.is_disabled(), || { + Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled) + })?; + + let test_mode = merchant_connector_account.is_test_mode_on(); + + let auth_type: types::ConnectorAuthType = merchant_connector_account + .get_connector_account_details() + .parse_value("ConnectorAuthType") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while parsing value for ConnectorAuthType")?; + + payment_method = payment_data + .payment_attempt + .payment_method + .or(payment_data.payment_attempt.payment_method) + .get_required_value("payment_method_type")?; + + // [#44]: why should response be filled during request + let response = Err(hyperswitch_domain_models::router_data::ErrorResponse { + code: "IR_20".to_string(), + message: "Update metadata is not implemented for this connector".to_string(), + reason: None, + status_code: http::StatusCode::BAD_REQUEST.as_u16(), + attempt_status: None, + connector_transaction_id: None, + network_decline_code: None, + network_advice_code: None, + network_error_message: None, + }); + + let additional_data = PaymentAdditionalData { + router_base_url: state.base_url.clone(), + connector_name: connector_id.to_string(), + payment_data: payment_data.clone(), + state, + customer_data: customer, + }; + + let customer_id = customer.to_owned().map(|customer| customer.customer_id); + + let supported_connector = &state + .conf + .multiple_api_version_supported_connectors + .supported_connectors; + let connector_enum = api_models::enums::Connector::from_str(connector_id) + .change_context(errors::ConnectorError::InvalidConnectorName) + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "connector", + }) + .attach_printable_lazy(|| format!("unable to parse connector name {connector_id:?}"))?; + + let connector_api_version = if supported_connector.contains(&connector_enum) { + state + .store + .find_config_by_key(&format!("connector_api_version_{connector_id}")) + .await + .map(|value| value.config) + .ok() + } else { + None + }; + + let apple_pay_flow = payments::decide_apple_pay_flow( + state, + payment_data.payment_attempt.payment_method_type, + Some(merchant_connector_account), + ); + + let unified_address = if let Some(payment_method_info) = + payment_data.payment_method_info.clone() + { + let payment_method_billing = payment_method_info + .payment_method_billing_address + .map(|decrypted_data| decrypted_data.into_inner().expose()) + .map(|decrypted_value| decrypted_value.parse_value("payment_method_billing_address")) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to parse payment_method_billing_address")?; + payment_data + .address + .clone() + .unify_with_payment_data_billing(payment_method_billing) + } else { + payment_data.address + }; + let connector_mandate_request_reference_id = payment_data + .payment_attempt + .connector_mandate_detail + .as_ref() + .and_then(|detail| detail.get_connector_mandate_request_reference_id()); + + crate::logger::debug!("unified address details {:?}", unified_address); + + router_data = types::RouterData { + flow: PhantomData, + merchant_id: merchant_context.get_merchant_account().get_id().clone(), + customer_id, + tenant_id: state.tenant.tenant_id.clone(), + connector: connector_id.to_owned(), + payment_id: payment_data + .payment_attempt + .payment_id + .get_string_repr() + .to_owned(), + attempt_id: payment_data.payment_attempt.attempt_id.clone(), + status: payment_data.payment_attempt.status, + payment_method, + connector_auth_type: auth_type, + description: payment_data.payment_intent.description.clone(), + address: unified_address, + auth_type: payment_data + .payment_attempt + .authentication_type + .unwrap_or_default(), + connector_meta_data: merchant_connector_account.get_metadata(), + connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), + request: types::PaymentsUpdateMetadataData::try_from(additional_data)?, + response, + amount_captured: payment_data + .payment_intent + .amount_captured + .map(|amt| amt.get_amount_as_i64()), + minor_amount_captured: payment_data.payment_intent.amount_captured, + access_token: None, + session_token: None, + reference_id: None, + payment_method_status: payment_data.payment_method_info.map(|info| info.status), + payment_method_token: payment_data + .pm_token + .map(|token| types::PaymentMethodToken::Token(Secret::new(token))), + connector_customer: payment_data.connector_customer_id, + recurring_mandate_payment_data: payment_data.recurring_mandate_payment_data, + connector_request_reference_id: core_utils::get_connector_request_reference_id( + &state.conf, + merchant_context.get_merchant_account().get_id(), + &payment_data.payment_attempt, + ), + preprocessing_id: payment_data.payment_attempt.preprocessing_step_id, + #[cfg(feature = "payouts")] + payout_method_data: None, + #[cfg(feature = "payouts")] + quote_id: None, + test_mode, + payment_method_balance: None, + connector_api_version, + connector_http_status_code: None, + external_latency: None, + apple_pay_flow, + frm_metadata: None, + refund_id: None, + dispute_id: None, + connector_response: None, + integrity_check: Ok(()), + additional_merchant_data: merchant_recipient_data.map(|data| { + api_models::admin::AdditionalMerchantData::foreign_from( + types::AdditionalMerchantData::OpenBankingRecipientData(data), + ) + }), + header_payload, + connector_mandate_request_reference_id, + authentication_id: None, + psd2_sca_exemption_type: payment_data.payment_intent.psd2_sca_exemption_type, + }; + + Ok(router_data) +} + pub trait ToResponse<F, D, Op> where Self: Sized,
2025-05-08T08:53:44Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Update metadata gives `500` error for other connectors than stripe Change this to `400` ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - Make a successful payment using any connector other than stripe - make update metadata request ```sh curl --location 'http://localhost:8080/payments/pay_X77ffJsUvEW94JadFVpw/update_metadata' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_bTSpZN98PGIduROqZNoagEkN7XUxd7dof6cgl8K061T2Vvw6rRaplOVejfRiYUI9' \ --data '{ "metadata": { "order_id": "999999897989", "dbehcb": "2324", "abb": "efe" } }' ``` Response should be 400 ```json { "error": { "type": "connector", "message": "IR_20: Flow is not implemented for this connector", "code": "CE_00", "connector": "cybersource" } } ``` - update metadata for successful payment created via stripe should give success response ```json { "payment_id": "pay_fvWhpXtZwWZSE1JfTUI4", "metadata": { "abb": "efe", "dbehcb": "2324", "order_id": "999999897989" } } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
a4a564fee2782947e3d75ed20d4b18f9b45e7e8a
a4a564fee2782947e3d75ed20d4b18f9b45e7e8a
juspay/hyperswitch
juspay__hyperswitch-7974
Bug: [FEATURE] add validations for API models ### Feature Description Some of the fields in API requests are passed as is to the DB for storing them. The problem is that DB mostly has length constraints which usually leads to 5xx in the API response. This behavior is incorrect as it should be a 4xx error (incorrect request). For these reasons, an interface can be implemented in the API layer which takes such validations into consideration. For example - `return_url` in API request can exceed 255 characters, but if a request is made, it will throw a 5xx error. ### Possible Implementation 1. Make use of https://docs.rs/validator/latest/validator/ 2. Write a procedural macro for validating the schema attributes being used for generating OpenAPI specifications. This helps in keeping a single source of truth between different components (DB and API specifications) ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/Cargo.lock b/Cargo.lock index 2f690549217..85eb9fb2345 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6586,6 +6586,7 @@ dependencies = [ "serde_json", "strum 0.26.3", "syn 2.0.100", + "url", "utoipa", ] diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 2315a94b5e0..c4bf23abfad 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -19091,7 +19091,8 @@ "type": "string", "description": "The URL to which you want the user to be redirected after the completion of the payment operation", "example": "https://hyperswitch.io", - "nullable": true + "nullable": true, + "maxLength": 255 }, "setup_future_usage": { "allOf": [ @@ -19181,7 +19182,7 @@ "description": "A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data", "example": "mandate_iwer89rnjef349dni3", "nullable": true, - "maxLength": 255 + "maxLength": 64 }, "browser_info": { "allOf": [ @@ -19495,7 +19496,8 @@ "type": "string", "description": "The URL to which you want the user to be redirected after the completion of the payment operation", "example": "https://hyperswitch.io", - "nullable": true + "nullable": true, + "maxLength": 255 }, "setup_future_usage": { "allOf": [ @@ -19579,7 +19581,7 @@ "description": "A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data", "example": "mandate_iwer89rnjef349dni3", "nullable": true, - "maxLength": 255 + "maxLength": 64 }, "browser_info": { "allOf": [ @@ -20752,7 +20754,8 @@ "type": "string", "description": "The URL to which you want the user to be redirected after the completion of the payment operation", "example": "https://hyperswitch.io", - "nullable": true + "nullable": true, + "maxLength": 255 }, "setup_future_usage": { "allOf": [ @@ -20848,7 +20851,7 @@ "description": "A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data", "example": "mandate_iwer89rnjef349dni3", "nullable": true, - "maxLength": 255 + "maxLength": 64 }, "browser_info": { "allOf": [ @@ -21962,7 +21965,8 @@ "type": "string", "description": "The URL to which you want the user to be redirected after the completion of the payment operation", "example": "https://hyperswitch.io", - "nullable": true + "nullable": true, + "maxLength": 255 }, "setup_future_usage": { "allOf": [ diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index b313a3b3033..5286f071a1a 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -847,6 +847,7 @@ impl AmountDetailsUpdate { Clone, ToSchema, router_derive::PolymorphicSchema, + router_derive::ValidateSchema, )] #[generate_schemas(PaymentsCreateRequest, PaymentsUpdateRequest, PaymentsConfirmRequest)] #[serde(deny_unknown_fields)] @@ -963,7 +964,7 @@ pub struct PaymentsRequest { pub description: Option<String>, /// The URL to which you want the user to be redirected after the completion of the payment operation - #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] + #[schema(value_type = Option<String>, example = "https://hyperswitch.io", max_length = 255)] pub return_url: Option<Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] @@ -1018,7 +1019,7 @@ pub struct PaymentsRequest { pub customer_acceptance: Option<CustomerAcceptance>, /// A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data - #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] + #[schema(max_length = 64, example = "mandate_iwer89rnjef349dni3")] #[remove_in(PaymentsUpdateRequest)] pub mandate_id: Option<String>, diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 3ea5049742d..36c8b727b5a 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -37,6 +37,12 @@ pub async fn payments_create( ) -> impl Responder { let flow = Flow::PaymentsCreate; let mut payload = json_payload.into_inner(); + if let Err(err) = payload + .validate() + .map_err(|message| errors::ApiErrorResponse::InvalidRequestData { message }) + { + return api::log_and_return_error_response(err.into()); + }; if let Some(api_enums::CaptureMethod::Scheduled) = payload.capture_method { return http_not_implemented(); @@ -575,6 +581,12 @@ pub async fn payments_update( ) -> impl Responder { let flow = Flow::PaymentsUpdate; let mut payload = json_payload.into_inner(); + if let Err(err) = payload + .validate() + .map_err(|message| errors::ApiErrorResponse::InvalidRequestData { message }) + { + return api::log_and_return_error_response(err.into()); + }; if let Some(api_enums::CaptureMethod::Scheduled) = payload.capture_method { return http_not_implemented(); @@ -755,6 +767,12 @@ pub async fn payments_confirm( ) -> impl Responder { let flow = Flow::PaymentsConfirm; let mut payload = json_payload.into_inner(); + if let Err(err) = payload + .validate() + .map_err(|message| errors::ApiErrorResponse::InvalidRequestData { message }) + { + return api::log_and_return_error_response(err.into()); + }; if let Some(api_enums::CaptureMethod::Scheduled) = payload.capture_method { return http_not_implemented(); diff --git a/crates/router/tests/macros.rs b/crates/router/tests/macros.rs index 3a5301efa5f..50244b99514 100644 --- a/crates/router/tests/macros.rs +++ b/crates/router/tests/macros.rs @@ -40,3 +40,64 @@ mod flat_struct_test { assert_eq!(flat_user_map, required_map); } } + +#[cfg(test)] +mod validate_schema_test { + #![allow(clippy::unwrap_used)] + + use router_derive::ValidateSchema; + use url::Url; + + #[test] + fn test_validate_schema() { + #[derive(ValidateSchema)] + struct Payment { + #[schema(min_length = 5, max_length = 12)] + payment_id: String, + + #[schema(min_length = 10, max_length = 100)] + description: Option<String>, + + #[schema(max_length = 255)] + return_url: Option<Url>, + } + + // Valid case + let valid_payment = Payment { + payment_id: "payment_123".to_string(), + description: Some("This is a valid description".to_string()), + return_url: Some("https://example.com/return".parse().unwrap()), + }; + assert!(valid_payment.validate().is_ok()); + + // Invalid: payment_id too short + let invalid_id = Payment { + payment_id: "pay".to_string(), + description: Some("This is a valid description".to_string()), + return_url: Some("https://example.com/return".parse().unwrap()), + }; + let err = invalid_id.validate().unwrap_err(); + assert!( + err.contains("payment_id must be at least 5 characters long. Received 3 characters") + ); + + // Invalid: payment_id too long + let invalid_desc = Payment { + payment_id: "payment_12345".to_string(), + description: Some("This is a valid description".to_string()), + return_url: Some("https://example.com/return".parse().unwrap()), + }; + let err = invalid_desc.validate().unwrap_err(); + assert!( + err.contains("payment_id must be at most 12 characters long. Received 13 characters") + ); + + // None values should pass validation + let none_values = Payment { + payment_id: "payment_123".to_string(), + description: None, + return_url: None, + }; + assert!(none_values.validate().is_ok()); + } +} diff --git a/crates/router_derive/Cargo.toml b/crates/router_derive/Cargo.toml index 72cf9605f9b..d6d25f281ca 100644 --- a/crates/router_derive/Cargo.toml +++ b/crates/router_derive/Cargo.toml @@ -24,6 +24,7 @@ diesel = { version = "2.2.3", features = ["postgres"] } error-stack = "0.4.1" serde = { version = "1.0.197", features = ["derive"] } serde_json = "1.0.115" +url = { version = "2.5.0", features = ["serde"] } utoipa = "4.2.0" common_utils = { version = "0.1.0", path = "../common_utils" } diff --git a/crates/router_derive/src/lib.rs b/crates/router_derive/src/lib.rs index d1fb543318f..5e422dcda59 100644 --- a/crates/router_derive/src/lib.rs +++ b/crates/router_derive/src/lib.rs @@ -764,3 +764,65 @@ pub fn derive_to_encryption_attr(input: proc_macro::TokenStream) -> proc_macro:: .unwrap_or_else(|err| err.into_compile_error()) .into() } + +/// Derives validation functionality for structs with string-based fields that have +/// schema attributes specifying constraints like minimum and maximum lengths. +/// +/// This macro generates a `validate()` method that checks if string based fields +/// meet the length requirements specified in their schema attributes. +/// +/// ## Supported Types +/// - Option<T> or T: where T: String or Url +/// +/// ## Supported Schema Attributes +/// +/// - `min_length`: Specifies the minimum allowed character length +/// - `max_length`: Specifies the maximum allowed character length +/// +/// ## Example +/// +/// ``` +/// use utoipa::ToSchema; +/// use router_derive::ValidateSchema; +/// use url::Url; +/// +/// #[derive(Default, ToSchema, ValidateSchema)] +/// pub struct PaymentRequest { +/// #[schema(min_length = 10, max_length = 255)] +/// pub description: String, +/// +/// #[schema(example = "https://example.com/return", max_length = 255)] +/// pub return_url: Option<Url>, +/// +/// // Field without constraints +/// pub amount: u64, +/// } +/// +/// let payment = PaymentRequest { +/// description: "Too short".to_string(), +/// return_url: Some(Url::parse("https://very-long-domain.com/callback").unwrap()), +/// amount: 1000, +/// }; +/// +/// let validation_result = payment.validate(); +/// assert!(validation_result.is_err()); +/// assert_eq!( +/// validation_result.unwrap_err(), +/// "description must be at least 10 characters long. Received 9 characters" +/// ); +/// ``` +/// +/// ## Notes +/// - For `Option` fields, validation is only performed when the value is `Some` +/// - Fields without schema attributes or with unsupported types are ignored +/// - The validation stops on the first error encountered +/// - The generated `validate()` method returns `Ok(())` if all validations pass, or +/// `Err(String)` with an error message if any validations fail. +#[proc_macro_derive(ValidateSchema, attributes(schema))] +pub fn validate_schema(input: proc_macro::TokenStream) -> proc_macro::TokenStream { + let input = syn::parse_macro_input!(input as syn::DeriveInput); + + macros::validate_schema_derive(input) + .unwrap_or_else(|error| error.into_compile_error()) + .into() +} diff --git a/crates/router_derive/src/macros.rs b/crates/router_derive/src/macros.rs index e227c6533e9..42afb638cff 100644 --- a/crates/router_derive/src/macros.rs +++ b/crates/router_derive/src/macros.rs @@ -4,6 +4,7 @@ pub(crate) mod generate_permissions; pub(crate) mod generate_schema; pub(crate) mod misc; pub(crate) mod operation; +pub(crate) mod schema; pub(crate) mod to_encryptable; pub(crate) mod try_get_enum; @@ -18,6 +19,7 @@ pub(crate) use self::{ diesel::{diesel_enum_derive_inner, diesel_enum_text_derive_inner}, generate_permissions::generate_permissions_inner, generate_schema::polymorphic_macro_derive_inner, + schema::validate_schema_derive, to_encryptable::derive_to_encryption, }; diff --git a/crates/router_derive/src/macros/schema.rs b/crates/router_derive/src/macros/schema.rs new file mode 100644 index 00000000000..c79d9a071cc --- /dev/null +++ b/crates/router_derive/src/macros/schema.rs @@ -0,0 +1,88 @@ +mod helpers; + +use quote::quote; + +use crate::macros::{ + helpers as macro_helpers, + schema::helpers::{HasSchemaParameters, IsSchemaFieldApplicableForValidation}, +}; + +pub fn validate_schema_derive(input: syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> { + let name = &input.ident; + + // Extract struct fields + let fields = macro_helpers::get_struct_fields(input.data) + .map_err(|error| syn::Error::new(proc_macro2::Span::call_site(), error))?; + + // Map over each field + let validation_checks = fields.iter().filter_map(|field| { + let field_name = field.ident.as_ref()?; + let field_type = &field.ty; + + // Check if field type is valid for validation + let is_field_valid = match IsSchemaFieldApplicableForValidation::from(field_type) { + IsSchemaFieldApplicableForValidation::Invalid => return None, + val => val, + }; + + // Parse attribute parameters for 'schema' + let schema_params = match field.get_schema_parameters() { + Ok(params) => params, + Err(_) => return None, + }; + + let min_length = schema_params.min_length; + let max_length = schema_params.max_length; + + // Skip if no length validation is needed + if min_length.is_none() && max_length.is_none() { + return None; + } + + let min_check = min_length.map(|min_val| { + quote! { + if value_len < #min_val { + return Err(format!("{} must be at least {} characters long. Received {} characters", + stringify!(#field_name), #min_val, value_len)); + } + } + }).unwrap_or_else(|| quote! {}); + + let max_check = max_length.map(|max_val| { + quote! { + if value_len > #max_val { + return Err(format!("{} must be at most {} characters long. Received {} characters", + stringify!(#field_name), #max_val, value_len)); + } + } + }).unwrap_or_else(|| quote! {}); + + // Generate length validation + if is_field_valid == IsSchemaFieldApplicableForValidation::ValidOptional { + Some(quote! { + if let Some(value) = &self.#field_name { + let value_len = value.as_str().len(); + #min_check + #max_check + } + }) + } else { + Some(quote! { + { + let value_len = self.#field_name.as_str().len(); + #min_check + #max_check + } + }) + } + }).collect::<Vec<_>>(); + + Ok(quote! { + impl #name { + pub fn validate(&self) -> Result<(), String> { + #(#validation_checks)* + Ok(()) + } + } + }) +} diff --git a/crates/router_derive/src/macros/schema/helpers.rs b/crates/router_derive/src/macros/schema/helpers.rs new file mode 100644 index 00000000000..54954e24d64 --- /dev/null +++ b/crates/router_derive/src/macros/schema/helpers.rs @@ -0,0 +1,189 @@ +use proc_macro2::TokenStream; +use quote::ToTokens; +use syn::{parse::Parse, Field, LitInt, LitStr, Token, TypePath}; + +use crate::macros::helpers::{get_metadata_inner, occurrence_error}; + +mod keyword { + use syn::custom_keyword; + + // Schema metadata + custom_keyword!(value_type); + custom_keyword!(min_length); + custom_keyword!(max_length); + custom_keyword!(example); +} + +pub enum SchemaParameterVariant { + ValueType { + keyword: keyword::value_type, + value: TypePath, + }, + MinLength { + keyword: keyword::min_length, + value: LitInt, + }, + MaxLength { + keyword: keyword::max_length, + value: LitInt, + }, + Example { + keyword: keyword::example, + value: LitStr, + }, +} + +impl Parse for SchemaParameterVariant { + fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { + let lookahead = input.lookahead1(); + if lookahead.peek(keyword::value_type) { + let keyword = input.parse()?; + input.parse::<Token![=]>()?; + let value = input.parse()?; + Ok(Self::ValueType { keyword, value }) + } else if lookahead.peek(keyword::min_length) { + let keyword = input.parse()?; + input.parse::<Token![=]>()?; + let value = input.parse()?; + Ok(Self::MinLength { keyword, value }) + } else if lookahead.peek(keyword::max_length) { + let keyword = input.parse()?; + input.parse::<Token![=]>()?; + let value = input.parse()?; + Ok(Self::MaxLength { keyword, value }) + } else if lookahead.peek(keyword::example) { + let keyword = input.parse()?; + input.parse::<Token![=]>()?; + let value = input.parse()?; + Ok(Self::Example { keyword, value }) + } else { + Err(lookahead.error()) + } + } +} + +impl ToTokens for SchemaParameterVariant { + fn to_tokens(&self, tokens: &mut TokenStream) { + match self { + Self::ValueType { keyword, .. } => keyword.to_tokens(tokens), + Self::MinLength { keyword, .. } => keyword.to_tokens(tokens), + Self::MaxLength { keyword, .. } => keyword.to_tokens(tokens), + Self::Example { keyword, .. } => keyword.to_tokens(tokens), + } + } +} + +pub trait FieldExt { + /// Get all the schema metadata associated with a field. + fn get_schema_metadata(&self) -> syn::Result<Vec<SchemaParameterVariant>>; +} + +impl FieldExt for Field { + fn get_schema_metadata(&self) -> syn::Result<Vec<SchemaParameterVariant>> { + get_metadata_inner("schema", &self.attrs) + } +} + +#[derive(Clone, Debug, Default)] +pub struct SchemaParameters { + pub value_type: Option<TypePath>, + pub min_length: Option<usize>, + pub max_length: Option<usize>, + pub example: Option<String>, +} + +pub trait HasSchemaParameters { + fn get_schema_parameters(&self) -> syn::Result<SchemaParameters>; +} + +impl HasSchemaParameters for Field { + fn get_schema_parameters(&self) -> syn::Result<SchemaParameters> { + let mut output = SchemaParameters::default(); + + let mut value_type_keyword = None; + let mut min_length_keyword = None; + let mut max_length_keyword = None; + let mut example_keyword = None; + + for meta in self.get_schema_metadata()? { + match meta { + SchemaParameterVariant::ValueType { keyword, value } => { + if let Some(first_keyword) = value_type_keyword { + return Err(occurrence_error(first_keyword, keyword, "value_type")); + } + + value_type_keyword = Some(keyword); + output.value_type = Some(value); + } + SchemaParameterVariant::MinLength { keyword, value } => { + if let Some(first_keyword) = min_length_keyword { + return Err(occurrence_error(first_keyword, keyword, "min_length")); + } + + min_length_keyword = Some(keyword); + let min_length = value.base10_parse::<usize>()?; + output.min_length = Some(min_length); + } + SchemaParameterVariant::MaxLength { keyword, value } => { + if let Some(first_keyword) = max_length_keyword { + return Err(occurrence_error(first_keyword, keyword, "max_length")); + } + + max_length_keyword = Some(keyword); + let max_length = value.base10_parse::<usize>()?; + output.max_length = Some(max_length); + } + SchemaParameterVariant::Example { keyword, value } => { + if let Some(first_keyword) = example_keyword { + return Err(occurrence_error(first_keyword, keyword, "example")); + } + + example_keyword = Some(keyword); + output.example = Some(value.value()); + } + } + } + + Ok(output) + } +} + +/// Check if the field is applicable for running validations +#[derive(PartialEq)] +pub enum IsSchemaFieldApplicableForValidation { + /// Not applicable for running validation checks + Invalid, + /// Applicable for running validation checks + Valid, + /// Applicable for validation but field is optional - this is needed for generating validation code only if the value of the field is present + ValidOptional, +} + +/// From implementation for checking if the field type is applicable for running schema validations +impl From<&syn::Type> for IsSchemaFieldApplicableForValidation { + fn from(ty: &syn::Type) -> Self { + if let syn::Type::Path(type_path) = ty { + if let Some(segment) = type_path.path.segments.last() { + let ident = &segment.ident; + if ident == "String" || ident == "Url" { + return Self::Valid; + } + + if ident == "Option" { + if let syn::PathArguments::AngleBracketed(generic_args) = &segment.arguments { + if let Some(syn::GenericArgument::Type(syn::Type::Path(inner_path))) = + generic_args.args.first() + { + if let Some(inner_segment) = inner_path.path.segments.last() { + if inner_segment.ident == "String" || inner_segment.ident == "Url" { + return Self::ValidOptional; + } + } + } + } + } + } + } + Self::Invalid + } +}
2025-05-12T12:20:56Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR adds automatic validation for string length constraints defined in schema attributes. The validation prevents 5xx errors that occur when strings exceeding database column length limits are passed to the database. The implementation: 1. Creates a proc macro `ValidateSchema` that reads `min_length` and `max_length` parameters from schema attributes 2. Generates validation code that is invoked at runtime 3. Returns appropriate 4xx errors with helpful messages when validation fails ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context When API requests contain fields that exceed database column length limits, the application currently returns 5xx errors when those values are stored. This is incorrect behavior - it should be a 4xx error (invalid request) since the client provided invalid data. This change implements the correct behavior, and also uses the same schema attributes for both OpenAPI spec generation and validation giving us a single source of truth. It also improves error handling - returning 4xx instead of 5xx errors for invalid requests ## How did you test it? <details> <summary>1. Added unit test cases for the macro</summary> <img width="1025" alt="Screenshot 2025-05-12 at 5 50 33 PM" src="https://github.com/user-attachments/assets/1659f4aa-6918-4db4-be3c-fd241dc0bf49" /> </details> <details> <summary>2. Pass invalid return_url (length exceeding 255 characters)</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Accept-Language: es-ES' \ --header 'api-key: dev_tizBo0XFMZBNZ3jWBlkrc6C81CiCdliXrLXFoAg2fTgoTmKvOIk2oAP43Gwb3AGK' \ --data-raw '{"customer_id":"cus_Wz8ND2QMGUTQCZBgO4Jx_1","profile_id":"pro_DC4DZ899zblYKajNmd0K","customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"amount":12,"currency":"SGD","confirm":false,"payment_link":true,"setup_future_usage":"off_session","capture_method":"automatic","billing":{"address":{},"email":"[email protected]"},"return_url":"https://example.com?q=example.com&q=example.com&q=example.com&q=example.com&q=example.com&q=example.com&q=example.com&q=example.com&q=example.com&q=example.com&q=example.com&q=example.com&q=example.com&q=example.com&q=example.com&q=example.com&q=example.abc","payment_link_config":{"theme":"#111111","is_setup_mandate_flow":true,"background_image":{"url":"https://img.freepik.com/free-photo/abstract-blue-geometric-shapes-background_24972-1841.jpg","position":"bottom","size":"cover"}}}' Response { "error": { "type": "invalid_request", "message": "return_url must be at most 255 characters long. Received 258 characters", "code": "IR_06" } } </details> <details> <summary>3. Updated DocTest</summary> <img width="458" alt="Screenshot 2025-05-17 at 1 27 14 AM" src="https://github.com/user-attachments/assets/374ed02a-776a-443a-87e4-fbb3287a420b" /> </details> <details> <summary>4. Added cypress test cases</summary> <img width="457" alt="Screenshot 2025-05-20 at 5 14 54 PM" src="https://github.com/user-attachments/assets/b7a3951c-2145-473d-89ee-6cc0f059b726" /> </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
e62f8ee8aba4ba05041b221e9af6f30100fdefcb
e62f8ee8aba4ba05041b221e9af6f30100fdefcb
juspay/hyperswitch
juspay__hyperswitch-7981
Bug: [BUG] consider only the language for locale for translations ### Bug Description `Accept-Language` header is meant for passing locales in the API requests. Sample - `es-ES` In application, the value of this header is consumed as is for language translations (for payment and payout links). However, the language for Spanish will be mapped to `es` rather than the language-location combination, which ends up defaulting to English for such scenarios (as `es-ES` != `es`) ### Expected Behavior For `es-ES` locale, the translation must be present in Spanish ### Actual Behavior For `es-ES` locale, the translation is present in English ### Steps To Reproduce During creation of payment links, pass `Accept-Language: es-ES` in the request. ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/locales/en-GB.yml b/crates/router/locales/en_gb.yml similarity index 100% rename from crates/router/locales/en-GB.yml rename to crates/router/locales/en_gb.yml diff --git a/crates/router/locales/fr-BE.yml b/crates/router/locales/fr_be.yml similarity index 100% rename from crates/router/locales/fr-BE.yml rename to crates/router/locales/fr_be.yml diff --git a/crates/router/src/core/payment_link/locale.js b/crates/router/src/core/payment_link/locale.js index f70d9cefbdf..5a404c93a5b 100644 --- a/crates/router/src/core/payment_link/locale.js +++ b/crates/router/src/core/payment_link/locale.js @@ -619,8 +619,25 @@ const locales = { }, }; - function getTranslations(locale_str) { - var fallback_locale = 'en'; - var locale = locale_str.toLowerCase().replace(/-/g, "_") || fallback_locale; // defaults if locale is not present in payment details. - return locales[locale] || locales['en']; // defaults if locale is not implemented in locales. - } \ No newline at end of file +function getLanguage(localeStr) { + var fallback_locale = 'en'; + var primaryLocale = (localeStr.toLowerCase() || fallback_locale).split(',')[0].trim(); + + // Split into language and country parts + var parts = primaryLocale.split('-'); + var language = parts[0]; + var country = parts.length > 1 ? parts[1] : null; + + var key = `${language}_${country}`; + switch (key) { + case 'en_gb': return 'en_gb'; + case 'fr_be': return 'fr_be'; + default: return language; + } +} + +function getTranslations(localeStr) { + var fallback_locale = 'en'; + var language = getLanguage(localeStr); + return locales[language] || locales[fallback_locale]; +} \ No newline at end of file diff --git a/crates/router/src/services/api/generic_link_response/context.rs b/crates/router/src/services/api/generic_link_response/context.rs index 25d2e3f1662..9589081d07e 100644 --- a/crates/router/src/services/api/generic_link_response/context.rs +++ b/crates/router/src/services/api/generic_link_response/context.rs @@ -1,7 +1,29 @@ +use common_utils::consts::DEFAULT_LOCALE; use rust_i18n::t; use tera::Context; +fn get_language(locale_str: &str) -> String { + let lowercase_str = locale_str.to_lowercase(); + let primary_locale = lowercase_str.split(',').next().unwrap_or("").trim(); + + if primary_locale.is_empty() { + return DEFAULT_LOCALE.to_string(); + } + + let parts = primary_locale.split('-').collect::<Vec<&str>>(); + let language = *parts.first().unwrap_or(&DEFAULT_LOCALE); + let country = parts.get(1).copied(); + + match (language, country) { + ("en", Some("gb")) => "en_gb".to_string(), + ("fr", Some("be")) => "fr_be".to_string(), + (lang, _) => lang.to_string(), + } +} + pub fn insert_locales_in_context_for_payout_link(context: &mut Context, locale: &str) { + let language = get_language(locale); + let locale = language.as_str(); let i18n_payout_link_title = t!("payout_link.initiate.title", locale = locale); let i18n_january = t!("months.january", locale = locale); let i18n_february = t!("months.february", locale = locale); @@ -38,6 +60,8 @@ pub fn insert_locales_in_context_for_payout_link(context: &mut Context, locale: } pub fn insert_locales_in_context_for_payout_link_status(context: &mut Context, locale: &str) { + let language = get_language(locale); + let locale = language.as_str(); let i18n_payout_link_status_title = t!("payout_link.status.title", locale = locale); let i18n_success_text = t!("payout_link.status.text.success", locale = locale); let i18n_success_message = t!("payout_link.status.message.success", locale = locale);
2025-05-09T08:21:34Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Fix the locale handling in the payment and payout links translation functionality to properly support language-location combinations like `es-ES`. Currently, the system is using the full locale value from the `Accept-Language` header without parsing it, causing translations for such locales to fail when the header includes region information. The fix extracts the base language code from locale strings containing region identifiers to ensure proper translation mapping (e.g., `es-ES` will now correctly map to `es` translations). ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> This PR fixes issue #7981 where the translation system fails to properly handle locale codes with region identifiers in the `Accept-Language` header. When users send requests with headers like `Accept-Language: es-ES`, the system was using the full string (`es-ES`) for translation lookup instead of extracting the base language code (`es`). This caused Spanish translations to default to English because no exact match for `es-ES` was found in the translation data. By parsing the locale string and extracting just the language part, we ensure that users receive translations in their requested language regardless of whether they include region information. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> <details> <summary>1. Create a payment link with es-ES in Accept-Language header</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Accept-Language: es-ES' \ --header 'api-key: dev_tizBo0XFMZBNZ3jWBlkrc6C81CiCdliXrLXFoAg2fTgoTmKvOIk2oAP43Gwb3AGK' \ --data-raw '{"customer_id":"cus_Wz8ND2QMGUTQCZBgO4Jx_1","profile_id":"pro_DC4DZ899zblYKajNmd0K","customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"amount":10,"currency":"EUR","confirm":false,"payment_link":true,"setup_future_usage":"off_session","capture_method":"automatic","billing":{"address":{},"email":"[email protected]"},"return_url":"https://example.com","payment_link_config":{"theme":"#111111","background_image":{"url":"https://img.freepik.com/free-photo/abstract-blue-geometric-shapes-background_24972-1841.jpg","position":"bottom","size":"cover"}}}' Response {"payment_id":"pay_zjyjvsTOPQKx0sYDzkzq","merchant_id":"merchant_1746522436","status":"requires_payment_method","amount":10,"net_amount":10,"shipping_cost":null,"amount_capturable":0,"amount_received":null,"connector":null,"client_secret":"pay_zjyjvsTOPQKx0sYDzkzq_secret_hD6KQpqlkWdk9wTPPDIB","created":"2025-05-09T08:09:43.323Z","currency":"EUR","customer_id":"cus_Wz8ND2QMGUTQCZBgO4Jx_1","customer":{"id":"cus_Wz8ND2QMGUTQCZBgO4Jx_1","name":null,"email":null,"phone":null,"phone_country_code":null},"description":null,"refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":"off_session","off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":null,"payment_method_data":null,"payment_token":null,"shipping":null,"billing":{"address":null,"phone":null,"email":"[email protected]"},"order_details":null,"email":null,"name":null,"phone":null,"return_url":"https://example.com/","authentication_type":null,"statement_descriptor_name":null,"statement_descriptor_suffix":null,"next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":null,"connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_Wz8ND2QMGUTQCZBgO4Jx_1","created_at":1746778183,"expires":1746781783,"secret":"epk_f853d34ab7444310b3a54b0704e34867"},"manual_retry_allowed":null,"connector_transaction_id":null,"frm_message":null,"metadata":null,"connector_metadata":null,"feature_metadata":null,"reference_id":null,"payment_link":{"link":"http://localhost:8080/payment_link/merchant_1746522436/pay_zjyjvsTOPQKx0sYDzkzq?locale=es-ES","secure_link":null,"payment_link_id":"plink_FAtpjPaeg4T5UjMsVBeg"},"profile_id":"pro_DC4DZ899zblYKajNmd0K","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":null,"incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-05-09T08:24:43.318Z","fingerprint":null,"browser_info":null,"payment_method_id":null,"payment_method_status":null,"updated":"2025-05-09T08:09:43.343Z","split_payments":null,"frm_metadata":null,"extended_authorization_applied":null,"capture_before":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null,"card_discovery":null,"force_3ds_challenge":false,"force_3ds_challenge_trigger":false,"issuer_error_code":null,"issuer_error_message":null} <img width="1509" alt="Screenshot 2025-05-09 at 1 51 02 PM" src="https://github.com/user-attachments/assets/f70bbdfe-d375-4b1b-a1c5-53ed012adfab" /> </details> <details> <summary>2. Create a payout link</summary> cURL curl --location --request POST 'http://localhost:8080/payouts/create' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_tizBo0XFMZBNZ3jWBlkrc6C81CiCdliXrLXFoAg2fTgoTmKvOIk2oAP43Gwb3AGK' \ --data '{"amount":1,"currency":"EUR","customer_id":"cus_Wz8ND2QMGUTQCZBgO4Jx","description":"Its my first payout request","entity_type":"Individual","confirm":false,"auto_fulfill":true,"session_expiry":1000000,"priority":"instant","profile_id":"pro_DC4DZ899zblYKajNmd0K","payout_link":true,"return_url":"https://www.google.com","payout_link_config":{"form_layout":"journey","theme":"#0066ff","logo":"https://hyperswitch.io/favicon.ico","merchant_name":"HyperSwitch Inc.","test_mode":true}}' Response {"payout_id":"93d4cfee-cfcd-4be0-b750-049c98a1f220","merchant_id":"merchant_1746522436","amount":1,"currency":"EUR","connector":null,"payout_type":null,"payout_method_data":null,"billing":null,"auto_fulfill":true,"customer_id":"cus_Wz8ND2QMGUTQCZBgO4Jx","customer":{"id":"cus_Wz8ND2QMGUTQCZBgO4Jx","name":null,"email":"[email protected]","phone":null,"phone_country_code":null},"client_secret":"payout_93d4cfee-cfcd-4be0-b750-049c98a1f220_secret_UllSmh3B4jG5IMkov2ft","return_url":"https://www.google.com","business_country":null,"business_label":null,"description":"Its my first payout request","entity_type":"Individual","recurring":false,"metadata":{},"merchant_connector_id":null,"status":"requires_payout_method_data","error_message":null,"error_code":null,"profile_id":"pro_DC4DZ899zblYKajNmd0K","created":"2025-05-09T08:11:21.214Z","connector_transaction_id":null,"priority":"instant","payout_link":{"payout_link_id":"payout_link_DkmRGHGOrm12ZZRvYH5o","link":"http://localhost:8080/payout_link/merchant_1746522436/93d4cfee-cfcd-4be0-b750-049c98a1f220?locale=en"},"email":"[email protected]","name":null,"phone":null,"phone_country_code":null,"unified_code":null,"unified_message":null,"payout_method_id":null} <img width="1505" alt="Screenshot 2025-05-09 at 1 50 16 PM" src="https://github.com/user-attachments/assets/4f85519e-50b4-407a-9be9-9498b1b8f09d" /> </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [x] I added unit tests for my changes where possible
v1.114.0
3cdb9e174ca384704781a4c56e826c3a5e39d295
3cdb9e174ca384704781a4c56e826c3a5e39d295
juspay/hyperswitch
juspay__hyperswitch-7967
Bug: [FEATURE]: Add refunds list feature in v2 apis Add refunds list feature in v2 apis
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index b6d6fb87e27..59d5f5437c2 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -3306,6 +3306,43 @@ ] } }, + "/v2/refunds/list": { + "get": { + "tags": [ + "Refunds" + ], + "summary": "Refunds - List", + "description": "To list the refunds associated with a payment_id or with the merchant, if payment_id is not provided", + "operationId": "List all Refunds", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RefundListRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "List of refunds", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RefundListResponse" + } + } + } + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, "/v2/process_tracker/revenue_recovery_workflow/{revenue_recovery_id}": { "get": { "tags": [ @@ -20386,13 +20423,11 @@ "nullable": true }, "refund_id": { - "type": "string", - "description": "The identifier for the refund", - "nullable": true - }, - "profile_id": { - "type": "string", - "description": "The identifier for business profile", + "allOf": [ + { + "$ref": "#/components/schemas/common_utils.id_type.GlobalRefundId" + } + ], "nullable": true }, "limit": { @@ -20423,7 +20458,7 @@ "description": "The list of connectors to filter refunds list", "nullable": true }, - "merchant_connector_id": { + "connector_id_list": { "type": "array", "items": { "type": "string" diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs index 775e0dfeef7..bb20978e0d2 100644 --- a/crates/api_models/src/refunds.rs +++ b/crates/api_models/src/refunds.rs @@ -330,6 +330,7 @@ pub struct RefundErrorDetails { pub message: String, } +#[cfg(feature = "v1")] #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)] pub struct RefundListRequest { /// The identifier for the payment @@ -361,7 +362,35 @@ pub struct RefundListRequest { #[schema(value_type = Option<Vec<RefundStatus>>)] pub refund_status: Option<Vec<enums::RefundStatus>>, } - +#[cfg(feature = "v2")] +#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)] +pub struct RefundListRequest { + /// The identifier for the payment + #[schema(value_type = Option<String>)] + pub payment_id: Option<common_utils::id_type::GlobalPaymentId>, + /// The identifier for the refund + pub refund_id: Option<common_utils::id_type::GlobalRefundId>, + /// Limit on the number of objects to return + pub limit: Option<i64>, + /// The starting point within a list of objects + pub offset: Option<i64>, + /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc) + #[serde(flatten)] + pub time_range: Option<TimeRange>, + /// The amount to filter reufnds list. Amount takes two option fields start_amount and end_amount from which objects can be filtered as per required scenarios (less_than, greater_than, equal_to and range) + pub amount_filter: Option<AmountFilter>, + /// The list of connectors to filter refunds list + pub connector: Option<Vec<String>>, + /// The list of merchant connector ids to filter the refunds list for selected label + #[schema(value_type = Option<Vec<String>>)] + pub connector_id_list: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, + /// The list of currencies to filter refunds list + #[schema(value_type = Option<Vec<Currency>>)] + pub currency: Option<Vec<enums::Currency>>, + /// The list of refund statuses to filter refunds list + #[schema(value_type = Option<Vec<RefundStatus>>)] + pub refund_status: Option<Vec<enums::RefundStatus>>, +} #[derive(Debug, Clone, Eq, PartialEq, Serialize, ToSchema)] pub struct RefundListResponse { /// The number of refunds included in the list diff --git a/crates/hyperswitch_domain_models/Cargo.toml b/crates/hyperswitch_domain_models/Cargo.toml index 39aadb90db6..e889d2c16c3 100644 --- a/crates/hyperswitch_domain_models/Cargo.toml +++ b/crates/hyperswitch_domain_models/Cargo.toml @@ -17,6 +17,7 @@ v2 = ["api_models/v2", "diesel_models/v2", "common_utils/v2", "common_types/v2"] v1 = ["api_models/v1", "diesel_models/v1", "common_utils/v1", "common_types/v1"] customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2"] payment_methods_v2 = ["api_models/payment_methods_v2", "diesel_models/payment_methods_v2"] +refunds_v2 = ["api_models/refunds_v2"] dummy_connector = [] revenue_recovery= [] diff --git a/crates/hyperswitch_domain_models/src/refunds.rs b/crates/hyperswitch_domain_models/src/refunds.rs index 4016754510a..f8e7e0bad11 100644 --- a/crates/hyperswitch_domain_models/src/refunds.rs +++ b/crates/hyperswitch_domain_models/src/refunds.rs @@ -1,5 +1,9 @@ +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +use crate::business_profile::Profile; +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] use crate::errors; +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] pub struct RefundListConstraints { pub payment_id: Option<common_utils::id_type::PaymentId>, pub refund_id: Option<String>, @@ -14,6 +18,22 @@ pub struct RefundListConstraints { pub refund_status: Option<Vec<common_enums::RefundStatus>>, } +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +pub struct RefundListConstraints { + pub payment_id: Option<common_utils::id_type::GlobalPaymentId>, + pub refund_id: Option<common_utils::id_type::GlobalRefundId>, + pub profile_id: common_utils::id_type::ProfileId, + pub limit: Option<i64>, + pub offset: Option<i64>, + pub time_range: Option<common_utils::types::TimeRange>, + pub amount_filter: Option<api_models::payments::AmountFilter>, + pub connector: Option<Vec<String>>, + pub connector_id_list: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, + pub currency: Option<Vec<common_enums::Currency>>, + pub refund_status: Option<Vec<common_enums::RefundStatus>>, +} + +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] impl TryFrom<( api_models::refunds::RefundListRequest, @@ -80,3 +100,35 @@ impl }) } } + +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +impl From<(api_models::refunds::RefundListRequest, Profile)> for RefundListConstraints { + fn from((value, profile): (api_models::refunds::RefundListRequest, Profile)) -> Self { + let api_models::refunds::RefundListRequest { + payment_id, + refund_id, + connector, + currency, + refund_status, + limit, + offset, + time_range, + amount_filter, + connector_id_list, + } = value; + + Self { + payment_id, + refund_id, + profile_id: profile.get_id().to_owned(), + limit, + offset, + time_range, + amount_filter, + connector, + connector_id_list, + currency, + refund_status, + } + } +} diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index bb48871190e..e9338af8d81 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -149,6 +149,7 @@ Never share your secret api keys. Keep them guarded and secure. //Routes for refunds routes::refunds::refunds_create, routes::refunds::refunds_retrieve, + routes::refunds::refunds_list, // Routes for Revenue Recovery flow under Process Tracker routes::revenue_recovery::revenue_recovery_pt_retrieve_api diff --git a/crates/openapi/src/routes/refunds.rs b/crates/openapi/src/routes/refunds.rs index 5c55de2d177..8fb6d4f1835 100644 --- a/crates/openapi/src/routes/refunds.rs +++ b/crates/openapi/src/routes/refunds.rs @@ -128,6 +128,7 @@ pub async fn refunds_update() {} operation_id = "List all Refunds", security(("api_key" = [])) )] +#[cfg(feature = "v1")] pub fn refunds_list() {} /// Refunds - List For the Given profiles @@ -233,3 +234,20 @@ pub async fn refunds_create() {} )] #[cfg(feature = "v2")] pub async fn refunds_retrieve() {} + +/// Refunds - List +/// +/// To list the refunds associated with a payment_id or with the merchant, if payment_id is not provided +#[utoipa::path( + get, + path = "/v2/refunds/list", + request_body=RefundListRequest, + responses( + (status = 200, description = "List of refunds", body = RefundListResponse), + ), + tag = "Refunds", + operation_id = "List all Refunds", + security(("api_key" = [])) +)] +#[cfg(feature = "v2")] +pub fn refunds_list() {} diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index e80b9672f23..d14eaaf83d5 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -39,7 +39,7 @@ customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswit payment_methods_v2 = ["api_models/payment_methods_v2", "diesel_models/payment_methods_v2", "hyperswitch_domain_models/payment_methods_v2", "storage_impl/payment_methods_v2", "common_utils/payment_methods_v2"] dynamic_routing = ["external_services/dynamic_routing", "storage_impl/dynamic_routing", "api_models/dynamic_routing"] revenue_recovery =["api_models/revenue_recovery","hyperswitch_interfaces/revenue_recovery","hyperswitch_domain_models/revenue_recovery","hyperswitch_connectors/revenue_recovery"] -refunds_v2 = ["api_models/refunds_v2", "diesel_models/refunds_v2", "storage_impl/refunds_v2"] +refunds_v2 = ["api_models/refunds_v2", "diesel_models/refunds_v2", "storage_impl/refunds_v2", "hyperswitch_domain_models/refunds_v2"] # Partial Auth # The feature reduces the overhead of the router authenticating the merchant for every request, and trusts on `x-merchant-id` header to be present in the request. diff --git a/crates/router/src/core/refunds_v2.rs b/crates/router/src/core/refunds_v2.rs index b6ccfe8376b..8d113d5a329 100644 --- a/crates/router/src/core/refunds_v2.rs +++ b/crates/router/src/core/refunds_v2.rs @@ -4,6 +4,7 @@ use api_models::{enums::Connector, refunds::RefundErrorDetails}; use common_utils::{id_type, types as common_utils_types}; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ + refunds::RefundListConstraints, router_data::{ErrorResponse, RouterData}, router_data_v2::RefundFlowData, }; @@ -734,6 +735,56 @@ pub fn build_refund_update_for_rsync( } } +// ********************************************** Refund list ********************************************** + +/// If payment_id is provided, lists all the refunds associated with that particular payment_id +/// If payment_id is not provided, lists the refunds associated with that particular merchant - to the limit specified,if no limits given, it is 10 by default +#[instrument(skip_all)] +#[cfg(feature = "olap")] +pub async fn refund_list( + state: SessionState, + merchant_account: domain::MerchantAccount, + profile: domain::Profile, + req: refunds::RefundListRequest, +) -> errors::RouterResponse<refunds::RefundListResponse> { + let db = state.store; + let limit = refunds_validator::validate_refund_list(req.limit)?; + let offset = req.offset.unwrap_or_default(); + + let refund_list = db + .filter_refund_by_constraints( + merchant_account.get_id(), + RefundListConstraints::from((req.clone(), profile.clone())), + merchant_account.storage_scheme, + limit, + offset, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; + + let data: Vec<refunds::RefundResponse> = refund_list + .into_iter() + .map(refunds::RefundResponse::foreign_try_from) + .collect::<Result<_, _>>()?; + + let total_count = db + .get_total_count_of_refunds( + merchant_account.get_id(), + RefundListConstraints::from((req, profile)), + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; + + Ok(services::ApplicationResponse::Json( + api_models::refunds::RefundListResponse { + count: data.len(), + total_count, + data, + }, + )) +} + // ********************************************** VALIDATIONS ********************************************** #[instrument(skip_all)] diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 6e59e0c95d7..13f0cb857ed 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -2843,6 +2843,26 @@ impl RefundInterface for KafkaStore { .await } + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + async fn filter_refund_by_constraints( + &self, + merchant_id: &id_type::MerchantId, + refund_details: refunds::RefundListConstraints, + storage_scheme: MerchantStorageScheme, + limit: i64, + offset: i64, + ) -> CustomResult<Vec<storage::Refund>, errors::StorageError> { + self.diesel_store + .filter_refund_by_constraints( + merchant_id, + refund_details, + storage_scheme, + limit, + offset, + ) + .await + } + #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "refunds_v2"), @@ -2891,6 +2911,18 @@ impl RefundInterface for KafkaStore { .get_total_count_of_refunds(merchant_id, refund_details, storage_scheme) .await } + + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + async fn get_total_count_of_refunds( + &self, + merchant_id: &id_type::MerchantId, + refund_details: refunds::RefundListConstraints, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<i64, errors::StorageError> { + self.diesel_store + .get_total_count_of_refunds(merchant_id, refund_details, storage_scheme) + .await + } } #[async_trait::async_trait] diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs index fbbe0a6d159..7d9a8703169 100644 --- a/crates/router/src/db/refund.rs +++ b/crates/router/src/db/refund.rs @@ -91,6 +91,16 @@ pub trait RefundInterface { offset: i64, ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError>; + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + async fn filter_refund_by_constraints( + &self, + merchant_id: &common_utils::id_type::MerchantId, + refund_details: refunds::RefundListConstraints, + storage_scheme: enums::MerchantStorageScheme, + limit: i64, + offset: i64, + ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError>; + #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "refunds_v2"), @@ -127,6 +137,14 @@ pub trait RefundInterface { refund_details: &refunds::RefundListConstraints, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError>; + + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + async fn get_total_count_of_refunds( + &self, + merchant_id: &common_utils::id_type::MerchantId, + refund_details: refunds::RefundListConstraints, + storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<i64, errors::StorageError>; } #[cfg(not(feature = "kv_store"))] @@ -925,6 +943,28 @@ mod storage { .map_err(|error| report!(errors::StorageError::from(error))) } + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + #[instrument(skip_all)] + async fn filter_refund_by_constraints( + &self, + merchant_id: &common_utils::id_type::MerchantId, + refund_details: refunds::RefundListConstraints, + _storage_scheme: enums::MerchantStorageScheme, + limit: i64, + offset: i64, + ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + <diesel_models::refund::Refund as storage_types::RefundDbExt>::filter_by_constraints( + &conn, + merchant_id, + refund_details, + limit, + offset, + ) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } + #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "refunds_v2"), @@ -983,6 +1023,24 @@ mod storage { .await .map_err(|error| report!(errors::StorageError::from(error))) } + + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + #[instrument(skip_all)] + async fn get_total_count_of_refunds( + &self, + merchant_id: &common_utils::id_type::MerchantId, + refund_details: refunds::RefundListConstraints, + _storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<i64, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + <diesel_models::refund::Refund as storage_types::RefundDbExt>::get_refunds_count( + &conn, + merchant_id, + refund_details, + ) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } } } @@ -1369,6 +1427,115 @@ impl RefundInterface for MockDb { Ok(filtered_refunds) } + #[cfg(all(feature = "v2", feature = "refunds_v2", feature = "olap"))] + async fn filter_refund_by_constraints( + &self, + merchant_id: &common_utils::id_type::MerchantId, + refund_details: refunds::RefundListConstraints, + _storage_scheme: enums::MerchantStorageScheme, + limit: i64, + offset: i64, + ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError> { + let mut unique_connectors = HashSet::new(); + let mut unique_connector_ids = HashSet::new(); + let mut unique_currencies = HashSet::new(); + let mut unique_statuses = HashSet::new(); + + // Fill the hash sets with data from refund_details + if let Some(connectors) = &refund_details.connector { + connectors.iter().for_each(|connector| { + unique_connectors.insert(connector); + }); + } + + if let Some(connector_id_list) = &refund_details.connector_id_list { + connector_id_list.iter().for_each(|unique_connector_id| { + unique_connector_ids.insert(unique_connector_id); + }); + } + + if let Some(currencies) = &refund_details.currency { + currencies.iter().for_each(|currency| { + unique_currencies.insert(currency); + }); + } + + if let Some(refund_statuses) = &refund_details.refund_status { + refund_statuses.iter().for_each(|refund_status| { + unique_statuses.insert(refund_status); + }); + } + + let refunds = self.refunds.lock().await; + let filtered_refunds = refunds + .iter() + .filter(|refund| refund.merchant_id == *merchant_id) + .filter(|refund| { + refund_details + .payment_id + .clone() + .map_or(true, |id| id == refund.payment_id) + }) + .filter(|refund| { + refund_details + .refund_id + .clone() + .map_or(true, |id| id == refund.id) + }) + .filter(|refund| { + refund + .profile_id + .as_ref() + .is_some_and(|profile_id| profile_id == &refund_details.profile_id) + }) + .filter(|refund| { + refund.created_at + >= refund_details.time_range.map_or( + common_utils::date_time::now() - time::Duration::days(60), + |range| range.start_time, + ) + && refund.created_at + <= refund_details + .time_range + .map_or(common_utils::date_time::now(), |range| { + range.end_time.unwrap_or_else(common_utils::date_time::now) + }) + }) + .filter(|refund| { + refund_details + .amount_filter + .as_ref() + .map_or(true, |amount| { + refund.refund_amount + >= MinorUnit::new(amount.start_amount.unwrap_or(i64::MIN)) + && refund.refund_amount + <= MinorUnit::new(amount.end_amount.unwrap_or(i64::MAX)) + }) + }) + .filter(|refund| { + unique_connectors.is_empty() || unique_connectors.contains(&refund.connector) + }) + .filter(|refund| { + unique_connector_ids.is_empty() + || refund + .connector_id + .as_ref() + .is_some_and(|id| unique_connector_ids.contains(id)) + }) + .filter(|refund| { + unique_currencies.is_empty() || unique_currencies.contains(&refund.currency) + }) + .filter(|refund| { + unique_statuses.is_empty() || unique_statuses.contains(&refund.refund_status) + }) + .skip(usize::try_from(offset).unwrap_or_default()) + .take(usize::try_from(limit).unwrap_or(MAX_LIMIT)) + .cloned() + .collect::<Vec<_>>(); + + Ok(filtered_refunds) + } + #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "refunds_v2"), @@ -1586,4 +1753,111 @@ impl RefundInterface for MockDb { Ok(filtered_refunds_count) } + + #[cfg(all(feature = "v2", feature = "refunds_v2", feature = "olap"))] + async fn get_total_count_of_refunds( + &self, + merchant_id: &common_utils::id_type::MerchantId, + refund_details: refunds::RefundListConstraints, + _storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<i64, errors::StorageError> { + let mut unique_connectors = HashSet::new(); + let mut unique_connector_ids = HashSet::new(); + let mut unique_currencies = HashSet::new(); + let mut unique_statuses = HashSet::new(); + + // Fill the hash sets with data from refund_details + if let Some(connectors) = &refund_details.connector { + connectors.iter().for_each(|connector| { + unique_connectors.insert(connector); + }); + } + + if let Some(connector_id_list) = &refund_details.connector_id_list { + connector_id_list.iter().for_each(|unique_connector_id| { + unique_connector_ids.insert(unique_connector_id); + }); + } + + if let Some(currencies) = &refund_details.currency { + currencies.iter().for_each(|currency| { + unique_currencies.insert(currency); + }); + } + + if let Some(refund_statuses) = &refund_details.refund_status { + refund_statuses.iter().for_each(|refund_status| { + unique_statuses.insert(refund_status); + }); + } + + let refunds = self.refunds.lock().await; + let filtered_refunds = refunds + .iter() + .filter(|refund| refund.merchant_id == *merchant_id) + .filter(|refund| { + refund_details + .payment_id + .clone() + .map_or(true, |id| id == refund.payment_id) + }) + .filter(|refund| { + refund_details + .refund_id + .clone() + .map_or(true, |id| id == refund.id) + }) + .filter(|refund| { + refund + .profile_id + .as_ref() + .is_some_and(|profile_id| profile_id == &refund_details.profile_id) + }) + .filter(|refund| { + refund.created_at + >= refund_details.time_range.map_or( + common_utils::date_time::now() - time::Duration::days(60), + |range| range.start_time, + ) + && refund.created_at + <= refund_details + .time_range + .map_or(common_utils::date_time::now(), |range| { + range.end_time.unwrap_or_else(common_utils::date_time::now) + }) + }) + .filter(|refund| { + refund_details + .amount_filter + .as_ref() + .map_or(true, |amount| { + refund.refund_amount + >= MinorUnit::new(amount.start_amount.unwrap_or(i64::MIN)) + && refund.refund_amount + <= MinorUnit::new(amount.end_amount.unwrap_or(i64::MAX)) + }) + }) + .filter(|refund| { + unique_connectors.is_empty() || unique_connectors.contains(&refund.connector) + }) + .filter(|refund| { + unique_connector_ids.is_empty() + || refund + .connector_id + .as_ref() + .is_some_and(|id| unique_connector_ids.contains(id)) + }) + .filter(|refund| { + unique_currencies.is_empty() || unique_currencies.contains(&refund.currency) + }) + .filter(|refund| { + unique_statuses.is_empty() || unique_statuses.contains(&refund.refund_status) + }) + .cloned() + .collect::<Vec<_>>(); + + let filtered_refunds_count = filtered_refunds.len().try_into().unwrap_or_default(); + + Ok(filtered_refunds_count) + } } diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index f75fb9ad7f6..57a1c74893d 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1169,14 +1169,26 @@ impl Refunds { } } -#[cfg(all(feature = "v2", feature = "refunds_v2", feature = "oltp"))] +#[cfg(all( + feature = "v2", + feature = "refunds_v2", + any(feature = "olap", feature = "oltp") +))] impl Refunds { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/v2/refunds").app_data(web::Data::new(state)); - route = route - .service(web::resource("").route(web::post().to(refunds::refunds_create))) - .service(web::resource("/{id}").route(web::get().to(refunds::refunds_retrieve))); + #[cfg(feature = "olap")] + { + route = + route.service(web::resource("/list").route(web::get().to(refunds::refunds_list))); + } + #[cfg(feature = "oltp")] + { + route = route + .service(web::resource("").route(web::post().to(refunds::refunds_create))) + .service(web::resource("/{id}").route(web::get().to(refunds::refunds_retrieve))); + } route } diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs index 65ea8720f99..dc92545841e 100644 --- a/crates/router/src/routes/refunds.rs +++ b/crates/router/src/routes/refunds.rs @@ -375,6 +375,37 @@ pub async fn refunds_list( .await } +#[cfg(all(feature = "v2", feature = "refunds_v2", feature = "olap"))] +#[instrument(skip_all, fields(flow = ?Flow::RefundsList))] +pub async fn refunds_list( + state: web::Data<AppState>, + req: HttpRequest, + payload: web::Json<api_models::refunds::RefundListRequest>, +) -> HttpResponse { + let flow = Flow::RefundsList; + Box::pin(api::server_wrap( + flow, + state, + &req, + payload.into_inner(), + |state, auth: auth::AuthenticationData, req, _| { + refund_list(state, auth.merchant_account, auth.profile, req) + }, + auth::auth_type( + &auth::V2ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: false, + }, + &auth::JWTAuth { + permission: Permission::MerchantRefundRead, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} + #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "refunds_v2"), diff --git a/crates/router/src/types/api/refunds.rs b/crates/router/src/types/api/refunds.rs index 8beaf7010f9..935cb14c1f7 100644 --- a/crates/router/src/types/api/refunds.rs +++ b/crates/router/src/types/api/refunds.rs @@ -3,8 +3,8 @@ pub use api_models::refunds::RefundRequest; #[cfg(all(feature = "v2", feature = "refunds_v2"))] pub use api_models::refunds::RefundsCreateRequest; pub use api_models::refunds::{ - RefundResponse, RefundStatus, RefundType, RefundUpdateRequest, RefundsRetrieveBody, - RefundsRetrieveRequest, + RefundListRequest, RefundListResponse, RefundResponse, RefundStatus, RefundType, + RefundUpdateRequest, RefundsRetrieveBody, RefundsRetrieveRequest, }; pub use hyperswitch_domain_models::router_flow_types::refunds::{Execute, RSync}; pub use hyperswitch_interfaces::api::refunds::{Refund, RefundExecute, RefundSync}; diff --git a/crates/router/src/types/storage/refund.rs b/crates/router/src/types/storage/refund.rs index 646b2742d5b..8f0472bb8f5 100644 --- a/crates/router/src/types/storage/refund.rs +++ b/crates/router/src/types/storage/refund.rs @@ -5,11 +5,14 @@ use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Q pub use diesel_models::refund::{ Refund, RefundCoreWorkflow, RefundNew, RefundUpdate, RefundUpdateInternal, }; +#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] +use diesel_models::schema::refund::dsl; +#[cfg(all(feature = "v2", feature = "refunds_v2"))] +use diesel_models::schema_v2::refund::dsl; use diesel_models::{ enums::{Currency, RefundStatus}, errors, query::generics::db_metrics, - schema::refund::dsl, }; use error_stack::ResultExt; use hyperswitch_domain_models::refunds; @@ -27,6 +30,15 @@ pub trait RefundDbExt: Sized { offset: i64, ) -> CustomResult<Vec<Self>, errors::DatabaseError>; + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + async fn filter_by_constraints( + conn: &PgPooledConn, + merchant_id: &common_utils::id_type::MerchantId, + refund_list_details: refunds::RefundListConstraints, + limit: i64, + offset: i64, + ) -> CustomResult<Vec<Self>, errors::DatabaseError>; + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn filter_by_meta_constraints( conn: &PgPooledConn, @@ -48,6 +60,13 @@ pub trait RefundDbExt: Sized { profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: &common_utils::types::TimeRange, ) -> CustomResult<Vec<(RefundStatus, i64)>, errors::DatabaseError>; + + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + async fn get_refunds_count( + conn: &PgPooledConn, + merchant_id: &common_utils::id_type::MerchantId, + refund_list_details: refunds::RefundListConstraints, + ) -> CustomResult<i64, errors::DatabaseError>; } #[async_trait::async_trait] @@ -164,6 +183,82 @@ impl RefundDbExt for Refund { .attach_printable_lazy(|| "Error filtering records by predicate") } + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + async fn filter_by_constraints( + conn: &PgPooledConn, + merchant_id: &common_utils::id_type::MerchantId, + refund_list_details: refunds::RefundListConstraints, + limit: i64, + offset: i64, + ) -> CustomResult<Vec<Self>, errors::DatabaseError> { + let mut filter = <Self as HasTable>::table() + .filter(dsl::merchant_id.eq(merchant_id.to_owned())) + .order(dsl::modified_at.desc()) + .into_boxed(); + + if let Some(payment_id) = &refund_list_details.payment_id { + filter = filter.filter(dsl::payment_id.eq(payment_id.to_owned())); + } + + if let Some(refund_id) = &refund_list_details.refund_id { + filter = filter.filter(dsl::id.eq(refund_id.to_owned())); + } + + if let Some(time_range) = &refund_list_details.time_range { + filter = filter.filter(dsl::created_at.ge(time_range.start_time)); + + if let Some(end_time) = time_range.end_time { + filter = filter.filter(dsl::created_at.le(end_time)); + } + } + + filter = match refund_list_details.amount_filter { + Some(AmountFilter { + start_amount: Some(start), + end_amount: Some(end), + }) => filter.filter(dsl::refund_amount.between(start, end)), + Some(AmountFilter { + start_amount: Some(start), + end_amount: None, + }) => filter.filter(dsl::refund_amount.ge(start)), + Some(AmountFilter { + start_amount: None, + end_amount: Some(end), + }) => filter.filter(dsl::refund_amount.le(end)), + _ => filter, + }; + + if let Some(connector) = refund_list_details.connector { + filter = filter.filter(dsl::connector.eq_any(connector)); + } + + if let Some(connector_id_list) = refund_list_details.connector_id_list { + filter = filter.filter(dsl::connector_id.eq_any(connector_id_list)); + } + + if let Some(filter_currency) = refund_list_details.currency { + filter = filter.filter(dsl::currency.eq_any(filter_currency)); + } + + if let Some(filter_refund_status) = refund_list_details.refund_status { + filter = filter.filter(dsl::refund_status.eq_any(filter_refund_status)); + } + + filter = filter.limit(limit).offset(offset); + + logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string()); + + db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>( + filter.get_results_async(conn), + db_metrics::DatabaseOperation::Filter, + ) + .await + .change_context(errors::DatabaseError::NotFound) + .attach_printable_lazy(|| "Error filtering records by predicate") + + // todo!() + } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn filter_by_meta_constraints( conn: &PgPooledConn, @@ -309,6 +404,74 @@ impl RefundDbExt for Refund { .attach_printable_lazy(|| "Error filtering count of refunds") } + #[cfg(all(feature = "v2", feature = "refunds_v2"))] + async fn get_refunds_count( + conn: &PgPooledConn, + merchant_id: &common_utils::id_type::MerchantId, + refund_list_details: refunds::RefundListConstraints, + ) -> CustomResult<i64, errors::DatabaseError> { + let mut filter = <Self as HasTable>::table() + .count() + .filter(dsl::merchant_id.eq(merchant_id.to_owned())) + .into_boxed(); + + if let Some(payment_id) = &refund_list_details.payment_id { + filter = filter.filter(dsl::payment_id.eq(payment_id.to_owned())); + } + + if let Some(refund_id) = &refund_list_details.refund_id { + filter = filter.filter(dsl::id.eq(refund_id.to_owned())); + } + + if let Some(time_range) = refund_list_details.time_range { + filter = filter.filter(dsl::created_at.ge(time_range.start_time)); + + if let Some(end_time) = time_range.end_time { + filter = filter.filter(dsl::created_at.le(end_time)); + } + } + + filter = match refund_list_details.amount_filter { + Some(AmountFilter { + start_amount: Some(start), + end_amount: Some(end), + }) => filter.filter(dsl::refund_amount.between(start, end)), + Some(AmountFilter { + start_amount: Some(start), + end_amount: None, + }) => filter.filter(dsl::refund_amount.ge(start)), + Some(AmountFilter { + start_amount: None, + end_amount: Some(end), + }) => filter.filter(dsl::refund_amount.le(end)), + _ => filter, + }; + + if let Some(connector) = refund_list_details.connector { + filter = filter.filter(dsl::connector.eq_any(connector)); + } + + if let Some(connector_id_list) = refund_list_details.connector_id_list { + filter = filter.filter(dsl::connector_id.eq_any(connector_id_list)); + } + + if let Some(filter_currency) = refund_list_details.currency { + filter = filter.filter(dsl::currency.eq_any(filter_currency)); + } + + if let Some(filter_refund_status) = refund_list_details.refund_status { + filter = filter.filter(dsl::refund_status.eq_any(filter_refund_status)); + } + + logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string()); + + filter + .get_result_async::<i64>(conn) + .await + .change_context(errors::DatabaseError::NotFound) + .attach_printable_lazy(|| "Error filtering count of refunds") + } + #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn get_refund_status_with_count( conn: &PgPooledConn,
2025-05-06T09:49:44Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR introduces support for listing refunds in v2 apis. Available filters for listing are as follows - `payment_id`: Filter by a specific payment identifier. - `refund_id`: Filter by a specific refund identifier. - `limit`: Maximum number of refund records to return. - `offset`: Starting index for pagination. - `time_range`: Filter refunds by a range of creation timestamps (start_time, end_time). - `amount_filter`: Filter by refund amount (start_amount, end_amount). - `connector`: Filter by a list of connector names. - `connector_id_list`: Filter by specific merchant connector account IDs. - `currency`: Filter by a list of currency codes. - `refund_status`: Filter by a list of refund statuses. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Merchants will be able to list refunds upon merging this PR. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Create some payments and refunds before hand. - List all refunds API call ``` curl --location --request GET 'http://localhost:8080/v2/refunds/list' \ --header 'x-profile-id: pro_PiIU0MSYNuU5kS96H0kV' \ --header 'Content-Type: application/json' \ --header 'Authorization: api-key=dev_nG2oG32R2dnadMOvkwfRyl0j1YB8uNf3t1FcDqhFgFxO7TtVS1kPQ8m4F3DEngVb' \ --data '{ }' ``` - Response from the above call ``` { "count": 4, "total_count": 4, "data": [ { "id": "12345_ref_0196a4badf2f7ed2b16c4ecaf1c814db", "payment_id": "12345_pay_0196a4baa48772909f72eac2cd863d7b", "merchant_reference_id": "1746520432", "amount": 70, "currency": "EUR", "status": "succeeded", "reason": "Paid by mistake", "metadata": { "foo": "bar" }, "error_details": { "code": "", "message": "" }, "created_at": "2025-05-06T08:33:52.433Z", "updated_at": "2025-05-06T08:33:53.474Z", "connector": "stripe", "profile_id": "pro_PiIU0MSYNuU5kS96H0kV", "merchant_connector_id": "mca_jQBjGAAN1BgqzXa0Gpoy", "connector_refund_reference_id": null }, { "id": "12345_ref_0196a4ba41147d138621293a283b9d3e", "payment_id": "12345_pay_0196a4ba295477d0a4156e65135d8fb2", "merchant_reference_id": "1746520392", "amount": 1000, "currency": "BBD", "status": "succeeded", "reason": "Paid by mistake", "metadata": { "foo": "bar" }, "error_details": { "code": "", "message": "" }, "created_at": "2025-05-06T08:33:11.959Z", "updated_at": "2025-05-06T08:33:13.047Z", "connector": "stripe", "profile_id": "pro_PiIU0MSYNuU5kS96H0kV", "merchant_connector_id": "mca_jQBjGAAN1BgqzXa0Gpoy", "connector_refund_reference_id": null }, { "id": "12345_ref_0196a4b978637810b17d2f855afb0305", "payment_id": "12345_pay_0196a4b9609179429e3e0decc9892a55", "merchant_reference_id": "1746520341", "amount": 100, "currency": "USD", "status": "succeeded", "reason": "Paid by mistake", "metadata": { "foo": "bar" }, "error_details": { "code": "", "message": "" }, "created_at": "2025-05-06T08:32:20.588Z", "updated_at": "2025-05-06T08:32:21.669Z", "connector": "stripe", "profile_id": "pro_PiIU0MSYNuU5kS96H0kV", "merchant_connector_id": "mca_jQBjGAAN1BgqzXa0Gpoy", "connector_refund_reference_id": null }, { "id": "12345_ref_01969f96f27e7213b4257eb238ec3a46", "payment_id": "12345_pay_01969f96e02a7dd3a183592c24c6693e", "merchant_reference_id": "1746434192", "amount": 100, "currency": "USD", "status": "succeeded", "reason": "Paid by mistake", "metadata": { "foo": "bar" }, "error_details": { "code": "", "message": "" }, "created_at": "2025-05-05T08:36:32.015Z", "updated_at": "2025-05-05T08:36:46.580Z", "connector": "stripe", "profile_id": "pro_PiIU0MSYNuU5kS96H0kV", "merchant_connector_id": "mca_jQBjGAAN1BgqzXa0Gpoy", "connector_refund_reference_id": null } ] } ``` - List refund by payment id API Call ``` curl --location --request GET 'http://localhost:8080/v2/refunds/list' \ --header 'x-profile-id: pro_PiIU0MSYNuU5kS96H0kV' \ --header 'Content-Type: application/json' \ --header 'Authorization: api-key=dev_nG2oG32R2dnadMOvkwfRyl0j1YB8uNf3t1FcDqhFgFxO7TtVS1kPQ8m4F3DEngVb' \ --data '{ "payment_id":"12345_pay_0196a4baa48772909f72eac2cd863d7b" }' ``` - Response from the above call ``` { "count": 1, "total_count": 1, "data": [ { "id": "12345_ref_0196a4badf2f7ed2b16c4ecaf1c814db", "payment_id": "12345_pay_0196a4baa48772909f72eac2cd863d7b", "merchant_reference_id": "1746520432", "amount": 70, "currency": "EUR", "status": "succeeded", "reason": "Paid by mistake", "metadata": { "foo": "bar" }, "error_details": { "code": "", "message": "" }, "created_at": "2025-05-06T08:33:52.433Z", "updated_at": "2025-05-06T08:33:53.474Z", "connector": "stripe", "profile_id": "pro_PiIU0MSYNuU5kS96H0kV", "merchant_connector_id": "mca_jQBjGAAN1BgqzXa0Gpoy", "connector_refund_reference_id": null } ] } ``` - List refund by refund id API Call ``` curl --location --request GET 'http://localhost:8080/v2/refunds/list' \ --header 'x-profile-id: pro_PiIU0MSYNuU5kS96H0kV' \ --header 'Content-Type: application/json' \ --header 'Authorization: api-key=dev_nG2oG32R2dnadMOvkwfRyl0j1YB8uNf3t1FcDqhFgFxO7TtVS1kPQ8m4F3DEngVb' \ --data '{ "refund_id":"12345_ref_0196a4ba41147d138621293a283b9d3e" }' ``` - Response from the above call ``` { "count": 1, "total_count": 1, "data": [ { "id": "12345_ref_0196a4ba41147d138621293a283b9d3e", "payment_id": "12345_pay_0196a4ba295477d0a4156e65135d8fb2", "merchant_reference_id": "1746520392", "amount": 1000, "currency": "BBD", "status": "succeeded", "reason": "Paid by mistake", "metadata": { "foo": "bar" }, "error_details": { "code": "", "message": "" }, "created_at": "2025-05-06T08:33:11.959Z", "updated_at": "2025-05-06T08:33:13.047Z", "connector": "stripe", "profile_id": "pro_PiIU0MSYNuU5kS96H0kV", "merchant_connector_id": "mca_jQBjGAAN1BgqzXa0Gpoy", "connector_refund_reference_id": null } ] } ``` - List refund by currencies API Call ``` curl --location --request GET 'http://localhost:8080/v2/refunds/list' \ --header 'x-profile-id: pro_PiIU0MSYNuU5kS96H0kV' \ --header 'Content-Type: application/json' \ --header 'Authorization: api-key=dev_nG2oG32R2dnadMOvkwfRyl0j1YB8uNf3t1FcDqhFgFxO7TtVS1kPQ8m4F3DEngVb' \ --data '{ "currency":["EUR","USD"] }' ``` - Response from the above call ``` { "count": 3, "total_count": 3, "data": [ { "id": "12345_ref_0196a4badf2f7ed2b16c4ecaf1c814db", "payment_id": "12345_pay_0196a4baa48772909f72eac2cd863d7b", "merchant_reference_id": "1746520432", "amount": 70, "currency": "EUR", "status": "succeeded", "reason": "Paid by mistake", "metadata": { "foo": "bar" }, "error_details": { "code": "", "message": "" }, "created_at": "2025-05-06T08:33:52.433Z", "updated_at": "2025-05-06T08:33:53.474Z", "connector": "stripe", "profile_id": "pro_PiIU0MSYNuU5kS96H0kV", "merchant_connector_id": "mca_jQBjGAAN1BgqzXa0Gpoy", "connector_refund_reference_id": null }, { "id": "12345_ref_0196a4b978637810b17d2f855afb0305", "payment_id": "12345_pay_0196a4b9609179429e3e0decc9892a55", "merchant_reference_id": "1746520341", "amount": 100, "currency": "USD", "status": "succeeded", "reason": "Paid by mistake", "metadata": { "foo": "bar" }, "error_details": { "code": "", "message": "" }, "created_at": "2025-05-06T08:32:20.588Z", "updated_at": "2025-05-06T08:32:21.669Z", "connector": "stripe", "profile_id": "pro_PiIU0MSYNuU5kS96H0kV", "merchant_connector_id": "mca_jQBjGAAN1BgqzXa0Gpoy", "connector_refund_reference_id": null }, { "id": "12345_ref_01969f96f27e7213b4257eb238ec3a46", "payment_id": "12345_pay_01969f96e02a7dd3a183592c24c6693e", "merchant_reference_id": "1746434192", "amount": 100, "currency": "USD", "status": "succeeded", "reason": "Paid by mistake", "metadata": { "foo": "bar" }, "error_details": { "code": "", "message": "" }, "created_at": "2025-05-05T08:36:32.015Z", "updated_at": "2025-05-05T08:36:46.580Z", "connector": "stripe", "profile_id": "pro_PiIU0MSYNuU5kS96H0kV", "merchant_connector_id": "mca_jQBjGAAN1BgqzXa0Gpoy", "connector_refund_reference_id": null } ] } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
1e243fada10f430d317c666d81483ae3246afd83
1e243fada10f430d317c666d81483ae3246afd83
juspay/hyperswitch
juspay__hyperswitch-7971
Bug: refactor(Connector): [signifyd,threedsecureio,wellsfargopayout,wise] move from routers to hyperswitch_connectors Move the following connectors from crates/router to crates/hyperswitch_connectors signifyd threedsecureio wellsfargopayout wise
diff --git a/Cargo.lock b/Cargo.lock index 39154406f6e..1c2f7d2c22e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3854,10 +3854,13 @@ dependencies = [ "hyperswitch_domain_models", "hyperswitch_interfaces", "image", + "iso_currency", + "isocountry", "josekit 0.8.6", "lazy_static", "masking", "mime", + "num-traits", "once_cell", "qrcode", "quick-xml", @@ -3880,6 +3883,7 @@ dependencies = [ "unidecode", "url", "urlencoding", + "utoipa", "uuid", ] @@ -6500,8 +6504,6 @@ dependencies = [ "hyperswitch_domain_models", "hyperswitch_interfaces", "infer", - "iso_currency", - "isocountry", "josekit 0.8.7", "jsonwebtoken", "kgraph_utils", diff --git a/crates/hyperswitch_connectors/Cargo.toml b/crates/hyperswitch_connectors/Cargo.toml index d3372b79411..38647cc14a2 100644 --- a/crates/hyperswitch_connectors/Cargo.toml +++ b/crates/hyperswitch_connectors/Cargo.toml @@ -22,9 +22,12 @@ encoding_rs = "0.8.33" error-stack = "0.4.1" hex = "0.4.3" http = "0.2.12" +iso_currency = "0.4.4" +isocountry = "0.3.2" image = { version = "0.25.1", default-features = false, features = ["png"] } josekit = { git = "https://github.com/sumanmaji4/josekit-rs.git", rev = "5ab54876c29a84f86aef8c169413a46026883efe", features = ["support-empty-payload"]} mime = "0.3.17" +num-traits = "0.2.19" once_cell = "1.19.0" qrcode = "0.14.0" quick-xml = { version = "0.31.0", features = ["serialize"] } @@ -43,6 +46,7 @@ serde_with = "3.7.0" sha1 = { version = "0.10.6" } strum = { version = "0.26", features = ["derive"] } time = "0.3.35" +utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order", "time"] } url = "2.5.0" urlencoding = "2.1.3" uuid = { version = "1.8.0", features = ["v4"] } diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs index 0679e873d40..99e83b1374e 100644 --- a/crates/hyperswitch_connectors/src/connectors.rs +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -75,16 +75,20 @@ pub mod recurly; pub mod redsys; pub mod riskified; pub mod shift4; +pub mod signifyd; pub mod square; pub mod stax; pub mod stripebilling; pub mod taxjar; +pub mod threedsecureio; pub mod thunes; pub mod trustpay; pub mod tsys; pub mod unified_authentication_service; pub mod volt; pub mod wellsfargo; +pub mod wellsfargopayout; +pub mod wise; pub mod worldline; pub mod worldpay; pub mod worldpayxml; @@ -109,9 +113,10 @@ pub use self::{ opayo::Opayo, opennode::Opennode, paybox::Paybox, payeezy::Payeezy, payme::Payme, payone::Payone, paypal::Paypal, paystack::Paystack, payu::Payu, placetopay::Placetopay, plaid::Plaid, powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, - recurly::Recurly, redsys::Redsys, riskified::Riskified, shift4::Shift4, square::Square, - stax::Stax, stripebilling::Stripebilling, taxjar::Taxjar, thunes::Thunes, trustpay::Trustpay, - tsys::Tsys, unified_authentication_service::UnifiedAuthenticationService, volt::Volt, - wellsfargo::Wellsfargo, worldline::Worldline, worldpay::Worldpay, worldpayxml::Worldpayxml, - xendit::Xendit, zen::Zen, zsl::Zsl, + recurly::Recurly, redsys::Redsys, riskified::Riskified, shift4::Shift4, signifyd::Signifyd, + square::Square, stax::Stax, stripebilling::Stripebilling, taxjar::Taxjar, + threedsecureio::Threedsecureio, thunes::Thunes, trustpay::Trustpay, tsys::Tsys, + unified_authentication_service::UnifiedAuthenticationService, volt::Volt, + wellsfargo::Wellsfargo, wellsfargopayout::Wellsfargopayout, wise::Wise, worldline::Worldline, + worldpay::Worldpay, worldpayxml::Worldpayxml, xendit::Xendit, zen::Zen, zsl::Zsl, }; diff --git a/crates/hyperswitch_connectors/src/connectors/signifyd.rs b/crates/hyperswitch_connectors/src/connectors/signifyd.rs new file mode 100644 index 00000000000..ce744b8d682 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/signifyd.rs @@ -0,0 +1,724 @@ +pub mod transformers; +use std::fmt::Debug; + +#[cfg(feature = "frm")] +use api_models::webhooks::IncomingWebhookEvent; +#[cfg(feature = "frm")] +use base64::Engine; +#[cfg(feature = "frm")] +use common_utils::{ + consts, + request::{Method, RequestBuilder}, +}; +#[cfg(feature = "frm")] +use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent}; +use common_utils::{errors::CustomResult, request::Request}; +#[cfg(feature = "frm")] +use error_stack::ResultExt; +use hyperswitch_domain_models::{ + router_data::{AccessToken, RouterData}, + router_flow_types::{ + AccessTokenAuth, Authorize, Capture, Execute, PSync, PaymentMethodToken, RSync, Session, + SetupMandate, Void, + }, + router_request_types::{ + AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, + RefundsData, SetupMandateRequestData, + }, + router_response_types::{PaymentsResponseData, RefundsResponseData}, +}; +#[cfg(feature = "frm")] +use hyperswitch_domain_models::{ + router_data::{ConnectorAuthType, ErrorResponse}, + router_flow_types::{Checkout, Fulfillment, RecordReturn, Sale, Transaction}, + router_request_types::fraud_check::{ + FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData, + FraudCheckSaleData, FraudCheckTransactionData, + }, + router_response_types::fraud_check::FraudCheckResponseData, +}; +use hyperswitch_interfaces::{ + api::{ + ConnectorAccessToken, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, + ConnectorSpecifications, ConnectorValidation, MandateSetup, Payment, PaymentAuthorize, + PaymentCapture, PaymentSession, PaymentSync, PaymentToken, PaymentVoid, Refund, + RefundExecute, RefundSync, + }, + configs::Connectors, + errors::ConnectorError, +}; +#[cfg(feature = "frm")] +use hyperswitch_interfaces::{ + api::{ + FraudCheck, FraudCheckCheckout, FraudCheckFulfillment, FraudCheckRecordReturn, + FraudCheckSale, FraudCheckTransaction, + }, + consts::NO_ERROR_CODE, + events::connector_api_logs::ConnectorEvent, + types::Response, + webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, +}; +#[cfg(feature = "frm")] +use masking::Mask; +use masking::Maskable; +#[cfg(feature = "frm")] +use masking::{PeekInterface, Secret}; +#[cfg(feature = "frm")] +use ring::hmac; +#[cfg(feature = "frm")] +use transformers as signifyd; + +use crate::constants::headers; +#[cfg(feature = "frm")] +use crate::{ + types::{ + FrmCheckoutRouterData, FrmCheckoutType, FrmFulfillmentRouterData, FrmFulfillmentType, + FrmRecordReturnRouterData, FrmRecordReturnType, FrmSaleRouterData, FrmSaleType, + FrmTransactionRouterData, FrmTransactionType, ResponseRouterData, + }, + utils::get_header_key_value, +}; + +#[derive(Debug, Clone)] +pub struct Signifyd; + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Signifyd +where + Self: ConnectorIntegration<Flow, Request, Response>, +{ + fn build_headers( + &self, + req: &RouterData<Flow, Request, Response>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + let mut header = vec![( + headers::CONTENT_TYPE.to_string(), + self.get_content_type().to_string().into(), + )]; + + let mut api_key = self.get_auth_header(&req.connector_auth_type)?; + header.append(&mut api_key); + Ok(header) + } +} + +impl ConnectorCommon for Signifyd { + fn id(&self) -> &'static str { + "signifyd" + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { + connectors.signifyd.base_url.as_ref() + } + + #[cfg(feature = "frm")] + fn get_auth_header( + &self, + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + let auth = signifyd::SignifydAuthType::try_from(auth_type) + .change_context(ConnectorError::FailedToObtainAuthType)?; + let auth_api_key = format!( + "Basic {}", + consts::BASE64_ENGINE.encode(auth.api_key.peek()) + ); + + Ok(vec![( + headers::AUTHORIZATION.to_string(), + Mask::into_masked(auth_api_key), + )]) + } + + #[cfg(feature = "frm")] + fn build_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, ConnectorError> { + let response: signifyd::SignifydErrorResponse = res + .response + .parse_struct("SignifydErrorResponse") + .change_context(ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + + Ok(ErrorResponse { + status_code: res.status_code, + code: NO_ERROR_CODE.to_string(), + message: response.messages.join(" &"), + reason: Some(response.errors.to_string()), + attempt_status: None, + connector_transaction_id: None, + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + }) + } +} + +impl Payment for Signifyd {} +impl PaymentAuthorize for Signifyd {} +impl PaymentSync for Signifyd {} +impl PaymentVoid for Signifyd {} +impl PaymentCapture for Signifyd {} +impl MandateSetup for Signifyd {} +impl ConnectorAccessToken for Signifyd {} +impl PaymentToken for Signifyd {} +impl Refund for Signifyd {} +impl RefundExecute for Signifyd {} +impl RefundSync for Signifyd {} +impl ConnectorValidation for Signifyd {} + +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Signifyd +{ +} + +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Signifyd {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> + for Signifyd +{ + fn build_request( + &self, + _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + Err(ConnectorError::NotImplemented("Setup Mandate flow for Signifyd".to_string()).into()) + } +} + +impl PaymentSession for Signifyd {} + +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Signifyd {} + +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Signifyd {} + +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Signifyd {} + +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Signifyd {} + +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Signifyd {} + +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Signifyd {} + +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Signifyd {} + +#[cfg(feature = "frm")] +impl FraudCheck for Signifyd {} +#[cfg(feature = "frm")] +impl FraudCheckSale for Signifyd {} +#[cfg(feature = "frm")] +impl FraudCheckCheckout for Signifyd {} +#[cfg(feature = "frm")] +impl FraudCheckTransaction for Signifyd {} +#[cfg(feature = "frm")] +impl FraudCheckFulfillment for Signifyd {} +#[cfg(feature = "frm")] +impl FraudCheckRecordReturn for Signifyd {} + +#[cfg(feature = "frm")] +impl ConnectorIntegration<Sale, FraudCheckSaleData, FraudCheckResponseData> for Signifyd { + fn get_headers( + &self, + req: &FrmSaleRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &FrmSaleRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { + Ok(format!( + "{}{}", + self.base_url(connectors), + "v3/orders/events/sales" + )) + } + + fn get_request_body( + &self, + req: &FrmSaleRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let req_obj = signifyd::SignifydPaymentsSaleRequest::try_from(req)?; + Ok(RequestContent::Json(Box::new(req_obj))) + } + + fn build_request( + &self, + req: &FrmSaleRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&FrmSaleType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(FrmSaleType::get_headers(self, req, connectors)?) + .set_body(FrmSaleType::get_request_body(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &FrmSaleRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<FrmSaleRouterData, ConnectorError> { + let response: signifyd::SignifydPaymentsResponse = res + .response + .parse_struct("SignifydPaymentsResponse Sale") + .change_context(ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + + <FrmSaleRouterData>::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +#[cfg(feature = "frm")] +impl ConnectorIntegration<Checkout, FraudCheckCheckoutData, FraudCheckResponseData> for Signifyd { + fn get_headers( + &self, + req: &FrmCheckoutRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &FrmCheckoutRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { + Ok(format!( + "{}{}", + self.base_url(connectors), + "v3/orders/events/checkouts" + )) + } + + fn get_request_body( + &self, + req: &FrmCheckoutRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let req_obj = signifyd::SignifydPaymentsCheckoutRequest::try_from(req)?; + Ok(RequestContent::Json(Box::new(req_obj))) + } + + fn build_request( + &self, + req: &FrmCheckoutRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&FrmCheckoutType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(FrmCheckoutType::get_headers(self, req, connectors)?) + .set_body(FrmCheckoutType::get_request_body(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &FrmCheckoutRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<FrmCheckoutRouterData, ConnectorError> { + let response: signifyd::SignifydPaymentsResponse = res + .response + .parse_struct("SignifydPaymentsResponse Checkout") + .change_context(ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + <FrmCheckoutRouterData>::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +#[cfg(feature = "frm")] +impl ConnectorIntegration<Transaction, FraudCheckTransactionData, FraudCheckResponseData> + for Signifyd +{ + fn get_headers( + &self, + req: &FrmTransactionRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &FrmTransactionRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { + Ok(format!( + "{}{}", + self.base_url(connectors), + "v3/orders/events/transactions" + )) + } + + fn get_request_body( + &self, + req: &FrmTransactionRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let req_obj = signifyd::SignifydPaymentsTransactionRequest::try_from(req)?; + Ok(RequestContent::Json(Box::new(req_obj))) + } + + fn build_request( + &self, + req: &FrmTransactionRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&FrmTransactionType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(FrmTransactionType::get_headers(self, req, connectors)?) + .set_body(FrmTransactionType::get_request_body(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &FrmTransactionRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<FrmTransactionRouterData, ConnectorError> { + let response: signifyd::SignifydPaymentsResponse = res + .response + .parse_struct("SignifydPaymentsResponse Transaction") + .change_context(ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + <FrmTransactionRouterData>::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +#[cfg(feature = "frm")] +impl ConnectorIntegration<Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData> + for Signifyd +{ + fn get_headers( + &self, + req: &FrmFulfillmentRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &FrmFulfillmentRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { + Ok(format!( + "{}{}", + self.base_url(connectors), + "v3/orders/events/fulfillments" + )) + } + + fn get_request_body( + &self, + req: &FrmFulfillmentRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let req_obj = signifyd::FrmFulfillmentSignifydRequest::try_from(req)?; + Ok(RequestContent::Json(Box::new(req_obj.clone()))) + } + + fn build_request( + &self, + req: &FrmFulfillmentRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&FrmFulfillmentType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(FrmFulfillmentType::get_headers(self, req, connectors)?) + .set_body(FrmFulfillmentType::get_request_body(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &FrmFulfillmentRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<FrmFulfillmentRouterData, ConnectorError> { + let response: signifyd::FrmFulfillmentSignifydApiResponse = res + .response + .parse_struct("FrmFulfillmentSignifydApiResponse Sale") + .change_context(ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + FrmFulfillmentRouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +#[cfg(feature = "frm")] +impl ConnectorIntegration<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData> + for Signifyd +{ + fn get_headers( + &self, + req: &FrmRecordReturnRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &FrmRecordReturnRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { + Ok(format!( + "{}{}", + self.base_url(connectors), + "v3/orders/events/returns/records" + )) + } + + fn get_request_body( + &self, + req: &FrmRecordReturnRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let req_obj = signifyd::SignifydPaymentsRecordReturnRequest::try_from(req)?; + Ok(RequestContent::Json(Box::new(req_obj))) + } + + fn build_request( + &self, + req: &FrmRecordReturnRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&FrmRecordReturnType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(FrmRecordReturnType::get_headers(self, req, connectors)?) + .set_body(FrmRecordReturnType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &FrmRecordReturnRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<FrmRecordReturnRouterData, ConnectorError> { + let response: signifyd::SignifydPaymentsRecordReturnResponse = res + .response + .parse_struct("SignifydPaymentsResponse Transaction") + .change_context(ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + <FrmRecordReturnRouterData>::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +#[cfg(feature = "frm")] +#[async_trait::async_trait] +impl IncomingWebhook for Signifyd { + fn get_webhook_source_verification_algorithm( + &self, + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, ConnectorError> { + Ok(Box::new(crypto::HmacSha256)) + } + + fn get_webhook_source_verification_signature( + &self, + request: &IncomingWebhookRequestDetails<'_>, + _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, + ) -> CustomResult<Vec<u8>, ConnectorError> { + let header_value = get_header_key_value("x-signifyd-sec-hmac-sha256", request.headers)?; + Ok(header_value.as_bytes().to_vec()) + } + + fn get_webhook_source_verification_message( + &self, + request: &IncomingWebhookRequestDetails<'_>, + _merchant_id: &common_utils::id_type::MerchantId, + _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, + ) -> CustomResult<Vec<u8>, ConnectorError> { + Ok(request.body.to_vec()) + } + + async fn verify_webhook_source( + &self, + request: &IncomingWebhookRequestDetails<'_>, + merchant_id: &common_utils::id_type::MerchantId, + connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, + _connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>, + connector_label: &str, + ) -> CustomResult<bool, ConnectorError> { + let connector_webhook_secrets = self + .get_webhook_source_verification_merchant_secret( + merchant_id, + connector_label, + connector_webhook_details, + ) + .await + .change_context(ConnectorError::WebhookSourceVerificationFailed)?; + + let signature = self + .get_webhook_source_verification_signature(request, &connector_webhook_secrets) + .change_context(ConnectorError::WebhookSourceVerificationFailed)?; + + let message = self + .get_webhook_source_verification_message( + request, + merchant_id, + &connector_webhook_secrets, + ) + .change_context(ConnectorError::WebhookSourceVerificationFailed)?; + + let signing_key = hmac::Key::new(hmac::HMAC_SHA256, &connector_webhook_secrets.secret); + let signed_message = hmac::sign(&signing_key, &message); + let payload_sign = consts::BASE64_ENGINE.encode(signed_message.as_ref()); + Ok(payload_sign.as_bytes().eq(&signature)) + } + + fn get_webhook_object_reference_id( + &self, + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::ObjectReferenceId, ConnectorError> { + let resource: signifyd::SignifydWebhookBody = request + .body + .parse_struct("SignifydWebhookBody") + .change_context(ConnectorError::WebhookReferenceIdNotFound)?; + Ok(api_models::webhooks::ObjectReferenceId::PaymentId( + api_models::payments::PaymentIdType::PaymentAttemptId(resource.order_id), + )) + } + + fn get_webhook_event_type( + &self, + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<IncomingWebhookEvent, ConnectorError> { + let resource: signifyd::SignifydWebhookBody = request + .body + .parse_struct("SignifydWebhookBody") + .change_context(ConnectorError::WebhookEventTypeNotFound)?; + Ok(IncomingWebhookEvent::from(resource.review_disposition)) + } + + fn get_webhook_resource_object( + &self, + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> { + let resource: signifyd::SignifydWebhookBody = request + .body + .parse_struct("SignifydWebhookBody") + .change_context(ConnectorError::WebhookResourceObjectNotFound)?; + Ok(Box::new(resource)) + } +} + +impl ConnectorSpecifications for Signifyd {} diff --git a/crates/router/src/connector/signifyd/transformers.rs b/crates/hyperswitch_connectors/src/connectors/signifyd/transformers.rs similarity index 100% rename from crates/router/src/connector/signifyd/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/signifyd/transformers.rs diff --git a/crates/router/src/connector/signifyd/transformers/api.rs b/crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs similarity index 77% rename from crates/router/src/connector/signifyd/transformers/api.rs rename to crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs index 028c0e82518..4df231a918e 100644 --- a/crates/router/src/connector/signifyd/transformers/api.rs +++ b/crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs @@ -1,6 +1,18 @@ +use api_models::webhooks::IncomingWebhookEvent; +use common_enums::{AttemptStatus, Currency, FraudCheckStatus, PaymentMethod}; use common_utils::{ext_traits::ValueExt, pii::Email}; use error_stack::{self, ResultExt}; pub use hyperswitch_domain_models::router_request_types::fraud_check::RefundMethod; +use hyperswitch_domain_models::{ + router_data::RouterData, + router_flow_types::Fulfillment, + router_request_types::{ + fraud_check::{self, FraudCheckFulfillmentData, FrmFulfillmentRequest}, + ResponseId, + }, + router_response_types::fraud_check::FraudCheckResponseData, +}; +use hyperswitch_interfaces::errors::ConnectorError; use masking::Secret; use num_traits::ToPrimitive; use serde::{Deserialize, Serialize}; @@ -8,17 +20,15 @@ use time::PrimitiveDateTime; use utoipa::ToSchema; use crate::{ - connector::utils::{ - AddressDetailsData, FraudCheckCheckoutRequest, FraudCheckRecordReturnRequest, - FraudCheckSaleRequest, FraudCheckTransactionRequest, RouterData, - }, - core::{errors, fraud_check::types as core_types}, types::{ - self, api, api::Fulfillment, fraud_check as frm_types, storage::enums as storage_enums, - transformers::ForeignFrom, ResponseId, ResponseRouterData, + FrmCheckoutRouterData, FrmFulfillmentRouterData, FrmRecordReturnRouterData, + FrmSaleRouterData, FrmTransactionRouterData, ResponseRouterData, + }, + utils::{ + AddressDetailsData as _, FraudCheckCheckoutRequest, FraudCheckRecordReturnRequest as _, + FraudCheckSaleRequest as _, FraudCheckTransactionRequest as _, RouterData as _, }, }; - #[allow(dead_code)] #[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] @@ -36,7 +46,7 @@ pub struct Purchase { total_price: i64, products: Vec<Products>, shipments: Shipments, - currency: Option<common_enums::Currency>, + currency: Option<Currency>, total_shipping_cost: Option<i64>, confirmation_email: Option<Email>, confirmation_phone: Option<Secret<String>>, @@ -136,9 +146,9 @@ pub struct SignifydFrmMetadata { pub order_channel: OrderChannel, } -impl TryFrom<&frm_types::FrmSaleRouterData> for SignifydPaymentsSaleRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &frm_types::FrmSaleRouterData) -> Result<Self, Self::Error> { +impl TryFrom<&FrmSaleRouterData> for SignifydPaymentsSaleRequest { + type Error = error_stack::Report<ConnectorError>; + fn try_from(item: &FrmSaleRouterData) -> Result<Self, Self::Error> { let products = item .request .get_order_details()? @@ -159,11 +169,11 @@ impl TryFrom<&frm_types::FrmSaleRouterData> for SignifydPaymentsSaleRequest { let metadata: SignifydFrmMetadata = item .frm_metadata .clone() - .ok_or(errors::ConnectorError::MissingRequiredField { + .ok_or(ConnectorError::MissingRequiredField { field_name: "frm_metadata", })? .parse_value("Signifyd Frm Metadata") - .change_context(errors::ConnectorError::InvalidDataFormat { + .change_context(ConnectorError::InvalidDataFormat { field_name: "frm_metadata", })?; let ship_address = item.get_shipping_address()?; @@ -239,7 +249,7 @@ pub enum SignifydPaymentStatus { Reject, } -impl From<SignifydPaymentStatus> for storage_enums::FraudCheckStatus { +impl From<SignifydPaymentStatus> for FraudCheckStatus { fn from(item: SignifydPaymentStatus) -> Self { match item { SignifydPaymentStatus::Accept => Self::Legit, @@ -257,20 +267,17 @@ pub struct SignifydPaymentsResponse { decision: Decision, } -impl<F, T> - TryFrom<ResponseRouterData<F, SignifydPaymentsResponse, T, frm_types::FraudCheckResponseData>> - for types::RouterData<F, T, frm_types::FraudCheckResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, SignifydPaymentsResponse, T, FraudCheckResponseData>> + for RouterData<F, T, FraudCheckResponseData> { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: ResponseRouterData<F, SignifydPaymentsResponse, T, frm_types::FraudCheckResponseData>, + item: ResponseRouterData<F, SignifydPaymentsResponse, T, FraudCheckResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(frm_types::FraudCheckResponseData::TransactionResponse { + response: Ok(FraudCheckResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.order_id), - status: storage_enums::FraudCheckStatus::from( - item.response.decision.checkpoint_action, - ), + status: FraudCheckStatus::from(item.response.decision.checkpoint_action), connector_metadata: None, score: item.response.decision.score.and_then(|data| data.to_i32()), reason: item @@ -295,9 +302,9 @@ pub struct SignifydErrorResponse { pub struct Transactions { transaction_id: String, gateway_status_code: String, - payment_method: storage_enums::PaymentMethod, + payment_method: PaymentMethod, amount: i64, - currency: storage_enums::Currency, + currency: Currency, gateway: Option<String>, } @@ -309,20 +316,20 @@ pub struct SignifydPaymentsTransactionRequest { transactions: Transactions, } -impl From<storage_enums::AttemptStatus> for GatewayStatusCode { - fn from(item: storage_enums::AttemptStatus) -> Self { +impl From<AttemptStatus> for GatewayStatusCode { + fn from(item: AttemptStatus) -> Self { match item { - storage_enums::AttemptStatus::Pending => Self::Pending, - storage_enums::AttemptStatus::Failure => Self::Failure, - storage_enums::AttemptStatus::Charged => Self::Success, + AttemptStatus::Pending => Self::Pending, + AttemptStatus::Failure => Self::Failure, + AttemptStatus::Charged => Self::Success, _ => Self::Pending, } } } -impl TryFrom<&frm_types::FrmTransactionRouterData> for SignifydPaymentsTransactionRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &frm_types::FrmTransactionRouterData) -> Result<Self, Self::Error> { +impl TryFrom<&FrmTransactionRouterData> for SignifydPaymentsTransactionRequest { + type Error = error_stack::Report<ConnectorError>; + fn try_from(item: &FrmTransactionRouterData) -> Result<Self, Self::Error> { let currency = item.request.get_currency()?; let transactions = Transactions { amount: item.request.amount, @@ -373,9 +380,9 @@ pub struct SignifydPaymentsCheckoutRequest { coverage_requests: Option<CoverageRequests>, } -impl TryFrom<&frm_types::FrmCheckoutRouterData> for SignifydPaymentsCheckoutRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &frm_types::FrmCheckoutRouterData) -> Result<Self, Self::Error> { +impl TryFrom<&FrmCheckoutRouterData> for SignifydPaymentsCheckoutRequest { + type Error = error_stack::Report<ConnectorError>; + fn try_from(item: &FrmCheckoutRouterData) -> Result<Self, Self::Error> { let products = item .request .get_order_details()? @@ -396,11 +403,11 @@ impl TryFrom<&frm_types::FrmCheckoutRouterData> for SignifydPaymentsCheckoutRequ let metadata: SignifydFrmMetadata = item .frm_metadata .clone() - .ok_or(errors::ConnectorError::MissingRequiredField { + .ok_or(ConnectorError::MissingRequiredField { field_name: "frm_metadata", })? .parse_value("Signifyd Frm Metadata") - .change_context(errors::ConnectorError::InvalidDataFormat { + .change_context(ConnectorError::InvalidDataFormat { field_name: "frm_metadata", })?; let ship_address = item.get_shipping_address()?; @@ -499,9 +506,9 @@ pub struct Product { pub item_id: String, } -impl TryFrom<&frm_types::FrmFulfillmentRouterData> for FrmFulfillmentSignifydRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &frm_types::FrmFulfillmentRouterData) -> Result<Self, Self::Error> { +impl TryFrom<&FrmFulfillmentRouterData> for FrmFulfillmentSignifydRequest { + type Error = error_stack::Report<ConnectorError>; + fn try_from(item: &FrmFulfillmentRouterData) -> Result<Self, Self::Error> { Ok(Self { order_id: item.request.fulfillment_req.order_id.clone(), fulfillment_status: item @@ -510,47 +517,48 @@ impl TryFrom<&frm_types::FrmFulfillmentRouterData> for FrmFulfillmentSignifydReq .fulfillment_status .as_ref() .map(|fulfillment_status| FulfillmentStatus::from(&fulfillment_status.clone())), - fulfillments: Vec::<Fulfillments>::foreign_from(&item.request.fulfillment_req), + fulfillments: get_signifyd_fulfillments_from_frm_fulfillment_request( + &item.request.fulfillment_req, + ), }) } } -impl From<&core_types::FulfillmentStatus> for FulfillmentStatus { - fn from(status: &core_types::FulfillmentStatus) -> Self { +impl From<&fraud_check::FulfillmentStatus> for FulfillmentStatus { + fn from(status: &fraud_check::FulfillmentStatus) -> Self { match status { - core_types::FulfillmentStatus::PARTIAL => Self::PARTIAL, - core_types::FulfillmentStatus::COMPLETE => Self::COMPLETE, - core_types::FulfillmentStatus::REPLACEMENT => Self::REPLACEMENT, - core_types::FulfillmentStatus::CANCELED => Self::CANCELED, + fraud_check::FulfillmentStatus::PARTIAL => Self::PARTIAL, + fraud_check::FulfillmentStatus::COMPLETE => Self::COMPLETE, + fraud_check::FulfillmentStatus::REPLACEMENT => Self::REPLACEMENT, + fraud_check::FulfillmentStatus::CANCELED => Self::CANCELED, } } } - -impl ForeignFrom<&core_types::FrmFulfillmentRequest> for Vec<Fulfillments> { - fn foreign_from(fulfillment_req: &core_types::FrmFulfillmentRequest) -> Self { - fulfillment_req - .fulfillments - .iter() - .map(|fulfillment| Fulfillments { - shipment_id: fulfillment.shipment_id.clone(), - products: fulfillment - .products - .as_ref() - .map(|products| products.iter().map(|p| Product::from(p.clone())).collect()), - destination: Destination::from(fulfillment.destination.clone()), - tracking_urls: fulfillment_req.tracking_urls.clone(), - tracking_numbers: fulfillment_req.tracking_numbers.clone(), - fulfillment_method: fulfillment_req.fulfillment_method.clone(), - carrier: fulfillment_req.carrier.clone(), - shipment_status: fulfillment_req.shipment_status.clone(), - shipped_at: fulfillment_req.shipped_at.clone(), - }) - .collect() - } +pub(crate) fn get_signifyd_fulfillments_from_frm_fulfillment_request( + fulfillment_req: &FrmFulfillmentRequest, +) -> Vec<Fulfillments> { + fulfillment_req + .fulfillments + .iter() + .map(|fulfillment| Fulfillments { + shipment_id: fulfillment.shipment_id.clone(), + products: fulfillment + .products + .as_ref() + .map(|products| products.iter().map(|p| Product::from(p.clone())).collect()), + destination: Destination::from(fulfillment.destination.clone()), + tracking_urls: fulfillment_req.tracking_urls.clone(), + tracking_numbers: fulfillment_req.tracking_numbers.clone(), + fulfillment_method: fulfillment_req.fulfillment_method.clone(), + carrier: fulfillment_req.carrier.clone(), + shipment_status: fulfillment_req.shipment_status.clone(), + shipped_at: fulfillment_req.shipped_at.clone(), + }) + .collect() } -impl From<core_types::Product> for Product { - fn from(product: core_types::Product) -> Self { +impl From<fraud_check::Product> for Product { + fn from(product: fraud_check::Product) -> Self { Self { item_name: product.item_name, item_quantity: product.item_quantity, @@ -559,8 +567,8 @@ impl From<core_types::Product> for Product { } } -impl From<core_types::Destination> for Destination { - fn from(destination: core_types::Destination) -> Self { +impl From<fraud_check::Destination> for Destination { + fn from(destination: fraud_check::Destination) -> Self { Self { full_name: destination.full_name, organization: destination.organization, @@ -570,8 +578,8 @@ impl From<core_types::Destination> for Destination { } } -impl From<core_types::Address> for Address { - fn from(address: core_types::Address) -> Self { +impl From<fraud_check::Address> for Address { + fn from(address: fraud_check::Address) -> Self { Self { street_address: address.street_address, unit: address.unit, @@ -596,27 +604,22 @@ impl ResponseRouterData< Fulfillment, FrmFulfillmentSignifydApiResponse, - frm_types::FraudCheckFulfillmentData, - frm_types::FraudCheckResponseData, + FraudCheckFulfillmentData, + FraudCheckResponseData, >, - > - for types::RouterData< - Fulfillment, - frm_types::FraudCheckFulfillmentData, - frm_types::FraudCheckResponseData, - > + > for RouterData<Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData> { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from( item: ResponseRouterData< Fulfillment, FrmFulfillmentSignifydApiResponse, - frm_types::FraudCheckFulfillmentData, - frm_types::FraudCheckResponseData, + FraudCheckFulfillmentData, + FraudCheckResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(frm_types::FraudCheckResponseData::FulfillmentResponse { + response: Ok(FraudCheckResponseData::FulfillmentResponse { order_id: item.response.order_id, shipment_ids: item.response.shipment_ids, }), @@ -631,7 +634,7 @@ impl pub struct SignifydRefund { method: RefundMethod, amount: String, - currency: storage_enums::Currency, + currency: Currency, } #[derive(Debug, Serialize, Eq, PartialEq)] @@ -653,26 +656,20 @@ pub struct SignifydPaymentsRecordReturnResponse { } impl<F, T> - TryFrom< - ResponseRouterData< - F, - SignifydPaymentsRecordReturnResponse, - T, - frm_types::FraudCheckResponseData, - >, - > for types::RouterData<F, T, frm_types::FraudCheckResponseData> + TryFrom<ResponseRouterData<F, SignifydPaymentsRecordReturnResponse, T, FraudCheckResponseData>> + for RouterData<F, T, FraudCheckResponseData> { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from( item: ResponseRouterData< F, SignifydPaymentsRecordReturnResponse, T, - frm_types::FraudCheckResponseData, + FraudCheckResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(frm_types::FraudCheckResponseData::RecordReturnResponse { + response: Ok(FraudCheckResponseData::RecordReturnResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.order_id), return_id: Some(item.response.return_id.to_string()), connector_metadata: None, @@ -682,9 +679,9 @@ impl<F, T> } } -impl TryFrom<&frm_types::FrmRecordReturnRouterData> for SignifydPaymentsRecordReturnRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &frm_types::FrmRecordReturnRouterData) -> Result<Self, Self::Error> { +impl TryFrom<&FrmRecordReturnRouterData> for SignifydPaymentsRecordReturnRequest { + type Error = error_stack::Report<ConnectorError>; + fn try_from(item: &FrmRecordReturnRouterData) -> Result<Self, Self::Error> { let currency = item.request.get_currency()?; let refund = SignifydRefund { method: item.request.refund_method.clone(), @@ -714,7 +711,7 @@ pub enum ReviewDisposition { Good, } -impl From<ReviewDisposition> for api::IncomingWebhookEvent { +impl From<ReviewDisposition> for IncomingWebhookEvent { fn from(value: ReviewDisposition) -> Self { match value { ReviewDisposition::Fraudulent => Self::FrmRejected, diff --git a/crates/hyperswitch_connectors/src/connectors/signifyd/transformers/auth.rs b/crates/hyperswitch_connectors/src/connectors/signifyd/transformers/auth.rs new file mode 100644 index 00000000000..1462e2e7297 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/signifyd/transformers/auth.rs @@ -0,0 +1,20 @@ +use error_stack; +use hyperswitch_domain_models::router_data::ConnectorAuthType; +use hyperswitch_interfaces::errors::ConnectorError; +use masking::Secret; + +pub struct SignifydAuthType { + pub api_key: Secret<String>, +} + +impl TryFrom<&ConnectorAuthType> for SignifydAuthType { + type Error = error_stack::Report<ConnectorError>; + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { + match auth_type { + ConnectorAuthType::HeaderKey { api_key } => Ok(Self { + api_key: api_key.to_owned(), + }), + _ => Err(ConnectorError::FailedToObtainAuthType.into()), + } + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/threedsecureio.rs b/crates/hyperswitch_connectors/src/connectors/threedsecureio.rs new file mode 100644 index 00000000000..7f98cf9d958 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/threedsecureio.rs @@ -0,0 +1,512 @@ +pub mod transformers; + +use std::fmt::Debug; + +use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId}; +use common_utils::{ + errors::CustomResult, + ext_traits::BytesExt, + request::{Method, Request, RequestBuilder, RequestContent}, +}; +use error_stack::{report, ResultExt}; +use hyperswitch_domain_models::{ + router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, + router_flow_types::{ + authentication::{ + Authentication, PostAuthentication, PreAuthentication, PreAuthenticationVersionCall, + }, + AccessTokenAuth, Authorize, Capture, Execute, PSync, PaymentMethodToken, RSync, Session, + SetupMandate, Void, + }, + router_request_types::{ + authentication::{ + ConnectorAuthenticationRequestData, ConnectorPostAuthenticationRequestData, + PreAuthNRequestData, + }, + AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, + RefundsData, SetupMandateRequestData, + }, + router_response_types::{ + AuthenticationResponseData, PaymentsResponseData, RefundsResponseData, + }, +}; +use hyperswitch_interfaces::{ + api::{ + authentication::{ + ConnectorAuthentication, ConnectorPostAuthentication, ConnectorPreAuthentication, + ConnectorPreAuthenticationVersionCall, ExternalAuthentication, + }, + ConnectorAccessToken, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, + ConnectorSpecifications, ConnectorValidation, CurrencyUnit, MandateSetup, Payment, + PaymentAuthorize, PaymentCapture, PaymentSession, PaymentSync, PaymentToken, PaymentVoid, + Refund, RefundExecute, RefundSync, + }, + configs::Connectors, + consts::NO_ERROR_MESSAGE, + errors::ConnectorError, + events::connector_api_logs::ConnectorEvent, + types::Response, + webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, +}; +use masking::{ExposeInterface, Mask as _, Maskable}; +use transformers as threedsecureio; + +use crate::{ + constants::headers, + types::{ + ConnectorAuthenticationRouterData, ConnectorAuthenticationType, + ConnectorPostAuthenticationRouterData, ConnectorPostAuthenticationType, + ConnectorPreAuthenticationType, PreAuthNRouterData, ResponseRouterData, + }, + utils::handle_json_response_deserialization_failure, +}; +#[derive(Debug, Clone)] +pub struct Threedsecureio; + +impl Payment for Threedsecureio {} +impl PaymentSession for Threedsecureio {} +impl ConnectorAccessToken for Threedsecureio {} +impl MandateSetup for Threedsecureio {} +impl PaymentAuthorize for Threedsecureio {} +impl PaymentSync for Threedsecureio {} +impl PaymentCapture for Threedsecureio {} +impl PaymentVoid for Threedsecureio {} +impl Refund for Threedsecureio {} +impl RefundExecute for Threedsecureio {} +impl RefundSync for Threedsecureio {} +impl PaymentToken for Threedsecureio {} + +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Threedsecureio +{ +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Threedsecureio +where + Self: ConnectorIntegration<Flow, Request, Response>, +{ + fn build_headers( + &self, + req: &RouterData<Flow, Request, Response>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + let mut header = vec![( + headers::CONTENT_TYPE.to_string(), + "application/json; charset=utf-8".to_string().into(), + )]; + let mut api_key = self.get_auth_header(&req.connector_auth_type)?; + header.append(&mut api_key); + Ok(header) + } +} + +impl ConnectorCommon for Threedsecureio { + fn id(&self) -> &'static str { + "threedsecureio" + } + + fn get_currency_unit(&self) -> CurrencyUnit { + CurrencyUnit::Minor + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { + connectors.threedsecureio.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + let auth = threedsecureio::ThreedsecureioAuthType::try_from(auth_type) + .change_context(ConnectorError::FailedToObtainAuthType)?; + Ok(vec![( + headers::APIKEY.to_string(), + auth.api_key.expose().into_masked(), + )]) + } + + fn build_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, ConnectorError> { + let response_result: Result< + threedsecureio::ThreedsecureioErrorResponse, + error_stack::Report<common_utils::errors::ParsingError>, + > = res.response.parse_struct("ThreedsecureioErrorResponse"); + + match response_result { + Ok(response) => { + event_builder.map(|i| i.set_error_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(ErrorResponse { + status_code: res.status_code, + code: response.error_code, + message: response + .error_description + .clone() + .unwrap_or(NO_ERROR_MESSAGE.to_owned()), + reason: response.error_description, + attempt_status: None, + connector_transaction_id: None, + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + }) + } + Err(err) => { + router_env::logger::error!(deserialization_error =? err); + handle_json_response_deserialization_failure(res, "threedsecureio") + } + } + } +} + +impl ConnectorValidation for Threedsecureio {} + +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Threedsecureio {} + +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Threedsecureio {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> + for Threedsecureio +{ +} + +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> + for Threedsecureio +{ +} + +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Threedsecureio {} + +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Threedsecureio {} + +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Threedsecureio {} + +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Threedsecureio {} + +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Threedsecureio {} + +#[async_trait::async_trait] +impl IncomingWebhook for Threedsecureio { + fn get_webhook_object_reference_id( + &self, + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<ObjectReferenceId, ConnectorError> { + Err(report!(ConnectorError::WebhooksNotImplemented)) + } + + fn get_webhook_event_type( + &self, + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<IncomingWebhookEvent, ConnectorError> { + Err(report!(ConnectorError::WebhooksNotImplemented)) + } + + fn get_webhook_resource_object( + &self, + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> { + Err(report!(ConnectorError::WebhooksNotImplemented)) + } +} + +impl ConnectorPreAuthentication for Threedsecureio {} +impl ConnectorPreAuthenticationVersionCall for Threedsecureio {} +impl ExternalAuthentication for Threedsecureio {} +impl ConnectorAuthentication for Threedsecureio {} +impl ConnectorPostAuthentication for Threedsecureio {} + +impl + ConnectorIntegration< + Authentication, + ConnectorAuthenticationRequestData, + AuthenticationResponseData, + > for Threedsecureio +{ + fn get_headers( + &self, + req: &ConnectorAuthenticationRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &ConnectorAuthenticationRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { + Ok(format!("{}/auth", self.base_url(connectors),)) + } + + fn get_request_body( + &self, + req: &ConnectorAuthenticationRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let connector_router_data = threedsecureio::ThreedsecureioRouterData::try_from(( + &self.get_currency_unit(), + req.request + .currency + .ok_or(ConnectorError::MissingRequiredField { + field_name: "currency", + })?, + req.request + .amount + .ok_or(ConnectorError::MissingRequiredField { + field_name: "amount", + })?, + req, + ))?; + let req_obj = + threedsecureio::ThreedsecureioAuthenticationRequest::try_from(&connector_router_data); + Ok(RequestContent::Json(Box::new(req_obj?))) + } + + fn build_request( + &self, + req: &ConnectorAuthenticationRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&ConnectorAuthenticationType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(ConnectorAuthenticationType::get_headers( + self, req, connectors, + )?) + .set_body(ConnectorAuthenticationType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &ConnectorAuthenticationRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<ConnectorAuthenticationRouterData, ConnectorError> { + let response: threedsecureio::ThreedsecureioAuthenticationResponse = res + .response + .parse_struct("ThreedsecureioAuthenticationResponse") + .change_context(ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<PreAuthentication, PreAuthNRequestData, AuthenticationResponseData> + for Threedsecureio +{ + fn get_headers( + &self, + req: &PreAuthNRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &PreAuthNRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { + Ok(format!("{}/preauth", self.base_url(connectors),)) + } + + fn get_request_body( + &self, + req: &PreAuthNRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let connector_router_data = threedsecureio::ThreedsecureioRouterData::try_from((0, req))?; + let req_obj = threedsecureio::ThreedsecureioPreAuthenticationRequest::try_from( + &connector_router_data, + )?; + Ok(RequestContent::Json(Box::new(req_obj))) + } + + fn build_request( + &self, + req: &PreAuthNRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&ConnectorPreAuthenticationType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(ConnectorPreAuthenticationType::get_headers( + self, req, connectors, + )?) + .set_body(ConnectorPreAuthenticationType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PreAuthNRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PreAuthNRouterData, ConnectorError> { + let response: threedsecureio::ThreedsecureioPreAuthenticationResponse = res + .response + .parse_struct("threedsecureio ThreedsecureioPreAuthenticationResponse") + .change_context(ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl + ConnectorIntegration< + PostAuthentication, + ConnectorPostAuthenticationRequestData, + AuthenticationResponseData, + > for Threedsecureio +{ + fn get_headers( + &self, + req: &ConnectorPostAuthenticationRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &ConnectorPostAuthenticationRouterData, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { + Ok(format!("{}/postauth", self.base_url(connectors),)) + } + + fn get_request_body( + &self, + req: &ConnectorPostAuthenticationRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let req_obj = threedsecureio::ThreedsecureioPostAuthenticationRequest { + three_ds_server_trans_id: req.request.threeds_server_transaction_id.clone(), + }; + Ok(RequestContent::Json(Box::new(req_obj))) + } + + fn build_request( + &self, + req: &ConnectorPostAuthenticationRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&ConnectorPostAuthenticationType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(ConnectorPostAuthenticationType::get_headers( + self, req, connectors, + )?) + .set_body(ConnectorPostAuthenticationType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &ConnectorPostAuthenticationRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<ConnectorPostAuthenticationRouterData, ConnectorError> { + let response: threedsecureio::ThreedsecureioPostAuthenticationResponse = res + .response + .parse_struct("threedsecureio PaymentsSyncResponse") + .change_context(ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + Ok(ConnectorPostAuthenticationRouterData { + response: Ok(AuthenticationResponseData::PostAuthNResponse { + trans_status: response.trans_status.into(), + authentication_value: response.authentication_value, + eci: response.eci, + }), + ..data.clone() + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl + ConnectorIntegration< + PreAuthenticationVersionCall, + PreAuthNRequestData, + AuthenticationResponseData, + > for Threedsecureio +{ +} + +impl ConnectorSpecifications for Threedsecureio {} diff --git a/crates/router/src/connector/threedsecureio/transformers.rs b/crates/hyperswitch_connectors/src/connectors/threedsecureio/transformers.rs similarity index 78% rename from crates/router/src/connector/threedsecureio/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/threedsecureio/transformers.rs index e6d608b68d3..d74d667b087 100644 --- a/crates/router/src/connector/threedsecureio/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/threedsecureio/transformers.rs @@ -2,25 +2,30 @@ use std::str::FromStr; use api_models::payments::{DeviceChannel, ThreeDsCompletionIndicator}; use base64::Engine; -use common_utils::date_time; +use common_enums::enums; +use common_utils::{consts::BASE64_ENGINE, date_time, ext_traits::OptionExt as _}; use error_stack::ResultExt; -use hyperswitch_connectors::utils::AddressDetailsData; +use hyperswitch_domain_models::{ + router_data::{ConnectorAuthType, ErrorResponse}, + router_flow_types::authentication::{Authentication, PreAuthentication}, + router_request_types::{ + authentication::{ + AuthNFlowType, ChallengeParams, ConnectorAuthenticationRequestData, MessageCategory, + PreAuthNRequestData, + }, + BrowserInformation, + }, + router_response_types::AuthenticationResponseData, +}; +use hyperswitch_interfaces::{api::CurrencyUnit, consts::NO_ERROR_MESSAGE, errors}; use iso_currency::Currency; -use isocountry; use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use serde_json::{json, to_string}; use crate::{ - connector::utils::{get_card_details, to_connector_meta, CardData}, - consts::{BASE64_ENGINE, NO_ERROR_MESSAGE}, - core::errors, - types::{ - self, - api::{self, MessageCategory}, - authentication::ChallengeParams, - }, - utils::OptionExt, + types::{ConnectorAuthenticationRouterData, PreAuthNRouterData, ResponseRouterData}, + utils::{get_card_details, to_connector_meta, AddressDetailsData, CardData as _}, }; pub struct ThreedsecureioRouterData<T> { @@ -28,17 +33,10 @@ pub struct ThreedsecureioRouterData<T> { pub router_data: T, } -impl<T> TryFrom<(&api::CurrencyUnit, types::storage::enums::Currency, i64, T)> - for ThreedsecureioRouterData<T> -{ +impl<T> TryFrom<(&CurrencyUnit, enums::Currency, i64, T)> for ThreedsecureioRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - (_currency_unit, _currency, amount, item): ( - &api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - ), + (_currency_unit, _currency, amount, item): (&CurrencyUnit, enums::Currency, i64, T), ) -> Result<Self, Self::Error> { Ok(Self { amount: amount.to_string(), @@ -59,21 +57,21 @@ impl<T> TryFrom<(i64, T)> for ThreedsecureioRouterData<T> { impl TryFrom< - types::ResponseRouterData< - api::PreAuthentication, + ResponseRouterData< + PreAuthentication, ThreedsecureioPreAuthenticationResponse, - types::authentication::PreAuthNRequestData, - types::authentication::AuthenticationResponseData, + PreAuthNRequestData, + AuthenticationResponseData, >, - > for types::authentication::PreAuthNRouterData + > for PreAuthNRouterData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData< - api::PreAuthentication, + item: ResponseRouterData< + PreAuthentication, ThreedsecureioPreAuthenticationResponse, - types::authentication::PreAuthNRequestData, - types::authentication::AuthenticationResponseData, + PreAuthNRequestData, + AuthenticationResponseData, >, ) -> Result<Self, Self::Error> { let response = match item.response { @@ -91,30 +89,27 @@ impl acs_start_protocol_version: pre_authn_response.acs_start_protocol_version, acs_end_protocol_version: pre_authn_response.acs_end_protocol_version.clone(), }); - Ok( - types::authentication::AuthenticationResponseData::PreAuthNResponse { - threeds_server_transaction_id: pre_authn_response - .threeds_server_trans_id - .clone(), - maximum_supported_3ds_version: - common_utils::types::SemanticVersion::from_str( - &pre_authn_response.acs_end_protocol_version, - ) - .change_context(errors::ConnectorError::ParsingFailed)?, - connector_authentication_id: pre_authn_response.threeds_server_trans_id, - three_ds_method_data: Some(three_ds_method_data_base64), - three_ds_method_url: pre_authn_response.threeds_method_url, - message_version: common_utils::types::SemanticVersion::from_str( - &pre_authn_response.acs_end_protocol_version, - ) - .change_context(errors::ConnectorError::ParsingFailed)?, - connector_metadata: Some(connector_metadata), - directory_server_id: None, - }, - ) + Ok(AuthenticationResponseData::PreAuthNResponse { + threeds_server_transaction_id: pre_authn_response + .threeds_server_trans_id + .clone(), + maximum_supported_3ds_version: common_utils::types::SemanticVersion::from_str( + &pre_authn_response.acs_end_protocol_version, + ) + .change_context(errors::ConnectorError::ParsingFailed)?, + connector_authentication_id: pre_authn_response.threeds_server_trans_id, + three_ds_method_data: Some(three_ds_method_data_base64), + three_ds_method_url: pre_authn_response.threeds_method_url, + message_version: common_utils::types::SemanticVersion::from_str( + &pre_authn_response.acs_end_protocol_version, + ) + .change_context(errors::ConnectorError::ParsingFailed)?, + connector_metadata: Some(connector_metadata), + directory_server_id: None, + }) } ThreedsecureioPreAuthenticationResponse::Failure(error_response) => { - Err(types::ErrorResponse { + Err(ErrorResponse { code: error_response.error_code, message: error_response .error_description @@ -139,21 +134,21 @@ impl impl TryFrom< - types::ResponseRouterData< - api::Authentication, + ResponseRouterData< + Authentication, ThreedsecureioAuthenticationResponse, - types::authentication::ConnectorAuthenticationRequestData, - types::authentication::AuthenticationResponseData, + ConnectorAuthenticationRequestData, + AuthenticationResponseData, >, - > for types::authentication::ConnectorAuthenticationRouterData + > for ConnectorAuthenticationRouterData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData< - api::Authentication, + item: ResponseRouterData< + Authentication, ThreedsecureioAuthenticationResponse, - types::authentication::ConnectorAuthenticationRequestData, - types::authentication::AuthenticationResponseData, + ConnectorAuthenticationRequestData, + AuthenticationResponseData, >, ) -> Result<Self, Self::Error> { let response = match item.response { @@ -171,61 +166,51 @@ impl let creq_base64 = Engine::encode(&BASE64_ENGINE, creq_str) .trim_end_matches('=') .to_owned(); - Ok( - types::authentication::AuthenticationResponseData::AuthNResponse { - trans_status: response.trans_status.clone().into(), - authn_flow_type: if response.trans_status == ThreedsecureioTransStatus::C { - types::authentication::AuthNFlowType::Challenge(Box::new( - ChallengeParams { - acs_url: response.acs_url, - challenge_request: Some(creq_base64), - acs_reference_number: Some( - response.acs_reference_number.clone(), - ), - acs_trans_id: Some(response.acs_trans_id.clone()), - three_dsserver_trans_id: Some(response.three_dsserver_trans_id), - acs_signed_content: response.acs_signed_content, - }, - )) - } else { - types::authentication::AuthNFlowType::Frictionless - }, - authentication_value: response.authentication_value, - connector_metadata: None, - ds_trans_id: Some(response.ds_trans_id), + Ok(AuthenticationResponseData::AuthNResponse { + trans_status: response.trans_status.clone().into(), + authn_flow_type: if response.trans_status == ThreedsecureioTransStatus::C { + AuthNFlowType::Challenge(Box::new(ChallengeParams { + acs_url: response.acs_url, + challenge_request: Some(creq_base64), + acs_reference_number: Some(response.acs_reference_number.clone()), + acs_trans_id: Some(response.acs_trans_id.clone()), + three_dsserver_trans_id: Some(response.three_dsserver_trans_id), + acs_signed_content: response.acs_signed_content, + })) + } else { + AuthNFlowType::Frictionless }, - ) + authentication_value: response.authentication_value, + connector_metadata: None, + ds_trans_id: Some(response.ds_trans_id), + }) } ThreedsecureioAuthenticationResponse::Error(err_response) => match *err_response { - ThreedsecureioErrorResponseWrapper::ErrorResponse(resp) => { - Err(types::ErrorResponse { - code: resp.error_code, - message: resp - .error_description - .clone() - .unwrap_or(NO_ERROR_MESSAGE.to_owned()), - reason: resp.error_description, - status_code: item.http_code, - attempt_status: None, - connector_transaction_id: None, - network_advice_code: None, - network_decline_code: None, - network_error_message: None, - }) - } - ThreedsecureioErrorResponseWrapper::ErrorString(error) => { - Err(types::ErrorResponse { - code: error.clone(), - message: error.clone(), - reason: Some(error), - status_code: item.http_code, - attempt_status: None, - connector_transaction_id: None, - network_advice_code: None, - network_decline_code: None, - network_error_message: None, - }) - } + ThreedsecureioErrorResponseWrapper::ErrorResponse(resp) => Err(ErrorResponse { + code: resp.error_code, + message: resp + .error_description + .clone() + .unwrap_or(NO_ERROR_MESSAGE.to_owned()), + reason: resp.error_description, + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: None, + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + }), + ThreedsecureioErrorResponseWrapper::ErrorString(error) => Err(ErrorResponse { + code: error.clone(), + message: error.clone(), + reason: Some(error), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: None, + network_advice_code: None, + network_decline_code: None, + network_error_message: None, + }), }, }; Ok(Self { @@ -239,11 +224,11 @@ pub struct ThreedsecureioAuthType { pub(super) api_key: Secret<String>, } -impl TryFrom<&types::ConnectorAuthType> for ThreedsecureioAuthType { +impl TryFrom<&ConnectorAuthType> for ThreedsecureioAuthType { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { - types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self { + ConnectorAuthType::HeaderKey { api_key } => Ok(Self { api_key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), @@ -251,17 +236,17 @@ impl TryFrom<&types::ConnectorAuthType> for ThreedsecureioAuthType { } } -impl TryFrom<&ThreedsecureioRouterData<&types::authentication::ConnectorAuthenticationRouterData>> +impl TryFrom<&ThreedsecureioRouterData<&ConnectorAuthenticationRouterData>> for ThreedsecureioAuthenticationRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: &ThreedsecureioRouterData<&types::authentication::ConnectorAuthenticationRouterData>, + item: &ThreedsecureioRouterData<&ConnectorAuthenticationRouterData>, ) -> Result<Self, Self::Error> { let request = &item.router_data.request; //browser_details are mandatory for Browser flows let browser_details = match request.browser_details.clone() { - Some(details) => Ok::<Option<types::BrowserInformation>, Self::Error>(Some(details)), + Some(details) => Ok::<Option<BrowserInformation>, Self::Error>(Some(details)), None => { if request.device_channel == DeviceChannel::Browser { Err(errors::ConnectorError::MissingRequiredField { @@ -693,13 +678,13 @@ pub struct ThreedsecureioPreAuthenticationResponseData { pub message_type: Option<String>, } -impl TryFrom<&ThreedsecureioRouterData<&types::authentication::PreAuthNRouterData>> +impl TryFrom<&ThreedsecureioRouterData<&PreAuthNRouterData>> for ThreedsecureioPreAuthenticationRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - value: &ThreedsecureioRouterData<&types::authentication::PreAuthNRouterData>, + value: &ThreedsecureioRouterData<&PreAuthNRouterData>, ) -> Result<Self, Self::Error> { let router_data = value.router_data; Ok(Self { diff --git a/crates/router/src/connector/wellsfargopayout.rs b/crates/hyperswitch_connectors/src/connectors/wellsfargopayout.rs similarity index 50% rename from crates/router/src/connector/wellsfargopayout.rs rename to crates/hyperswitch_connectors/src/connectors/wellsfargopayout.rs index 8ed0c1dbd3b..d76bf386877 100644 --- a/crates/router/src/connector/wellsfargopayout.rs +++ b/crates/hyperswitch_connectors/src/connectors/wellsfargopayout.rs @@ -1,28 +1,48 @@ pub mod transformers; -use common_utils::types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}; +use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId}; +use common_utils::{ + errors::CustomResult, + ext_traits::BytesExt, + request::{Method, Request, RequestBuilder, RequestContent}, + types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}, +}; use error_stack::{report, ResultExt}; -use masking::ExposeInterface; - -use self::transformers as wellsfargopayout; -use super::utils as connector_utils; -use crate::{ - configs::settings, - core::errors::{self, CustomResult}, - events::connector_api_logs::ConnectorEvent, - headers, - services::{ - self, - request::{self, Mask}, - ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, +use hyperswitch_domain_models::{ + router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, + router_flow_types::{ + AccessTokenAuth, Authorize, Capture, Execute, PSync, PaymentMethodToken, RSync, Session, + SetupMandate, Void, + }, + router_request_types::{ + AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, + RefundsData, SetupMandateRequestData, + }, + router_response_types::{PaymentsResponseData, RefundsResponseData}, + types::{ + PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, + RefundSyncRouterData, RefundsRouterData, + }, +}; +use hyperswitch_interfaces::{ + api::{ + self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, + ConnectorValidation, }, + configs::Connectors, + errors::ConnectorError, + events::connector_api_logs::ConnectorEvent, types::{ - self, - api::{self, ConnectorCommon, ConnectorCommonExt}, - ErrorResponse, RequestContent, Response, + PaymentsAuthorizeType, PaymentsCaptureType, PaymentsSyncType, RefundExecuteType, + RefundSyncType, Response, }, - utils::BytesExt, + webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, }; +use masking::{ExposeInterface, Mask as _, Maskable}; + +use self::transformers as wellsfargopayout; +use crate::{constants::headers, types::ResponseRouterData, utils::convert_amount}; #[derive(Clone)] pub struct Wellsfargopayout { @@ -50,12 +70,8 @@ impl api::RefundExecute for Wellsfargopayout {} impl api::RefundSync for Wellsfargopayout {} impl api::PaymentToken for Wellsfargopayout {} -impl - ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Wellsfargopayout +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Wellsfargopayout { // Not Implemented (R) } @@ -66,9 +82,9 @@ where { fn build_headers( &self, - req: &types::RouterData<Flow, Request, Response>, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RouterData<Flow, Request, Response>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), @@ -96,16 +112,16 @@ impl ConnectorCommon for Wellsfargopayout { "application/json" } - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.wellsfargopayout.base_url.as_ref() } fn get_auth_header( &self, - auth_type: &types::ConnectorAuthType, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let auth = wellsfargopayout::WellsfargopayoutAuthType::try_from(auth_type) - .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + .change_context(ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::AUTHORIZATION.to_string(), auth.api_key.expose().into_masked(), @@ -116,11 +132,11 @@ impl ConnectorCommon for Wellsfargopayout { &self, res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { let response: wellsfargopayout::WellsfargopayoutErrorResponse = res .response .parse_struct("WellsfargopayoutErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -143,34 +159,28 @@ impl ConnectorValidation for Wellsfargopayout { //TODO: implement functions when support enabled } -impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> - for Wellsfargopayout -{ +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Wellsfargopayout { //TODO: implement sessions flow } -impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Wellsfargopayout { } -impl - ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for Wellsfargopayout +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> + for Wellsfargopayout { } -impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Wellsfargopayout { fn get_headers( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } @@ -180,18 +190,18 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_url( &self, - _req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + _req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { + Err(ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn get_request_body( &self, - req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let amount = connector_utils::convert_amount( + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let amount = convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, @@ -206,20 +216,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn build_request( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsAuthorizeType::get_url( - self, req, connectors, - )?) + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PaymentsAuthorizeType::get_headers( - self, req, connectors, - )?) - .set_body(types::PaymentsAuthorizeType::get_request_body( + .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?) + .set_body(PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), @@ -228,17 +234,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, - data: &types::PaymentsAuthorizeRouterData, + data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsAuthorizeRouterData, ConnectorError> { let response: wellsfargopayout::WellsfargopayoutPaymentsResponse = res .response .parse_struct("Wellsfargopayout PaymentsAuthorizeResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -249,19 +255,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P &self, res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } -impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for Wellsfargopayout -{ +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Wellsfargopayout { fn get_headers( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } @@ -271,40 +275,40 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_url( &self, - _req: &types::PaymentsSyncRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + _req: &PaymentsSyncRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { + Err(ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn build_request( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Get) - .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) + RequestBuilder::new() + .method(Method::Get) + .url(&PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) + .headers(PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, - data: &types::PaymentsSyncRouterData, + data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsSyncRouterData, ConnectorError> { let response: wellsfargopayout::WellsfargopayoutPaymentsResponse = res .response .parse_struct("wellsfargopayout PaymentsSyncResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -315,19 +319,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe &self, res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } -impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> - for Wellsfargopayout -{ +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Wellsfargopayout { fn get_headers( &self, - req: &types::PaymentsCaptureRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } @@ -337,34 +339,32 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_url( &self, - _req: &types::PaymentsCaptureRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + _req: &PaymentsCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { + Err(ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn get_request_body( &self, - _req: &types::PaymentsCaptureRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) + _req: &PaymentsCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + Err(ConnectorError::NotImplemented("get_request_body method".to_string()).into()) } fn build_request( &self, - req: &types::PaymentsCaptureRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PaymentsCaptureType::get_headers( - self, req, connectors, - )?) - .set_body(types::PaymentsCaptureType::get_request_body( + .headers(PaymentsCaptureType::get_headers(self, req, connectors)?) + .set_body(PaymentsCaptureType::get_request_body( self, req, connectors, )?) .build(), @@ -373,17 +373,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, - data: &types::PaymentsCaptureRouterData, + data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsCaptureRouterData, ConnectorError> { let response: wellsfargopayout::WellsfargopayoutPaymentsResponse = res .response .parse_struct("Wellsfargopayout PaymentsCaptureResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -394,24 +394,19 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme &self, res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } -impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> - for Wellsfargopayout -{ -} +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Wellsfargopayout {} -impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> - for Wellsfargopayout -{ +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Wellsfargopayout { fn get_headers( &self, - req: &types::RefundsRouterData<api::Execute>, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } @@ -421,18 +416,18 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_url( &self, - _req: &types::RefundsRouterData<api::Execute>, - _connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + _req: &RefundsRouterData<Execute>, + _connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { + Err(ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn get_request_body( &self, - req: &types::RefundsRouterData<api::Execute>, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let refund_amount = connector_utils::convert_amount( + req: &RefundsRouterData<Execute>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { + let refund_amount = convert_amount( self.amount_converter, req.request.minor_refund_amount, req.request.currency, @@ -447,36 +442,32 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn build_request( &self, - req: &types::RefundsRouterData<api::Execute>, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::RefundExecuteType::get_url(self, req, connectors)?) + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::RefundExecuteType::get_headers( - self, req, connectors, - )?) - .set_body(types::RefundExecuteType::get_request_body( - self, req, connectors, - )?) + .headers(RefundExecuteType::get_headers(self, req, connectors)?) + .set_body(RefundExecuteType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) } fn handle_response( &self, - data: &types::RefundsRouterData<api::Execute>, + data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { + ) -> CustomResult<RefundsRouterData<Execute>, ConnectorError> { let response: wellsfargopayout::RefundResponse = res .response .parse_struct("wellsfargopayout RefundResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -487,19 +478,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon &self, res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } -impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> - for Wellsfargopayout -{ +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Wellsfargopayout { fn get_headers( &self, - req: &types::RefundSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } @@ -509,43 +498,41 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_url( &self, - _req: &types::RefundSyncRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + _req: &RefundSyncRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { + Err(ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn build_request( &self, - req: &types::RefundSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Get) - .url(&types::RefundSyncType::get_url(self, req, connectors)?) + RequestBuilder::new() + .method(Method::Get) + .url(&RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::RefundSyncType::get_headers(self, req, connectors)?) - .set_body(types::RefundSyncType::get_request_body( - self, req, connectors, - )?) + .headers(RefundSyncType::get_headers(self, req, connectors)?) + .set_body(RefundSyncType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, - data: &types::RefundSyncRouterData, + data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { + ) -> CustomResult<RefundSyncRouterData, ConnectorError> { let response: wellsfargopayout::RefundResponse = res .response .parse_struct("wellsfargopayout RefundSyncResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -556,32 +543,32 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse &self, res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } #[async_trait::async_trait] -impl api::IncomingWebhook for Wellsfargopayout { +impl IncomingWebhook for Wellsfargopayout { fn get_webhook_object_reference_id( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<ObjectReferenceId, ConnectorError> { + Err(report!(ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<IncomingWebhookEvent, ConnectorError> { + Err(report!(ConnectorError::WebhooksNotImplemented)) } fn get_webhook_resource_object( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> { + Err(report!(ConnectorError::WebhooksNotImplemented)) } } diff --git a/crates/router/src/connector/wellsfargopayout/transformers.rs b/crates/hyperswitch_connectors/src/connectors/wellsfargopayout/transformers.rs similarity index 60% rename from crates/router/src/connector/wellsfargopayout/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/wellsfargopayout/transformers.rs index 3a194550dfd..ebe3a3fd1b9 100644 --- a/crates/router/src/connector/wellsfargopayout/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/wellsfargopayout/transformers.rs @@ -1,11 +1,20 @@ +use common_enums::{AttemptStatus, RefundStatus}; use common_utils::types::StringMinorUnit; +use hyperswitch_domain_models::{ + payment_method_data::PaymentMethodData, + router_data::{ConnectorAuthType, RouterData}, + router_flow_types::{Execute, RSync}, + router_request_types::ResponseId, + router_response_types::{PaymentsResponseData, RefundsResponseData}, + types::{PaymentsAuthorizeRouterData, RefundsRouterData}, +}; +use hyperswitch_interfaces::errors::ConnectorError; use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::PaymentsAuthorizeRequestData, - core::errors, - types::{self, api, domain, storage::enums}, + types::{RefundsResponseRouterData, ResponseRouterData}, + utils::PaymentsAuthorizeRequestData as _, }; //TODO: Fill the struct with respective fields @@ -40,15 +49,15 @@ pub struct WellsfargopayoutCard { complete: bool, } -impl TryFrom<&WellsfargopayoutRouterData<&types::PaymentsAuthorizeRouterData>> +impl TryFrom<&WellsfargopayoutRouterData<&PaymentsAuthorizeRouterData>> for WellsfargopayoutPaymentsRequest { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: &WellsfargopayoutRouterData<&types::PaymentsAuthorizeRouterData>, + item: &WellsfargopayoutRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { - domain::PaymentMethodData::Card(req_card) => { + PaymentMethodData::Card(req_card) => { let card = WellsfargopayoutCard { number: req_card.card_number, expiry_month: req_card.card_exp_month, @@ -61,7 +70,7 @@ impl TryFrom<&WellsfargopayoutRouterData<&types::PaymentsAuthorizeRouterData>> card, }) } - _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + _ => Err(ConnectorError::NotImplemented("Payment methods".to_string()).into()), } } } @@ -72,14 +81,14 @@ pub struct WellsfargopayoutAuthType { pub(super) api_key: Secret<String>, } -impl TryFrom<&types::ConnectorAuthType> for WellsfargopayoutAuthType { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { +impl TryFrom<&ConnectorAuthType> for WellsfargopayoutAuthType { + type Error = error_stack::Report<ConnectorError>; + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { - types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self { + ConnectorAuthType::HeaderKey { api_key } => Ok(Self { api_key: api_key.to_owned(), }), - _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + _ => Err(ConnectorError::FailedToObtainAuthType.into()), } } } @@ -94,7 +103,7 @@ pub enum WellsfargopayoutPaymentStatus { Processing, } -impl From<WellsfargopayoutPaymentStatus> for enums::AttemptStatus { +impl From<WellsfargopayoutPaymentStatus> for AttemptStatus { fn from(item: WellsfargopayoutPaymentStatus) -> Self { match item { WellsfargopayoutPaymentStatus::Succeeded => Self::Charged, @@ -111,29 +120,17 @@ pub struct WellsfargopayoutPaymentsResponse { id: String, } -impl<F, T> - TryFrom< - types::ResponseRouterData< - F, - WellsfargopayoutPaymentsResponse, - T, - types::PaymentsResponseData, - >, - > for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, WellsfargopayoutPaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: types::ResponseRouterData< - F, - WellsfargopayoutPaymentsResponse, - T, - types::PaymentsResponseData, - >, + item: ResponseRouterData<F, WellsfargopayoutPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { - status: enums::AttemptStatus::from(item.response.status), - response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + status: AttemptStatus::from(item.response.status), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.id), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, @@ -155,12 +152,12 @@ pub struct WellsfargopayoutRefundRequest { pub amount: StringMinorUnit, } -impl<F> TryFrom<&WellsfargopayoutRouterData<&types::RefundsRouterData<F>>> +impl<F> TryFrom<&WellsfargopayoutRouterData<&RefundsRouterData<F>>> for WellsfargopayoutRefundRequest { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: &WellsfargopayoutRouterData<&types::RefundsRouterData<F>>, + item: &WellsfargopayoutRouterData<&RefundsRouterData<F>>, ) -> Result<Self, Self::Error> { Ok(Self { amount: item.amount.to_owned(), @@ -172,19 +169,19 @@ impl<F> TryFrom<&WellsfargopayoutRouterData<&types::RefundsRouterData<F>>> #[allow(dead_code)] #[derive(Debug, Serialize, Default, Deserialize, Clone)] -pub enum RefundStatus { +pub enum WellsfargopayoutRefundStatus { Succeeded, Failed, #[default] Processing, } -impl From<RefundStatus> for enums::RefundStatus { - fn from(item: RefundStatus) -> Self { +impl From<WellsfargopayoutRefundStatus> for RefundStatus { + fn from(item: WellsfargopayoutRefundStatus) -> Self { match item { - RefundStatus::Succeeded => Self::Success, - RefundStatus::Failed => Self::Failure, - RefundStatus::Processing => Self::Pending, + WellsfargopayoutRefundStatus::Succeeded => Self::Success, + WellsfargopayoutRefundStatus::Failed => Self::Failure, + WellsfargopayoutRefundStatus::Processing => Self::Pending, //TODO: Review mapping } } @@ -194,37 +191,33 @@ impl From<RefundStatus> for enums::RefundStatus { #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse { id: String, - status: RefundStatus, + status: WellsfargopayoutRefundStatus, } -impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> - for types::RefundsRouterData<api::Execute> -{ - type Error = error_stack::Report<errors::ConnectorError>; +impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, + item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(types::RefundsResponseData { + response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), - refund_status: enums::RefundStatus::from(item.response.status), + refund_status: RefundStatus::from(item.response.status), }), ..item.data }) } } -impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> - for types::RefundsRouterData<api::RSync> -{ - type Error = error_stack::Report<errors::ConnectorError>; +impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { + type Error = error_stack::Report<ConnectorError>; fn try_from( - item: types::RefundsResponseRouterData<api::RSync, RefundResponse>, + item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(types::RefundsResponseData { + response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), - refund_status: enums::RefundStatus::from(item.response.status), + refund_status: RefundStatus::from(item.response.status), }), ..item.data }) diff --git a/crates/router/src/connector/wise.rs b/crates/hyperswitch_connectors/src/connectors/wise.rs similarity index 50% rename from crates/router/src/connector/wise.rs rename to crates/hyperswitch_connectors/src/connectors/wise.rs index 0ee45b22f9f..1041a6e7b2b 100644 --- a/crates/router/src/connector/wise.rs +++ b/crates/hyperswitch_connectors/src/connectors/wise.rs @@ -1,41 +1,68 @@ pub mod transformers; +use api_models::webhooks::IncomingWebhookEvent; +#[cfg(feature = "payouts")] +use common_utils::request::{Method, RequestBuilder, RequestContent}; #[cfg(feature = "payouts")] -use common_utils::request::RequestContent; use common_utils::types::{AmountConvertor, MinorUnit, MinorUnitForConnector}; +use common_utils::{errors::CustomResult, ext_traits::ByteSliceExt, request::Request}; use error_stack::{report, ResultExt}; +use hyperswitch_domain_models::{ + router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, + router_flow_types::{ + AccessTokenAuth, Authorize, Capture, Execute, PSync, PaymentMethodToken, RSync, Session, + SetupMandate, Void, + }, + router_request_types::{ + AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, + RefundsData, SetupMandateRequestData, + }, + router_response_types::{PaymentsResponseData, RefundsResponseData}, +}; +#[cfg(feature = "payouts")] +use hyperswitch_domain_models::{ + router_flow_types::{PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient}, + types::{PayoutsData, PayoutsResponseData, PayoutsRouterData}, +}; +#[cfg(feature = "payouts")] +use hyperswitch_interfaces::types::PayoutQuoteType; +#[cfg(feature = "payouts")] +use hyperswitch_interfaces::types::{ + PayoutCancelType, PayoutCreateType, PayoutFulfillType, PayoutRecipientType, +}; +use hyperswitch_interfaces::{ + api::{ + self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, + Refund, RefundExecute, RefundSync, + }, + configs::Connectors, + errors::ConnectorError, + events::connector_api_logs::ConnectorEvent, + types::Response, + webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, +}; #[cfg(feature = "payouts")] use masking::PeekInterface; +use masking::{Mask as _, Maskable}; #[cfg(feature = "payouts")] use router_env::{instrument, tracing}; use self::transformers as wise; -use super::utils::convert_amount; -use crate::{ - configs::settings, - core::errors::{self, CustomResult}, - events::connector_api_logs::ConnectorEvent, - headers, - services::{ - self, - request::{self, Mask}, - ConnectorSpecifications, ConnectorValidation, - }, - types::{ - self, - api::{self, ConnectorCommon, ConnectorCommonExt}, - }, - utils::BytesExt, -}; +use crate::constants::headers; +#[cfg(feature = "payouts")] +use crate::{types::ResponseRouterData, utils::convert_amount}; #[derive(Clone)] pub struct Wise { + #[cfg(feature = "payouts")] amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), } impl Wise { pub fn new() -> &'static Self { &Self { + #[cfg(feature = "payouts")] amount_converter: &MinorUnitForConnector, } } @@ -43,22 +70,22 @@ impl Wise { impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Wise where - Self: services::ConnectorIntegration<Flow, Request, Response>, + Self: ConnectorIntegration<Flow, Request, Response>, { #[cfg(feature = "payouts")] fn build_headers( &self, - req: &types::RouterData<Flow, Request, Response>, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RouterData<Flow, Request, Response>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + use masking::Mask as _; + let mut header = vec![( headers::CONTENT_TYPE.to_string(), - types::PayoutQuoteType::get_content_type(self) - .to_string() - .into(), + PayoutQuoteType::get_content_type(self).to_string().into(), )]; let auth = wise::WiseAuthType::try_from(&req.connector_auth_type) - .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + .change_context(ConnectorError::FailedToObtainAuthType)?; let mut api_key = vec![( headers::AUTHORIZATION.to_string(), auth.api_key.into_masked(), @@ -75,29 +102,29 @@ impl ConnectorCommon for Wise { fn get_auth_header( &self, - auth_type: &types::ConnectorAuthType, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let auth = wise::WiseAuthType::try_from(auth_type) - .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + .change_context(ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::AUTHORIZATION.to_string(), auth.api_key.into_masked(), )]) } - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.wise.base_url.as_ref() } fn build_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { let response: wise::ErrorResponse = res .response .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -106,7 +133,7 @@ impl ConnectorCommon for Wise { match response.errors { Some(errs) => { if let Some(e) = errs.first() { - Ok(types::ErrorResponse { + Ok(ErrorResponse { status_code: res.status_code, code: e.code.clone(), message: e.message.clone(), @@ -118,7 +145,7 @@ impl ConnectorCommon for Wise { network_error_message: None, }) } else { - Ok(types::ErrorResponse { + Ok(ErrorResponse { status_code: res.status_code, code: default_status, message: response.message.unwrap_or_default(), @@ -131,7 +158,7 @@ impl ConnectorCommon for Wise { }) } } - None => Ok(types::ErrorResponse { + None => Ok(ErrorResponse { status_code: res.status_code, code: default_status, message: response.message.unwrap_or_default(), @@ -154,92 +181,36 @@ impl api::PaymentCapture for Wise {} impl api::MandateSetup for Wise {} impl api::ConnectorAccessToken for Wise {} impl api::PaymentToken for Wise {} -impl ConnectorValidation for Wise {} - -impl - services::ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Wise -{ -} +impl api::ConnectorValidation for Wise {} -impl - services::ConnectorIntegration< - api::AccessTokenAuth, - types::AccessTokenRequestData, - types::AccessToken, - > for Wise +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Wise { } -impl - services::ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for Wise -{ +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Wise {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Wise { fn build_request( &self, - _req: &types::RouterData< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - >, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - Err( - errors::ConnectorError::NotImplemented("Setup Mandate flow for Wise".to_string()) - .into(), - ) + _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + Err(ConnectorError::NotImplemented("Setup Mandate flow for Wise".to_string()).into()) } } impl api::PaymentSession for Wise {} -impl - services::ConnectorIntegration< - api::Session, - types::PaymentsSessionData, - types::PaymentsResponseData, - > for Wise -{ -} +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Wise {} -impl - services::ConnectorIntegration< - api::Capture, - types::PaymentsCaptureData, - types::PaymentsResponseData, - > for Wise -{ -} +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Wise {} -impl - services::ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for Wise -{ -} +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Wise {} -impl - services::ConnectorIntegration< - api::Authorize, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, - > for Wise -{ -} +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Wise {} -impl - services::ConnectorIntegration< - api::Void, - types::PaymentsCancelData, - types::PaymentsResponseData, - > for Wise -{ -} +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Wise {} impl api::Payouts for Wise {} #[cfg(feature = "payouts")] @@ -256,16 +227,14 @@ impl api::PayoutRecipient for Wise {} impl api::PayoutFulfill for Wise {} #[cfg(feature = "payouts")] -impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::PayoutsResponseData> - for Wise -{ +impl ConnectorIntegration<PoCancel, PayoutsData, PayoutsResponseData> for Wise { fn get_url( &self, - req: &types::PayoutsRouterData<api::PoCancel>, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + req: &PayoutsRouterData<PoCancel>, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { let transfer_id = req.request.connector_payout_id.clone().ok_or( - errors::ConnectorError::MissingRequiredField { + ConnectorError::MissingRequiredField { field_name: "transfer_id", }, )?; @@ -277,22 +246,22 @@ impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::Pa fn get_headers( &self, - req: &types::PayoutsRouterData<api::PoCancel>, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PayoutsRouterData<PoCancel>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, _connectors) } fn build_request( &self, - req: &types::PayoutsRouterData<api::PoCancel>, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Put) - .url(&types::PayoutCancelType::get_url(self, req, connectors)?) + req: &PayoutsRouterData<PoCancel>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Put) + .url(&PayoutCancelType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PayoutCancelType::get_headers(self, req, connectors)?) + .headers(PayoutCancelType::get_headers(self, req, connectors)?) .build(); Ok(Some(request)) @@ -301,19 +270,19 @@ impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::Pa #[instrument(skip_all)] fn handle_response( &self, - data: &types::PayoutsRouterData<api::PoCancel>, + data: &PayoutsRouterData<PoCancel>, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PayoutsRouterData<api::PoCancel>, errors::ConnectorError> { + res: Response, + ) -> CustomResult<PayoutsRouterData<PoCancel>, ConnectorError> { let response: wise::WisePayoutResponse = res .response .parse_struct("WisePayoutResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -322,13 +291,13 @@ impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::Pa fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { let response: wise::ErrorResponse = res .response .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -340,7 +309,7 @@ impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::Pa } else { (def_res, response.message.unwrap_or_default()) }; - Ok(types::ErrorResponse { + Ok(ErrorResponse { status_code: res.status_code, code, message, @@ -355,16 +324,14 @@ impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::Pa } #[cfg(feature = "payouts")] -impl services::ConnectorIntegration<api::PoQuote, types::PayoutsData, types::PayoutsResponseData> - for Wise -{ +impl ConnectorIntegration<PoQuote, PayoutsData, PayoutsResponseData> for Wise { fn get_url( &self, - req: &types::PayoutsRouterData<api::PoQuote>, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + req: &PayoutsRouterData<PoQuote>, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { let auth = wise::WiseAuthType::try_from(&req.connector_auth_type) - .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + .change_context(ConnectorError::FailedToObtainAuthType)?; Ok(format!( "{}v3/profiles/{}/quotes", connectors.wise.base_url, @@ -374,17 +341,17 @@ impl services::ConnectorIntegration<api::PoQuote, types::PayoutsData, types::Pay fn get_headers( &self, - req: &types::PayoutsRouterData<api::PoQuote>, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PayoutsRouterData<PoQuote>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_request_body( &self, - req: &types::PayoutsRouterData<api::PoQuote>, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &PayoutsRouterData<PoQuote>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let amount = convert_amount( self.amount_converter, req.request.minor_amount, @@ -397,17 +364,15 @@ impl services::ConnectorIntegration<api::PoQuote, types::PayoutsData, types::Pay fn build_request( &self, - req: &types::PayoutsRouterData<api::PoQuote>, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PayoutQuoteType::get_url(self, req, connectors)?) + req: &PayoutsRouterData<PoQuote>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&PayoutQuoteType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PayoutQuoteType::get_headers(self, req, connectors)?) - .set_body(types::PayoutQuoteType::get_request_body( - self, req, connectors, - )?) + .headers(PayoutQuoteType::get_headers(self, req, connectors)?) + .set_body(PayoutQuoteType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) @@ -416,19 +381,19 @@ impl services::ConnectorIntegration<api::PoQuote, types::PayoutsData, types::Pay #[instrument(skip_all)] fn handle_response( &self, - data: &types::PayoutsRouterData<api::PoQuote>, + data: &PayoutsRouterData<PoQuote>, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PayoutsRouterData<api::PoQuote>, errors::ConnectorError> { + res: Response, + ) -> CustomResult<PayoutsRouterData<PoQuote>, ConnectorError> { let response: wise::WisePayoutQuoteResponse = res .response .parse_struct("WisePayoutQuoteResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -437,39 +402,36 @@ impl services::ConnectorIntegration<api::PoQuote, types::PayoutsData, types::Pay fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "payouts")] -impl - services::ConnectorIntegration<api::PoRecipient, types::PayoutsData, types::PayoutsResponseData> - for Wise -{ +impl ConnectorIntegration<PoRecipient, PayoutsData, PayoutsResponseData> for Wise { fn get_url( &self, - _req: &types::PayoutsRouterData<api::PoRecipient>, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &PayoutsRouterData<PoRecipient>, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!("{}v1/accounts", connectors.wise.base_url)) } fn get_headers( &self, - req: &types::PayoutsRouterData<api::PoRecipient>, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PayoutsRouterData<PoRecipient>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_request_body( &self, - req: &types::PayoutsRouterData<api::PoRecipient>, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &PayoutsRouterData<PoRecipient>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let amount = convert_amount( self.amount_converter, req.request.minor_amount, @@ -482,17 +444,15 @@ impl fn build_request( &self, - req: &types::PayoutsRouterData<api::PoRecipient>, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PayoutRecipientType::get_url(self, req, connectors)?) + req: &PayoutsRouterData<PoRecipient>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&PayoutRecipientType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PayoutRecipientType::get_headers( - self, req, connectors, - )?) - .set_body(types::PayoutRecipientType::get_request_body( + .headers(PayoutRecipientType::get_headers(self, req, connectors)?) + .set_body(PayoutRecipientType::get_request_body( self, req, connectors, )?) .build(); @@ -503,19 +463,19 @@ impl #[instrument(skip_all)] fn handle_response( &self, - data: &types::PayoutsRouterData<api::PoRecipient>, + data: &PayoutsRouterData<PoRecipient>, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PayoutsRouterData<api::PoRecipient>, errors::ConnectorError> { + res: Response, + ) -> CustomResult<PayoutsRouterData<PoRecipient>, ConnectorError> { let response: wise::WiseRecipientCreateResponse = res .response .parse_struct("WiseRecipientCreateResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -524,56 +484,52 @@ impl fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } #[async_trait::async_trait] #[cfg(feature = "payouts")] -impl services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::PayoutsResponseData> - for Wise -{ +impl ConnectorIntegration<PoCreate, PayoutsData, PayoutsResponseData> for Wise { fn get_url( &self, - _req: &types::PayoutsRouterData<api::PoCreate>, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + _req: &PayoutsRouterData<PoCreate>, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { Ok(format!("{}/v1/transfers", connectors.wise.base_url)) } fn get_headers( &self, - req: &types::PayoutsRouterData<api::PoCreate>, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PayoutsRouterData<PoCreate>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_request_body( &self, - req: &types::PayoutsRouterData<api::PoCreate>, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &PayoutsRouterData<PoCreate>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let connector_req = wise::WisePayoutCreateRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, - req: &types::PayoutsRouterData<api::PoCreate>, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PayoutCreateType::get_url(self, req, connectors)?) + req: &PayoutsRouterData<PoCreate>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&PayoutCreateType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PayoutCreateType::get_headers(self, req, connectors)?) - .set_body(types::PayoutCreateType::get_request_body( - self, req, connectors, - )?) + .headers(PayoutCreateType::get_headers(self, req, connectors)?) + .set_body(PayoutCreateType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) @@ -582,19 +538,19 @@ impl services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::Pa #[instrument(skip_all)] fn handle_response( &self, - data: &types::PayoutsRouterData<api::PoCreate>, + data: &PayoutsRouterData<PoCreate>, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PayoutsRouterData<api::PoCreate>, errors::ConnectorError> { + res: Response, + ) -> CustomResult<PayoutsRouterData<PoCreate>, ConnectorError> { let response: wise::WisePayoutResponse = res .response .parse_struct("WisePayoutResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -603,47 +559,36 @@ impl services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::Pa fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "payouts")] -impl - services::ConnectorIntegration< - api::PoEligibility, - types::PayoutsData, - types::PayoutsResponseData, - > for Wise -{ +impl ConnectorIntegration<PoEligibility, PayoutsData, PayoutsResponseData> for Wise { fn build_request( &self, - _req: &types::PayoutsRouterData<api::PoEligibility>, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + _req: &PayoutsRouterData<PoEligibility>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { // Eligibility check for cards is not implemented - Err( - errors::ConnectorError::NotImplemented("Payout Eligibility for Wise".to_string()) - .into(), - ) + Err(ConnectorError::NotImplemented("Payout Eligibility for Wise".to_string()).into()) } } #[cfg(feature = "payouts")] -impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResponseData> - for Wise -{ +impl ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for Wise { fn get_url( &self, - req: &types::PayoutsRouterData<api::PoFulfill>, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { + req: &PayoutsRouterData<PoFulfill>, + connectors: &Connectors, + ) -> CustomResult<String, ConnectorError> { let auth = wise::WiseAuthType::try_from(&req.connector_auth_type) - .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + .change_context(ConnectorError::FailedToObtainAuthType)?; let transfer_id = req.request.connector_payout_id.to_owned().ok_or( - errors::ConnectorError::MissingRequiredField { + ConnectorError::MissingRequiredField { field_name: "transfer_id", }, )?; @@ -657,36 +602,32 @@ impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::P fn get_headers( &self, - req: &types::PayoutsRouterData<api::PoFulfill>, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PayoutsRouterData<PoFulfill>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_request_body( &self, - req: &types::PayoutsRouterData<api::PoFulfill>, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { + req: &PayoutsRouterData<PoFulfill>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, ConnectorError> { let connector_req = wise::WisePayoutFulfillRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, - req: &types::PayoutsRouterData<api::PoFulfill>, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PayoutFulfillType::get_url(self, req, connectors)?) + req: &PayoutsRouterData<PoFulfill>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&PayoutFulfillType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PayoutFulfillType::get_headers( - self, req, connectors, - )?) - .set_body(types::PayoutFulfillType::get_request_body( - self, req, connectors, - )?) + .headers(PayoutFulfillType::get_headers(self, req, connectors)?) + .set_body(PayoutFulfillType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) @@ -695,19 +636,19 @@ impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::P #[instrument(skip_all)] fn handle_response( &self, - data: &types::PayoutsRouterData<api::PoFulfill>, + data: &PayoutsRouterData<PoFulfill>, event_builder: Option<&mut ConnectorEvent>, - res: types::Response, - ) -> CustomResult<types::PayoutsRouterData<api::PoFulfill>, errors::ConnectorError> { + res: Response, + ) -> CustomResult<PayoutsRouterData<PoFulfill>, ConnectorError> { let response: wise::WiseFulfillResponse = res .response .parse_struct("WiseFulfillResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -716,48 +657,42 @@ impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::P fn get_error_response( &self, - res: types::Response, + res: Response, event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } -impl api::Refund for Wise {} -impl api::RefundExecute for Wise {} -impl api::RefundSync for Wise {} +impl Refund for Wise {} +impl RefundExecute for Wise {} +impl RefundSync for Wise {} -impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> - for Wise -{ -} +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Wise {} -impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> - for Wise -{ -} +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Wise {} #[async_trait::async_trait] -impl api::IncomingWebhook for Wise { +impl IncomingWebhook for Wise { fn get_webhook_object_reference_id( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::ObjectReferenceId, ConnectorError> { + Err(report!(ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<IncomingWebhookEvent, ConnectorError> { + Err(report!(ConnectorError::WebhooksNotImplemented)) } fn get_webhook_resource_object( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + _request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> { + Err(report!(ConnectorError::WebhooksNotImplemented)) } } diff --git a/crates/router/src/connector/wise/transformers.rs b/crates/hyperswitch_connectors/src/connectors/wise/transformers.rs similarity index 73% rename from crates/router/src/connector/wise/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/wise/transformers.rs index d3e9efa0f7f..1a9ff7bf89f 100644 --- a/crates/router/src/connector/wise/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/wise/transformers.rs @@ -1,22 +1,30 @@ #[cfg(feature = "payouts")] +use api_models::payouts::Bank; +#[cfg(feature = "payouts")] use api_models::payouts::PayoutMethodData; #[cfg(feature = "payouts")] +use common_enums::PayoutEntityType; +#[cfg(feature = "payouts")] +use common_enums::{CountryAlpha2, PayoutStatus, PayoutType}; +#[cfg(feature = "payouts")] use common_utils::pii::Email; use common_utils::types::MinorUnit; +use hyperswitch_domain_models::router_data::ConnectorAuthType; +#[cfg(feature = "payouts")] +use hyperswitch_domain_models::types::{PayoutsResponseData, PayoutsRouterData}; +use hyperswitch_interfaces::errors::ConnectorError; use masking::Secret; use serde::{Deserialize, Serialize}; -type Error = error_stack::Report<errors::ConnectorError>; - #[cfg(feature = "payouts")] -use crate::{ - connector::utils::{self, PayoutsData, RouterData}, - types::{ - api::payouts, - storage::enums::{self as storage_enums, PayoutEntityType}, - }, -}; -use crate::{core::errors, types}; +use crate::types::PayoutsResponseRouterData; +#[cfg(feature = "payouts")] +use crate::utils::get_unimplemented_payment_method_error_message; +#[cfg(feature = "payouts")] +use crate::utils::{PayoutsData as _, RouterData as _}; + +type Error = error_stack::Report<ConnectorError>; + #[derive(Debug, Serialize)] pub struct WiseRouterData<T> { pub amount: MinorUnit, @@ -38,15 +46,15 @@ pub struct WiseAuthType { pub(super) profile_id: Secret<String>, } -impl TryFrom<&types::ConnectorAuthType> for WiseAuthType { +impl TryFrom<&ConnectorAuthType> for WiseAuthType { type Error = Error; - fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { - types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { + ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { api_key: api_key.to_owned(), profile_id: key1.to_owned(), }), - _ => Err(errors::ConnectorError::FailedToObtainAuthType)?, + _ => Err(ConnectorError::FailedToObtainAuthType)?, } } } @@ -141,8 +149,8 @@ pub enum LegalType { #[derive(Debug, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct WiseAddressDetails { - country: Option<storage_enums::CountryAlpha2>, - country_code: Option<storage_enums::CountryAlpha2>, + country: Option<CountryAlpha2>, + country_code: Option<CountryAlpha2>, first_line: Option<Secret<String>>, post_code: Option<Secret<String>>, city: Option<String>, @@ -325,15 +333,15 @@ fn get_payout_bank_details( payout_method_data: PayoutMethodData, address: Option<&hyperswitch_domain_models::address::Address>, entity_type: PayoutEntityType, -) -> Result<WiseBankDetails, errors::ConnectorError> { +) -> Result<WiseBankDetails, ConnectorError> { let wise_address_details = match get_payout_address_details(address) { Some(a) => Ok(a), - None => Err(errors::ConnectorError::MissingRequiredField { + None => Err(ConnectorError::MissingRequiredField { field_name: "address", }), }?; match payout_method_data { - PayoutMethodData::Bank(payouts::BankPayout::Ach(b)) => Ok(WiseBankDetails { + PayoutMethodData::Bank(Bank::Ach(b)) => Ok(WiseBankDetails { legal_type: LegalType::from(entity_type), address: Some(wise_address_details), account_number: Some(b.bank_account_number.to_owned()), @@ -341,33 +349,31 @@ fn get_payout_bank_details( account_type: Some(AccountType::Checking), ..WiseBankDetails::default() }), - PayoutMethodData::Bank(payouts::BankPayout::Bacs(b)) => Ok(WiseBankDetails { + PayoutMethodData::Bank(Bank::Bacs(b)) => Ok(WiseBankDetails { legal_type: LegalType::from(entity_type), address: Some(wise_address_details), account_number: Some(b.bank_account_number.to_owned()), sort_code: Some(b.bank_sort_code), ..WiseBankDetails::default() }), - PayoutMethodData::Bank(payouts::BankPayout::Sepa(b)) => Ok(WiseBankDetails { + PayoutMethodData::Bank(Bank::Sepa(b)) => Ok(WiseBankDetails { legal_type: LegalType::from(entity_type), address: Some(wise_address_details), iban: Some(b.iban.to_owned()), bic: b.bic, ..WiseBankDetails::default() }), - _ => Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Wise"), + _ => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("Wise"), ))?, } } // Payouts recipient create request transform #[cfg(feature = "payouts")] -impl<F> TryFrom<&WiseRouterData<&types::PayoutsRouterData<F>>> for WiseRecipientCreateRequest { +impl<F> TryFrom<&WiseRouterData<&PayoutsRouterData<F>>> for WiseRecipientCreateRequest { type Error = Error; - fn try_from( - item_data: &WiseRouterData<&types::PayoutsRouterData<F>>, - ) -> Result<Self, Self::Error> { + fn try_from(item_data: &WiseRouterData<&PayoutsRouterData<F>>) -> Result<Self, Self::Error> { let item = item_data.router_data; let request = item.request.to_owned(); let customer_details = request.customer_details.to_owned(); @@ -378,25 +384,23 @@ impl<F> TryFrom<&WiseRouterData<&types::PayoutsRouterData<F>>> for WiseRecipient item.request.entity_type, )?; let source_id = match item.connector_auth_type.to_owned() { - types::ConnectorAuthType::BodyKey { api_key: _, key1 } => Ok(key1), - _ => Err(errors::ConnectorError::MissingRequiredField { + ConnectorAuthType::BodyKey { api_key: _, key1 } => Ok(key1), + _ => Err(ConnectorError::MissingRequiredField { field_name: "source_id for PayoutRecipient creation", }), }?; let payout_type = request.get_payout_type()?; match payout_type { - storage_enums::PayoutType::Card | storage_enums::PayoutType::Wallet => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Wise"), - ))? - } - storage_enums::PayoutType::Bank => { + PayoutType::Card | PayoutType::Wallet => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("Wise"), + ))?, + PayoutType::Bank => { let account_holder_name = customer_details - .ok_or(errors::ConnectorError::MissingRequiredField { + .ok_or(ConnectorError::MissingRequiredField { field_name: "customer_details for PayoutRecipient creation", })? .name - .ok_or(errors::ConnectorError::MissingRequiredField { + .ok_or(ConnectorError::MissingRequiredField { field_name: "customer_details.name for PayoutRecipient creation", })?; Ok(Self { @@ -413,18 +417,18 @@ impl<F> TryFrom<&WiseRouterData<&types::PayoutsRouterData<F>>> for WiseRecipient // Payouts recipient fulfill response transform #[cfg(feature = "payouts")] -impl<F> TryFrom<types::PayoutsResponseRouterData<F, WiseRecipientCreateResponse>> - for types::PayoutsRouterData<F> +impl<F> TryFrom<PayoutsResponseRouterData<F, WiseRecipientCreateResponse>> + for PayoutsRouterData<F> { type Error = Error; fn try_from( - item: types::PayoutsResponseRouterData<F, WiseRecipientCreateResponse>, + item: PayoutsResponseRouterData<F, WiseRecipientCreateResponse>, ) -> Result<Self, Self::Error> { let response: WiseRecipientCreateResponse = item.response; Ok(Self { - response: Ok(types::PayoutsResponseData { - status: Some(storage_enums::PayoutStatus::RequiresCreation), + response: Ok(PayoutsResponseData { + status: Some(PayoutStatus::RequiresCreation), connector_payout_id: Some(response.id.to_string()), payout_eligible: None, should_add_next_step_to_process_tracker: false, @@ -438,45 +442,39 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, WiseRecipientCreateResponse> // Payouts quote request transform #[cfg(feature = "payouts")] -impl<F> TryFrom<&WiseRouterData<&types::PayoutsRouterData<F>>> for WisePayoutQuoteRequest { +impl<F> TryFrom<&WiseRouterData<&PayoutsRouterData<F>>> for WisePayoutQuoteRequest { type Error = Error; - fn try_from( - item_data: &WiseRouterData<&types::PayoutsRouterData<F>>, - ) -> Result<Self, Self::Error> { + fn try_from(item_data: &WiseRouterData<&PayoutsRouterData<F>>) -> Result<Self, Self::Error> { let item = item_data.router_data; let request = item.request.to_owned(); let payout_type = request.get_payout_type()?; match payout_type { - storage_enums::PayoutType::Bank => Ok(Self { + PayoutType::Bank => Ok(Self { source_amount: Some(item_data.amount), source_currency: request.source_currency.to_string(), target_amount: None, target_currency: request.destination_currency.to_string(), pay_out: WisePayOutOption::default(), }), - storage_enums::PayoutType::Card | storage_enums::PayoutType::Wallet => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Wise"), - ))? - } + PayoutType::Card | PayoutType::Wallet => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("Wise"), + ))?, } } } // Payouts quote response transform #[cfg(feature = "payouts")] -impl<F> TryFrom<types::PayoutsResponseRouterData<F, WisePayoutQuoteResponse>> - for types::PayoutsRouterData<F> -{ +impl<F> TryFrom<PayoutsResponseRouterData<F, WisePayoutQuoteResponse>> for PayoutsRouterData<F> { type Error = Error; fn try_from( - item: types::PayoutsResponseRouterData<F, WisePayoutQuoteResponse>, + item: PayoutsResponseRouterData<F, WisePayoutQuoteResponse>, ) -> Result<Self, Self::Error> { let response: WisePayoutQuoteResponse = item.response; Ok(Self { - response: Ok(types::PayoutsResponseData { - status: Some(storage_enums::PayoutStatus::RequiresCreation), + response: Ok(PayoutsResponseData { + status: Some(PayoutStatus::RequiresCreation), connector_payout_id: Some(response.id), payout_eligible: None, should_add_next_step_to_process_tracker: false, @@ -490,13 +488,13 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, WisePayoutQuoteResponse>> // Payouts transfer creation request #[cfg(feature = "payouts")] -impl<F> TryFrom<&types::PayoutsRouterData<F>> for WisePayoutCreateRequest { +impl<F> TryFrom<&PayoutsRouterData<F>> for WisePayoutCreateRequest { type Error = Error; - fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> { + fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> { let request = item.request.to_owned(); let payout_type = request.get_payout_type()?; match payout_type { - storage_enums::PayoutType::Bank => { + PayoutType::Bank => { let connector_customer_id = item.get_connector_customer_id()?; let quote_uuid = item.get_quote_id()?; let wise_transfer_details = WiseTransferDetails { @@ -505,7 +503,7 @@ impl<F> TryFrom<&types::PayoutsRouterData<F>> for WisePayoutCreateRequest { transfer_purpose_sub_transfer_purpose: None, }; let target_account: i64 = connector_customer_id.trim().parse().map_err(|_| { - errors::ConnectorError::MissingRequiredField { + ConnectorError::MissingRequiredField { field_name: "profile", } })?; @@ -516,32 +514,28 @@ impl<F> TryFrom<&types::PayoutsRouterData<F>> for WisePayoutCreateRequest { details: wise_transfer_details, }) } - storage_enums::PayoutType::Card | storage_enums::PayoutType::Wallet => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Wise"), - ))? - } + PayoutType::Card | PayoutType::Wallet => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("Wise"), + ))?, } } } // Payouts transfer creation response #[cfg(feature = "payouts")] -impl<F> TryFrom<types::PayoutsResponseRouterData<F, WisePayoutResponse>> - for types::PayoutsRouterData<F> -{ +impl<F> TryFrom<PayoutsResponseRouterData<F, WisePayoutResponse>> for PayoutsRouterData<F> { type Error = Error; fn try_from( - item: types::PayoutsResponseRouterData<F, WisePayoutResponse>, + item: PayoutsResponseRouterData<F, WisePayoutResponse>, ) -> Result<Self, Self::Error> { let response: WisePayoutResponse = item.response; - let status = match storage_enums::PayoutStatus::from(response.status) { - storage_enums::PayoutStatus::Cancelled => storage_enums::PayoutStatus::Cancelled, - _ => storage_enums::PayoutStatus::RequiresFulfillment, + let status = match PayoutStatus::from(response.status) { + PayoutStatus::Cancelled => PayoutStatus::Cancelled, + _ => PayoutStatus::RequiresFulfillment, }; Ok(Self { - response: Ok(types::PayoutsResponseData { + response: Ok(PayoutsResponseData { status: Some(status), connector_payout_id: Some(response.id.to_string()), payout_eligible: None, @@ -556,43 +550,39 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, WisePayoutResponse>> // Payouts fulfill request transform #[cfg(feature = "payouts")] -impl<F> TryFrom<&types::PayoutsRouterData<F>> for WisePayoutFulfillRequest { +impl<F> TryFrom<&PayoutsRouterData<F>> for WisePayoutFulfillRequest { type Error = Error; - fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> { + fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> { let payout_type = item.request.get_payout_type()?; match payout_type { - storage_enums::PayoutType::Bank => Ok(Self { + PayoutType::Bank => Ok(Self { fund_type: FundType::default(), }), - storage_enums::PayoutType::Card | storage_enums::PayoutType::Wallet => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Wise"), - ))? - } + PayoutType::Card | PayoutType::Wallet => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("Wise"), + ))?, } } } // Payouts fulfill response transform #[cfg(feature = "payouts")] -impl<F> TryFrom<types::PayoutsResponseRouterData<F, WiseFulfillResponse>> - for types::PayoutsRouterData<F> -{ +impl<F> TryFrom<PayoutsResponseRouterData<F, WiseFulfillResponse>> for PayoutsRouterData<F> { type Error = Error; fn try_from( - item: types::PayoutsResponseRouterData<F, WiseFulfillResponse>, + item: PayoutsResponseRouterData<F, WiseFulfillResponse>, ) -> Result<Self, Self::Error> { let response: WiseFulfillResponse = item.response; Ok(Self { - response: Ok(types::PayoutsResponseData { - status: Some(storage_enums::PayoutStatus::from(response.status)), + response: Ok(PayoutsResponseData { + status: Some(PayoutStatus::from(response.status)), connector_payout_id: Some( item.data .request .connector_payout_id .clone() - .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?, + .ok_or(ConnectorError::MissingConnectorTransactionID)?, ), payout_eligible: None, should_add_next_step_to_process_tracker: false, @@ -605,7 +595,7 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, WiseFulfillResponse>> } #[cfg(feature = "payouts")] -impl From<WiseStatus> for storage_enums::PayoutStatus { +impl From<WiseStatus> for PayoutStatus { fn from(wise_status: WiseStatus) -> Self { match wise_status { WiseStatus::Completed => Self::Success, @@ -635,14 +625,14 @@ impl From<PayoutEntityType> for LegalType { #[cfg(feature = "payouts")] impl TryFrom<PayoutMethodData> for RecipientType { - type Error = error_stack::Report<errors::ConnectorError>; + type Error = error_stack::Report<ConnectorError>; fn try_from(payout_method_type: PayoutMethodData) -> Result<Self, Self::Error> { match payout_method_type { - PayoutMethodData::Bank(api_models::payouts::Bank::Ach(_)) => Ok(Self::Aba), - PayoutMethodData::Bank(api_models::payouts::Bank::Bacs(_)) => Ok(Self::SortCode), - PayoutMethodData::Bank(api_models::payouts::Bank::Sepa(_)) => Ok(Self::Iban), - _ => Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Wise"), + PayoutMethodData::Bank(Bank::Ach(_)) => Ok(Self::Aba), + PayoutMethodData::Bank(Bank::Bacs(_)) => Ok(Self::SortCode), + PayoutMethodData::Bank(Bank::Sepa(_)) => Ok(Self::Iban), + _ => Err(ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("Wise"), ) .into()), } diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index f7b01800aa3..6f20e7222dd 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -191,18 +191,22 @@ default_imp_for_authorize_session_token!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Stripebilling, connectors::Taxjar, connectors::UnifiedAuthenticationService, connectors::Volt, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl, @@ -300,18 +304,22 @@ default_imp_for_calculate_tax!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Volt, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl, @@ -377,6 +385,7 @@ default_imp_for_session_update!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, @@ -410,15 +419,18 @@ default_imp_for_session_update!( connectors::Gocardless, connectors::Gpayments, connectors::Hipay, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl, connectors::Powertranz, connectors::Prophetpay, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, @@ -486,6 +498,7 @@ default_imp_for_post_session_tokens!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Square, connectors::Stax, connectors::Stripebilling, @@ -518,13 +531,16 @@ default_imp_for_post_session_tokens!( connectors::Gocardless, connectors::Gpayments, connectors::Hipay, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Xendit, connectors::Powertranz, connectors::Prophetpay, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, @@ -595,6 +611,7 @@ default_imp_for_update_metadata!( connectors::Recurly, connectors::Redsys, connectors::Shift4, + connectors::Signifyd, connectors::Square, connectors::Stax, connectors::Stripebilling, @@ -627,14 +644,17 @@ default_imp_for_update_metadata!( connectors::Gocardless, connectors::Gpayments, connectors::Hipay, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Xendit, connectors::Powertranz, connectors::Prophetpay, connectors::Riskified, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, @@ -719,15 +739,19 @@ default_imp_for_complete_authorize!( connectors::Razorpay, connectors::Recurly, connectors::Riskified, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Worldline, connectors::Worldpayxml, connectors::Volt, @@ -828,14 +852,18 @@ default_imp_for_incremental_authorization!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wellsfargopayout, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, @@ -936,17 +964,21 @@ default_imp_for_create_customer!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -1031,14 +1063,18 @@ default_imp_for_connector_redirect_response!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Worldline, connectors::Worldpayxml, connectors::Volt, @@ -1127,17 +1163,21 @@ default_imp_for_pre_processing_steps!( connectors::Razorpay, connectors::Recurly, connectors::Riskified, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Zen, connectors::Zsl, @@ -1235,18 +1275,22 @@ default_imp_for_post_processing_steps!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -1346,18 +1390,22 @@ default_imp_for_approve!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -1457,18 +1505,22 @@ default_imp_for_reject!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -1567,18 +1619,22 @@ default_imp_for_webhook_source_verification!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -1677,18 +1733,22 @@ default_imp_for_accept_dispute!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -1786,18 +1846,22 @@ default_imp_for_submit_evidence!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -1895,18 +1959,22 @@ default_imp_for_defend_dispute!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -2013,18 +2081,22 @@ default_imp_for_file_upload!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -2110,10 +2182,12 @@ default_imp_for_payouts!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Square, connectors::Stax, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, @@ -2122,6 +2196,7 @@ default_imp_for_payouts!( connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl, @@ -2218,10 +2293,12 @@ default_imp_for_payouts_create!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, @@ -2230,6 +2307,7 @@ default_imp_for_payouts_create!( connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -2329,18 +2407,22 @@ default_imp_for_payouts_retrieve!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -2439,10 +2521,12 @@ default_imp_for_payouts_eligibility!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, @@ -2451,6 +2535,7 @@ default_imp_for_payouts_eligibility!( connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -2545,10 +2630,12 @@ default_imp_for_payouts_fulfill!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, @@ -2557,6 +2644,7 @@ default_imp_for_payouts_fulfill!( connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -2655,10 +2743,12 @@ default_imp_for_payouts_cancel!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, @@ -2667,6 +2757,7 @@ default_imp_for_payouts_cancel!( connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -2766,10 +2857,12 @@ default_imp_for_payouts_quote!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, @@ -2778,6 +2871,7 @@ default_imp_for_payouts_quote!( connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -2877,10 +2971,12 @@ default_imp_for_payouts_recipient!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, @@ -2889,6 +2985,7 @@ default_imp_for_payouts_recipient!( connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -2989,18 +3086,22 @@ default_imp_for_payouts_recipient_account!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -3105,14 +3206,17 @@ default_imp_for_frm_sale!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -3217,14 +3321,17 @@ default_imp_for_frm_checkout!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -3329,14 +3436,17 @@ default_imp_for_frm_transaction!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -3441,14 +3551,17 @@ default_imp_for_frm_fulfillment!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -3553,14 +3666,17 @@ default_imp_for_frm_record_return!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -3656,14 +3772,17 @@ default_imp_for_revoking_mandates!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, @@ -3766,17 +3885,21 @@ default_imp_for_uas_pre_authentication!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -3874,17 +3997,21 @@ default_imp_for_uas_post_authentication!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -3983,17 +4110,21 @@ default_imp_for_uas_authentication_confirmation!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -4083,18 +4214,22 @@ default_imp_for_connector_request_id!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -4191,14 +4326,17 @@ default_imp_for_fraud_check!( connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -4320,6 +4458,7 @@ default_imp_for_connector_authentication!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, @@ -4328,10 +4467,12 @@ default_imp_for_connector_authentication!( connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -4428,14 +4569,18 @@ default_imp_for_uas_authentication!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, + connectors::Wise, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, @@ -4530,18 +4675,22 @@ default_imp_for_revenue_recovery! { connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -4642,17 +4791,21 @@ default_imp_for_billing_connector_payment_sync!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -4752,17 +4905,21 @@ default_imp_for_revenue_recovery_record_back!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, @@ -4862,19 +5019,23 @@ default_imp_for_billing_connector_invoice_sync!( connectors::Recurly, connectors::Redsys, connectors::Riskified, + connectors::Signifyd, connectors::Shift4, connectors::Stax, connectors::Square, connectors::Stripebilling, + connectors::Threedsecureio, connectors::Taxjar, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Volt, connectors::Xendit, connectors::Zen, diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index 897241b687b..bbe705d33c5 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -315,19 +315,23 @@ default_imp_for_new_connector_integration_payment!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl @@ -427,15 +431,19 @@ default_imp_for_new_connector_integration_refund!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, connectors::Wellsfargo, + connectors::Wellsfargopayout, + connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, @@ -534,19 +542,23 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl @@ -646,19 +658,23 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl @@ -757,19 +773,23 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl @@ -869,19 +889,23 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl @@ -991,19 +1015,23 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl @@ -1105,19 +1133,23 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl @@ -1219,19 +1251,23 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl @@ -1333,19 +1369,23 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl @@ -1447,19 +1487,23 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl @@ -1561,19 +1605,23 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl @@ -1675,19 +1723,23 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl @@ -1789,19 +1841,23 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl @@ -1903,19 +1959,23 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl @@ -2015,19 +2075,23 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl @@ -2129,19 +2193,23 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl @@ -2243,19 +2311,23 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl @@ -2357,19 +2429,23 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl @@ -2471,19 +2547,23 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl @@ -2585,19 +2665,23 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl @@ -2695,19 +2779,23 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Stripebilling, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Trustpay, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, connectors::Worldpayxml, connectors::Wellsfargo, + connectors::Wellsfargopayout, connectors::Xendit, connectors::Zen, connectors::Zsl @@ -2777,12 +2865,15 @@ default_imp_for_new_connector_integration_frm!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, @@ -2887,12 +2978,15 @@ default_imp_for_new_connector_integration_connector_authentication!( connectors::Riskified, connectors::Recurly, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, @@ -2989,12 +3083,15 @@ default_imp_for_new_connector_integration_revenue_recovery!( connectors::Redsys, connectors::Riskified, connectors::Shift4, + connectors::Signifyd, connectors::Stax, connectors::Square, connectors::Taxjar, + connectors::Threedsecureio, connectors::Thunes, connectors::Tsys, connectors::UnifiedAuthenticationService, + connectors::Wise, connectors::Worldline, connectors::Volt, connectors::Worldpay, diff --git a/crates/hyperswitch_connectors/src/types.rs b/crates/hyperswitch_connectors/src/types.rs index 79c032a8dae..a072317ea70 100644 --- a/crates/hyperswitch_connectors/src/types.rs +++ b/crates/hyperswitch_connectors/src/types.rs @@ -28,9 +28,10 @@ use hyperswitch_domain_models::{ }; #[cfg(feature = "frm")] use hyperswitch_domain_models::{ - router_flow_types::{Checkout, Fulfillment, Transaction}, + router_flow_types::{Checkout, Fulfillment, RecordReturn, Sale, Transaction}, router_request_types::fraud_check::{ - FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckTransactionData, + FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData, + FraudCheckSaleData, FraudCheckTransactionData, }, router_response_types::fraud_check::FraudCheckResponseData, }; @@ -129,3 +130,14 @@ pub(crate) type ConnectorPreAuthenticationVersionCallType = dyn ConnectorIntegra pub(crate) type PaymentsPostProcessingRouterData = RouterData<PostProcessing, PaymentsPostProcessingData, PaymentsResponseData>; +#[cfg(feature = "frm")] +pub(crate) type FrmSaleRouterData = RouterData<Sale, FraudCheckSaleData, FraudCheckResponseData>; +#[cfg(feature = "frm")] +pub(crate) type FrmRecordReturnRouterData = + RouterData<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData>; +#[cfg(feature = "frm")] +pub(crate) type FrmRecordReturnType = + dyn ConnectorIntegration<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData>; +#[cfg(feature = "frm")] +pub(crate) type FrmSaleType = + dyn ConnectorIntegration<Sale, FraudCheckSaleData, FraudCheckResponseData>; diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index 216b096b7a7..5a1b320ea14 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -40,7 +40,8 @@ use common_utils::{ use error_stack::{report, ResultExt}; #[cfg(feature = "frm")] use hyperswitch_domain_models::router_request_types::fraud_check::{ - FraudCheckCheckoutData, FraudCheckTransactionData, + FraudCheckCheckoutData, FraudCheckRecordReturnData, FraudCheckSaleData, + FraudCheckTransactionData, }; use hyperswitch_domain_models::{ address::{Address, AddressDetails, PhoneDetails}, @@ -6292,3 +6293,27 @@ pub fn get_card_details( })?, } } + +#[cfg(feature = "frm")] +pub trait FraudCheckSaleRequest { + fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>; +} +#[cfg(feature = "frm")] +impl FraudCheckSaleRequest for FraudCheckSaleData { + fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error> { + self.order_details + .clone() + .ok_or_else(missing_field_err("order_details")) + } +} + +#[cfg(feature = "frm")] +pub trait FraudCheckRecordReturnRequest { + fn get_currency(&self) -> Result<enums::Currency, Error>; +} +#[cfg(feature = "frm")] +impl FraudCheckRecordReturnRequest for FraudCheckRecordReturnData { + fn get_currency(&self) -> Result<enums::Currency, Error> { + self.currency.ok_or_else(missing_field_err("currency")) + } +} diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index d14eaaf83d5..b5acee66db0 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -74,8 +74,6 @@ hkdf = "0.12.4" http = "0.2.12" hyper = "0.14.28" infer = "0.15.0" -iso_currency = "0.4.4" -isocountry = "0.3.2" josekit = "0.8.6" jsonwebtoken = "9.2.0" maud = { version = "0.26.0", features = ["actix-web"] } diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index e6965134788..fcf751b9d15 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -1,11 +1,7 @@ #[cfg(feature = "dummy_connector")] pub mod dummyconnector; -pub mod signifyd; pub mod stripe; -pub mod threedsecureio; pub mod utils; -pub mod wellsfargopayout; -pub mod wise; pub use hyperswitch_connectors::connectors::{ aci, aci::Aci, adyen, adyen::Adyen, adyenplatform, adyenplatform::Adyenplatform, airwallex, @@ -34,17 +30,16 @@ pub use hyperswitch_connectors::connectors::{ paystack, paystack::Paystack, payu, payu::Payu, placetopay, placetopay::Placetopay, plaid, plaid::Plaid, powertranz, powertranz::Powertranz, prophetpay, prophetpay::Prophetpay, rapyd, rapyd::Rapyd, razorpay, razorpay::Razorpay, recurly, recurly::Recurly, redsys, redsys::Redsys, - riskified, riskified::Riskified, shift4, shift4::Shift4, square, square::Square, stax, - stax::Stax, stripebilling, stripebilling::Stripebilling, taxjar, taxjar::Taxjar, thunes, - thunes::Thunes, trustpay, trustpay::Trustpay, tsys, tsys::Tsys, unified_authentication_service, + riskified, riskified::Riskified, shift4, shift4::Shift4, signifyd, signifyd::Signifyd, square, + square::Square, stax, stax::Stax, stripebilling, stripebilling::Stripebilling, taxjar, + taxjar::Taxjar, threedsecureio, threedsecureio::Threedsecureio, thunes, thunes::Thunes, + trustpay, trustpay::Trustpay, tsys, tsys::Tsys, unified_authentication_service, unified_authentication_service::UnifiedAuthenticationService, volt, volt::Volt, wellsfargo, - wellsfargo::Wellsfargo, worldline, worldline::Worldline, worldpay, worldpay::Worldpay, - worldpayxml, worldpayxml::Worldpayxml, xendit, xendit::Xendit, zen, zen::Zen, zsl, zsl::Zsl, + wellsfargo::Wellsfargo, wellsfargopayout, wellsfargopayout::Wellsfargopayout, wise, wise::Wise, + worldline, worldline::Worldline, worldpay, worldpay::Worldpay, worldpayxml, + worldpayxml::Worldpayxml, xendit, xendit::Xendit, zen, zen::Zen, zsl, zsl::Zsl, }; #[cfg(feature = "dummy_connector")] pub use self::dummyconnector::DummyConnector; -pub use self::{ - signifyd::Signifyd, stripe::Stripe, threedsecureio::Threedsecureio, - wellsfargopayout::Wellsfargopayout, wise::Wise, -}; +pub use self::stripe::Stripe; diff --git a/crates/router/src/connector/signifyd.rs b/crates/router/src/connector/signifyd.rs deleted file mode 100644 index 75b78c19b78..00000000000 --- a/crates/router/src/connector/signifyd.rs +++ /dev/null @@ -1,761 +0,0 @@ -pub mod transformers; -use std::fmt::Debug; - -#[cfg(feature = "frm")] -use base64::Engine; -#[cfg(feature = "frm")] -use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent}; -#[cfg(feature = "frm")] -use error_stack::ResultExt; -#[cfg(feature = "frm")] -use masking::{PeekInterface, Secret}; -#[cfg(feature = "frm")] -use ring::hmac; -#[cfg(feature = "frm")] -use transformers as signifyd; - -#[cfg(feature = "frm")] -use super::utils as connector_utils; -use crate::{ - configs::settings, - core::errors::{self, CustomResult}, - headers, - services::{self, request, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation}, - types::{ - self, - api::{self, ConnectorCommon, ConnectorCommonExt}, - }, -}; -#[cfg(feature = "frm")] -use crate::{ - consts, - events::connector_api_logs::ConnectorEvent, - types::{api::fraud_check as frm_api, fraud_check as frm_types, ErrorResponse, Response}, - utils::BytesExt, -}; - -#[derive(Debug, Clone)] -pub struct Signifyd; - -impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Signifyd -where - Self: ConnectorIntegration<Flow, Request, Response>, -{ - fn build_headers( - &self, - req: &types::RouterData<Flow, Request, Response>, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - self.get_content_type().to_string().into(), - )]; - - let mut api_key = self.get_auth_header(&req.connector_auth_type)?; - header.append(&mut api_key); - Ok(header) - } -} - -impl ConnectorCommon for Signifyd { - fn id(&self) -> &'static str { - "signifyd" - } - - fn common_get_content_type(&self) -> &'static str { - "application/json" - } - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { - connectors.signifyd.base_url.as_ref() - } - - #[cfg(feature = "frm")] - fn get_auth_header( - &self, - auth_type: &types::ConnectorAuthType, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - let auth = signifyd::SignifydAuthType::try_from(auth_type) - .change_context(errors::ConnectorError::FailedToObtainAuthType)?; - let auth_api_key = format!( - "Basic {}", - consts::BASE64_ENGINE.encode(auth.api_key.peek()) - ); - - Ok(vec![( - headers::AUTHORIZATION.to_string(), - request::Mask::into_masked(auth_api_key), - )]) - } - - #[cfg(feature = "frm")] - fn build_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - let response: signifyd::SignifydErrorResponse = res - .response - .parse_struct("SignifydErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - - event_builder.map(|i| i.set_error_response_body(&response)); - router_env::logger::info!(connector_response=?response); - - Ok(ErrorResponse { - status_code: res.status_code, - code: consts::NO_ERROR_CODE.to_string(), - message: response.messages.join(" &"), - reason: Some(response.errors.to_string()), - attempt_status: None, - connector_transaction_id: None, - network_advice_code: None, - network_decline_code: None, - network_error_message: None, - }) - } -} - -impl api::Payment for Signifyd {} -impl api::PaymentAuthorize for Signifyd {} -impl api::PaymentSync for Signifyd {} -impl api::PaymentVoid for Signifyd {} -impl api::PaymentCapture for Signifyd {} -impl api::MandateSetup for Signifyd {} -impl api::ConnectorAccessToken for Signifyd {} -impl api::PaymentToken for Signifyd {} -impl api::Refund for Signifyd {} -impl api::RefundExecute for Signifyd {} -impl api::RefundSync for Signifyd {} -impl ConnectorValidation for Signifyd {} - -impl - ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Signifyd -{ -} - -impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> - for Signifyd -{ -} - -impl - ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for Signifyd -{ - fn build_request( - &self, - _req: &types::RouterData< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - >, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - Err( - errors::ConnectorError::NotImplemented("Setup Mandate flow for Signifyd".to_string()) - .into(), - ) - } -} - -impl api::PaymentSession for Signifyd {} - -impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> - for Signifyd -{ -} - -impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> - for Signifyd -{ -} - -impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for Signifyd -{ -} - -impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> - for Signifyd -{ -} - -impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> - for Signifyd -{ -} - -impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> - for Signifyd -{ -} - -impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Signifyd {} - -#[cfg(feature = "frm")] -impl api::FraudCheck for Signifyd {} -#[cfg(feature = "frm")] -impl frm_api::FraudCheckSale for Signifyd {} -#[cfg(feature = "frm")] -impl frm_api::FraudCheckCheckout for Signifyd {} -#[cfg(feature = "frm")] -impl frm_api::FraudCheckTransaction for Signifyd {} -#[cfg(feature = "frm")] -impl frm_api::FraudCheckFulfillment for Signifyd {} -#[cfg(feature = "frm")] -impl frm_api::FraudCheckRecordReturn for Signifyd {} - -#[cfg(feature = "frm")] -impl - ConnectorIntegration< - frm_api::Sale, - frm_types::FraudCheckSaleData, - frm_types::FraudCheckResponseData, - > for Signifyd -{ - fn get_headers( - &self, - req: &frm_types::FrmSaleRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, connectors) - } - - fn get_content_type(&self) -> &'static str { - self.common_get_content_type() - } - - fn get_url( - &self, - _req: &frm_types::FrmSaleRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!( - "{}{}", - self.base_url(connectors), - "v3/orders/events/sales" - )) - } - - fn get_request_body( - &self, - req: &frm_types::FrmSaleRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let req_obj = signifyd::SignifydPaymentsSaleRequest::try_from(req)?; - Ok(RequestContent::Json(Box::new(req_obj))) - } - - fn build_request( - &self, - req: &frm_types::FrmSaleRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&frm_types::FrmSaleType::get_url(self, req, connectors)?) - .attach_default_headers() - .headers(frm_types::FrmSaleType::get_headers(self, req, connectors)?) - .set_body(frm_types::FrmSaleType::get_request_body( - self, req, connectors, - )?) - .build(), - )) - } - - fn handle_response( - &self, - data: &frm_types::FrmSaleRouterData, - event_builder: Option<&mut ConnectorEvent>, - res: Response, - ) -> CustomResult<frm_types::FrmSaleRouterData, errors::ConnectorError> { - let response: signifyd::SignifydPaymentsResponse = res - .response - .parse_struct("SignifydPaymentsResponse Sale") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - - <frm_types::FrmSaleRouterData>::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - } - fn get_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res, event_builder) - } -} - -#[cfg(feature = "frm")] -impl - ConnectorIntegration< - frm_api::Checkout, - frm_types::FraudCheckCheckoutData, - frm_types::FraudCheckResponseData, - > for Signifyd -{ - fn get_headers( - &self, - req: &frm_types::FrmCheckoutRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, connectors) - } - - fn get_content_type(&self) -> &'static str { - self.common_get_content_type() - } - - fn get_url( - &self, - _req: &frm_types::FrmCheckoutRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!( - "{}{}", - self.base_url(connectors), - "v3/orders/events/checkouts" - )) - } - - fn get_request_body( - &self, - req: &frm_types::FrmCheckoutRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let req_obj = signifyd::SignifydPaymentsCheckoutRequest::try_from(req)?; - Ok(RequestContent::Json(Box::new(req_obj))) - } - - fn build_request( - &self, - req: &frm_types::FrmCheckoutRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&frm_types::FrmCheckoutType::get_url(self, req, connectors)?) - .attach_default_headers() - .headers(frm_types::FrmCheckoutType::get_headers( - self, req, connectors, - )?) - .set_body(frm_types::FrmCheckoutType::get_request_body( - self, req, connectors, - )?) - .build(), - )) - } - - fn handle_response( - &self, - data: &frm_types::FrmCheckoutRouterData, - event_builder: Option<&mut ConnectorEvent>, - res: Response, - ) -> CustomResult<frm_types::FrmCheckoutRouterData, errors::ConnectorError> { - let response: signifyd::SignifydPaymentsResponse = res - .response - .parse_struct("SignifydPaymentsResponse Checkout") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - <frm_types::FrmCheckoutRouterData>::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - } - fn get_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res, event_builder) - } -} - -#[cfg(feature = "frm")] -impl - ConnectorIntegration< - frm_api::Transaction, - frm_types::FraudCheckTransactionData, - frm_types::FraudCheckResponseData, - > for Signifyd -{ - fn get_headers( - &self, - req: &frm_types::FrmTransactionRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, connectors) - } - - fn get_content_type(&self) -> &'static str { - self.common_get_content_type() - } - - fn get_url( - &self, - _req: &frm_types::FrmTransactionRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!( - "{}{}", - self.base_url(connectors), - "v3/orders/events/transactions" - )) - } - - fn get_request_body( - &self, - req: &frm_types::FrmTransactionRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let req_obj = signifyd::SignifydPaymentsTransactionRequest::try_from(req)?; - Ok(RequestContent::Json(Box::new(req_obj))) - } - - fn build_request( - &self, - req: &frm_types::FrmTransactionRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&frm_types::FrmTransactionType::get_url( - self, req, connectors, - )?) - .attach_default_headers() - .headers(frm_types::FrmTransactionType::get_headers( - self, req, connectors, - )?) - .set_body(frm_types::FrmTransactionType::get_request_body( - self, req, connectors, - )?) - .build(), - )) - } - - fn handle_response( - &self, - data: &frm_types::FrmTransactionRouterData, - event_builder: Option<&mut ConnectorEvent>, - res: Response, - ) -> CustomResult<frm_types::FrmTransactionRouterData, errors::ConnectorError> { - let response: signifyd::SignifydPaymentsResponse = res - .response - .parse_struct("SignifydPaymentsResponse Transaction") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - <frm_types::FrmTransactionRouterData>::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - } - fn get_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res, event_builder) - } -} - -#[cfg(feature = "frm")] -impl - ConnectorIntegration< - frm_api::Fulfillment, - frm_types::FraudCheckFulfillmentData, - frm_types::FraudCheckResponseData, - > for Signifyd -{ - fn get_headers( - &self, - req: &frm_types::FrmFulfillmentRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, connectors) - } - - fn get_content_type(&self) -> &'static str { - self.common_get_content_type() - } - - fn get_url( - &self, - _req: &frm_types::FrmFulfillmentRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!( - "{}{}", - self.base_url(connectors), - "v3/orders/events/fulfillments" - )) - } - - fn get_request_body( - &self, - req: &frm_types::FrmFulfillmentRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let req_obj = signifyd::FrmFulfillmentSignifydRequest::try_from(req)?; - Ok(RequestContent::Json(Box::new(req_obj.clone()))) - } - - fn build_request( - &self, - req: &frm_types::FrmFulfillmentRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&frm_types::FrmFulfillmentType::get_url( - self, req, connectors, - )?) - .attach_default_headers() - .headers(frm_types::FrmFulfillmentType::get_headers( - self, req, connectors, - )?) - .set_body(frm_types::FrmFulfillmentType::get_request_body( - self, req, connectors, - )?) - .build(), - )) - } - - fn handle_response( - &self, - data: &frm_types::FrmFulfillmentRouterData, - event_builder: Option<&mut ConnectorEvent>, - res: Response, - ) -> CustomResult<frm_types::FrmFulfillmentRouterData, errors::ConnectorError> { - let response: signifyd::FrmFulfillmentSignifydApiResponse = res - .response - .parse_struct("FrmFulfillmentSignifydApiResponse Sale") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - frm_types::FrmFulfillmentRouterData::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - } - fn get_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res, event_builder) - } -} - -#[cfg(feature = "frm")] -impl - ConnectorIntegration< - frm_api::RecordReturn, - frm_types::FraudCheckRecordReturnData, - frm_types::FraudCheckResponseData, - > for Signifyd -{ - fn get_headers( - &self, - req: &frm_types::FrmRecordReturnRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, connectors) - } - - fn get_content_type(&self) -> &'static str { - self.common_get_content_type() - } - - fn get_url( - &self, - _req: &frm_types::FrmRecordReturnRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!( - "{}{}", - self.base_url(connectors), - "v3/orders/events/returns/records" - )) - } - - fn get_request_body( - &self, - req: &frm_types::FrmRecordReturnRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let req_obj = signifyd::SignifydPaymentsRecordReturnRequest::try_from(req)?; - Ok(RequestContent::Json(Box::new(req_obj))) - } - - fn build_request( - &self, - req: &frm_types::FrmRecordReturnRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&frm_types::FrmRecordReturnType::get_url( - self, req, connectors, - )?) - .attach_default_headers() - .headers(frm_types::FrmRecordReturnType::get_headers( - self, req, connectors, - )?) - .set_body(frm_types::FrmRecordReturnType::get_request_body( - self, req, connectors, - )?) - .build(), - )) - } - - fn handle_response( - &self, - data: &frm_types::FrmRecordReturnRouterData, - event_builder: Option<&mut ConnectorEvent>, - res: Response, - ) -> CustomResult<frm_types::FrmRecordReturnRouterData, errors::ConnectorError> { - let response: signifyd::SignifydPaymentsRecordReturnResponse = res - .response - .parse_struct("SignifydPaymentsResponse Transaction") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - <frm_types::FrmRecordReturnRouterData>::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - } - fn get_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res, event_builder) - } -} - -#[cfg(feature = "frm")] -#[async_trait::async_trait] -impl api::IncomingWebhook for Signifyd { - fn get_webhook_source_verification_algorithm( - &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { - Ok(Box::new(crypto::HmacSha256)) - } - - fn get_webhook_source_verification_signature( - &self, - request: &api::IncomingWebhookRequestDetails<'_>, - _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, - ) -> CustomResult<Vec<u8>, errors::ConnectorError> { - let header_value = - connector_utils::get_header_key_value("x-signifyd-sec-hmac-sha256", request.headers)?; - Ok(header_value.as_bytes().to_vec()) - } - - fn get_webhook_source_verification_message( - &self, - request: &api::IncomingWebhookRequestDetails<'_>, - _merchant_id: &common_utils::id_type::MerchantId, - _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, - ) -> CustomResult<Vec<u8>, errors::ConnectorError> { - Ok(request.body.to_vec()) - } - - async fn verify_webhook_source( - &self, - request: &api::IncomingWebhookRequestDetails<'_>, - merchant_id: &common_utils::id_type::MerchantId, - connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, - _connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>, - connector_label: &str, - ) -> CustomResult<bool, errors::ConnectorError> { - let connector_webhook_secrets = self - .get_webhook_source_verification_merchant_secret( - merchant_id, - connector_label, - connector_webhook_details, - ) - .await - .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; - - let signature = self - .get_webhook_source_verification_signature(request, &connector_webhook_secrets) - .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; - - let message = self - .get_webhook_source_verification_message( - request, - merchant_id, - &connector_webhook_secrets, - ) - .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; - - let signing_key = hmac::Key::new(hmac::HMAC_SHA256, &connector_webhook_secrets.secret); - let signed_message = hmac::sign(&signing_key, &message); - let payload_sign = consts::BASE64_ENGINE.encode(signed_message.as_ref()); - Ok(payload_sign.as_bytes().eq(&signature)) - } - - fn get_webhook_object_reference_id( - &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { - let resource: signifyd::SignifydWebhookBody = request - .body - .parse_struct("SignifydWebhookBody") - .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; - Ok(api::webhooks::ObjectReferenceId::PaymentId( - api_models::payments::PaymentIdType::PaymentAttemptId(resource.order_id), - )) - } - - fn get_webhook_event_type( - &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { - let resource: signifyd::SignifydWebhookBody = request - .body - .parse_struct("SignifydWebhookBody") - .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; - Ok(api::IncomingWebhookEvent::from(resource.review_disposition)) - } - - fn get_webhook_resource_object( - &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { - let resource: signifyd::SignifydWebhookBody = request - .body - .parse_struct("SignifydWebhookBody") - .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?; - Ok(Box::new(resource)) - } -} - -impl ConnectorSpecifications for Signifyd {} diff --git a/crates/router/src/connector/signifyd/transformers/auth.rs b/crates/router/src/connector/signifyd/transformers/auth.rs deleted file mode 100644 index cc5867aea36..00000000000 --- a/crates/router/src/connector/signifyd/transformers/auth.rs +++ /dev/null @@ -1,20 +0,0 @@ -use error_stack; -use masking::Secret; - -use crate::{core::errors, types}; - -pub struct SignifydAuthType { - pub api_key: Secret<String>, -} - -impl TryFrom<&types::ConnectorAuthType> for SignifydAuthType { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { - match auth_type { - types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self { - api_key: api_key.to_owned(), - }), - _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), - } - } -} diff --git a/crates/router/src/connector/threedsecureio.rs b/crates/router/src/connector/threedsecureio.rs deleted file mode 100644 index c01a1d894c4..00000000000 --- a/crates/router/src/connector/threedsecureio.rs +++ /dev/null @@ -1,537 +0,0 @@ -pub mod transformers; - -use std::fmt::Debug; - -use error_stack::{report, ResultExt}; -use masking::ExposeInterface; -use pm_auth::consts; -use transformers as threedsecureio; - -use crate::{ - configs::settings, - core::errors::{self, CustomResult}, - events::connector_api_logs::ConnectorEvent, - headers, - services::{ - self, - request::{self, Mask}, - ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, - }, - types::{ - self, - api::{self, ConnectorCommon, ConnectorCommonExt}, - ErrorResponse, RequestContent, Response, - }, - utils::{self, BytesExt}, -}; - -#[derive(Debug, Clone)] -pub struct Threedsecureio; - -impl api::Payment for Threedsecureio {} -impl api::PaymentSession for Threedsecureio {} -impl api::ConnectorAccessToken for Threedsecureio {} -impl api::MandateSetup for Threedsecureio {} -impl api::PaymentAuthorize for Threedsecureio {} -impl api::PaymentSync for Threedsecureio {} -impl api::PaymentCapture for Threedsecureio {} -impl api::PaymentVoid for Threedsecureio {} -impl api::Refund for Threedsecureio {} -impl api::RefundExecute for Threedsecureio {} -impl api::RefundSync for Threedsecureio {} -impl api::PaymentToken for Threedsecureio {} - -impl - ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Threedsecureio -{ -} - -impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Threedsecureio -where - Self: ConnectorIntegration<Flow, Request, Response>, -{ - fn build_headers( - &self, - req: &types::RouterData<Flow, Request, Response>, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - "application/json; charset=utf-8".to_string().into(), - )]; - let mut api_key = self.get_auth_header(&req.connector_auth_type)?; - header.append(&mut api_key); - Ok(header) - } -} - -impl ConnectorCommon for Threedsecureio { - fn id(&self) -> &'static str { - "threedsecureio" - } - - fn get_currency_unit(&self) -> api::CurrencyUnit { - api::CurrencyUnit::Minor - } - - fn common_get_content_type(&self) -> &'static str { - "application/json" - } - - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { - connectors.threedsecureio.base_url.as_ref() - } - - fn get_auth_header( - &self, - auth_type: &types::ConnectorAuthType, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - let auth = threedsecureio::ThreedsecureioAuthType::try_from(auth_type) - .change_context(errors::ConnectorError::FailedToObtainAuthType)?; - Ok(vec![( - headers::APIKEY.to_string(), - auth.api_key.expose().into_masked(), - )]) - } - - fn build_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - let response_result: Result< - threedsecureio::ThreedsecureioErrorResponse, - error_stack::Report<common_utils::errors::ParsingError>, - > = res.response.parse_struct("ThreedsecureioErrorResponse"); - - match response_result { - Ok(response) => { - event_builder.map(|i| i.set_error_response_body(&response)); - router_env::logger::info!(connector_response=?response); - Ok(ErrorResponse { - status_code: res.status_code, - code: response.error_code, - message: response - .error_description - .clone() - .unwrap_or(consts::NO_ERROR_MESSAGE.to_owned()), - reason: response.error_description, - attempt_status: None, - connector_transaction_id: None, - network_advice_code: None, - network_decline_code: None, - network_error_message: None, - }) - } - Err(err) => { - router_env::logger::error!(deserialization_error =? err); - utils::handle_json_response_deserialization_failure(res, "threedsecureio") - } - } - } -} - -impl ConnectorValidation for Threedsecureio {} - -impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> - for Threedsecureio -{ -} - -impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> - for Threedsecureio -{ -} - -impl - ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for Threedsecureio -{ -} - -impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> - for Threedsecureio -{ -} - -impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for Threedsecureio -{ -} - -impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> - for Threedsecureio -{ -} - -impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> - for Threedsecureio -{ -} - -impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> - for Threedsecureio -{ -} - -impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> - for Threedsecureio -{ -} - -#[async_trait::async_trait] -impl api::IncomingWebhook for Threedsecureio { - fn get_webhook_object_reference_id( - &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) - } - - fn get_webhook_event_type( - &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) - } - - fn get_webhook_resource_object( - &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) - } -} - -impl api::ConnectorPreAuthentication for Threedsecureio {} -impl api::ConnectorPreAuthenticationVersionCall for Threedsecureio {} -impl api::ExternalAuthentication for Threedsecureio {} -impl api::ConnectorAuthentication for Threedsecureio {} -impl api::ConnectorPostAuthentication for Threedsecureio {} - -impl - ConnectorIntegration< - api::Authentication, - types::authentication::ConnectorAuthenticationRequestData, - types::authentication::AuthenticationResponseData, - > for Threedsecureio -{ - fn get_headers( - &self, - req: &types::authentication::ConnectorAuthenticationRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, connectors) - } - - fn get_content_type(&self) -> &'static str { - self.common_get_content_type() - } - - fn get_url( - &self, - _req: &types::authentication::ConnectorAuthenticationRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!("{}/auth", self.base_url(connectors),)) - } - - fn get_request_body( - &self, - req: &types::authentication::ConnectorAuthenticationRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = threedsecureio::ThreedsecureioRouterData::try_from(( - &self.get_currency_unit(), - req.request - .currency - .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "currency", - })?, - req.request - .amount - .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "amount", - })?, - req, - ))?; - let req_obj = - threedsecureio::ThreedsecureioAuthenticationRequest::try_from(&connector_router_data); - Ok(RequestContent::Json(Box::new(req_obj?))) - } - - fn build_request( - &self, - req: &types::authentication::ConnectorAuthenticationRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url( - &types::authentication::ConnectorAuthenticationType::get_url( - self, req, connectors, - )?, - ) - .attach_default_headers() - .headers( - types::authentication::ConnectorAuthenticationType::get_headers( - self, req, connectors, - )?, - ) - .set_body( - types::authentication::ConnectorAuthenticationType::get_request_body( - self, req, connectors, - )?, - ) - .build(), - )) - } - - fn handle_response( - &self, - data: &types::authentication::ConnectorAuthenticationRouterData, - event_builder: Option<&mut ConnectorEvent>, - res: Response, - ) -> CustomResult< - types::authentication::ConnectorAuthenticationRouterData, - errors::ConnectorError, - > { - let response: threedsecureio::ThreedsecureioAuthenticationResponse = res - .response - .parse_struct("ThreedsecureioAuthenticationResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - } - - fn get_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res, event_builder) - } -} - -impl - ConnectorIntegration< - api::PreAuthentication, - types::authentication::PreAuthNRequestData, - types::authentication::AuthenticationResponseData, - > for Threedsecureio -{ - fn get_headers( - &self, - req: &types::authentication::PreAuthNRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, connectors) - } - - fn get_content_type(&self) -> &'static str { - self.common_get_content_type() - } - - fn get_url( - &self, - _req: &types::authentication::PreAuthNRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!("{}/preauth", self.base_url(connectors),)) - } - - fn get_request_body( - &self, - req: &types::authentication::PreAuthNRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = threedsecureio::ThreedsecureioRouterData::try_from((0, req))?; - let req_obj = threedsecureio::ThreedsecureioPreAuthenticationRequest::try_from( - &connector_router_data, - )?; - Ok(RequestContent::Json(Box::new(req_obj))) - } - - fn build_request( - &self, - req: &types::authentication::PreAuthNRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url( - &types::authentication::ConnectorPreAuthenticationType::get_url( - self, req, connectors, - )?, - ) - .attach_default_headers() - .headers( - types::authentication::ConnectorPreAuthenticationType::get_headers( - self, req, connectors, - )?, - ) - .set_body( - types::authentication::ConnectorPreAuthenticationType::get_request_body( - self, req, connectors, - )?, - ) - .build(), - )) - } - - fn handle_response( - &self, - data: &types::authentication::PreAuthNRouterData, - event_builder: Option<&mut ConnectorEvent>, - res: Response, - ) -> CustomResult<types::authentication::PreAuthNRouterData, errors::ConnectorError> { - let response: threedsecureio::ThreedsecureioPreAuthenticationResponse = res - .response - .parse_struct("threedsecureio ThreedsecureioPreAuthenticationResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - } - - fn get_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res, event_builder) - } -} - -impl - ConnectorIntegration< - api::PostAuthentication, - types::authentication::ConnectorPostAuthenticationRequestData, - types::authentication::AuthenticationResponseData, - > for Threedsecureio -{ - fn get_headers( - &self, - req: &types::authentication::ConnectorPostAuthenticationRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - self.build_headers(req, connectors) - } - - fn get_content_type(&self) -> &'static str { - self.common_get_content_type() - } - - fn get_url( - &self, - _req: &types::authentication::ConnectorPostAuthenticationRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!("{}/postauth", self.base_url(connectors),)) - } - - fn get_request_body( - &self, - req: &types::authentication::ConnectorPostAuthenticationRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - let req_obj = threedsecureio::ThreedsecureioPostAuthenticationRequest { - three_ds_server_trans_id: req.request.threeds_server_transaction_id.clone(), - }; - Ok(RequestContent::Json(Box::new(req_obj))) - } - - fn build_request( - &self, - req: &types::authentication::ConnectorPostAuthenticationRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url( - &types::authentication::ConnectorPostAuthenticationType::get_url( - self, req, connectors, - )?, - ) - .attach_default_headers() - .headers( - types::authentication::ConnectorPostAuthenticationType::get_headers( - self, req, connectors, - )?, - ) - .set_body( - types::authentication::ConnectorPostAuthenticationType::get_request_body( - self, req, connectors, - )?, - ) - .build(), - )) - } - - fn handle_response( - &self, - data: &types::authentication::ConnectorPostAuthenticationRouterData, - event_builder: Option<&mut ConnectorEvent>, - res: Response, - ) -> CustomResult< - types::authentication::ConnectorPostAuthenticationRouterData, - errors::ConnectorError, - > { - let response: threedsecureio::ThreedsecureioPostAuthenticationResponse = res - .response - .parse_struct("threedsecureio PaymentsSyncResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - event_builder.map(|i| i.set_response_body(&response)); - router_env::logger::info!(connector_response=?response); - Ok( - types::authentication::ConnectorPostAuthenticationRouterData { - response: Ok( - types::authentication::AuthenticationResponseData::PostAuthNResponse { - trans_status: response.trans_status.into(), - authentication_value: response.authentication_value, - eci: response.eci, - }, - ), - ..data.clone() - }, - ) - } - - fn get_error_response( - &self, - res: Response, - event_builder: Option<&mut ConnectorEvent>, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res, event_builder) - } -} - -impl - ConnectorIntegration< - api::PreAuthenticationVersionCall, - types::authentication::PreAuthNRequestData, - types::authentication::AuthenticationResponseData, - > for Threedsecureio -{ -} - -impl ConnectorSpecifications for Threedsecureio {} diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index e0034a63335..ddef185649b 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -2395,30 +2395,6 @@ impl FraudCheckSaleRequest for fraud_check::FraudCheckSaleData { } } -#[cfg(feature = "frm")] -pub trait FraudCheckCheckoutRequest { - fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>; -} -#[cfg(feature = "frm")] -impl FraudCheckCheckoutRequest for fraud_check::FraudCheckCheckoutData { - fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error> { - self.order_details - .clone() - .ok_or_else(missing_field_err("order_details")) - } -} - -#[cfg(feature = "frm")] -pub trait FraudCheckTransactionRequest { - fn get_currency(&self) -> Result<storage_enums::Currency, Error>; -} -#[cfg(feature = "frm")] -impl FraudCheckTransactionRequest for fraud_check::FraudCheckTransactionData { - fn get_currency(&self) -> Result<storage_enums::Currency, Error> { - self.currency.ok_or_else(missing_field_err("currency")) - } -} - #[cfg(feature = "frm")] pub trait FraudCheckRecordReturnRequest { fn get_currency(&self) -> Result<storage_enums::Currency, Error>; diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 68daf6f1531..ff52833cd49 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -217,13 +217,7 @@ impl<const T: u8> { } -default_imp_for_complete_authorize!( - connector::Signifyd, - connector::Stripe, - connector::Threedsecureio, - connector::Wise, - connector::Wellsfargopayout -); +default_imp_for_complete_authorize!(connector::Stripe); macro_rules! default_imp_for_webhook_source_verification { ($($path:ident::$connector:ident),*) => { $( @@ -250,13 +244,7 @@ impl<const T: u8> > for connector::DummyConnector<T> { } -default_imp_for_webhook_source_verification!( - connector::Signifyd, - connector::Stripe, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_webhook_source_verification!(connector::Stripe); macro_rules! default_imp_for_create_customer { ($($path:ident::$connector:ident),*) => { @@ -285,12 +273,7 @@ impl<const T: u8> { } -default_imp_for_create_customer!( - connector::Signifyd, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_create_customer!(); macro_rules! default_imp_for_connector_redirect_response { ($($path:ident::$connector:ident),*) => { @@ -321,12 +304,7 @@ impl<const T: u8> services::ConnectorRedirectResponse for connector::DummyConnec } } -default_imp_for_connector_redirect_response!( - connector::Signifyd, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_connector_redirect_response!(); macro_rules! default_imp_for_connector_request_id { ($($path:ident::$connector:ident),*) => { @@ -339,13 +317,7 @@ macro_rules! default_imp_for_connector_request_id { #[cfg(feature = "dummy_connector")] impl<const T: u8> api::ConnectorTransactionId for connector::DummyConnector<T> {} -default_imp_for_connector_request_id!( - connector::Signifyd, - connector::Stripe, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_connector_request_id!(connector::Stripe); macro_rules! default_imp_for_accept_dispute { ($($path:ident::$connector:ident),*) => { @@ -377,13 +349,7 @@ impl<const T: u8> { } -default_imp_for_accept_dispute!( - connector::Signifyd, - connector::Stripe, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_accept_dispute!(connector::Stripe); macro_rules! default_imp_for_file_upload { ($($path:ident::$connector:ident),*) => { @@ -434,12 +400,7 @@ impl<const T: u8> { } -default_imp_for_file_upload!( - connector::Signifyd, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_file_upload!(); macro_rules! default_imp_for_submit_evidence { ($($path:ident::$connector:ident),*) => { @@ -468,12 +429,7 @@ impl<const T: u8> { } -default_imp_for_submit_evidence!( - connector::Signifyd, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_submit_evidence!(); macro_rules! default_imp_for_defend_dispute { ($($path:ident::$connector:ident),*) => { @@ -502,13 +458,7 @@ impl<const T: u8> { } -default_imp_for_defend_dispute!( - connector::Signifyd, - connector::Stripe, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_defend_dispute!(connector::Stripe); macro_rules! default_imp_for_pre_processing_steps{ ($($path:ident::$connector:ident),*)=> { @@ -552,13 +502,7 @@ impl<const T: u8> { } -default_imp_for_pre_processing_steps!( - connector::Signifyd, - connector::Stripe, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_pre_processing_steps!(connector::Stripe); #[cfg(feature = "dummy_connector")] impl<const T: u8> api::PaymentsPostProcessing for connector::DummyConnector<T> {} @@ -572,13 +516,7 @@ impl<const T: u8> { } -default_imp_for_post_processing_steps!( - connector::Stripe, - connector::Signifyd, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_post_processing_steps!(connector::Stripe); macro_rules! default_imp_for_payouts { ($($path:ident::$connector:ident),*) => { @@ -591,11 +529,7 @@ macro_rules! default_imp_for_payouts { #[cfg(feature = "dummy_connector")] impl<const T: u8> Payouts for connector::DummyConnector<T> {} -default_imp_for_payouts!( - connector::Signifyd, - connector::Threedsecureio, - connector::Wellsfargopayout -); +default_imp_for_payouts!(); #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_create { @@ -625,11 +559,7 @@ impl<const T: u8> } #[cfg(feature = "payouts")] -default_imp_for_payouts_create!( - connector::Signifyd, - connector::Threedsecureio, - connector::Wellsfargopayout -); +default_imp_for_payouts_create!(); #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_retrieve { @@ -659,13 +589,7 @@ impl<const T: u8> } #[cfg(feature = "payouts")] -default_imp_for_payouts_retrieve!( - connector::Signifyd, - connector::Stripe, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_payouts_retrieve!(connector::Stripe); #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_eligibility { @@ -698,12 +622,7 @@ impl<const T: u8> } #[cfg(feature = "payouts")] -default_imp_for_payouts_eligibility!( - connector::Signifyd, - connector::Stripe, - connector::Threedsecureio, - connector::Wellsfargopayout -); +default_imp_for_payouts_eligibility!(connector::Stripe); #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_fulfill { @@ -733,11 +652,7 @@ impl<const T: u8> } #[cfg(feature = "payouts")] -default_imp_for_payouts_fulfill!( - connector::Signifyd, - connector::Threedsecureio, - connector::Wellsfargopayout -); +default_imp_for_payouts_fulfill!(); #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_cancel { @@ -767,11 +682,7 @@ impl<const T: u8> } #[cfg(feature = "payouts")] -default_imp_for_payouts_cancel!( - connector::Signifyd, - connector::Threedsecureio, - connector::Wellsfargopayout -); +default_imp_for_payouts_cancel!(); #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_quote { @@ -801,12 +712,7 @@ impl<const T: u8> } #[cfg(feature = "payouts")] -default_imp_for_payouts_quote!( - connector::Signifyd, - connector::Stripe, - connector::Threedsecureio, - connector::Wellsfargopayout -); +default_imp_for_payouts_quote!(connector::Stripe); #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_recipient { @@ -836,11 +742,7 @@ impl<const T: u8> } #[cfg(feature = "payouts")] -default_imp_for_payouts_recipient!( - connector::Signifyd, - connector::Threedsecureio, - connector::Wellsfargopayout -); +default_imp_for_payouts_recipient!(); #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_recipient_account { @@ -873,12 +775,7 @@ impl<const T: u8> } #[cfg(feature = "payouts")] -default_imp_for_payouts_recipient_account!( - connector::Signifyd, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_payouts_recipient_account!(); macro_rules! default_imp_for_approve { ($($path:ident::$connector:ident),*) => { @@ -907,13 +804,7 @@ impl<const T: u8> { } -default_imp_for_approve!( - connector::Signifyd, - connector::Stripe, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_approve!(connector::Stripe); macro_rules! default_imp_for_reject { ($($path:ident::$connector:ident),*) => { @@ -942,13 +833,7 @@ impl<const T: u8> { } -default_imp_for_reject!( - connector::Signifyd, - connector::Stripe, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_reject!(connector::Stripe); #[cfg(feature = "frm")] macro_rules! default_imp_for_fraud_check { @@ -963,12 +848,7 @@ macro_rules! default_imp_for_fraud_check { impl<const T: u8> api::FraudCheck for connector::DummyConnector<T> {} #[cfg(feature = "frm")] -default_imp_for_fraud_check!( - connector::Stripe, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_fraud_check!(connector::Stripe); #[cfg(feature = "frm")] macro_rules! default_imp_for_frm_sale { @@ -999,12 +879,7 @@ impl<const T: u8> } #[cfg(feature = "frm")] -default_imp_for_frm_sale!( - connector::Stripe, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_frm_sale!(connector::Stripe); #[cfg(feature = "frm")] macro_rules! default_imp_for_frm_checkout { @@ -1035,12 +910,7 @@ impl<const T: u8> } #[cfg(feature = "frm")] -default_imp_for_frm_checkout!( - connector::Stripe, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_frm_checkout!(connector::Stripe); #[cfg(feature = "frm")] macro_rules! default_imp_for_frm_transaction { @@ -1071,12 +941,7 @@ impl<const T: u8> } #[cfg(feature = "frm")] -default_imp_for_frm_transaction!( - connector::Stripe, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_frm_transaction!(connector::Stripe); #[cfg(feature = "frm")] macro_rules! default_imp_for_frm_fulfillment { @@ -1107,12 +972,7 @@ impl<const T: u8> } #[cfg(feature = "frm")] -default_imp_for_frm_fulfillment!( - connector::Stripe, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_frm_fulfillment!(connector::Stripe); #[cfg(feature = "frm")] macro_rules! default_imp_for_frm_record_return { @@ -1143,12 +1003,7 @@ impl<const T: u8> } #[cfg(feature = "frm")] -default_imp_for_frm_record_return!( - connector::Stripe, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_frm_record_return!(connector::Stripe); macro_rules! default_imp_for_incremental_authorization { ($($path:ident::$connector:ident),*) => { @@ -1177,13 +1032,7 @@ impl<const T: u8> { } -default_imp_for_incremental_authorization!( - connector::Signifyd, - connector::Stripe, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_incremental_authorization!(connector::Stripe); macro_rules! default_imp_for_revoking_mandates { ($($path:ident::$connector:ident),*) => { @@ -1210,12 +1059,7 @@ impl<const T: u8> > for connector::DummyConnector<T> { } -default_imp_for_revoking_mandates!( - connector::Signifyd, - connector::Stripe, - connector::Threedsecureio, - connector::Wise -); +default_imp_for_revoking_mandates!(connector::Stripe); macro_rules! default_imp_for_connector_authentication { ($($path:ident::$connector:ident),*) => { @@ -1303,12 +1147,7 @@ impl<const T: u8> > for connector::DummyConnector<T> { } -default_imp_for_connector_authentication!( - connector::Signifyd, - connector::Stripe, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_connector_authentication!(connector::Stripe); macro_rules! default_imp_for_authorize_session_token { ($($path:ident::$connector:ident),*) => { @@ -1334,13 +1173,7 @@ impl<const T: u8> > for connector::DummyConnector<T> { } -default_imp_for_authorize_session_token!( - connector::Signifyd, - connector::Stripe, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_authorize_session_token!(connector::Stripe); macro_rules! default_imp_for_calculate_tax { ($($path:ident::$connector:ident),*) => { @@ -1367,13 +1200,7 @@ impl<const T: u8> { } -default_imp_for_calculate_tax!( - connector::Signifyd, - connector::Stripe, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_calculate_tax!(connector::Stripe); macro_rules! default_imp_for_session_update { ($($path:ident::$connector:ident),*) => { @@ -1400,13 +1227,7 @@ impl<const T: u8> { } -default_imp_for_session_update!( - connector::Signifyd, - connector::Stripe, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_session_update!(connector::Stripe); macro_rules! default_imp_for_post_session_tokens { ($($path:ident::$connector:ident),*) => { @@ -1433,13 +1254,7 @@ impl<const T: u8> { } -default_imp_for_post_session_tokens!( - connector::Signifyd, - connector::Stripe, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_post_session_tokens!(connector::Stripe); macro_rules! default_imp_for_update_metadata { ($($path:ident::$connector:ident),*) => { @@ -1466,12 +1281,7 @@ impl<const T: u8> { } -default_imp_for_update_metadata!( - connector::Signifyd, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_update_metadata!(); macro_rules! default_imp_for_uas_pre_authentication { ($($path:ident::$connector:ident),*) => { @@ -1501,13 +1311,7 @@ impl<const T: u8> { } -default_imp_for_uas_pre_authentication!( - connector::Signifyd, - connector::Stripe, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_uas_pre_authentication!(connector::Stripe); macro_rules! default_imp_for_uas_post_authentication { ($($path:ident::$connector:ident),*) => { @@ -1534,13 +1338,7 @@ impl<const T: u8> { } -default_imp_for_uas_post_authentication!( - connector::Signifyd, - connector::Stripe, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_uas_post_authentication!(connector::Stripe); macro_rules! default_imp_for_uas_authentication_confirmation { ($($path:ident::$connector:ident),*) => { @@ -1556,13 +1354,7 @@ macro_rules! default_imp_for_uas_authentication_confirmation { }; } -default_imp_for_uas_authentication_confirmation!( - connector::Signifyd, - connector::Stripe, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_uas_authentication_confirmation!(connector::Stripe); #[cfg(feature = "dummy_connector")] impl<const T: u8> UasAuthenticationConfirmation for connector::DummyConnector<T> {} @@ -1602,13 +1394,7 @@ impl<const T: u8> { } -default_imp_for_uas_authentication!( - connector::Signifyd, - connector::Stripe, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_uas_authentication!(connector::Stripe); /// Determines whether a capture API call should be made for a payment attempt /// This function evaluates whether an authorized payment should proceed with a capture API call @@ -1731,11 +1517,11 @@ macro_rules! default_imp_for_revenue_recovery { impl<const T: u8> api::RevenueRecovery for connector::DummyConnector<T> {} default_imp_for_revenue_recovery! { - connector::Signifyd, - connector::Stripe, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise + + connector::Stripe + + + } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] @@ -1767,13 +1553,7 @@ impl<const T: u8> } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] -default_imp_for_billing_connector_payment_sync!( - connector::Signifyd, - connector::Stripe, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_billing_connector_payment_sync!(connector::Stripe); #[cfg(all(feature = "v2", feature = "revenue_recovery"))] macro_rules! default_imp_for_revenue_recovery_record_back { @@ -1804,13 +1584,7 @@ impl<const T: u8> { } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] -default_imp_for_revenue_recovery_record_back!( - connector::Signifyd, - connector::Stripe, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_revenue_recovery_record_back!(connector::Stripe); #[cfg(all(feature = "v2", feature = "revenue_recovery"))] macro_rules! default_imp_for_billing_connector_invoice_sync { @@ -1841,10 +1615,4 @@ impl<const T: u8> { } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] -default_imp_for_billing_connector_invoice_sync!( - connector::Signifyd, - connector::Stripe, - connector::Threedsecureio, - connector::Wellsfargopayout, - connector::Wise -); +default_imp_for_billing_connector_invoice_sync!(connector::Stripe);
2025-05-05T09:17:29Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Move the following connectors from `crates/router` to `crates/hyperswitch_connectors` - signifyd - threedsecureio - wellsfargopayout - wise ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ### WISE ```sh curl --location 'http://localhost:8080/account/merchant_1746603147/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-feature: integ-custom' \ --header 'api-key: dev_vE5MxDUUu9eQJ7AMwI4vD9nVj3IlxZy1qdpct9JB7Mt3j2mbYF7jLyjMz8KvAq94' \ --data '{ "connector_type": "payout_processor", "connector_name": "wise", "connector_account_details": { "api_key": "***", "auth_type": "BodyKey", "key1": "2***3" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "city": "NY", "unit": "245" }, "connector_webhook_details": { "merchant_secret": "MyWebhookSecret" }, "business_country": "US", "business_label": "default" }' ``` Response ```json { "connector_type": "payout_processor", "connector_name": "wise", "connector_label": "wise_US_default", "merchant_connector_id": "mca_w92QHyUrQYCIrMmO4Lzp", "profile_id": "pro_SRkbVeuCZykOW6G2bCTL", "connector_account_details": { "auth_type": "BodyKey", "api_key": "Be***************************************d4", "key1": "28****33" }, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "connector_webhook_details": { "merchant_secret": "MyWebhookSecret", "additional_secret": null }, "metadata": { "city": "NY", "unit": "245" }, "test_mode": false, "disabled": false, "frm_configs": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "applepay_verified_domains": null, "pm_auth_config": null, "status": "active", "additional_merchant_data": null, "connector_wallets_details": null } ``` Create payout ```sh curl --location 'http://localhost:8080/payouts/create' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-feature: integ-custom' \ --header 'api-key: dev_vE5MxDUUu9eQJ7AMwI4vD9nVj3IlxZy1qdpct9JB7Mt3j2mbYF7jLyjMz8KvAq94' \ --data-raw '{ "amount": 100, "currency": "EUR", "customer": { "id": "new_id", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65" }, "connector": [ "wise" ], "description": "Its my first payout request", "payout_type": "card", "payout_method_data": { "card": { "card_number": "4000000000002503", "expiry_month": "08", "expiry_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "999" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "city": "San Fransico", "zip": "94122", "country": "CH", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "entity_type": "Individual", "recurring": true, "metadata": { "city": "NY", "unit": "245", "source_balance_account": "BA32CNH223227G5KQKQDJ48HB" }, "confirm": true, "auto_fulfill": true }' ``` response -- LOOKS like card payment ```json { "error": { "type": "invalid_request", "message": "Payout Eligibility for Wise is not implemented", "code": "IR_00" } } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
40fd473989b04f70c1dc78025a555a972ffe2596
40fd473989b04f70c1dc78025a555a972ffe2596
juspay/hyperswitch
juspay__hyperswitch-7957
Bug: [BUG] Facilitapay env connector configs breaking WASM It is `BodyKey` and not `Bodykey`. Affected files: `crates/connector_configs/toml/production.toml` `crates/connector_configs/toml/sandbox.toml` `crates/connector_configs/toml/integration_test.toml` this isn't affecting the current wasm as Facilitapay is not yet on dashboard.
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index eaf3101aa8c..d64b01368d1 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -5816,6 +5816,6 @@ api_secret="Secret Key" [facilitapay] [[facilitapay.bank_transfer]] payment_method_type = "pix" -[facilitapay.connector_auth.Bodykey] +[facilitapay.connector_auth.BodyKey] api_key="Password" key1="Username" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index fe0cf95f242..f2d6898286c 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -4403,6 +4403,6 @@ type="Text" [facilitapay] [[facilitapay.bank_transfer]] payment_method_type = "pix" -[facilitapay.connector_auth.Bodykey] +[facilitapay.connector_auth.BodyKey] api_key="Password" key1="Username" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index c8d9cd5f66f..be69cdd35b1 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -5791,6 +5791,6 @@ api_secret = "Secret Key" [facilitapay] [[facilitapay.bank_transfer]] payment_method_type = "pix" -[facilitapay.connector_auth.Bodykey] +[facilitapay.connector_auth.BodyKey] api_key="Password" key1="Username"
2025-05-05T10:23:35Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR fixes Facilitapay payment method env that broke WASM. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> WASM broke. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> WASM shouldn't break now. closes #7957 ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
31e109a9a1367ef53786c146604b31fca69b15ef
31e109a9a1367ef53786c146604b31fca69b15ef
juspay/hyperswitch
juspay__hyperswitch-7960
Bug: refactor(open_router): call elimination routing of open router if enabled instead of dynamo
diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index a683e3343aa..fddeda6088c 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -643,6 +643,17 @@ impl DynamicRoutingAlgorithmRef { self.dynamic_routing_volume_split = volume } + pub fn is_success_rate_routing_enabled(&self) -> bool { + self.success_based_algorithm + .as_ref() + .map(|success_based_routing| { + success_based_routing.enabled_feature + == DynamicRoutingFeatures::DynamicConnectorSelection + || success_based_routing.enabled_feature == DynamicRoutingFeatures::Metrics + }) + .unwrap_or_default() + } + pub fn is_elimination_enabled(&self) -> bool { self.elimination_routing_algorithm .as_ref() diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index 7f3fd98d777..213cbfa66d6 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -419,8 +419,8 @@ pub enum RoutingError { ContractRoutingClientInitializationError, #[error("Invalid contract based connector label received from dynamic routing service: '{0}'")] InvalidContractBasedConnectorLabel(String), - #[error("Failed to perform {algo} in open_router")] - OpenRouterCallFailed { algo: String }, + #[error("Failed to perform routing in open_router")] + OpenRouterCallFailed, #[error("Error from open_router: {0}")] OpenRouterError(String), } diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 1b7249cfa44..ec9cd9a2c51 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -7243,7 +7243,7 @@ where if routing_choice.routing_type.is_dynamic_routing() { if state.conf.open_router.enabled { - routing::perform_open_routing( + routing::perform_dynamic_routing_with_open_router( state, connectors.clone(), business_profile, @@ -7285,7 +7285,7 @@ where .map(|card_isin| card_isin.to_string()), ); - routing::perform_dynamic_routing( + routing::perform_dynamic_routing_with_intelligent_router( state, connectors.clone(), business_profile, diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index c7b40b3e75b..da401f60377 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -2147,36 +2147,49 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( ); tokio::spawn( async move { - routing_helpers::push_metrics_with_update_window_for_success_based_routing( - &state, - &payment_attempt, - routable_connectors.clone(), - &profile_id, - dynamic_routing_algo_ref.clone(), - dynamic_routing_config_params_interpolator.clone(), - ) - .await - .map_err(|e| logger::error!(success_based_routing_metrics_error=?e)) - .ok(); - - if let Some(gsm_error_category) = gsm_error_category { - if gsm_error_category.should_perform_elimination_routing() { - logger::info!("Performing update window for elimination routing"); - routing_helpers::update_window_for_elimination_routing( - &state, - &payment_attempt, - &profile_id, - dynamic_routing_algo_ref.clone(), - dynamic_routing_config_params_interpolator.clone(), - gsm_error_category, - ) - .await - .map_err(|e| logger::error!(dynamic_routing_metrics_error=?e)) - .ok(); + let should_route_to_open_router = state.conf.open_router.enabled; + + if should_route_to_open_router { + routing_helpers::update_gateway_score_helper_with_open_router( + &state, + &payment_attempt, + &profile_id, + dynamic_routing_algo_ref.clone(), + ) + .await + .map_err(|e| logger::error!(open_router_update_gateway_score_err=?e)) + .ok(); + } else { + routing_helpers::push_metrics_with_update_window_for_success_based_routing( + &state, + &payment_attempt, + routable_connectors.clone(), + &profile_id, + dynamic_routing_algo_ref.clone(), + dynamic_routing_config_params_interpolator.clone(), + ) + .await + .map_err(|e| logger::error!(success_based_routing_metrics_error=?e)) + .ok(); + + if let Some(gsm_error_category) = gsm_error_category { + if gsm_error_category.should_perform_elimination_routing() { + logger::info!("Performing update window for elimination routing"); + routing_helpers::update_window_for_elimination_routing( + &state, + &payment_attempt, + &profile_id, + dynamic_routing_algo_ref.clone(), + dynamic_routing_config_params_interpolator.clone(), + gsm_error_category, + ) + .await + .map_err(|e| logger::error!(dynamic_routing_metrics_error=?e)) + .ok(); + }; }; - }; - routing_helpers::push_metrics_with_update_window_for_contract_based_routing( + routing_helpers::push_metrics_with_update_window_for_contract_based_routing( &state, &payment_attempt, routable_connectors, @@ -2187,6 +2200,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( .await .map_err(|e| logger::error!(contract_based_routing_metrics_error=?e)) .ok(); + } } .in_current_span(), ); diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 6bc55203615..0b5b7003c07 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -1491,7 +1491,7 @@ pub fn make_dsl_input_for_surcharge( } #[cfg(all(feature = "v1", feature = "dynamic_routing"))] -pub async fn perform_open_routing( +pub async fn perform_dynamic_routing_with_open_router( state: &SessionState, routable_connectors: Vec<api_routing::RoutableConnectorChoice>, profile: &domain::Profile, @@ -1516,48 +1516,50 @@ pub async fn perform_open_routing( profile.get_id().get_string_repr() ); + let is_success_rate_routing_enabled = + dynamic_routing_algo_ref.is_success_rate_routing_enabled(); let is_elimination_enabled = dynamic_routing_algo_ref.is_elimination_enabled(); - let connectors = dynamic_routing_algo_ref - .success_based_algorithm - .async_map(|algo| { - perform_success_based_routing_with_open_router( - state, - routable_connectors.clone(), - profile.get_id(), - algo, - &payment_data, - is_elimination_enabled, - ) - }) - .await - .transpose()? - .unwrap_or(routable_connectors); - - if is_elimination_enabled { - // This will initiate the elimination process for the connector. - // Penalize the elimination score of the connector before making a payment. - // Once the payment is made, we will update the score based on the payment status - if let Some(connector) = connectors.first() { - logger::debug!( - "penalizing the elimination score of the gateway with id {} in open router for profile {}", + + // Since success_based and elimination routing is being done in 1 api call, we call decide_gateway when either of it enabled + let connectors = if is_success_rate_routing_enabled || is_elimination_enabled { + let connectors = perform_decide_gateway_call_with_open_router( + state, + routable_connectors.clone(), + profile.get_id(), + &payment_data, + is_elimination_enabled, + ) + .await?; + + if is_elimination_enabled { + // This will initiate the elimination process for the connector. + // Penalize the elimination score of the connector before making a payment. + // Once the payment is made, we will update the score based on the payment status + if let Some(connector) = connectors.first() { + logger::debug!( + "penalizing the elimination score of the gateway with id {} in open_router for profile {}", connector, profile.get_id().get_string_repr() ); - update_success_rate_score_with_open_router( - state, - connector.clone(), - profile.get_id(), - &payment_data.payment_id, - common_enums::AttemptStatus::AuthenticationPending, - ) - .await? + update_gateway_score_with_open_router( + state, + connector.clone(), + profile.get_id(), + &payment_data.payment_id, + common_enums::AttemptStatus::AuthenticationPending, + ) + .await? + } } - } + connectors + } else { + routable_connectors + }; Ok(connectors) } #[cfg(all(feature = "v1", feature = "dynamic_routing"))] -pub async fn perform_dynamic_routing( +pub async fn perform_dynamic_routing_with_intelligent_router( state: &SessionState, routable_connectors: Vec<api_routing::RoutableConnectorChoice>, profile: &domain::Profile, @@ -1648,99 +1650,90 @@ pub async fn perform_dynamic_routing( #[cfg(all(feature = "v1", feature = "dynamic_routing"))] #[instrument(skip_all)] -pub async fn perform_success_based_routing_with_open_router( +pub async fn perform_decide_gateway_call_with_open_router( state: &SessionState, mut routable_connectors: Vec<api_routing::RoutableConnectorChoice>, profile_id: &common_utils::id_type::ProfileId, - success_based_algo_ref: api_routing::SuccessBasedAlgorithm, payment_attempt: &oss_storage::PaymentAttempt, is_elimination_enabled: bool, ) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> { - if success_based_algo_ref.enabled_feature - == api_routing::DynamicRoutingFeatures::DynamicConnectorSelection - { - logger::debug!( - "performing success_based_routing with open_router for profile {}", - profile_id.get_string_repr() - ); + logger::debug!( + "performing decide_gateway call with open_router for profile {}", + profile_id.get_string_repr() + ); - let open_router_req_body = OpenRouterDecideGatewayRequest::construct_sr_request( - payment_attempt, - routable_connectors.clone(), - Some(or_types::RankingAlgorithm::SrBasedRouting), - is_elimination_enabled, - ); + let open_router_req_body = OpenRouterDecideGatewayRequest::construct_sr_request( + payment_attempt, + routable_connectors.clone(), + Some(or_types::RankingAlgorithm::SrBasedRouting), + is_elimination_enabled, + ); - let url = format!("{}/{}", &state.conf.open_router.url, "decide-gateway"); - let mut request = request::Request::new(services::Method::Post, &url); - request.add_header(headers::CONTENT_TYPE, "application/json".into()); - request.add_header( - headers::X_TENANT_ID, - state.tenant.tenant_id.get_string_repr().to_owned().into(), - ); - request.set_body(request::RequestContent::Json(Box::new( - open_router_req_body, - ))); + let url = format!("{}/{}", &state.conf.open_router.url, "decide-gateway"); + let mut request = request::Request::new(services::Method::Post, &url); + request.add_header(headers::CONTENT_TYPE, "application/json".into()); + request.add_header( + headers::X_TENANT_ID, + state.tenant.tenant_id.get_string_repr().to_owned().into(), + ); + request.set_body(request::RequestContent::Json(Box::new( + open_router_req_body, + ))); - let response = services::call_connector_api(state, request, "open_router_sr_call") - .await - .change_context(errors::RoutingError::OpenRouterCallFailed { - algo: "success_rate".into(), - })?; - - let sr_sorted_connectors = match response { - Ok(resp) => { - let decided_gateway: DecidedGateway = resp - .response - .parse_struct("DecidedGateway") - .change_context(errors::RoutingError::OpenRouterError( - "Failed to parse the response from open_router".into(), - ))?; - - if let Some(gateway_priority_map) = decided_gateway.gateway_priority_map { - logger::debug!( - "Open router gateway_priority_map response: {:?}", - gateway_priority_map - ); - routable_connectors.sort_by(|connector_choice_a, connector_choice_b| { - let connector_choice_a_score = gateway_priority_map - .get(&connector_choice_a.connector.to_string()) - .copied() - .unwrap_or(0.0); - let connector_choice_b_score = gateway_priority_map - .get(&connector_choice_b.connector.to_string()) - .copied() - .unwrap_or(0.0); - connector_choice_b_score - .partial_cmp(&connector_choice_a_score) - .unwrap_or(std::cmp::Ordering::Equal) - }); - } - Ok(routable_connectors) - } - Err(err) => { - let err_resp: or_types::ErrorResponse = err - .response - .parse_struct("ErrorResponse") - .change_context(errors::RoutingError::OpenRouterError( - "Failed to parse the response from open_router".into(), - ))?; - logger::error!("open_router_error_response: {:?}", err_resp); - Err(errors::RoutingError::OpenRouterError( - "Failed to perform success based routing in open router".into(), - )) + let response = services::call_connector_api(state, request, "open_router_decide_gateway_call") + .await + .change_context(errors::RoutingError::OpenRouterCallFailed)?; + + let sr_sorted_connectors = match response { + Ok(resp) => { + let decided_gateway: DecidedGateway = resp + .response + .parse_struct("DecidedGateway") + .change_context(errors::RoutingError::OpenRouterError( + "Failed to parse the response from open_router".into(), + ))?; + + if let Some(gateway_priority_map) = decided_gateway.gateway_priority_map { + logger::debug!( + "open_router decide_gateway call response: {:?}", + gateway_priority_map + ); + routable_connectors.sort_by(|connector_choice_a, connector_choice_b| { + let connector_choice_a_score = gateway_priority_map + .get(&connector_choice_a.connector.to_string()) + .copied() + .unwrap_or(0.0); + let connector_choice_b_score = gateway_priority_map + .get(&connector_choice_b.connector.to_string()) + .copied() + .unwrap_or(0.0); + connector_choice_b_score + .partial_cmp(&connector_choice_a_score) + .unwrap_or(std::cmp::Ordering::Equal) + }); } - }?; + Ok(routable_connectors) + } + Err(err) => { + let err_resp: or_types::ErrorResponse = err + .response + .parse_struct("ErrorResponse") + .change_context(errors::RoutingError::OpenRouterError( + "Failed to parse the response from open_router".into(), + ))?; + logger::error!("open_router_error_response: {:?}", err_resp); + Err(errors::RoutingError::OpenRouterError( + "Failed to perform decide_gateway call in open_router".into(), + )) + } + }?; - Ok(sr_sorted_connectors) - } else { - Ok(routable_connectors) - } + Ok(sr_sorted_connectors) } #[cfg(all(feature = "v1", feature = "dynamic_routing"))] #[instrument(skip_all)] -pub async fn update_success_rate_score_with_open_router( +pub async fn update_gateway_score_with_open_router( state: &SessionState, payment_connector: api_routing::RoutableConnectorChoice, profile_id: &common_utils::id_type::ProfileId, @@ -1768,9 +1761,7 @@ pub async fn update_success_rate_score_with_open_router( let response = services::call_connector_api(state, request, "open_router_update_gateway_score_call") .await - .change_context(errors::RoutingError::OpenRouterCallFailed { - algo: "success_rate".into(), - })?; + .change_context(errors::RoutingError::OpenRouterCallFailed)?; match response { Ok(resp) => { @@ -1781,7 +1772,7 @@ pub async fn update_success_rate_score_with_open_router( )?; logger::debug!( - "Open router update_gateway_score response for gateway with id {}: {:?}", + "open_router update_gateway_score response for gateway with id {}: {:?}", payment_connector, update_score_resp ); @@ -1795,9 +1786,9 @@ pub async fn update_success_rate_score_with_open_router( .change_context(errors::RoutingError::OpenRouterError( "Failed to parse the response from open_router".into(), ))?; - logger::error!("open_router_error_response: {:?}", err_resp); + logger::error!("open_router_update_gateway_score_error: {:?}", err_resp); Err(errors::RoutingError::OpenRouterError( - "Failed to update gateway score for success based routing in open router".into(), + "Failed to update gateway score in open_router".into(), )) } }?; diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index cf14c70ca32..dc594180e70 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -705,6 +705,53 @@ where } } +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +#[instrument(skip_all)] +pub async fn update_gateway_score_helper_with_open_router( + state: &SessionState, + payment_attempt: &storage::PaymentAttempt, + profile_id: &id_type::ProfileId, + dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef, +) -> RouterResult<()> { + let is_success_rate_routing_enabled = + dynamic_routing_algo_ref.is_success_rate_routing_enabled(); + let is_elimination_enabled = dynamic_routing_algo_ref.is_elimination_enabled(); + + if is_success_rate_routing_enabled || is_elimination_enabled { + let payment_connector = &payment_attempt.connector.clone().ok_or( + errors::ApiErrorResponse::GenericNotFoundError { + message: "unable to derive payment connector from payment attempt".to_string(), + }, + )?; + + let routable_connector = routing_types::RoutableConnectorChoice { + choice_kind: api_models::routing::RoutableChoiceKind::FullStruct, + connector: common_enums::RoutableConnectors::from_str(payment_connector.as_str()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to infer routable_connector from connector")?, + merchant_connector_id: payment_attempt.merchant_connector_id.clone(), + }; + + logger::debug!( + "performing update-gateway-score for gateway with id {} in open_router for profile: {}", + routable_connector, + profile_id.get_string_repr() + ); + routing::payments_routing::update_gateway_score_with_open_router( + state, + routable_connector.clone(), + profile_id, + &payment_attempt.payment_id, + payment_attempt.status, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to update gateway score in open_router service")?; + } + + Ok(()) +} + /// metrics for success based dynamic routing #[cfg(all(feature = "v1", feature = "dynamic_routing"))] #[instrument(skip_all)] @@ -741,27 +788,6 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( merchant_connector_id: payment_attempt.merchant_connector_id.clone(), }; - let should_route_to_open_router = state.conf.open_router.enabled; - - if should_route_to_open_router { - logger::debug!( - "performing update-gateway-score for gateway with id {} in open router for profile: {}", - routable_connector, profile_id.get_string_repr() - ); - routing::payments_routing::update_success_rate_score_with_open_router( - state, - routable_connector.clone(), - profile_id, - &payment_attempt.payment_id, - payment_attempt.status, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("failed to update gateway score in open router service")?; - - return Ok(()); - } - let payment_status_attribute = get_desired_payment_status_for_dynamic_routing_metrics(payment_attempt.status);
2025-05-05T12:20:16Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This pull request introduces significant updates to the dynamic routing logic, focusing on enhancing the success-based routing mechanism and improving the integration with the "open router" service. Key changes include the addition of a new helper method, refactoring of existing methods for better clarity, and updates to the routing logic to streamline decision-making. ### Enhancements to Dynamic Routing Logic: * Added a new method `is_success_rate_routing_enabled` in `DynamicRoutingAlgorithmRef` to determine if success-based routing is enabled, improving readability and encapsulation. (`crates/api_models/src/routing.rs`) * Modified the `perform_open_routing` function to consolidate success-based and elimination routing into a single API call, simplifying the logic for deciding gateways. (`crates/router/src/core/payments/routing.rs`) [[1]](diffhunk://#diff-f9f43be4eb6b360f7b6962459a4943e79db89c6c253da0c3ad2b5096ea78cd9bR1519-R1532) [[2]](diffhunk://#diff-f9f43be4eb6b360f7b6962459a4943e79db89c6c253da0c3ad2b5096ea78cd9bR1553-R1556) ### Integration with Open Router: * Introduced a new helper function `update_gateway_score_helper_with_open_router` to handle gateway score updates when routing through the open router. This replaces the previous `push_metrics_with_update_window_for_success_based_routing` in relevant contexts. (`crates/router/src/core/routing/helpers.rs`) [[1]](diffhunk://#diff-ea48d33e52b2cb7edbbba1d236b55f946fdb2c178f8c76f4226818b3630c4658L708-R720) [[2]](diffhunk://#diff-ea48d33e52b2cb7edbbba1d236b55f946fdb2c178f8c76f4226818b3630c4658L744-R740) * Renamed methods like `update_success_rate_score_with_open_router` to `update_gateway_score_with_open_router` and `perform_success_based_routing_with_open_router` to `perform_decide_gateway_call_with_open_router` for better alignment with their functionality. (`crates/router/src/core/payments/routing.rs`) [[1]](diffhunk://#diff-f9f43be4eb6b360f7b6962459a4943e79db89c6c253da0c3ad2b5096ea78cd9bL1545-R1543) [[2]](diffhunk://#diff-f9f43be4eb6b360f7b6962459a4943e79db89c6c253da0c3ad2b5096ea78cd9bL1651-R1661) [[3]](diffhunk://#diff-f9f43be4eb6b360f7b6962459a4943e79db89c6c253da0c3ad2b5096ea78cd9bL1730-R1738) ### Refactor and Cleanup: * Refactored the `payment_response_update_tracker` function to include conditional logic for routing decisions based on the open router's configuration, ensuring better error handling and logging. (`crates/router/src/core/payments/operations/payment_response.rs`) [[1]](diffhunk://#diff-7f827636ccd9cbd48fa4f306d5aeba4f02f4011dacc6de6c87fadde2ed19f882R2150-R2162) [[2]](diffhunk://#diff-7f827636ccd9cbd48fa4f306d5aeba4f02f4011dacc6de6c87fadde2ed19f882R2204) * Reintroduced the `push_metrics_with_update_window_for_success_based_routing` function with a more focused implementation, while retaining the original logic for backward compatibility. (`crates/router/src/core/routing/helpers.rs`) These changes collectively improve the maintainability, readability, and functionality of the dynamic routing system, particularly in scenarios involving success-based routing and open router integration. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Since the feature cannot be deployed in main pod, this can be tested through custom pod which I can help with ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
18142a4fdb1f81e4b493067b669a68576bac5d08
18142a4fdb1f81e4b493067b669a68576bac5d08
juspay/hyperswitch
juspay__hyperswitch-7952
Bug: [FIX] Re-revert changes done in `pr#7866` by `pr#7882` ### Context [PR#7882](https://github.com/juspay/hyperswitch/pull/7882) accidentally reverted changes made in [PR#7882](https://github.com/juspay/hyperswitch/pull/7866), which was a merchant critical PR. ### Proposed Fix Re revert the changes.
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 5749715e51b..c228975faac 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -3485,61 +3485,6 @@ pub async fn list_payment_methods( response ); - // Filter out wallet payment method from mca if customer has already saved it - customer - .as_ref() - .async_map(|customer| async { - let wallet_pm_exists = response - .iter() - .any(|mca| mca.payment_method == enums::PaymentMethod::Wallet); - if wallet_pm_exists { - match db - .find_payment_method_by_customer_id_merchant_id_status( - &((&state).into()), - merchant_context.get_merchant_key_store(), - &customer.customer_id, - merchant_context.get_merchant_account().get_id(), - common_enums::PaymentMethodStatus::Active, - None, - merchant_context.get_merchant_account().storage_scheme, - ) - .await - { - Ok(customer_payment_methods) => { - let customer_wallet_pm = customer_payment_methods - .iter() - .filter(|cust_pm| { - cust_pm.get_payment_method_type() == Some(enums::PaymentMethod::Wallet) - }) - .collect::<Vec<_>>(); - - response.retain(|mca| { - !(mca.payment_method == enums::PaymentMethod::Wallet - && customer_wallet_pm.iter().any(|cust_pm| { - cust_pm.get_payment_method_subtype() == Some(mca.payment_method_type) - })) - }); - - logger::debug!("Filtered out wallet payment method from mca since customer has already saved it"); - Ok(()) - } - Err(error) => { - if error.current_context().is_db_not_found() { - Ok(()) - } else { - Err(error) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("failed to find payment methods for a customer") - } - } - } - } else { - Ok(()) - } - }) - .await - .transpose()?; - let mut pmt_to_auth_connector: HashMap< enums::PaymentMethod, HashMap<enums::PaymentMethodType, String>,
2025-05-05T09:22:23Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Context https://github.com/juspay/hyperswitch/pull/7882 accidentally reverted changes made in https://github.com/juspay/hyperswitch/pull/7866, which was a merchant critical PR. Reason: - This might have occured due to incorrect resolution of merge conflicts in [this PR](https://github.com/juspay/hyperswitch/pull/7882) ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ### Fixes #7952 ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - Create MA and an MCA with wallets - Create a payment and Save one wallet (eg: Paypal) - Create a new payment intent - List the Merchant PML again, Paypal would still be there ##### cURL ```bash curl --location 'http://localhost:8080/account/payment_methods?client_secret={{client_secret}}' \ --header 'Accept: application/json' \ --header 'api-key: {{publishable_key}}' ``` ##### Response ```json { "redirect_url": null, "currency": "USD", "payment_methods": [ { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "paypal", "payment_experience": [ { "payment_experience_type": "invoke_sdk_client", "eligible_connectors": [ "paypal" ] }, { "payment_experience_type": "redirect_to_url", "eligible_connectors": [ "paypal" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "shipping.address.city": { "required_field": "shipping.address.city", "display_name": "city", "field_type": "user_shipping_address_city", "value": "San Fransico" }, "shipping.address.first_name": { "required_field": "shipping.address.first_name", "display_name": "shipping_first_name", "field_type": "user_shipping_name", "value": "joseph" }, "shipping.address.state": { "required_field": "shipping.address.state", "display_name": "state", "field_type": "user_shipping_address_state", "value": "California" }, "shipping.address.country": { "required_field": "shipping.address.country", "display_name": "country", "field_type": { "user_shipping_address_country": { "options": [ "ALL" ] } }, "value": "US" }, "shipping.address.line1": { "required_field": "shipping.address.line1", "display_name": "line1", "field_type": "user_shipping_address_line1", "value": "1467" }, "shipping.address.zip": { "required_field": "shipping.address.zip", "display_name": "zip", "field_type": "user_shipping_address_pincode", "value": "94122" }, "shipping.address.last_name": { "required_field": "shipping.address.last_name", "display_name": "shipping_last_name", "field_type": "user_shipping_name", "value": "Doe" } }, "surcharge_details": null, "pm_auth_connector": null } ] }, { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ { "card_network": "Discover", "surcharge_details": null, "eligible_connectors": [ "paypal" ] }, { "card_network": "Mastercard", "surcharge_details": null, "eligible_connectors": [ "paypal" ] }, { "card_network": "Interac", "surcharge_details": null, "eligible_connectors": [ "paypal" ] }, { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "paypal" ] }, { "card_network": "DinersClub", "surcharge_details": null, "eligible_connectors": [ "paypal" ] }, { "card_network": "UnionPay", "surcharge_details": null, "eligible_connectors": [ "paypal" ] }, { "card_network": "JCB", "surcharge_details": null, "eligible_connectors": [ "paypal" ] }, { "card_network": "CartesBancaires", "surcharge_details": null, "eligible_connectors": [ "paypal" ] }, { "card_network": "AmericanExpress", "surcharge_details": null, "eligible_connectors": [ "paypal" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "payment_method_data.card.card_exp_year": { "required_field": "payment_method_data.card.card_exp_year", "display_name": "card_exp_year", "field_type": "user_card_expiry_year", "value": null }, "payment_method_data.card.card_exp_month": { "required_field": "payment_method_data.card.card_exp_month", "display_name": "card_exp_month", "field_type": "user_card_expiry_month", "value": null }, "payment_method_data.card.card_number": { "required_field": "payment_method_data.card.card_number", "display_name": "card_number", "field_type": "user_card_number", "value": null }, "payment_method_data.card.card_cvc": { "required_field": "payment_method_data.card.card_cvc", "display_name": "card_cvc", "field_type": "user_card_cvc", "value": null } }, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ { "card_network": "JCB", "surcharge_details": null, "eligible_connectors": [ "paypal" ] }, { "card_network": "Mastercard", "surcharge_details": null, "eligible_connectors": [ "paypal" ] }, { "card_network": "UnionPay", "surcharge_details": null, "eligible_connectors": [ "paypal" ] }, { "card_network": "Discover", "surcharge_details": null, "eligible_connectors": [ "paypal" ] }, { "card_network": "CartesBancaires", "surcharge_details": null, "eligible_connectors": [ "paypal" ] }, { "card_network": "DinersClub", "surcharge_details": null, "eligible_connectors": [ "paypal" ] }, { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "paypal" ] }, { "card_network": "Interac", "surcharge_details": null, "eligible_connectors": [ "paypal" ] }, { "card_network": "AmericanExpress", "surcharge_details": null, "eligible_connectors": [ "paypal" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "payment_method_data.card.card_exp_year": { "required_field": "payment_method_data.card.card_exp_year", "display_name": "card_exp_year", "field_type": "user_card_expiry_year", "value": null }, "payment_method_data.card.card_exp_month": { "required_field": "payment_method_data.card.card_exp_month", "display_name": "card_exp_month", "field_type": "user_card_expiry_month", "value": null }, "payment_method_data.card.card_number": { "required_field": "payment_method_data.card.card_number", "display_name": "card_number", "field_type": "user_card_number", "value": null }, "payment_method_data.card.card_cvc": { "required_field": "payment_method_data.card.card_cvc", "display_name": "card_cvc", "field_type": "user_card_cvc", "value": null } }, "surcharge_details": null, "pm_auth_connector": null } ] } ], "mandate_payment": null, "merchant_name": "standard", "show_surcharge_breakup_screen": false, "payment_type": "normal", "request_external_three_ds_authentication": false, "collect_shipping_details_from_wallets": false, "collect_billing_details_from_wallets": false, "is_tax_calculation_enabled": false } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
31e109a9a1367ef53786c146604b31fca69b15ef
31e109a9a1367ef53786c146604b31fca69b15ef
juspay/hyperswitch
juspay__hyperswitch-7939
Bug: [FEATURE]: Add support for updating elimination config ### Feature Description Add a new route for updating elimination config in the database when it is toggled. ### Possible Implementation Add a new route for updating elimination config in the database when it is toggled. ### Have you spent some time checking if this feature request has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [x] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/api_models/src/events/routing.rs b/crates/api_models/src/events/routing.rs index 122d1f8d3c8..c9fa118f596 100644 --- a/crates/api_models/src/events/routing.rs +++ b/crates/api_models/src/events/routing.rs @@ -2,9 +2,10 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::routing::{ ContractBasedRoutingPayloadWrapper, ContractBasedRoutingSetupPayloadWrapper, - DynamicRoutingUpdateConfigQuery, LinkedRoutingConfigRetrieveResponse, MerchantRoutingAlgorithm, - ProfileDefaultRoutingConfig, RoutingAlgorithmId, RoutingConfigRequest, RoutingDictionaryRecord, - RoutingKind, RoutingLinkWrapper, RoutingPayloadWrapper, RoutingRetrieveLinkQuery, + DynamicRoutingUpdateConfigQuery, EliminationRoutingPayloadWrapper, + LinkedRoutingConfigRetrieveResponse, MerchantRoutingAlgorithm, ProfileDefaultRoutingConfig, + RoutingAlgorithmId, RoutingConfigRequest, RoutingDictionaryRecord, RoutingKind, + RoutingLinkWrapper, RoutingPayloadWrapper, RoutingRetrieveLinkQuery, RoutingRetrieveLinkQueryWrapper, RoutingRetrieveQuery, RoutingVolumeSplitWrapper, SuccessBasedRoutingConfig, SuccessBasedRoutingPayloadWrapper, ToggleDynamicRoutingQuery, ToggleDynamicRoutingWrapper, @@ -98,6 +99,12 @@ impl ApiEventMetric for SuccessBasedRoutingPayloadWrapper { } } +impl ApiEventMetric for EliminationRoutingPayloadWrapper { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Routing) + } +} + impl ApiEventMetric for ContractBasedRoutingPayloadWrapper { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index a683e3343aa..bf03a53c27b 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -828,18 +828,42 @@ pub struct EliminationAnalyserConfig { pub bucket_leak_interval_in_secs: Option<u64>, } +impl EliminationAnalyserConfig { + pub fn update(&mut self, new: Self) { + if let Some(bucket_size) = new.bucket_size { + self.bucket_size = Some(bucket_size) + } + if let Some(bucket_leak_interval_in_secs) = new.bucket_leak_interval_in_secs { + self.bucket_leak_interval_in_secs = Some(bucket_leak_interval_in_secs) + } + } +} + impl Default for EliminationRoutingConfig { fn default() -> Self { Self { params: Some(vec![DynamicRoutingConfigParams::PaymentMethod]), elimination_analyser_config: Some(EliminationAnalyserConfig { bucket_size: Some(5), - bucket_leak_interval_in_secs: Some(2), + bucket_leak_interval_in_secs: Some(60), }), } } } +impl EliminationRoutingConfig { + pub fn update(&mut self, new: Self) { + if let Some(params) = new.params { + self.params = Some(params) + } + if let Some(new_config) = new.elimination_analyser_config { + self.elimination_analyser_config + .as_mut() + .map(|config| config.update(new_config)); + } + } +} + #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] pub struct SuccessBasedRoutingConfig { pub params: Option<Vec<DynamicRoutingConfigParams>>, @@ -906,6 +930,13 @@ pub struct SuccessBasedRoutingPayloadWrapper { pub profile_id: common_utils::id_type::ProfileId, } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct EliminationRoutingPayloadWrapper { + pub updated_config: EliminationRoutingConfig, + pub algorithm_id: common_utils::id_type::RoutingId, + pub profile_id: common_utils::id_type::ProfileId, +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ContractBasedRoutingPayloadWrapper { pub updated_config: ContractBasedRoutingConfig, diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs index 4487dd5a85d..25a1838e95e 100644 --- a/crates/router/src/core/routing.rs +++ b/crates/router/src/core/routing.rs @@ -16,6 +16,7 @@ use error_stack::ResultExt; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use external_services::grpc_client::dynamic_routing::{ contract_routing_client::ContractBasedDynamicRouting, + elimination_based_client::EliminationBasedRouting, success_rate_client::SuccessBasedDynamicRouting, }; use hyperswitch_domain_models::{mandates, payment_address}; @@ -1266,7 +1267,10 @@ pub async fn toggle_specific_dynamic_routing( ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { metrics::ROUTING_CREATE_REQUEST_RECEIVED.add( 1, - router_env::metric_attributes!(("profile_id", profile_id.clone())), + router_env::metric_attributes!( + ("profile_id", profile_id.clone()), + ("algorithm_type", dynamic_routing_type.to_string()) + ), ); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); @@ -1396,7 +1400,13 @@ pub async fn success_based_routing_update_configs( ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE.add( 1, - router_env::metric_attributes!(("profile_id", profile_id.clone())), + router_env::metric_attributes!( + ("profile_id", profile_id.clone()), + ( + "algorithm_type", + routing::DynamicRoutingType::SuccessRateBasedRouting.to_string() + ) + ), ); let db = state.store.as_ref(); @@ -1468,9 +1478,109 @@ pub async fn success_based_routing_update_configs( state.get_grpc_headers(), ) .await - .change_context(errors::ApiErrorResponse::GenericNotFoundError { - message: "Failed to invalidate the routing keys".to_string(), - }) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to invalidate the routing keys") + }) + .await + .transpose()?; + + Ok(service_api::ApplicationResponse::Json(new_record)) +} + +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +pub async fn elimination_routing_update_configs( + state: SessionState, + request: routing_types::EliminationRoutingConfig, + algorithm_id: common_utils::id_type::RoutingId, + profile_id: common_utils::id_type::ProfileId, +) -> RouterResponse<routing_types::RoutingDictionaryRecord> { + metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE.add( + 1, + router_env::metric_attributes!( + ("profile_id", profile_id.clone()), + ( + "algorithm_type", + routing::DynamicRoutingType::EliminationRouting.to_string() + ) + ), + ); + + let db = state.store.as_ref(); + + let dynamic_routing_algo_to_update = db + .find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algorithm_id) + .await + .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; + + let mut config_to_update: routing::EliminationRoutingConfig = dynamic_routing_algo_to_update + .algorithm_data + .parse_value::<routing::EliminationRoutingConfig>("EliminationRoutingConfig") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "unable to deserialize algorithm data from routing table into EliminationRoutingConfig", + )?; + + config_to_update.update(request); + + let updated_algorithm_id = common_utils::generate_routing_id_of_default_length(); + let timestamp = common_utils::date_time::now(); + let algo = RoutingAlgorithm { + algorithm_id: updated_algorithm_id, + profile_id: dynamic_routing_algo_to_update.profile_id, + merchant_id: dynamic_routing_algo_to_update.merchant_id, + name: dynamic_routing_algo_to_update.name, + description: dynamic_routing_algo_to_update.description, + kind: dynamic_routing_algo_to_update.kind, + algorithm_data: serde_json::json!(config_to_update), + created_at: timestamp, + modified_at: timestamp, + algorithm_for: dynamic_routing_algo_to_update.algorithm_for, + }; + + let record = db + .insert_routing_algorithm(algo) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to insert record in routing algorithm table")?; + + // redact cache for elimination routing configs + let cache_key = format!( + "{}_{}", + profile_id.get_string_repr(), + algorithm_id.get_string_repr() + ); + let cache_entries_to_redact = vec![cache::CacheKind::EliminationBasedDynamicRoutingCache( + cache_key.into(), + )]; + + cache::redact_from_redis_and_publish( + state.store.get_cache_store().as_ref(), + cache_entries_to_redact, + ) + .await + .map_err(|e| logger::error!("unable to publish into the redact channel for evicting the elimination routing config cache {e:?}")).ok(); + + let new_record = record.foreign_into(); + + metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE.add( + 1, + router_env::metric_attributes!(("profile_id", profile_id.clone())), + ); + + state + .grpc_client + .dynamic_routing + .elimination_based_client + .as_ref() + .async_map(|er_client| async { + er_client + .invalidate_elimination_bucket( + profile_id.get_string_repr().into(), + state.get_grpc_headers(), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to invalidate the elimination routing keys") }) .await .transpose()?; @@ -1683,7 +1793,13 @@ pub async fn contract_based_routing_update_configs( ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE.add( 1, - router_env::metric_attributes!(("profile_id", profile_id.get_string_repr().to_owned())), + router_env::metric_attributes!( + ("profile_id", profile_id.get_string_repr().to_owned()), + ( + "algorithm_type", + routing::DynamicRoutingType::ContractBasedRouting.to_string() + ) + ), ); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); @@ -1794,9 +1910,8 @@ pub async fn contract_based_routing_update_configs( state.get_grpc_headers(), ) .await - .change_context(errors::ApiErrorResponse::GenericNotFoundError { - message: "Failed to invalidate the contract based routing keys".to_string(), - }) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to invalidate the contract based routing keys") }) .await .transpose()?; diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index f75fb9ad7f6..1d875d2ac27 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -2027,10 +2027,18 @@ impl Profile { .route(web::post().to(routing::set_dynamic_routing_volume_split)), ) .service( - web::scope("/elimination").service( - web::resource("/toggle") - .route(web::post().to(routing::toggle_elimination_routing)), - ), + web::scope("/elimination") + .service( + web::resource("/toggle") + .route(web::post().to(routing::toggle_elimination_routing)), + ) + .service(web::resource("config/{algorithm_id}").route( + web::patch().to(|state, req, path, payload| { + routing::elimination_routing_update_configs( + state, req, path, payload, + ) + }), + )), ) .service( web::scope("/contracts") diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs index c01613615cb..3dcc947d133 100644 --- a/crates/router/src/routes/routing.rs +++ b/crates/router/src/routes/routing.rs @@ -1299,6 +1299,50 @@ pub async fn success_based_routing_update_configs( .await } +#[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))] +#[instrument(skip_all)] +pub async fn elimination_routing_update_configs( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<routing_types::DynamicRoutingUpdateConfigQuery>, + json_payload: web::Json<routing_types::EliminationRoutingConfig>, +) -> impl Responder { + let flow = Flow::UpdateDynamicRoutingConfigs; + let routing_payload_wrapper = routing_types::EliminationRoutingPayloadWrapper { + updated_config: json_payload.into_inner(), + algorithm_id: path.clone().algorithm_id, + profile_id: path.clone().profile_id, + }; + Box::pin(oss_api::server_wrap( + flow, + state, + &req, + routing_payload_wrapper.clone(), + |state, _, wrapper: routing_types::EliminationRoutingPayloadWrapper, _| async { + Box::pin(routing::elimination_routing_update_configs( + state, + wrapper.updated_config, + wrapper.algorithm_id, + wrapper.profile_id, + )) + .await + }, + auth::auth_type( + &auth::HeaderAuth(auth::ApiKeyAuth { + is_connected_allowed: false, + is_platform_allowed: false, + }), + &auth::JWTAuthProfileFromRoute { + profile_id: routing_payload_wrapper.profile_id, + required_permission: Permission::ProfileRoutingWrite, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} + #[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))] #[instrument(skip_all)] pub async fn contract_based_routing_setup_config(
2025-04-29T12:29:00Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Add a new route for updating the elimination routing config when it is toggled ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> This PR closes #7939 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Toggle elimination routing request ``` curl --location --request POST 'http://localhost:8080/account/merchant_174600xxxx/business_profile/pro_h9ecR6baV3b1eDvfxxxB/dynamic_routing/elimination/toggle?enable=metrics' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_YWu8PFM4pqgBjknNsvHimHsB*******' ``` response ``` { "id": "routing_yfRG8iqWlBreVTVlnYwB", "profile_id": "pro_h9ecR6baV3b1eDvfxxxB", "name": "Elimination based dynamic routing algorithm", "kind": "dynamic", "description": "", "created_at": 1746007881, "modified_at": 1746007881, "algorithm_for": "payment" } ``` 2. Update elimination routing config request ``` curl --location --request PATCH 'http://localhost:8080/account/merchant_174600xxxx/business_profile/pro_h9ecR6baV3b1eDvfxxxB/dynamic_routing/elimination/config/routing_yfRG8iqWlBreVTVlxxxB' \ --header 'api-key: dev_YWu8PFM4pqgBjknNsvHimHsBW1O9CBVy3*******' \ --header 'Content-Type: application/json' \ --data '{ "params": [ "Currency", "CardBin", "Country", "PaymentMethod", "PaymentMethodType", "AuthenticationType", "CardNetwork" ] }' ``` response ``` { "id": "routing_YYu14QIGKRrWgJ8QllpR", "profile_id": "pro_h9ecR6baV3b1eDvfxxxB", "name": "Elimination based dynamic routing algorithm", "kind": "dynamic", "description": "", "created_at": 1746008246, "modified_at": 1746008246, "algorithm_for": "payment" } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
9da96e890c5168692c2c2a73ac8c9b6f43ec7274
9da96e890c5168692c2c2a73ac8c9b6f43ec7274
juspay/hyperswitch
juspay__hyperswitch-7936
Bug: [FIX]: Fix error message while using generic filter Fix error message while using generic filter
diff --git a/crates/diesel_models/src/query/generics.rs b/crates/diesel_models/src/query/generics.rs index e23f4026ccf..d5581932eae 100644 --- a/crates/diesel_models/src/query/generics.rs +++ b/crates/diesel_models/src/query/generics.rs @@ -441,7 +441,7 @@ where track_database_call::<T, _, _>(query.get_results_async(conn), DatabaseOperation::Filter) .await - .change_context(errors::DatabaseError::NotFound) + .change_context(errors::DatabaseError::Others) .attach_printable("Error filtering records by predicate") }
2025-04-29T11:21:35Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR changes the way we raise error if something goes wrong with generic filter. Currently we throw not found error which is wrong. This feature is hard to test on hosted environments, as this requires to make some db changes so that we can get error in generic filter. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> We will able able to log correct error messages ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Tested it with dropping `organization_id` column in refund table while trying to create refund. According to current implementation, we are raising not found error which is incorrect because it is not displaying the right cause. <img width="1637" alt="Screenshot 2025-04-29 at 4 24 40 PM" src="https://github.com/user-attachments/assets/940fda38-c6dc-46ae-b6e1-01aabd6c2a4f" /> Implementation in this PR fixes this bug. <img width="1534" alt="Screenshot 2025-04-29 at 4 28 33 PM" src="https://github.com/user-attachments/assets/d8a61239-433c-4d17-bfb6-0ae2d81c9cdb" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
212ac27057762f9d4cd2073d93c2216f61711cfe
212ac27057762f9d4cd2073d93c2216f61711cfe
juspay/hyperswitch
juspay__hyperswitch-7931
Bug: Modify User-related Redis Operations to Use Global Tenant Prefix Currently, user-related data in Redis (such as SSO IDs, TOTP codes, email token blacklists, lineage_context etc.) is using tenant-specific prefixes like `public:` or `public_v2:`. This causes issues when users use different versions or environments (v1, v2), leading to inconsistency in fetching and setting Redis keys. The correct prefix for all global user-related data should be `global:`. ### Affected Areas - Blacklisting - Two-factor Authentication (TOTP, Recovery Codes) - SSO ID storage - OpenID Connect (OIDC) token handling - Role Info Caching - Lineage Context
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index b0d86839a5d..4120edb957f 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -155,8 +155,10 @@ pub trait GlobalStorageInterface: + user_role::UserRoleInterface + user_key_store::UserKeyStoreInterface + role::RoleInterface + + RedisConnInterface + 'static { + fn get_cache_store(&self) -> Box<(dyn RedisConnInterface + Send + Sync + 'static)>; } #[async_trait::async_trait] @@ -217,7 +219,11 @@ impl StorageInterface for Store { } #[async_trait::async_trait] -impl GlobalStorageInterface for Store {} +impl GlobalStorageInterface for Store { + fn get_cache_store(&self) -> Box<(dyn RedisConnInterface + Send + Sync + 'static)> { + Box::new(self.clone()) + } +} impl AccountsStorageInterface for Store {} @@ -233,7 +239,11 @@ impl StorageInterface for MockDb { } #[async_trait::async_trait] -impl GlobalStorageInterface for MockDb {} +impl GlobalStorageInterface for MockDb { + fn get_cache_store(&self) -> Box<(dyn RedisConnInterface + Send + Sync + 'static)> { + Box::new(self.clone()) + } +} impl AccountsStorageInterface for MockDb {} diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 0e39cbf841a..6e59e0c95d7 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -3269,7 +3269,11 @@ impl StorageInterface for KafkaStore { } } -impl GlobalStorageInterface for KafkaStore {} +impl GlobalStorageInterface for KafkaStore { + fn get_cache_store(&self) -> Box<(dyn RedisConnInterface + Send + Sync + 'static)> { + Box::new(self.clone()) + } +} impl AccountsStorageInterface for KafkaStore {} impl PaymentMethodsStorageInterface for KafkaStore {} diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 9dc67be1d2d..87307441d76 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -153,6 +153,7 @@ pub trait SessionStateInfo { #[cfg(feature = "partial-auth")] fn get_detached_auth(&self) -> RouterResult<(Blake3, &[u8])>; fn session_state(&self) -> SessionState; + fn global_store(&self) -> Box<dyn GlobalStorageInterface>; } impl SessionStateInfo for SessionState { @@ -209,6 +210,9 @@ impl SessionStateInfo for SessionState { fn session_state(&self) -> SessionState { self.clone() } + fn global_store(&self) -> Box<(dyn GlobalStorageInterface)> { + self.global_store.to_owned() + } } #[derive(Clone)] pub struct AppState { diff --git a/crates/router/src/services/authentication/blacklist.rs b/crates/router/src/services/authentication/blacklist.rs index 6be6cc467bf..77dd9861a07 100644 --- a/crates/router/src/services/authentication/blacklist.rs +++ b/crates/router/src/services/authentication/blacklist.rs @@ -27,7 +27,8 @@ pub async fn insert_user_in_blacklist(state: &SessionState, user_id: &str) -> Us let user_blacklist_key = format!("{}{}", USER_BLACKLIST_PREFIX, user_id); let expiry = expiry_to_i64(JWT_TOKEN_TIME_IN_SECS).change_context(UserErrors::InternalServerError)?; - let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?; + let redis_conn = get_redis_connection_for_global_tenant(state) + .change_context(UserErrors::InternalServerError)?; redis_conn .set_key_with_expiry( &user_blacklist_key.as_str().into(), @@ -43,7 +44,8 @@ pub async fn insert_role_in_blacklist(state: &SessionState, role_id: &str) -> Us let role_blacklist_key = format!("{}{}", ROLE_BLACKLIST_PREFIX, role_id); let expiry = expiry_to_i64(JWT_TOKEN_TIME_IN_SECS).change_context(UserErrors::InternalServerError)?; - let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?; + let redis_conn = get_redis_connection_for_global_tenant(state) + .change_context(UserErrors::InternalServerError)?; redis_conn .set_key_with_expiry( &role_blacklist_key.as_str().into(), @@ -59,7 +61,7 @@ pub async fn insert_role_in_blacklist(state: &SessionState, role_id: &str) -> Us #[cfg(feature = "olap")] async fn invalidate_role_cache(state: &SessionState, role_id: &str) -> RouterResult<()> { - let redis_conn = get_redis_connection(state)?; + let redis_conn = get_redis_connection_for_global_tenant(state)?; redis_conn .delete_key(&authz::get_cache_key_from_role_id(role_id).as_str().into()) .await @@ -74,7 +76,7 @@ pub async fn check_user_in_blacklist<A: SessionStateInfo>( ) -> RouterResult<bool> { let token = format!("{}{}", USER_BLACKLIST_PREFIX, user_id); let token_issued_at = expiry_to_i64(token_expiry - JWT_TOKEN_TIME_IN_SECS)?; - let redis_conn = get_redis_connection(state)?; + let redis_conn = get_redis_connection_for_global_tenant(state)?; redis_conn .get_key::<Option<i64>>(&token.as_str().into()) .await @@ -89,7 +91,7 @@ pub async fn check_role_in_blacklist<A: SessionStateInfo>( ) -> RouterResult<bool> { let token = format!("{}{}", ROLE_BLACKLIST_PREFIX, role_id); let token_issued_at = expiry_to_i64(token_expiry - JWT_TOKEN_TIME_IN_SECS)?; - let redis_conn = get_redis_connection(state)?; + let redis_conn = get_redis_connection_for_global_tenant(state)?; redis_conn .get_key::<Option<i64>>(&token.as_str().into()) .await @@ -99,7 +101,8 @@ pub async fn check_role_in_blacklist<A: SessionStateInfo>( #[cfg(feature = "email")] pub async fn insert_email_token_in_blacklist(state: &SessionState, token: &str) -> UserResult<()> { - let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?; + let redis_conn = get_redis_connection_for_global_tenant(state) + .change_context(UserErrors::InternalServerError)?; let blacklist_key = format!("{}{token}", EMAIL_TOKEN_BLACKLIST_PREFIX); let expiry = expiry_to_i64(EMAIL_TOKEN_TIME_IN_SECS).change_context(UserErrors::InternalServerError)?; @@ -111,7 +114,8 @@ pub async fn insert_email_token_in_blacklist(state: &SessionState, token: &str) #[cfg(feature = "email")] pub async fn check_email_token_in_blacklist(state: &SessionState, token: &str) -> UserResult<()> { - let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?; + let redis_conn = get_redis_connection_for_global_tenant(state) + .change_context(UserErrors::InternalServerError)?; let blacklist_key = format!("{}{token}", EMAIL_TOKEN_BLACKLIST_PREFIX); let key_exists = redis_conn .exists::<()>(&blacklist_key.as_str().into()) @@ -124,9 +128,11 @@ pub async fn check_email_token_in_blacklist(state: &SessionState, token: &str) - Ok(()) } -fn get_redis_connection<A: SessionStateInfo>(state: &A) -> RouterResult<Arc<RedisConnectionPool>> { +fn get_redis_connection_for_global_tenant<A: SessionStateInfo>( + state: &A, +) -> RouterResult<Arc<RedisConnectionPool>> { state - .store() + .global_store() .get_redis_conn() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection") diff --git a/crates/router/src/services/authorization.rs b/crates/router/src/services/authorization.rs index 0e66654b7b9..947e0860ae8 100644 --- a/crates/router/src/services/authorization.rs +++ b/crates/router/src/services/authorization.rs @@ -61,7 +61,7 @@ async fn get_role_info_from_cache<A>(state: &A, role_id: &str) -> RouterResult<r where A: SessionStateInfo + Sync, { - let redis_conn = get_redis_connection(state)?; + let redis_conn = get_redis_connection_for_global_tenant(state)?; redis_conn .get_and_deserialize_key(&get_cache_key_from_role_id(role_id).into(), "RoleInfo") @@ -100,7 +100,7 @@ pub async fn set_role_info_in_cache<A>( where A: SessionStateInfo + Sync, { - let redis_conn = get_redis_connection(state)?; + let redis_conn = get_redis_connection_for_global_tenant(state)?; redis_conn .serialize_and_set_key_with_expiry( @@ -143,9 +143,11 @@ pub fn check_tenant( Ok(()) } -fn get_redis_connection<A: SessionStateInfo>(state: &A) -> RouterResult<Arc<RedisConnectionPool>> { +fn get_redis_connection_for_global_tenant<A: SessionStateInfo>( + state: &A, +) -> RouterResult<Arc<RedisConnectionPool>> { state - .store() + .global_store() .get_redis_conn() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection") diff --git a/crates/router/src/services/openidconnect.rs b/crates/router/src/services/openidconnect.rs index 44f95b42607..c4dd0df6e13 100644 --- a/crates/router/src/services/openidconnect.rs +++ b/crates/router/src/services/openidconnect.rs @@ -34,7 +34,7 @@ pub async fn get_authorization_url( // Save csrf & nonce as key value respectively let key = get_oidc_redis_key(csrf_token.secret()); - get_redis_connection(&state)? + get_redis_connection_for_global_tenant(&state)? .set_key_with_expiry(&key.into(), nonce.secret(), consts::user::REDIS_SSO_TTL) .await .change_context(UserErrors::InternalServerError) @@ -138,7 +138,7 @@ async fn get_nonce_from_redis( state: &SessionState, redirect_state: &Secret<String>, ) -> UserResult<oidc::Nonce> { - let redis_connection = get_redis_connection(state)?; + let redis_connection = get_redis_connection_for_global_tenant(state)?; let redirect_state = redirect_state.clone().expose(); let key = get_oidc_redis_key(&redirect_state); redis_connection @@ -188,9 +188,11 @@ fn get_oidc_redis_key(csrf: &str) -> String { format!("{}OIDC_{}", consts::user::REDIS_SSO_PREFIX, csrf) } -fn get_redis_connection(state: &SessionState) -> UserResult<std::sync::Arc<RedisConnectionPool>> { +fn get_redis_connection_for_global_tenant( + state: &SessionState, +) -> UserResult<std::sync::Arc<RedisConnectionPool>> { state - .store + .global_store .get_redis_conn() .change_context(UserErrors::InternalServerError) .attach_printable("Failed to get redis connection") diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index 13190125d7d..bd5237c38c8 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -135,33 +135,14 @@ pub async fn get_user_from_db_by_email( .map(UserFromStorage::from) } -pub fn get_redis_connection(state: &SessionState) -> UserResult<Arc<RedisConnectionPool>> { - state - .store - .get_redis_conn() - .change_context(UserErrors::InternalServerError) - .attach_printable("Failed to get redis connection") -} - pub fn get_redis_connection_for_global_tenant( state: &SessionState, ) -> UserResult<Arc<RedisConnectionPool>> { - let redis_connection_pool = state - .store + state + .global_store .get_redis_conn() .change_context(UserErrors::InternalServerError) - .attach_printable("Failed to get redis connection")?; - - let global_tenant_prefix = &state.conf.multitenancy.global_tenant.redis_key_prefix; - - Ok(Arc::new(RedisConnectionPool { - pool: Arc::clone(&redis_connection_pool.pool), - key_prefix: global_tenant_prefix.to_string(), - config: Arc::clone(&redis_connection_pool.config), - subscriber: Arc::clone(&redis_connection_pool.subscriber), - publisher: Arc::clone(&redis_connection_pool.publisher), - is_redis_available: Arc::clone(&redis_connection_pool.is_redis_available), - })) + .attach_printable("Failed to get redis connection") } impl ForeignFrom<&user_api::AuthConfig> for UserAuthType { @@ -267,7 +248,7 @@ pub async fn set_sso_id_in_redis( oidc_state: Secret<String>, sso_id: String, ) -> UserResult<()> { - let connection = get_redis_connection(state)?; + let connection = get_redis_connection_for_global_tenant(state)?; let key = get_oidc_key(&oidc_state.expose()); connection .set_key_with_expiry(&key.into(), sso_id, REDIS_SSO_TTL) @@ -280,7 +261,7 @@ pub async fn get_sso_id_from_redis( state: &SessionState, oidc_state: Secret<String>, ) -> UserResult<String> { - let connection = get_redis_connection(state)?; + let connection = get_redis_connection_for_global_tenant(state)?; let key = get_oidc_key(&oidc_state.expose()); connection .get_key::<Option<String>>(&key.into()) diff --git a/crates/router/src/utils/user/two_factor_auth.rs b/crates/router/src/utils/user/two_factor_auth.rs index b4ced70d735..f5395626140 100644 --- a/crates/router/src/utils/user/two_factor_auth.rs +++ b/crates/router/src/utils/user/two_factor_auth.rs @@ -33,7 +33,7 @@ pub fn generate_default_totp( } pub async fn check_totp_in_redis(state: &SessionState, user_id: &str) -> UserResult<bool> { - let redis_conn = super::get_redis_connection(state)?; + let redis_conn = super::get_redis_connection_for_global_tenant(state)?; let key = format!("{}{}", consts::user::REDIS_TOTP_PREFIX, user_id); redis_conn .exists::<()>(&key.into()) @@ -42,7 +42,7 @@ pub async fn check_totp_in_redis(state: &SessionState, user_id: &str) -> UserRes } pub async fn check_recovery_code_in_redis(state: &SessionState, user_id: &str) -> UserResult<bool> { - let redis_conn = super::get_redis_connection(state)?; + let redis_conn = super::get_redis_connection_for_global_tenant(state)?; let key = format!("{}{}", consts::user::REDIS_RECOVERY_CODE_PREFIX, user_id); redis_conn .exists::<()>(&key.into()) @@ -51,7 +51,7 @@ pub async fn check_recovery_code_in_redis(state: &SessionState, user_id: &str) - } pub async fn insert_totp_in_redis(state: &SessionState, user_id: &str) -> UserResult<()> { - let redis_conn = super::get_redis_connection(state)?; + let redis_conn = super::get_redis_connection_for_global_tenant(state)?; let key = format!("{}{}", consts::user::REDIS_TOTP_PREFIX, user_id); redis_conn .set_key_with_expiry( @@ -68,7 +68,7 @@ pub async fn insert_totp_secret_in_redis( user_id: &str, secret: &masking::Secret<String>, ) -> UserResult<()> { - let redis_conn = super::get_redis_connection(state)?; + let redis_conn = super::get_redis_connection_for_global_tenant(state)?; redis_conn .set_key_with_expiry( &get_totp_secret_key(user_id).into(), @@ -83,7 +83,7 @@ pub async fn get_totp_secret_from_redis( state: &SessionState, user_id: &str, ) -> UserResult<Option<masking::Secret<String>>> { - let redis_conn = super::get_redis_connection(state)?; + let redis_conn = super::get_redis_connection_for_global_tenant(state)?; redis_conn .get_key::<Option<String>>(&get_totp_secret_key(user_id).into()) .await @@ -92,7 +92,7 @@ pub async fn get_totp_secret_from_redis( } pub async fn delete_totp_secret_from_redis(state: &SessionState, user_id: &str) -> UserResult<()> { - let redis_conn = super::get_redis_connection(state)?; + let redis_conn = super::get_redis_connection_for_global_tenant(state)?; redis_conn .delete_key(&get_totp_secret_key(user_id).into()) .await @@ -105,7 +105,7 @@ fn get_totp_secret_key(user_id: &str) -> String { } pub async fn insert_recovery_code_in_redis(state: &SessionState, user_id: &str) -> UserResult<()> { - let redis_conn = super::get_redis_connection(state)?; + let redis_conn = super::get_redis_connection_for_global_tenant(state)?; let key = format!("{}{}", consts::user::REDIS_RECOVERY_CODE_PREFIX, user_id); redis_conn .set_key_with_expiry( @@ -118,7 +118,7 @@ pub async fn insert_recovery_code_in_redis(state: &SessionState, user_id: &str) } pub async fn delete_totp_from_redis(state: &SessionState, user_id: &str) -> UserResult<()> { - let redis_conn = super::get_redis_connection(state)?; + let redis_conn = super::get_redis_connection_for_global_tenant(state)?; let key = format!("{}{}", consts::user::REDIS_TOTP_PREFIX, user_id); redis_conn .delete_key(&key.into()) @@ -131,7 +131,7 @@ pub async fn delete_recovery_code_from_redis( state: &SessionState, user_id: &str, ) -> UserResult<()> { - let redis_conn = super::get_redis_connection(state)?; + let redis_conn = super::get_redis_connection_for_global_tenant(state)?; let key = format!("{}{}", consts::user::REDIS_RECOVERY_CODE_PREFIX, user_id); redis_conn .delete_key(&key.into()) @@ -156,7 +156,7 @@ pub async fn insert_totp_attempts_in_redis( user_id: &str, user_totp_attempts: u8, ) -> UserResult<()> { - let redis_conn = super::get_redis_connection(state)?; + let redis_conn = super::get_redis_connection_for_global_tenant(state)?; redis_conn .set_key_with_expiry( &get_totp_attempts_key(user_id).into(), @@ -167,7 +167,7 @@ pub async fn insert_totp_attempts_in_redis( .change_context(UserErrors::InternalServerError) } pub async fn get_totp_attempts_from_redis(state: &SessionState, user_id: &str) -> UserResult<u8> { - let redis_conn = super::get_redis_connection(state)?; + let redis_conn = super::get_redis_connection_for_global_tenant(state)?; redis_conn .get_key::<Option<u8>>(&get_totp_attempts_key(user_id).into()) .await @@ -180,7 +180,7 @@ pub async fn insert_recovery_code_attempts_in_redis( user_id: &str, user_recovery_code_attempts: u8, ) -> UserResult<()> { - let redis_conn = super::get_redis_connection(state)?; + let redis_conn = super::get_redis_connection_for_global_tenant(state)?; redis_conn .set_key_with_expiry( &get_recovery_code_attempts_key(user_id).into(), @@ -195,7 +195,7 @@ pub async fn get_recovery_code_attempts_from_redis( state: &SessionState, user_id: &str, ) -> UserResult<u8> { - let redis_conn = super::get_redis_connection(state)?; + let redis_conn = super::get_redis_connection_for_global_tenant(state)?; redis_conn .get_key::<Option<u8>>(&get_recovery_code_attempts_key(user_id).into()) .await @@ -207,7 +207,7 @@ pub async fn delete_totp_attempts_from_redis( state: &SessionState, user_id: &str, ) -> UserResult<()> { - let redis_conn = super::get_redis_connection(state)?; + let redis_conn = super::get_redis_connection_for_global_tenant(state)?; redis_conn .delete_key(&get_totp_attempts_key(user_id).into()) .await @@ -219,7 +219,7 @@ pub async fn delete_recovery_code_attempts_from_redis( state: &SessionState, user_id: &str, ) -> UserResult<()> { - let redis_conn = super::get_redis_connection(state)?; + let redis_conn = super::get_redis_connection_for_global_tenant(state)?; redis_conn .delete_key(&get_recovery_code_attempts_key(user_id).into()) .await
2025-04-29T10:47:52Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR updates all **user-related Redis operations** to consistently use the **global Redis key prefix** (`global:`) instead of environment-specific prefixes like `public:` (V1) or `public_v2:` (V2). Previously, different deployments used different prefixes, which caused inconsistencies especially during login, logout, switch, and caching flows. ### Changes Introduced: - Updated Redis connection fetchers for all user modules (lineage context, SSO, blacklist, etc.) to use a global Redis connection. ## Affected functions: ### `utils/user.rs` - `set_sso_id_in_redis` - `get_sso_id_from_redis` ### `utils/user/two_factor_auth.rs` - `check_totp_in_redis` - `check_recovery_code_in_redis` - `insert_totp_in_redis` - `insert_totp_secret_in_redis` - `get_totp_secret_from_redis` - `delete_totp_secret_from_redis` - `insert_recovery_code_in_redis` - `delete_totp_from_redis` - `delete_recovery_code_from_redis` - `insert_totp_attempts_in_redis` - `get_totp_attempts_from_redis` - `insert_recovery_code_attempts_in_redis` - `get_recovery_code_attempts_from_redis` - `delete_totp_attempts_from_redis` - `delete_recovery_code_attempts_from_redis` ### `services/authorization.rs` - `get_role_info_from_cache` - `set_role_info_in_cache` ### `services/openidconnect.rs` - `get_authorization_url` - `get_nonce_from_redis` ### `services/user.rs` - `insert_user_in_blacklist` - `insert_role_in_blacklist` - `invalidate_role_cache` - `check_user_in_blacklist` - `check_role_in_blacklist` - `insert_email_token_in_blacklist` - `check_email_token_in_blacklist` ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> - It helps in storing the redis keys which are common to both v1 and v2 deployments under a common prefix, so it can be used irrespective of the version of the deployment. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Used the dashboard and then signed out. <img width="520" alt="Screenshot 2025-04-29 at 3 52 37 PM" src="https://github.com/user-attachments/assets/6ea3fde2-5e1a-4afd-8855-434bfc99d7da" /> As it is evident in the screenshot, blacklist functions, and lineage context now use `global:` prefix while setting the key in redis. We need to check the redis-cli and verify that the user-related keys have the `global` prefix, instead of deployment specific keys like `public` and `public_v2`. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
b04ccafe48394fad86bf072b2e3a74626cc26550
b04ccafe48394fad86bf072b2e3a74626cc26550
juspay/hyperswitch
juspay__hyperswitch-7928
Bug: refactor(routers,connectors) : Remove unused functions in `crates/router/src/connector/utils.rs` ## Analyze and Remove Unused Functions from `crates/router/src/connector/utils.rs` ### Description: There are functions in the crates/router/src/connector/utils.rs file that appear to be unused across the router crate. For example: • validate_currency is defined in utils.rs but is not used anywhere in the codebase. This function can be safely removed. ### Task: • Perform a comprehensive analysis of all the functions present in crates/router/src/connector/utils.rs. • Identify any functions that are not referenced anywhere in the router crate which are in utils. • Remove such unused functions to reduce dead code and improve maintainability.
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index e0034a63335..addb7dd7c8c 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -21,7 +21,6 @@ use common_utils::{ use diesel_models::{enums, types::OrderDetailsWithAmount}; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ - mandates, network_tokenization::NetworkTokenNumber, payments::payment_attempt::PaymentAttempt, router_request_types::{ @@ -32,8 +31,6 @@ use hyperswitch_domain_models::{ use masking::{Deserialize, ExposeInterface, Secret}; use once_cell::sync::Lazy; use regex::Regex; -use serde::Serializer; -use time::PrimitiveDateTime; #[cfg(feature = "frm")] use crate::types::fraud_check; @@ -1932,13 +1929,6 @@ pub fn get_header_key_value<'a>( get_header_field(headers.get(key)) } -pub fn get_http_header<'a>( - key: &str, - headers: &'a http::HeaderMap, -) -> CustomResult<&'a str, errors::ConnectorError> { - get_header_field(headers.get(key)) -} - fn get_header_field( field: Option<&http::HeaderValue>, ) -> CustomResult<&str, errors::ConnectorError> { @@ -1953,23 +1943,6 @@ fn get_header_field( ))? } -pub fn to_boolean(string: String) -> bool { - let str = string.as_str(); - match str { - "true" => true, - "false" => false, - "yes" => true, - "no" => false, - _ => false, - } -} - -pub fn get_connector_meta( - connector_meta: Option<serde_json::Value>, -) -> Result<serde_json::Value, Error> { - connector_meta.ok_or_else(missing_field_err("connector_meta_data")) -} - pub fn to_connector_meta<T>(connector_meta: Option<serde_json::Value>) -> Result<T, Error> where T: serde::de::DeserializeOwned, @@ -1990,77 +1963,6 @@ where json.parse_value(std::any::type_name::<T>()).switch() } -pub fn base64_decode(data: String) -> Result<Vec<u8>, Error> { - consts::BASE64_ENGINE - .decode(data) - .change_context(errors::ConnectorError::ResponseDeserializationFailed) -} - -pub fn to_currency_base_unit_from_optional_amount( - amount: Option<i64>, - currency: enums::Currency, -) -> Result<String, error_stack::Report<errors::ConnectorError>> { - match amount { - Some(a) => to_currency_base_unit(a, currency), - _ => Err(errors::ConnectorError::MissingRequiredField { - field_name: "amount", - } - .into()), - } -} - -pub fn get_amount_as_string( - currency_unit: &api::CurrencyUnit, - amount: i64, - currency: enums::Currency, -) -> Result<String, error_stack::Report<errors::ConnectorError>> { - let amount = match currency_unit { - api::CurrencyUnit::Minor => amount.to_string(), - api::CurrencyUnit::Base => to_currency_base_unit(amount, currency)?, - }; - Ok(amount) -} - -pub fn get_amount_as_f64( - currency_unit: &api::CurrencyUnit, - amount: i64, - currency: enums::Currency, -) -> Result<f64, error_stack::Report<errors::ConnectorError>> { - let amount = match currency_unit { - api::CurrencyUnit::Base => to_currency_base_unit_asf64(amount, currency)?, - api::CurrencyUnit::Minor => u32::try_from(amount) - .change_context(errors::ConnectorError::ParsingFailed)? - .into(), - }; - Ok(amount) -} - -pub fn to_currency_base_unit( - amount: i64, - currency: enums::Currency, -) -> Result<String, error_stack::Report<errors::ConnectorError>> { - currency - .to_currency_base_unit(amount) - .change_context(errors::ConnectorError::ParsingFailed) -} - -pub fn to_currency_lower_unit( - amount: String, - currency: enums::Currency, -) -> Result<String, error_stack::Report<errors::ConnectorError>> { - currency - .to_currency_lower_unit(amount) - .change_context(errors::ConnectorError::ResponseHandlingFailed) -} - -pub fn construct_not_implemented_error_report( - capture_method: enums::CaptureMethod, - connector_name: &str, -) -> error_stack::Report<errors::ConnectorError> { - errors::ConnectorError::NotImplemented(format!("{} for {}", capture_method, connector_name)) - .into() -} - pub fn construct_not_supported_error_report( capture_method: enums::CaptureMethod, connector_name: &'static str, @@ -2072,77 +1974,6 @@ pub fn construct_not_supported_error_report( .into() } -pub fn to_currency_base_unit_with_zero_decimal_check( - amount: i64, - currency: enums::Currency, -) -> Result<String, error_stack::Report<errors::ConnectorError>> { - currency - .to_currency_base_unit_with_zero_decimal_check(amount) - .change_context(errors::ConnectorError::RequestEncodingFailed) -} - -pub fn to_currency_base_unit_asf64( - amount: i64, - currency: enums::Currency, -) -> Result<f64, error_stack::Report<errors::ConnectorError>> { - currency - .to_currency_base_unit_asf64(amount) - .change_context(errors::ConnectorError::ParsingFailed) -} - -pub fn str_to_f32<S>(value: &str, serializer: S) -> Result<S::Ok, S::Error> -where - S: Serializer, -{ - let float_value = value.parse::<f64>().map_err(|_| { - serde::ser::Error::custom("Invalid string, cannot be converted to float value") - })?; - serializer.serialize_f64(float_value) -} - -pub fn collect_values_by_removing_signature( - value: &serde_json::Value, - signature: &String, -) -> Vec<String> { - match value { - serde_json::Value::Null => vec!["null".to_owned()], - serde_json::Value::Bool(b) => vec![b.to_string()], - serde_json::Value::Number(n) => match n.as_f64() { - Some(f) => vec![format!("{f:.2}")], - None => vec![n.to_string()], - }, - serde_json::Value::String(s) => { - if signature == s { - vec![] - } else { - vec![s.clone()] - } - } - serde_json::Value::Array(arr) => arr - .iter() - .flat_map(|v| collect_values_by_removing_signature(v, signature)) - .collect(), - serde_json::Value::Object(obj) => obj - .values() - .flat_map(|v| collect_values_by_removing_signature(v, signature)) - .collect(), - } -} - -pub fn collect_and_sort_values_by_removing_signature( - value: &serde_json::Value, - signature: &String, -) -> Vec<String> { - let mut values = collect_values_by_removing_signature(value, signature); - values.sort(); - values -} - -#[inline] -pub fn get_webhook_merchant_secret_key(connector_label: &str, merchant_id: &str) -> String { - format!("whsec_verification_{connector_label}_{merchant_id}") -} - impl ForeignTryFrom<String> for UsStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { @@ -2317,71 +2148,6 @@ pub trait MultipleCaptureSyncResponse { fn get_amount_captured(&self) -> Result<Option<MinorUnit>, error_stack::Report<ParsingError>>; } -pub fn construct_captures_response_hashmap<T>( - capture_sync_response_list: Vec<T>, -) -> CustomResult<HashMap<String, types::CaptureSyncResponse>, errors::ConnectorError> -where - T: MultipleCaptureSyncResponse, -{ - let mut hashmap = HashMap::new(); - for capture_sync_response in capture_sync_response_list { - let connector_capture_id = capture_sync_response.get_connector_capture_id(); - if capture_sync_response.is_capture_response() { - hashmap.insert( - connector_capture_id.clone(), - types::CaptureSyncResponse::Success { - resource_id: ResponseId::ConnectorTransactionId(connector_capture_id), - status: capture_sync_response.get_capture_attempt_status(), - connector_response_reference_id: capture_sync_response - .get_connector_reference_id(), - amount: capture_sync_response - .get_amount_captured() - .change_context(errors::ConnectorError::AmountConversionFailed) - .attach_printable( - "failed to convert back captured response amount to minor unit", - )?, - }, - ); - } - } - - Ok(hashmap) -} - -pub fn is_manual_capture(capture_method: Option<enums::CaptureMethod>) -> bool { - capture_method == Some(enums::CaptureMethod::Manual) - || capture_method == Some(enums::CaptureMethod::ManualMultiple) -} - -pub fn generate_random_bytes(length: usize) -> Vec<u8> { - // returns random bytes of length n - let mut rng = rand::thread_rng(); - (0..length).map(|_| rand::Rng::gen(&mut rng)).collect() -} - -pub fn validate_currency( - request_currency: types::storage::enums::Currency, - merchant_config_currency: Option<types::storage::enums::Currency>, -) -> Result<(), errors::ConnectorError> { - let merchant_config_currency = - merchant_config_currency.ok_or(errors::ConnectorError::NoConnectorMetaData)?; - if request_currency != merchant_config_currency { - Err(errors::ConnectorError::NotSupported { - message: format!( - "currency {} is not supported for this merchant account", - request_currency - ), - connector: "Braintree", - })? - } - Ok(()) -} - -pub fn get_timestamp_in_milliseconds(datetime: &PrimitiveDateTime) -> i64 { - let utc_datetime = datetime.assume_utc(); - utc_datetime.unix_timestamp() * 1000 -} - #[cfg(feature = "frm")] pub trait FraudCheckSaleRequest { fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>; @@ -2993,27 +2759,6 @@ impl From<domain::payments::PaymentMethodData> for PaymentMethodDataType { } } -pub fn get_mandate_details( - setup_mandate_details: Option<&mandates::MandateData>, -) -> Result<Option<&mandates::MandateAmountData>, error_stack::Report<errors::ConnectorError>> { - setup_mandate_details - .map(|mandate_data| match &mandate_data.mandate_type { - Some(mandates::MandateDataType::SingleUse(mandate)) - | Some(mandates::MandateDataType::MultiUse(Some(mandate))) => Ok(mandate), - Some(mandates::MandateDataType::MultiUse(None)) => { - Err(errors::ConnectorError::MissingRequiredField { - field_name: "setup_future_usage.mandate_data.mandate_type.multi_use.amount", - } - .into()) - } - None => Err(errors::ConnectorError::MissingRequiredField { - field_name: "setup_future_usage.mandate_data.mandate_type", - } - .into()), - }) - .transpose() -} - pub fn convert_amount<T>( amount_convertor: &dyn AmountConvertor<Output = T>, amount: MinorUnit,
2025-05-09T09:28:34Z
crates/router/src/connector/utils.rs ## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Removed functions that are not used in other files and removed imports that are only referenced by the unused functions. [crates/router/src/connector/utils.rs](https://github.com/juspay/hyperswitch/blob/3cdb9e174ca384704781a4c56e826c3a5e39d295/crates/router/src/connector/utils.rs) ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context fix: #7928 <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Only removed unused util functions hence no testing required. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
3cdb9e174ca384704781a4c56e826c3a5e39d295
3cdb9e174ca384704781a4c56e826c3a5e39d295
juspay/hyperswitch
juspay__hyperswitch-7924
Bug: Fix: populating the docker related changes from main to stable release Some docker related changes were made in the main branch, these need to be included in the stable release too.
diff --git a/README.md b/README.md index 72ac7e0e3a7..3033263e578 100644 --- a/README.md +++ b/README.md @@ -41,8 +41,8 @@ Single API to access the payments ecosystem and its features ## Table of Contents 1. [Introduction](#introduction) -2. [Architectural Overview](#architectural-overview) -3. [Try Hyperswitch](#try-hyperswitch) +2. [Try Hyperswitch](#try-hyperswitch) +3. [Architectural Overview](#architectural-overview) 4. [Support, Feature requests & Bugs](#support-feature-requests) 5. [Our Vision](#our-vision) 6. [Versioning](#versioning) @@ -63,51 +63,37 @@ Here are the key components of Hyperswitch that deliver the whole solution: Read more at [Hyperswitch docs](https://docs.hyperswitch.io/). -<a href="#architectural-overview"> - <h2 id="architectural-overview">Architectural Overview</h2> -</a> -<img src="./docs/imgs/features.png" /> -<img src="./docs/imgs/non-functional-features.png" /> - -<img src="./docs/imgs/hyperswitch-architecture-v1.png" /> - <a href="#try-hyperswitch"> <h2 id="try-hyperswitch">Try Hyperswitch</h2> </a> ### 1. Local Setup -You can run Hyperswitch on your system using Docker compose after cloning this repository. +#### One-Click Setup (Recommended) + +You can run Hyperswitch on your system with a single command using our one-click setup script: ```shell git clone --depth 1 --branch latest https://github.com/juspay/hyperswitch cd hyperswitch -docker compose up -d +scripts/setup.sh ``` -Check out the [local setup guide][local-setup-guide] for a more details on setting up the entire stack or component wise. This takes 15-mins and gives the following output -```shell -[+] Running 2/2 -✔ hyperswitch-control-center Pulled 2.9s -✔ hyperswitch-server Pulled 3.0s -[+] Running 6/0 - -✔ Container hyperswitch-pg-1 Created 0.0s -✔ Container hyperswitch-redis-standalone-1 Created 0.0s -✔ Container hyperswitch-migration_runner-1 Created 0.0s -✔ Container hyperswitch-hyperswitch-server-1 Created 0.0s -✔ Container hyperswitch-hyperswitch-web-1 Created 0.0s -✔ Container hyperswitch-hyperswitch-control-center-1 Created 0.0s - -Attaching to hyperswitch-control-center-1, hyperswitch-server-1, hyperswitch-web-1, migration_runner-1, pg-1, redis-standalone-1 -``` -You've now setup Hyperswitch in your local machine. In order to verify that the server is up and running hit the health endpoint: -```shell -curl --head --request GET 'http://localhost:8080/health' -``` -The expected response here is a `200 OK` status code. This indicates that the server and all of its dependent services are functioning correctly. -Now, you can access the Control Center in your browser at `http://localhost:9000`. -The next step is to configure a connector with the Hyperswitch Control Center and try a payment. +The above script will: +- Check for prerequisites (Docker Compose/Podman) +- Set up necessary configurations +- Let you select a deployment profile: + - **Standard**: Recommended - App server + Control Center + Web SDK. + - **Full**: Standard + Monitoring + Scheduler. + - **Standalone App Server**: Core services only (Hyperswitch server, PostgreSQL, Redis) +- Start the selected services +- Check service health +- Provide access information + +The next step is to [configure a connector][configure-a-connector] with the Hyperswitch Control Center and [try a payment][try-a-payment]. + +Check out the [local setup guide][local-setup-guide] for more details on setting up the entire stack or component wise. + ### 2. Deployment on cloud @@ -136,6 +122,14 @@ We support deployment on GCP and Azure via Helm charts which takes 30-45mins. Yo You can experience the product by signing up for our [hosted sandbox](https://app.hyperswitch.io/). The signup process accepts any email ID and provides access to the entire Control Center. You can set up connectors, define workflows for routing and retries, and even try payments from the dashboard. +<a href="#architectural-overview"> + <h2 id="architectural-overview">Architectural Overview</h2> +</a> +<img src="./docs/imgs/features.png" /> +<img src="./docs/imgs/non-functional-features.png" /> + +<img src="./docs/imgs/hyperswitch-architecture-v1.png" /> + [docs-link-for-enterprise]: https://docs.hyperswitch.io/hyperswitch-cloud/quickstart [docs-link-for-developers]: https://docs.hyperswitch.io/hyperswitch-open-source/overview [contributing-guidelines]: docs/CONTRIBUTING.md @@ -144,7 +138,8 @@ You can experience the product by signing up for our [hosted sandbox](https://ap [learning-resources]: https://docs.hyperswitch.io/learn-more/payment-flows [local-setup-guide]: /docs/try_local_system.md [docker-compose-scheduler-monitoring]: /docs/try_local_system.md#running-additional-services - +[configure-a-connector]: https://docs.hyperswitch.io/hyperswitch-open-source/account-setup/using-hyperswitch-control-center#add-a-payment-processor +[try-a-payment]: https://docs.hyperswitch.io/hyperswitch-open-source/account-setup/test-a-payment <a href="support-feature-requests"> <h2 id="support-feature-requests">Support, Feature requests & Bugs</h2> diff --git a/docker-compose.yml b/docker-compose.yml index cb39b23b133..cc58c38e88a 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -8,6 +8,20 @@ networks: services: ### Dependencies + prestart-hook: + image: curlimages/curl-base:latest + container_name: prestart-hook + entrypoint: + [ + "/bin/sh", + "-c", + "apk add --no-cache bash && /bin/bash /prestart_hook.sh", + ] + volumes: + - ./scripts/prestart_hook.sh:/prestart_hook.sh + networks: + - router_net + pg: image: postgres:latest ports: @@ -51,7 +65,7 @@ services: environment: # format -> postgresql://DB_USER:DB_PASSWORD@HOST:PORT/DATABASE_NAME - DATABASE_URL=postgresql://db_user:db_pass@pg:5432/hyperswitch_db - + mailhog: image: mailhog/mailhog networks: @@ -86,6 +100,23 @@ services: start_period: 5s timeout: 5s + poststart-hook: + image: curlimages/curl-base:latest + container_name: poststart-hook + depends_on: + hyperswitch-server: + condition: service_healthy # Ensures it only starts when `hyperswitch-server` is healthy + entrypoint: + [ + "/bin/sh", + "-c", + "apk add --no-cache bash jq && /bin/bash /poststart_hook.sh", + ] + volumes: + - ./scripts/poststart_hook.sh:/poststart_hook.sh + networks: + - router_net + hyperswitch-producer: image: docker.juspay.io/juspaydotin/hyperswitch-producer:standalone pull_policy: always @@ -153,20 +184,13 @@ services: pull_policy: always ports: - "9050:9050" - - "9060:9060" - - "5252:5252" networks: - router_net depends_on: hyperswitch-server: condition: service_healthy environment: - - HYPERSWITCH_PUBLISHABLE_KEY=placeholder_publishable_key - - HYPERSWITCH_SECRET_KEY=placeholder_api_key - - HYPERSWITCH_SERVER_URL=http://localhost:8080 - - HYPERSWITCH_SERVER_URL_FOR_DEMO_APP=http://hyperswitch-server:8080 - - HYPERSWITCH_CLIENT_URL=http://localhost:9050 - - SELF_SERVER_URL=http://localhost:5252 + - ENABLE_LOGGING=true - SDK_ENV=local - ENV_LOGGING_URL=http://localhost:3103 - ENV_BACKEND_URL=http://localhost:8080 @@ -421,3 +445,25 @@ services: volumes: - ./config/vector.yaml:/etc/vector/vector.yaml - /var/run/docker.sock:/var/run/docker.sock + + hyperswitch-demo: + image: docker.juspay.io/juspaydotin/hyperswitch-react-demo-app:latest + pull_policy: always + ports: + - "9060:9060" + - "5252:5252" + networks: + - router_net + depends_on: + hyperswitch-server: + condition: service_healthy + hyperswitch-web: + condition: service_healthy + environment: + - HYPERSWITCH_PUBLISHABLE_KEY=placeholder_publishable_key + - HYPERSWITCH_SECRET_KEY=placeholder_api_key + - PROFILE_ID=placeholder_profile_id + - HYPERSWITCH_CLIENT_URL=http://localhost:9050 + - HYPERSWITCH_SERVER_URL=http://localhost:8080 + labels: + logs: "promtail" diff --git a/docs/one_click_setup.md b/docs/one_click_setup.md new file mode 100644 index 00000000000..4eee5009360 --- /dev/null +++ b/docs/one_click_setup.md @@ -0,0 +1,97 @@ +# One-Click Docker Setup Guide + +This document provides detailed information about the one-click setup script for Hyperswitch. + +## Overview + +The `setup.sh` script simplifies the process of setting up Hyperswitch in a local development or testing environment. It provides an interactive setup experience that handles checking prerequisites, configuring the environment, and starting the necessary services. + +## Features + +- **Prerequisite Checking**: Verifies Docker/Podman and Docker/Podman Compose installation. +- **Port Availability Check**: Ensures required ports are available to avoid conflicts. +- **Configuration Management**: Automatically sets up necessary configuration files. +- **Multiple Deployment Profiles**: Choose the right setup for your needs. +- **Health Checking**: Verifies services are running and healthy. +- **Detailed Feedback**: Provides clear output and helpful error messages. + +## Deployment Profiles + +The script offers four deployment profiles to match your needs: + +### 1. Standard (Recommended) +- **Services**: App server + Control Center + Web SDK (includes PostgreSQL, Redis) +- **Best for**: General development and testing +- **Resources required**: Medium + +### 2. Full +- **Services**: Standard + Monitoring (Grafana, Prometheus) + Scheduler +- **Best for**: Complete system testing +- **Resources required**: Higher + +### 3. Standalone App Server +- **Services**: Hyperswitch server, PostgreSQL, Redis +- **Best for**: Testing basic API functionality +- **Resources required**: Lower + + +## Troubleshooting + +### Common Issues + +1. **Docker not running** + - **Error**: "Cannot connect to the Docker/Podman daemon" + - **Solution**: Start the Docker daemon/Docker Desktop or Use Orbstack. + +2. **Port conflicts** + - **Error**: "The following ports are already in use: [port list]" + - **Solution**: Stop services using those ports or choose different ports. + +3. **Server not becoming healthy** + - **Error**: "Hyperswitch server did not become healthy in the expected time." + - **Solution**: Check logs with `docker compose logs hyperswitch-server` or `podman compose logs hyperswitch-server`. + +### Viewing Logs + +To view logs for any service: +``` +docker compose logs -f [service-name] +``` + +Common service names: +- `hyperswitch-server` +- `pg` (PostgreSQL) +- `redis-standalone` +- `hyperswitch-control-center` + +## Advanced Usage + +### Environment Variables + +You can set these environment variables before running the script: + +- `DRAINER_INSTANCE_COUNT`: Number of drainer instances (default: 1) +- `REDIS_CLUSTER_COUNT`: Number of Redis cluster nodes (default: 3) + +Example: +``` +export DRAINER_INSTANCE_COUNT=2 +./setup.sh +``` + +### Manual Service Control + +After setup, you can manually control services: + +- Stop all services: `docker/podman compose down` +- Start specific services: `docker/podman compose up -d [service-name]` +- Restart a service: `docker/podman compose restart [service-name]` + +## Next Steps + +After running the setup script: + +1. Verify the server is running: `curl --head --request GET 'http://localhost:8080/health'`. +2. Access the Control Center at `http://localhost:9000`. +3. Configure payment connectors in the Control Center. +4. Try a test payment using the demo store. diff --git a/docs/try_local_system.md b/docs/try_local_system.md index 07756463e74..24ea5b9da6c 100644 --- a/docs/try_local_system.md +++ b/docs/try_local_system.md @@ -36,7 +36,7 @@ Check the Table Of Contents to jump to the relevant section. ## Run hyperswitch using Docker Compose -1. Install [Docker Compose][docker-compose-install]. +1. Install [Docker Compose][docker-compose-install] or [Podman Compose][podman-compose-install]. 2. Clone the repository and switch to the project directory: ```shell @@ -49,83 +49,15 @@ Check the Table Of Contents to jump to the relevant section. The provided configuration should work as is. If you do update the `docker_compose.toml` file, ensure to also update the corresponding values in the [`docker-compose.yml`][docker-compose-yml] file. -4. Start all the services using Docker Compose: +4. Start all the services using below script: ```shell - docker compose up -d + scripts/setup.sh ``` - - This should run the hyperswitch app server, web client and control center. - Wait for the `migration_runner` container to finish installing `diesel_cli` - and running migrations (approximately 2 minutes), and for the - `hyperswitch-web` container to finish compiling before proceeding further. - You can also choose to - [run the scheduler and monitoring services](#running-additional-services) - in addition to the app server, web client and control center. - -5. Verify that the server is up and running by hitting the health endpoint: - - ```shell - curl --head --request GET 'http://localhost:8080/health' - ``` - - If the command returned a `200 OK` status code, proceed with - [trying out our APIs](#try-out-our-apis). - -### Running additional services - -The default behaviour for docker compose only runs the following services: - -1. postgres -2. redis (standalone) -3. hyperswitch server -4. hyperswitch control center -5. hyperswitch web sdk - -You can run the scheduler, data and monitoring services by specifying suitable profile -names to the above Docker Compose command. -To understand more about the hyperswitch architecture and the components -involved, check out the [architecture document][architecture]. - -- To run the scheduler components (consumer and producer), you can specify - `--profile scheduler`: - - ```shell - docker compose --profile scheduler up -d - ``` - -- To run the monitoring services (Grafana, Promtail, Loki, Prometheus and Tempo), - you can specify `--profile monitoring`: - - ```shell - docker compose --profile monitoring up -d - ``` - - You can then access Grafana at `http://localhost:3000` and view application - logs using the "Explore" tab, select Loki as the data source, and select the - container to query logs from. - -- To run the data services (Clickhouse, Kafka and Opensearch) you can specify the `olap` profile - - ```shell - docker compose --profile olap up -d - ``` - - You can read more about using the data services [here][data-docs] - -- You can also specify multiple profile names by specifying the `--profile` flag - multiple times. - To run both the scheduler components and monitoring services, the Docker - Compose command would be: - - ```shell - docker compose --profile scheduler --profile monitoring up -d - ``` - -Once the services have been confirmed to be up and running, you can proceed with -[trying out our APIs](#try-out-our-apis) + You will get prompts to select your preferred setup option. [docker-compose-install]: https://docs.docker.com/compose/install/ +[podman-compose-install]: https://podman.io/docs/installation [docker-compose-config]: /config/docker_compose.toml [docker-compose-yml]: /docker-compose.yml [architecture]: /docs/architecture.md @@ -154,8 +86,8 @@ Once the services have been confirmed to be up and running, you can proceed with This will compile the payments router, the primary component within hyperswitch and then start it. - Depending on the specifications of your machine, compilation can take - around 15 minutes. + Depending on the specifications of your machine, **compilation can take + around 30 minutes**. 5. (Optional) You can also choose to [start the scheduler and/or monitoring services](#running-additional-services) diff --git a/scripts/docker_output.sh b/scripts/docker_output.sh new file mode 100755 index 00000000000..80d178ca75b --- /dev/null +++ b/scripts/docker_output.sh @@ -0,0 +1,33 @@ +#! /usr/bin/env bash +set -euo pipefail + +# Define the URL to check service availability (adjust HOST and PORT if needed) +HOST="localhost" +PORT="8080" +SERVICE_URL="http://${HOST}:${PORT}/health" + +MAX_RETRIES=70 +RETRY_COUNT=0 + +# Wait until the service is available or retries are exhausted +while ! curl --silent --fail "${SERVICE_URL}" > /dev/null; do + if (( RETRY_COUNT >= MAX_RETRIES )); then + echo "" + echo "Service failed to start. Kindly check the logs." + echo "You can view the logs using the command: docker-compose logs -f <service name>" + exit 1 + fi + printf "." + sleep 2 + ((RETRY_COUNT++)) +done + +# Define ANSI 24-bit (true color) escape sequences for Light Sky Blue +LIGHT_SKY_BLUE="\033[38;2;135;206;250m" +RESET="\033[0m" + +# Print the service URLs with only the links colored +echo -e "Control Centre running at ${LIGHT_SKY_BLUE}http://localhost:9000${RESET}" +echo -e "App server running at ${LIGHT_SKY_BLUE}http://localhost:8080${RESET}" +echo -e "Web-SDK running at ${LIGHT_SKY_BLUE}http://localhost:5252/HyperLoader.js${RESET}" +echo -e "Mailhog running at ${LIGHT_SKY_BLUE}http://localhost:8025${RESET}" \ No newline at end of file diff --git a/scripts/poststart_hook.sh b/scripts/poststart_hook.sh new file mode 100755 index 00000000000..dcd06aa02bc --- /dev/null +++ b/scripts/poststart_hook.sh @@ -0,0 +1,65 @@ +#! /usr/bin/env bash +set -euo pipefail + +# Configuration +PLATFORM="docker-compose" # Change to "helm" or "cdk" as needed +VERSION="unknown" +STATUS="" +SERVER_BASE_URL="http://hyperswitch-server:8080" +HYPERSWITCH_HEALTH_URL="${SERVER_BASE_URL}/health" +HYPERSWITCH_DEEP_HEALTH_URL="${SERVER_BASE_URL}/health/ready" +WEBHOOK_URL="https://hyperswitch.gateway.scarf.sh/${PLATFORM}" + +# Fetch health status +echo "Fetching app server health status..." +HEALTH_RESPONSE=$(curl --silent --fail "${HYPERSWITCH_HEALTH_URL}") || HEALTH_RESPONSE="connection_error" + +if [[ "${HEALTH_RESPONSE}" == "connection_error" ]]; then + STATUS="error" + ERROR_MESSAGE="404 response" + + curl --get "${WEBHOOK_URL}" \ + --data-urlencode "version=${VERSION}" \ + --data-urlencode "status=${STATUS}" \ + --data-urlencode "error_message=${ERROR_MESSAGE}" + + echo "Webhook sent with connection error." + exit 0 +fi + +# Fetch Hyperswitch version +VERSION=$(curl --silent --output /dev/null --request GET --write-out '%header{x-hyperswitch-version}' "${HYPERSWITCH_DEEP_HEALTH_URL}" | sed 's/-dirty$//') + +echo "Fetching Hyperswitch health status..." +HEALTH_RESPONSE=$(curl --silent "${HYPERSWITCH_DEEP_HEALTH_URL}") + +# Prepare curl command +CURL_COMMAND=("curl" "--get" "${WEBHOOK_URL}" "--data-urlencode" "version=${VERSION}") + +# Check if the response contains an error +if [[ "$(echo "${HEALTH_RESPONSE}" | jq --raw-output '.error')" != 'null' ]]; then + STATUS="error" + ERROR_TYPE=$(echo "${HEALTH_RESPONSE}" | jq --raw-output '.error.type') + ERROR_MESSAGE=$(echo "${HEALTH_RESPONSE}" | jq --raw-output '.error.message') + ERROR_CODE=$(echo "${HEALTH_RESPONSE}" | jq --raw-output '.error.code') + + CURL_COMMAND+=( + "--data-urlencode" "status=${STATUS}" + "--data-urlencode" "error_type=${ERROR_TYPE}" + "--data-urlencode" "error_message=${ERROR_MESSAGE}" + "--data-urlencode" "error_code=${ERROR_CODE}" + ) +else + STATUS="success" + CURL_COMMAND+=("--data-urlencode" "status=${STATUS}") + + for key in $(echo "${HEALTH_RESPONSE}" | jq --raw-output 'keys_unsorted[]'); do + value=$(echo "${HEALTH_RESPONSE}" | jq --raw-output --arg key "${key}" '.[$key]') + CURL_COMMAND+=("--data-urlencode" "'${key}=${value}'") + done +fi + +# Send the webhook request +bash -c "${CURL_COMMAND[*]}" + +echo "Webhook notification sent." diff --git a/scripts/prestart_hook.sh b/scripts/prestart_hook.sh new file mode 100755 index 00000000000..c4eb16efd8c --- /dev/null +++ b/scripts/prestart_hook.sh @@ -0,0 +1,14 @@ +#! /usr/bin/env bash +set -euo pipefail + +# Define the URL and parameters +PLATFORM="docker-compose" +WEBHOOK_URL="https://hyperswitch.gateway.scarf.sh/${PLATFORM}" +VERSION="unknown" +STATUS="initiated" + +# Send the GET request +curl --get "${WEBHOOK_URL}" --data-urlencode "version=${VERSION}" --data-urlencode "status=${STATUS}" + +# Print confirmation +echo "Request sent to ${WEBHOOK_URL} with version=${VERSION} and status=${STATUS}" diff --git a/scripts/setup.sh b/scripts/setup.sh new file mode 100755 index 00000000000..c40c5365c90 --- /dev/null +++ b/scripts/setup.sh @@ -0,0 +1,241 @@ +#! /usr/bin/env bash +set -euo pipefail + +# ANSI color codes for pretty output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[0;33m' +BLUE='\033[0;34m' +BOLD='\033[1m' +NC='\033[0m' # No Color + +# Alias for docker to use podman +alias docker=podman + +# Function to print colorful messages +echo_info() { + echo -e "${BLUE}[INFO]${NC} $1" +} + +echo_success() { + echo -e "${GREEN}[SUCCESS]${NC} $1" +} + +echo_warning() { + echo -e "${YELLOW}[WARNING]${NC} $1" +} + +echo_error() { + echo -e "${RED}[ERROR]${NC} $1" +} + +show_banner() { + echo -e "${BLUE}${BOLD}" + echo "" + echo " # " + echo " # # # #### ##### ## # # " + echo " # # # # # # # # # # " + echo " # # # #### # # # # # " + echo " # # # # # ##### ###### # " + echo " # # # # # # # # # # " + echo " ##### #### #### # # # # " + echo "" + echo "" + echo " # # # # ##### ###### ##### #### # # # ##### #### # # " + echo " # # # # # # # # # # # # # # # # # # " + echo " # # # # # ##### # # #### # # # # # ###### " + echo " ####### # ##### # ##### # # ## # # # # # # " + echo " # # # # # # # # # ## ## # # # # # # " + echo " # # # # ###### # # #### # # # # #### # # " + echo "" + sleep 1 + echo -e "${NC}" + echo -e "🚀 ${BLUE}One-Click Docker Setup${NC} 🚀" + echo +} + +# Detect Docker Compose version +detect_docker_compose() { + # Check Docker or Podman + if command -v docker &> /dev/null; then + CONTAINER_ENGINE="docker" + echo_success "Docker is installed." + elif command -v podman &> /dev/null; then + CONTAINER_ENGINE="podman" + echo_success "Podman is installed." + else + echo_error "Neither Docker nor Podman is installed. Please install one of them to proceed." + echo_info "Visit https://docs.docker.com/get-docker/ or https://podman.io/docs/installation for installation instructions." + echo_info "After installation, re-run this script: scripts/setup.sh" + exit 1 + fi + + # Check Docker Compose or Podman Compose + if $CONTAINER_ENGINE compose version &> /dev/null; then + DOCKER_COMPOSE="$CONTAINER_ENGINE compose" + echo_success "Compose is installed for $CONTAINER_ENGINE." + else + echo_error "Compose is not installed for $CONTAINER_ENGINE. Please install $CONTAINER_ENGINE compose to proceed." + if [ "$CONTAINER_ENGINE" = "docker" ]; then + echo_info "Visit https://docs.docker.com/compose/install/ for installation instructions." + elif [ "$CONTAINER_ENGINE" = "podman" ]; then + echo_info "Visit https://podman-desktop.io/docs/compose/setting-up-compose for installation instructions." + fi + echo_info "After installation, re-run this script: scripts/setup.sh" + exit 1 + fi +} + +check_prerequisites() { + # Check curl + if ! command -v curl &> /dev/null; then + echo_error "curl is not installed. Please install curl to proceed." + exit 1 + fi + echo_success "curl is installed." + + # Check ports + required_ports=(8080 9000 9050 5432 6379 9060) + unavailable_ports=() + + for port in "${required_ports[@]}"; do + if command -v nc &> /dev/null; then + if nc -z localhost "$port" 2>/dev/null; then + unavailable_ports+=("$port") + fi + elif command -v lsof &> /dev/null; then + if lsof -i :"$port" &> /dev/null; then + unavailable_ports+=("$port") + fi + else + echo_warning "Neither nc nor lsof available to check ports. Skipping port check." + break + fi + done + + if [ ${#unavailable_ports[@]} -ne 0 ]; then + echo_warning "The following ports are already in use: ${unavailable_ports[*]}" + echo_warning "This might cause conflicts with Hyperswitch services." + read -p "Do you want to continue anyway? (y/n): " -n 1 -r + echo + if [[ ! $REPLY =~ ^[Yy]$ ]]; then + exit 1 + fi + else + echo_success "All required ports are available." + fi +} + +setup_config() { + if [ ! -f "config/docker_compose.toml" ]; then + echo_error "Configuration file 'config/docker_compose.toml' not found. Please ensure the file exists and is correctly configured." + exit 1 + fi +} + +select_profile() { + echo "" + echo "Select a setup option:" + echo -e "1) Standard Setup: ${BLUE}[Recommended]${NC} Ideal for quick trial. Services included: ${BLUE}App Server, Control Center, Unified Checkout, PostgreSQL and Redis${NC}" + echo -e "2) Full Stack Setup: Ideal for comprehensive end-to-end payment testing. Services included: ${BLUE}Everything in Standard, Monitoring and Scheduler${NC}" + echo -e "3) Standalone App Server: Ideal for API-first integration testing. Services included: ${BLUE}App server, PostgreSQL and Redis)${NC}" + echo "" + local profile_selected=false + while [ "$profile_selected" = false ]; do + read -p "Enter your choice (1-3): " profile_choice + profile_choice=${profile_choice:-1} + + case $profile_choice in + 1) + PROFILE="standard" + profile_selected=true + ;; + 2) + PROFILE="full" + profile_selected=true + ;; + 3) + PROFILE="standalone" + profile_selected=true + ;; + *) + echo_error "Invalid choice. Please enter 1, 2, or 3." + ;; + esac + done + + echo "Selected setup: $PROFILE" +} + +start_services() { + + case $PROFILE in + standalone) + $DOCKER_COMPOSE up -d pg redis-standalone migration_runner hyperswitch-server + ;; + standard) + $DOCKER_COMPOSE up -d + ;; + full) + $DOCKER_COMPOSE --profile scheduler --profile monitoring --profile olap up -d + ;; + esac +} + +check_services_health() { + # Wait for the hyperswitch-server to be healthy + MAX_RETRIES=30 + RETRY_INTERVAL=5 + RETRIES=0 + + while [ $RETRIES -lt $MAX_RETRIES ]; do + if curl --silent --head --request GET 'http://localhost:8080/health' | grep "200 OK" > /dev/null; then + echo_success "Hyperswitch server is healthy!" + print_access_info # Call print_access_info only when the server is healthy + return + fi + + RETRIES=$((RETRIES+1)) + if [ $RETRIES -eq $MAX_RETRIES ]; then + echo "" + echo_error "${RED}${BOLD}Hyperswitch server did not become healthy in the expected time." + echo -e "Check logs with: $DOCKER_COMPOSE logs hyperswitch-server, Or reach out to us on slack(https://hyperswitch-io.slack.com/) for help." + echo -e "The setup process will continue, but some services might not work correctly.${NC}" + echo "" + else + echo "Waiting for server to become healthy... ($RETRIES/$MAX_RETRIES)" + sleep $RETRY_INTERVAL + fi + done +} + +print_access_info() { + echo "" + echo -e "${GREEN}${BOLD}Setup complete! You can access Hyperswitch services at:${NC}" + echo "" + + if [ "$PROFILE" != "standalone" ]; then + echo -e " • ${GREEN}${BOLD}Control Center${NC}: ${BLUE}${BOLD}http://localhost:9000${NC}" + fi + + echo -e " • ${GREEN}${BOLD}App Server${NC}: ${BLUE}${BOLD}http://localhost:8080${NC}" + + if [ "$PROFILE" != "standalone" ]; then + echo -e " • ${GREEN}${BOLD}Unified Checkout${NC}: ${BLUE}${BOLD}http://localhost:9060${NC}" + fi + + if [ "$PROFILE" = "full" ]; then + echo -e " • ${GREEN}${BOLD}Monitoring (Grafana)${NC}: ${BLUE}${BOLD}http://localhost:3000${NC}" + fi + echo "" + echo_info "To stop all services, run: $DOCKER_COMPOSE down" +} + +# Main execution flow +show_banner +detect_docker_compose +check_prerequisites +setup_config +select_profile +start_services +check_services_health # This will call print_access_info if the server is healthy
2025-04-24T13:02:22Z
This PR contains the docker compose file changes for stable release. The PRs included in this file are - https://github.com/juspay/hyperswitch/pull/7762 - https://github.com/juspay/hyperswitch/pull/7839 - https://github.com/juspay/hyperswitch/pull/7841 - https://github.com/juspay/hyperswitch/pull/7653
v1.113.0
a387bd4711a12c826f8ac0f66df17336778720c5
a387bd4711a12c826f8ac0f66df17336778720c5
juspay/hyperswitch
juspay__hyperswitch-7933
Bug: Persist Last Used Lineage Context in Database Instead of Redis Currently, the **last used lineage context** (org_id, merchant_id, profile_id, role_id, tenant_id) is cached temporarily in Redis with a 7-day TTL. While this improves user experience across sessions, it introduces problems like: - Redis is volatile — lineage context is lost if redis crashes - Users switching between v1/v2 deployments have inconsistent Redis prefixes, leading to stale context (this has been fixed) - Adds unnecessary dependency on Redis for critical authentication flow. ## Objectives: - Move the lineage context storage from Redis to the database (preferably to the users table as a new column). - Ensure lineage context is persistently stored and updated in DB. ## Tasks: - [x] Add a new nullable last_used_lineage_context (JSON/JSONB) column to the users table. - [x] Modify lineage context get and set helpers to use the DB instead of Redis.
diff --git a/crates/api_models/src/user/theme.rs b/crates/api_models/src/user/theme.rs index 29b6a5d81b9..0616a5aa220 100644 --- a/crates/api_models/src/user/theme.rs +++ b/crates/api_models/src/user/theme.rs @@ -2,7 +2,7 @@ use actix_multipart::form::{bytes::Bytes, text::Text, MultipartForm}; use common_enums::EntityType; use common_utils::{ id_type, - types::theme::{EmailThemeConfig, ThemeLineage}, + types::user::{EmailThemeConfig, ThemeLineage}, }; use masking::Secret; use serde::{Deserialize, Serialize}; diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs index ab61cf6cca1..55dcc4e5bd2 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -3,8 +3,8 @@ pub mod keymanager; /// Enum for Authentication Level pub mod authentication; -/// Enum for Theme Lineage -pub mod theme; +/// User related types +pub mod user; /// types that are wrappers around primitive types pub mod primitive_wrappers; diff --git a/crates/common_utils/src/types/user.rs b/crates/common_utils/src/types/user.rs new file mode 100644 index 00000000000..e00f07309d1 --- /dev/null +++ b/crates/common_utils/src/types/user.rs @@ -0,0 +1,9 @@ +/// User related types +pub mod core; + +/// Theme related types +pub mod theme; + +pub use core::*; + +pub use theme::*; diff --git a/crates/common_utils/src/types/user/core.rs b/crates/common_utils/src/types/user/core.rs new file mode 100644 index 00000000000..6bdecb1283b --- /dev/null +++ b/crates/common_utils/src/types/user/core.rs @@ -0,0 +1,28 @@ +use diesel::{deserialize::FromSqlRow, expression::AsExpression}; + +use crate::id_type; + +/// Struct for lineageContext +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, AsExpression, FromSqlRow)] +#[diesel(sql_type = diesel::sql_types::Jsonb)] +pub struct LineageContext { + /// user_id: String + pub user_id: String, + + /// merchant_id: MerchantId + pub merchant_id: id_type::MerchantId, + + /// role_id: String + pub role_id: String, + + /// org_id: OrganizationId + pub org_id: id_type::OrganizationId, + + /// profile_id: ProfileId + pub profile_id: id_type::ProfileId, + + /// tenant_id: TenantId + pub tenant_id: id_type::TenantId, +} + +crate::impl_to_sql_from_sql_json!(LineageContext); diff --git a/crates/common_utils/src/types/theme.rs b/crates/common_utils/src/types/user/theme.rs similarity index 100% rename from crates/common_utils/src/types/theme.rs rename to crates/common_utils/src/types/user/theme.rs diff --git a/crates/diesel_models/src/query/user/theme.rs b/crates/diesel_models/src/query/user/theme.rs index 945ce1a9bb2..e8fcf135770 100644 --- a/crates/diesel_models/src/query/user/theme.rs +++ b/crates/diesel_models/src/query/user/theme.rs @@ -1,5 +1,5 @@ use async_bb8_diesel::AsyncRunQueryDsl; -use common_utils::types::theme::ThemeLineage; +use common_utils::types::user::ThemeLineage; use diesel::{ associations::HasTable, debug_query, diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 46a36bab8c9..6f978a7afec 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -1551,6 +1551,7 @@ diesel::table! { totp_secret -> Nullable<Bytea>, totp_recovery_codes -> Nullable<Array<Nullable<Text>>>, last_password_modified_at -> Nullable<Timestamp>, + lineage_context -> Nullable<Jsonb>, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 5349ccf728c..caef78cf79a 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -1483,6 +1483,7 @@ diesel::table! { totp_secret -> Nullable<Bytea>, totp_recovery_codes -> Nullable<Array<Nullable<Text>>>, last_password_modified_at -> Nullable<Timestamp>, + lineage_context -> Nullable<Jsonb>, } } diff --git a/crates/diesel_models/src/user.rs b/crates/diesel_models/src/user.rs index cf584c09b12..a05e9768c09 100644 --- a/crates/diesel_models/src/user.rs +++ b/crates/diesel_models/src/user.rs @@ -1,4 +1,4 @@ -use common_utils::{encryption::Encryption, pii}; +use common_utils::{encryption::Encryption, pii, types::user::LineageContext}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::Secret; use time::PrimitiveDateTime; @@ -24,6 +24,7 @@ pub struct User { #[diesel(deserialize_as = OptionalDieselArray<Secret<String>>)] pub totp_recovery_codes: Option<Vec<Secret<String>>>, pub last_password_modified_at: Option<PrimitiveDateTime>, + pub lineage_context: Option<LineageContext>, } #[derive( @@ -42,6 +43,7 @@ pub struct UserNew { pub totp_secret: Option<Encryption>, pub totp_recovery_codes: Option<Vec<Secret<String>>>, pub last_password_modified_at: Option<PrimitiveDateTime>, + pub lineage_context: Option<LineageContext>, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] @@ -55,6 +57,7 @@ pub struct UserUpdateInternal { totp_secret: Option<Encryption>, totp_recovery_codes: Option<Vec<Secret<String>>>, last_password_modified_at: Option<PrimitiveDateTime>, + lineage_context: Option<LineageContext>, } #[derive(Debug)] @@ -72,6 +75,9 @@ pub enum UserUpdate { PasswordUpdate { password: Secret<String>, }, + LineageContextUpdate { + lineage_context: LineageContext, + }, } impl From<UserUpdate> for UserUpdateInternal { @@ -87,6 +93,7 @@ impl From<UserUpdate> for UserUpdateInternal { totp_secret: None, totp_recovery_codes: None, last_password_modified_at: None, + lineage_context: None, }, UserUpdate::AccountUpdate { name, is_verified } => Self { name, @@ -97,6 +104,7 @@ impl From<UserUpdate> for UserUpdateInternal { totp_secret: None, totp_recovery_codes: None, last_password_modified_at: None, + lineage_context: None, }, UserUpdate::TotpUpdate { totp_status, @@ -111,6 +119,7 @@ impl From<UserUpdate> for UserUpdateInternal { totp_secret, totp_recovery_codes, last_password_modified_at: None, + lineage_context: None, }, UserUpdate::PasswordUpdate { password } => Self { name: None, @@ -121,6 +130,18 @@ impl From<UserUpdate> for UserUpdateInternal { totp_status: None, totp_secret: None, totp_recovery_codes: None, + lineage_context: None, + }, + UserUpdate::LineageContextUpdate { lineage_context } => Self { + name: None, + password: None, + is_verified: None, + last_modified_at, + last_password_modified_at: None, + totp_status: None, + totp_secret: None, + totp_recovery_codes: None, + lineage_context: Some(lineage_context), }, } } diff --git a/crates/diesel_models/src/user/theme.rs b/crates/diesel_models/src/user/theme.rs index 46cc90a45ec..fad45995649 100644 --- a/crates/diesel_models/src/user/theme.rs +++ b/crates/diesel_models/src/user/theme.rs @@ -1,7 +1,7 @@ use common_enums::EntityType; use common_utils::{ date_time, id_type, - types::theme::{EmailThemeConfig, ThemeLineage}, + types::user::{EmailThemeConfig, ThemeLineage}, }; use diesel::{Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 10a72c4e82d..b0fd269bf79 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -7,7 +7,7 @@ use std::{ #[cfg(feature = "olap")] use analytics::{opensearch::OpenSearchConfig, ReportConfig}; use api_models::enums; -use common_utils::{ext_traits::ConfigExt, id_type, types::theme::EmailThemeConfig}; +use common_utils::{ext_traits::ConfigExt, id_type, types::user::EmailThemeConfig}; use config::{Environment, File}; use error_stack::ResultExt; #[cfg(feature = "email")] diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs index 649b8820859..4f681cda25b 100644 --- a/crates/router/src/consts/user.rs +++ b/crates/router/src/consts/user.rs @@ -41,6 +41,3 @@ pub const REDIS_SSO_TTL: i64 = 5 * 60; // 5 minutes pub const DEFAULT_PROFILE_NAME: &str = "default"; pub const DEFAULT_PRODUCT_TYPE: common_enums::MerchantProductType = common_enums::MerchantProductType::Orchestration; - -pub const LINEAGE_CONTEXT_TIME_EXPIRY_IN_SECS: i64 = 60 * 60 * 24 * 7; // 7 days -pub const LINEAGE_CONTEXT_PREFIX: &str = "LINEAGE_CONTEXT_"; diff --git a/crates/router/src/core/recon.rs b/crates/router/src/core/recon.rs index 3b2aacd4514..17e86dc41ca 100644 --- a/crates/router/src/core/recon.rs +++ b/crates/router/src/core/recon.rs @@ -1,6 +1,6 @@ use api_models::recon as recon_api; #[cfg(feature = "email")] -use common_utils::{ext_traits::AsyncExt, types::theme::ThemeLineage}; +use common_utils::{ext_traits::AsyncExt, types::user::ThemeLineage}; use error_stack::ResultExt; #[cfg(feature = "email")] use masking::{ExposeInterface, PeekInterface, Secret}; diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index ff90ca1dfac..9802edfd346 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -8,7 +8,10 @@ use api_models::{ user::{self as user_api, InviteMultipleUserResponse, NameIdUnit}, }; use common_enums::{EntityType, UserAuthType}; -use common_utils::{type_name, types::keymanager::Identifier}; +use common_utils::{ + type_name, + types::{keymanager::Identifier, user::LineageContext}, +}; #[cfg(feature = "email")] use diesel_models::user_role::UserRoleUpdate; use diesel_models::{ @@ -3237,7 +3240,7 @@ pub async fn switch_org_for_user( } }; - let lineage_context = domain::LineageContext { + let lineage_context = LineageContext { user_id: user_from_token.user_id.clone(), merchant_id: merchant_id.clone(), role_id: role_id.clone(), @@ -3250,9 +3253,11 @@ pub async fn switch_org_for_user( .clone(), }; - lineage_context - .try_set_lineage_context_in_cache(&state, user_from_token.user_id.as_str()) - .await; + utils::user::spawn_async_lineage_context_update_to_db( + &state, + &user_from_token.user_id, + lineage_context, + ); let token = utils::user::generate_jwt_auth_token_with_attributes( &state, @@ -3449,7 +3454,7 @@ pub async fn switch_merchant_for_user_in_org( } }; - let lineage_context = domain::LineageContext { + let lineage_context = LineageContext { user_id: user_from_token.user_id.clone(), merchant_id: merchant_id.clone(), role_id: role_id.clone(), @@ -3462,9 +3467,11 @@ pub async fn switch_merchant_for_user_in_org( .clone(), }; - lineage_context - .try_set_lineage_context_in_cache(&state, user_from_token.user_id.as_str()) - .await; + utils::user::spawn_async_lineage_context_update_to_db( + &state, + &user_from_token.user_id, + lineage_context, + ); let token = utils::user::generate_jwt_auth_token_with_attributes( &state, @@ -3582,7 +3589,7 @@ pub async fn switch_profile_for_user_in_org_and_merchant( } }; - let lineage_context = domain::LineageContext { + let lineage_context = LineageContext { user_id: user_from_token.user_id.clone(), merchant_id: user_from_token.merchant_id.clone(), role_id: role_id.clone(), @@ -3595,9 +3602,11 @@ pub async fn switch_profile_for_user_in_org_and_merchant( .clone(), }; - lineage_context - .try_set_lineage_context_in_cache(&state, user_from_token.user_id.as_str()) - .await; + utils::user::spawn_async_lineage_context_update_to_db( + &state, + &user_from_token.user_id, + lineage_context, + ); let token = utils::user::generate_jwt_auth_token_with_attributes( &state, diff --git a/crates/router/src/core/user/theme.rs b/crates/router/src/core/user/theme.rs index 2a896b7158f..d5c9e653066 100644 --- a/crates/router/src/core/user/theme.rs +++ b/crates/router/src/core/user/theme.rs @@ -1,7 +1,7 @@ use api_models::user::theme as theme_api; use common_utils::{ ext_traits::{ByteSliceExt, Encode}, - types::theme::ThemeLineage, + types::user::ThemeLineage, }; use diesel_models::user::theme::ThemeNew; use error_stack::ResultExt; diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index be903ef3bcc..1ef8178580b 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -5,7 +5,7 @@ use common_enums::enums::MerchantStorageScheme; use common_utils::{ errors::CustomResult, id_type, - types::{keymanager::KeyManagerState, theme::ThemeLineage}, + types::{keymanager::KeyManagerState, user::ThemeLineage}, }; #[cfg(feature = "v2")] use diesel_models::ephemeral_key::{ClientSecretType, ClientSecretTypeNew}; diff --git a/crates/router/src/db/user.rs b/crates/router/src/db/user.rs index 089c9fc6eb7..008c1f721d0 100644 --- a/crates/router/src/db/user.rs +++ b/crates/router/src/db/user.rs @@ -163,6 +163,7 @@ impl UserInterface for MockDb { totp_secret: user_data.totp_secret, totp_recovery_codes: user_data.totp_recovery_codes, last_password_modified_at: user_data.last_password_modified_at, + lineage_context: user_data.lineage_context, }; users.push(user.clone()); Ok(user) @@ -208,17 +209,20 @@ impl UserInterface for MockDb { update_user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError> { let mut users = self.users.lock().await; + let last_modified_at = common_utils::date_time::now(); users .iter_mut() .find(|user| user.user_id == user_id) .map(|user| { *user = match &update_user { storage::UserUpdate::VerifyUser => storage::User { + last_modified_at, is_verified: true, ..user.to_owned() }, storage::UserUpdate::AccountUpdate { name, is_verified } => storage::User { name: name.clone().map(Secret::new).unwrap_or(user.name.clone()), + last_modified_at, is_verified: is_verified.unwrap_or(user.is_verified), ..user.to_owned() }, @@ -227,6 +231,7 @@ impl UserInterface for MockDb { totp_secret, totp_recovery_codes, } => storage::User { + last_modified_at, totp_status: totp_status.unwrap_or(user.totp_status), totp_secret: totp_secret.clone().or(user.totp_secret.clone()), totp_recovery_codes: totp_recovery_codes @@ -239,6 +244,13 @@ impl UserInterface for MockDb { last_password_modified_at: Some(common_utils::date_time::now()), ..user.to_owned() }, + storage::UserUpdate::LineageContextUpdate { lineage_context } => { + storage::User { + last_modified_at, + lineage_context: Some(lineage_context.clone()), + ..user.to_owned() + } + } }; user.to_owned() }) @@ -256,17 +268,20 @@ impl UserInterface for MockDb { update_user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError> { let mut users = self.users.lock().await; + let last_modified_at = common_utils::date_time::now(); users .iter_mut() .find(|user| user.email.eq(user_email.get_inner())) .map(|user| { *user = match &update_user { storage::UserUpdate::VerifyUser => storage::User { + last_modified_at, is_verified: true, ..user.to_owned() }, storage::UserUpdate::AccountUpdate { name, is_verified } => storage::User { name: name.clone().map(Secret::new).unwrap_or(user.name.clone()), + last_modified_at, is_verified: is_verified.unwrap_or(user.is_verified), ..user.to_owned() }, @@ -275,6 +290,7 @@ impl UserInterface for MockDb { totp_secret, totp_recovery_codes, } => storage::User { + last_modified_at, totp_status: totp_status.unwrap_or(user.totp_status), totp_secret: totp_secret.clone().or(user.totp_secret.clone()), totp_recovery_codes: totp_recovery_codes @@ -287,6 +303,13 @@ impl UserInterface for MockDb { last_password_modified_at: Some(common_utils::date_time::now()), ..user.to_owned() }, + storage::UserUpdate::LineageContextUpdate { lineage_context } => { + storage::User { + last_modified_at, + lineage_context: Some(lineage_context.clone()), + ..user.to_owned() + } + } }; user.to_owned() }) diff --git a/crates/router/src/db/user/theme.rs b/crates/router/src/db/user/theme.rs index 51c0a52b3a0..4202b69d99d 100644 --- a/crates/router/src/db/user/theme.rs +++ b/crates/router/src/db/user/theme.rs @@ -1,4 +1,4 @@ -use common_utils::types::theme::ThemeLineage; +use common_utils::types::user::ThemeLineage; use diesel_models::user::theme as storage; use error_stack::report; diff --git a/crates/router/src/routes/user/theme.rs b/crates/router/src/routes/user/theme.rs index 69a8e9a5378..6f6926dadc3 100644 --- a/crates/router/src/routes/user/theme.rs +++ b/crates/router/src/routes/user/theme.rs @@ -1,7 +1,7 @@ use actix_multipart::form::MultipartForm; use actix_web::{web, HttpRequest, HttpResponse}; use api_models::user::theme as theme_api; -use common_utils::types::theme::ThemeLineage; +use common_utils::types::user::ThemeLineage; use masking::Secret; use router_env::Flow; diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs index d663f72cec7..0328ea988d4 100644 --- a/crates/router/src/services/email/types.rs +++ b/crates/router/src/services/email/types.rs @@ -1,6 +1,6 @@ use api_models::user::dashboard_metadata::ProdIntent; use common_enums::{EntityType, MerchantProductType}; -use common_utils::{errors::CustomResult, pii, types::theme::EmailThemeConfig}; +use common_utils::{errors::CustomResult, pii, types::user::EmailThemeConfig}; use error_stack::ResultExt; use external_services::email::{EmailContents, EmailData, EmailError}; use masking::{ExposeInterface, Secret}; diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index ca48d424d2a..45eb094053a 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -23,7 +23,6 @@ use hyperswitch_domain_models::api::ApplicationResponse; use masking::{ExposeInterface, PeekInterface, Secret}; use once_cell::sync::Lazy; use rand::distributions::{Alphanumeric, DistString}; -use router_env::logger; use time::PrimitiveDateTime; use unicode_segmentation::UnicodeSegmentation; #[cfg(feature = "keymanager_create")] @@ -925,6 +924,7 @@ impl TryFrom<NewUser> for storage_user::UserNew { last_password_modified_at: value .password .and_then(|password_inner| password_inner.is_temporary.not().then_some(now)), + lineage_context: None, }) } } @@ -1499,54 +1499,3 @@ where .change_context(UserErrors::InternalServerError) } } - -#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] -pub struct LineageContext { - pub user_id: String, - pub merchant_id: id_type::MerchantId, - pub role_id: String, - pub org_id: id_type::OrganizationId, - pub profile_id: id_type::ProfileId, - pub tenant_id: id_type::TenantId, -} - -impl LineageContext { - pub async fn try_get_lineage_context_from_cache( - state: &SessionState, - user_id: &str, - ) -> Option<Self> { - // The errors are not handled here because we don't want to fail the request if the cache operation fails. - // The errors are logged for debugging purposes. - match utils::user::get_lineage_context_from_cache(state, user_id).await { - Ok(Some(ctx)) => Some(ctx), - Ok(None) => { - logger::debug!("Lineage context not found in Redis for user {}", user_id); - None - } - Err(e) => { - logger::error!( - "Failed to retrieve lineage context from Redis for user {}: {:?}", - user_id, - e - ); - None - } - } - } - - pub async fn try_set_lineage_context_in_cache(&self, state: &SessionState, user_id: &str) { - // The errors are not handled here because we don't want to fail the request if the cache operation fails. - // The errors are logged for debugging purposes. - if let Err(e) = - utils::user::set_lineage_context_in_cache(state, user_id, self.clone()).await - { - logger::error!( - "Failed to set lineage context in Redis for user {}: {:?}", - user_id, - e - ); - } else { - logger::debug!("Lineage context cached for user {}", user_id); - } - } -} diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs index 0214d3cdd15..7bc11383da0 100644 --- a/crates/router/src/types/domain/user/decision_manager.rs +++ b/crates/router/src/types/domain/user/decision_manager.rs @@ -1,11 +1,12 @@ use common_enums::TokenPurpose; -use common_utils::id_type; +use common_utils::{id_type, types::user::LineageContext}; use diesel_models::{ enums::{UserRoleVersion, UserStatus}, user_role::UserRole, }; use error_stack::ResultExt; use masking::Secret; +use router_env::logger; use super::UserFromStorage; use crate::{ @@ -13,7 +14,6 @@ use crate::{ db::user_role::ListUserRolesByUserIdPayload, routes::SessionState, services::authentication as auth, - types::domain::LineageContext, utils, }; @@ -129,13 +129,25 @@ impl JWTFlow { user_role: &UserRole, ) -> UserResult<Secret<String>> { let user_id = next_flow.user.get_user_id(); - let cached_lineage_context = - LineageContext::try_get_lineage_context_from_cache(state, user_id).await; + // Fetch lineage context from DB + let lineage_context_from_db = state + .global_store + .find_user_by_id(user_id) + .await + .inspect_err(|e| { + logger::error!( + "Failed to fetch lineage context from DB for user {}: {:?}", + user_id, + e + ) + }) + .ok() + .and_then(|user| user.lineage_context); - let new_lineage_context = match cached_lineage_context { + let new_lineage_context = match lineage_context_from_db { Some(ctx) => { let tenant_id = ctx.tenant_id.clone(); - let user_role_match_v1 = state + let user_role_match_v2 = state .global_store .find_user_role_by_user_id_and_lineage( &ctx.user_id, @@ -143,15 +155,15 @@ impl JWTFlow { &ctx.org_id, &ctx.merchant_id, &ctx.profile_id, - UserRoleVersion::V1, + UserRoleVersion::V2, ) .await .is_ok(); - if user_role_match_v1 { + if user_role_match_v2 { ctx } else { - let user_role_match_v2 = state + let user_role_match_v1 = state .global_store .find_user_role_by_user_id_and_lineage( &ctx.user_id, @@ -159,12 +171,12 @@ impl JWTFlow { &ctx.org_id, &ctx.merchant_id, &ctx.profile_id, - UserRoleVersion::V2, + UserRoleVersion::V1, ) .await .is_ok(); - if user_role_match_v2 { + if user_role_match_v1 { ctx } else { // fallback to default lineage if cached context is invalid @@ -179,9 +191,11 @@ impl JWTFlow { } }; - new_lineage_context - .try_set_lineage_context_in_cache(state, user_id) - .await; + utils::user::spawn_async_lineage_context_update_to_db( + state, + user_id, + new_lineage_context.clone(), + ); auth::AuthToken::new_token( new_lineage_context.user_id, diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index 0c5fd187f92..ea3edd8dfc7 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -3,19 +3,19 @@ use std::sync::Arc; use api_models::user as user_api; use common_enums::UserAuthType; use common_utils::{ - encryption::Encryption, errors::CustomResult, id_type, type_name, types::keymanager::Identifier, + encryption::Encryption, + errors::CustomResult, + id_type, type_name, + types::{keymanager::Identifier, user::LineageContext}, }; use diesel_models::organization::{self, OrganizationBridge}; use error_stack::ResultExt; use masking::{ExposeInterface, Secret}; use redis_interface::RedisConnectionPool; -use router_env::env; +use router_env::{env, logger}; use crate::{ - consts::user::{ - LINEAGE_CONTEXT_PREFIX, LINEAGE_CONTEXT_TIME_EXPIRY_IN_SECS, REDIS_SSO_PREFIX, - REDIS_SSO_TTL, - }, + consts::user::{REDIS_SSO_PREFIX, REDIS_SSO_TTL}, core::errors::{StorageError, UserErrors, UserResult}, routes::SessionState, services::{ @@ -23,7 +23,7 @@ use crate::{ authorization::roles::RoleInfo, }, types::{ - domain::{self, LineageContext, MerchantAccount, UserFromStorage}, + domain::{self, MerchantAccount, UserFromStorage}, transformers::ForeignFrom, }, }; @@ -341,50 +341,35 @@ pub async fn validate_email_domain_auth_type_using_db( .ok_or(UserErrors::InvalidUserAuthMethodOperation.into()) } -pub async fn get_lineage_context_from_cache( - state: &SessionState, - user_id: &str, -) -> UserResult<Option<LineageContext>> { - let connection = get_redis_connection_for_global_tenant(state)?; - let key = format!("{}{}", LINEAGE_CONTEXT_PREFIX, user_id); - let lineage_context = connection - .get_key::<Option<String>>(&key.into()) - .await - .change_context(UserErrors::InternalServerError) - .attach_printable("Failed to get lineage context from redis")?; - - match lineage_context { - Some(json_str) => { - let ctx = serde_json::from_str::<LineageContext>(&json_str) - .change_context(UserErrors::InternalServerError) - .attach_printable("Failed to deserialize LineageContext from JSON")?; - Ok(Some(ctx)) - } - None => Ok(None), - } -} - -pub async fn set_lineage_context_in_cache( +pub fn spawn_async_lineage_context_update_to_db( state: &SessionState, user_id: &str, lineage_context: LineageContext, -) -> UserResult<()> { - let connection = get_redis_connection_for_global_tenant(state)?; - let key = format!("{}{}", LINEAGE_CONTEXT_PREFIX, user_id); - let serialized_lineage_context: String = serde_json::to_string(&lineage_context) - .change_context(UserErrors::InternalServerError) - .attach_printable("Failed to serialize LineageContext")?; - connection - .set_key_with_expiry( - &key.into(), - serialized_lineage_context, - LINEAGE_CONTEXT_TIME_EXPIRY_IN_SECS, - ) - .await - .change_context(UserErrors::InternalServerError) - .attach_printable("Failed to set lineage context in redis")?; - - Ok(()) +) { + let state = state.clone(); + let lineage_context = lineage_context.clone(); + let user_id = user_id.to_owned(); + tokio::spawn(async move { + match state + .global_store + .update_user_by_user_id( + &user_id, + diesel_models::user::UserUpdate::LineageContextUpdate { lineage_context }, + ) + .await + { + Ok(_) => { + logger::debug!("Successfully updated lineage context for user {}", user_id); + } + Err(e) => { + logger::error!( + "Failed to update lineage context for user {}: {:?}", + user_id, + e + ); + } + } + }); } pub fn generate_env_specific_merchant_id(value: String) -> UserResult<id_type::MerchantId> { diff --git a/crates/router/src/utils/user/theme.rs b/crates/router/src/utils/user/theme.rs index 0b9d4e2829a..33e1450f097 100644 --- a/crates/router/src/utils/user/theme.rs +++ b/crates/router/src/utils/user/theme.rs @@ -1,7 +1,7 @@ use std::path::PathBuf; use common_enums::EntityType; -use common_utils::{ext_traits::AsyncExt, id_type, types::theme::ThemeLineage}; +use common_utils::{ext_traits::AsyncExt, id_type, types::user::ThemeLineage}; use diesel_models::user::theme::Theme; use error_stack::ResultExt; use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore; diff --git a/crates/router/src/workflows/api_key_expiry.rs b/crates/router/src/workflows/api_key_expiry.rs index 2ff527a046e..4df78847b39 100644 --- a/crates/router/src/workflows/api_key_expiry.rs +++ b/crates/router/src/workflows/api_key_expiry.rs @@ -1,4 +1,4 @@ -use common_utils::{errors::ValidationError, ext_traits::ValueExt, types::theme::ThemeLineage}; +use common_utils::{errors::ValidationError, ext_traits::ValueExt, types::user::ThemeLineage}; use diesel_models::{ enums as storage_enums, process_tracker::business_status, ApiKeyExpiryTrackingData, }; diff --git a/migrations/2025-04-29-144409_add_lineage_context_to_users/down.sql b/migrations/2025-04-29-144409_add_lineage_context_to_users/down.sql new file mode 100644 index 00000000000..989e7ae64a0 --- /dev/null +++ b/migrations/2025-04-29-144409_add_lineage_context_to_users/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE users DROP COLUMN IF EXISTS lineage_context; diff --git a/migrations/2025-04-29-144409_add_lineage_context_to_users/up.sql b/migrations/2025-04-29-144409_add_lineage_context_to_users/up.sql new file mode 100644 index 00000000000..cbae98f97cc --- /dev/null +++ b/migrations/2025-04-29-144409_add_lineage_context_to_users/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE users ADD COLUMN IF NOT EXISTS lineage_context JSONB;
2025-04-29T19:00:30Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [x] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Previously, the user's `lineage_context` (userid, org_id, merchant_id, profile_id, role_id, tenant_id) was cached in Redis. This PR moves the storage and retrieval of `lineage_context` to the PostgreSQL `users` table instead of Redis. This ensures permanent persistence of lineage_context in DB, as opposed to the 7 days TTL when stored in Redis. ### Key Changes - **Schema Change:** - Added `lineage_context` as a `JSONB` column in the `users` table. - **During Login:** - Attempt to fetch `lineage_context` from DB (`users.lineage_context`). - If present: - Validate the context by checking if a matching user role exists (checks both v1 and v2 user roles). - If valid → use it for JWT generation. - If not → fallback to default DB-based role resolution. - If not present → fallback directly to default role resolution. - DB update for the new lineage context is now done via `tokio::spawn` to avoid blocking response. - **During Org/Merchant/Profile Switch:** - After switching, the new `lineage_context` is serialized and persisted in the `users` table. - This enables restoring the last used context during the next login. - The update is done in the background using `tokio::spawn` with success and failure logs. - **Error Handling:** - All DB failures or deserialization errors are logged. - Failures do not interrupt the login/switch flow — safe fallback ensures continuity. ### Additional Changes - [ ] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> By moving the `lineage_context` to the `users` table in DB: - We ensure the context is consistently available regardless of deployment environment. - The last used account context becomes part of the user's persistent record. - It simplifies logic and avoids prefix mismatches across tenants. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> <img width="1732" alt="Screenshot 2025-04-29 at 11 45 43 PM" src="https://github.com/user-attachments/assets/77a3ab50-add4-4091-b291-0bbe178bf617" /> ![image](https://github.com/user-attachments/assets/1fc5ec61-3dc4-43e9-9fe1-af66fa7127c4) #### Test Case 1: Lineage Context Caching on Login 1. Log in as a user with an assigned role. 2. Check that `lineage_context` is stored in the `users` table (PostgreSQL). 3. Log out and log back in → verify that the JWT reflects the same org/merchant/profile context without role fallback. #### Test Case 2: Lineage Context Update on Org/Profile Switch 1. Log in as a user and switch to another org/merchant/profile. 2. Confirm that the updated context is persisted in the `lineage_context` field in the DB. 3. Log out and log in again → JWT should reflect the newly switched context. #### Test Case 3: Fallback to Role Resolution upon clearing lineage_context in db (Tested on local) 1. Manually removed `lineage_context` from the DB for a user. 2. Logged in again → verified that the system correctly falls back to the default role resolution logic. 3. Confirm that the context is repopulated in the DB after login. #### Test Case 4: Fallback to Role Resolution upon deleting user_role (Tested on local) 1. Manually deleted `user_role` from the DB for a user (user_role corresponds to user invited to another account) 2. Tried to log in again → verified that the system correctly falls back to the default role resolution logic. 3. Confirm that the context is repopulated in the DB after login. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
839eb2e8fb436ec0a79fe0073923fcb060b42cfc
839eb2e8fb436ec0a79fe0073923fcb060b42cfc
juspay/hyperswitch
juspay__hyperswitch-7929
Bug: add debit routing support for saved card flow Once debit routing is performed for a card and the card is saved in the payment, we can also store the debit routing output. This allows us to reuse the saved data in future saved card flows instead of re-running the debit routing process.
diff --git a/crates/api_models/src/open_router.rs b/crates/api_models/src/open_router.rs index ce0960f04ea..f80623efc64 100644 --- a/crates/api_models/src/open_router.rs +++ b/crates/api_models/src/open_router.rs @@ -1,6 +1,6 @@ use std::{collections::HashMap, fmt::Debug}; -use common_utils::{id_type, types::MinorUnit}; +use common_utils::{errors, id_type, types::MinorUnit}; pub use euclid::{ dssa::types::EuclidAnalysable, frontend::{ @@ -10,7 +10,10 @@ pub use euclid::{ }; use serde::{Deserialize, Serialize}; -use crate::enums::{Currency, PaymentMethod}; +use crate::{ + enums::{Currency, PaymentMethod}, + payment_methods, +}; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -69,6 +72,37 @@ pub struct DebitRoutingOutput { pub card_type: common_enums::CardType, } +impl From<&DebitRoutingOutput> for payment_methods::CoBadgedCardData { + fn from(output: &DebitRoutingOutput) -> Self { + Self { + co_badged_card_networks: output.co_badged_card_networks.clone(), + issuer_country_code: output.issuer_country, + is_regulated: output.is_regulated, + regulated_name: output.regulated_name.clone(), + } + } +} + +impl TryFrom<(payment_methods::CoBadgedCardData, String)> for DebitRoutingRequestData { + type Error = error_stack::Report<errors::ParsingError>; + + fn try_from( + (output, card_type): (payment_methods::CoBadgedCardData, String), + ) -> Result<Self, Self::Error> { + let parsed_card_type = card_type.parse::<common_enums::CardType>().map_err(|_| { + error_stack::Report::new(errors::ParsingError::EnumParseFailure("CardType")) + })?; + + Ok(Self { + co_badged_card_networks: output.co_badged_card_networks, + issuer_country: output.issuer_country_code, + is_regulated: output.is_regulated, + regulated_name: output.regulated_name, + card_type: parsed_card_type, + }) + } +} + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct CoBadgedCardRequest { pub merchant_category_code: common_enums::MerchantCategoryCode, diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 0f53776e644..972b51d0f97 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -985,6 +985,15 @@ pub struct CardDetailsPaymentMethod { pub card_type: Option<String>, #[serde(default = "saved_in_locker_default")] pub saved_to_locker: bool, + pub co_badged_card_data: Option<CoBadgedCardData>, +} + +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +pub struct CoBadgedCardData { + pub co_badged_card_networks: Vec<api_enums::CardNetwork>, + pub issuer_country_code: common_enums::CountryAlpha2, + pub is_regulated: bool, + pub regulated_name: Option<common_enums::RegulatedName>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] @@ -1312,6 +1321,7 @@ impl From<CardDetail> for CardDetailsPaymentMethod { card_network: item.card_network, card_type: item.card_type.map(|card| card.to_string()), saved_to_locker: true, + co_badged_card_data: None, } } } @@ -1320,8 +1330,10 @@ impl From<CardDetail> for CardDetailsPaymentMethod { any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] -impl From<CardDetailFromLocker> for CardDetailsPaymentMethod { - fn from(item: CardDetailFromLocker) -> Self { +impl From<(CardDetailFromLocker, Option<&CoBadgedCardData>)> for CardDetailsPaymentMethod { + fn from( + (item, co_badged_card_data): (CardDetailFromLocker, Option<&CoBadgedCardData>), + ) -> Self { Self { issuer_country: item.issuer_country, last4_digits: item.last4_digits, @@ -1334,6 +1346,7 @@ impl From<CardDetailFromLocker> for CardDetailsPaymentMethod { card_network: item.card_network, card_type: item.card_type, saved_to_locker: item.saved_to_locker, + co_badged_card_data: co_badged_card_data.cloned(), } } } @@ -1353,6 +1366,7 @@ impl From<CardDetailFromLocker> for CardDetailsPaymentMethod { card_network: item.card_network, card_type: item.card_type, saved_to_locker: item.saved_to_locker, + co_badged_card_data: None, } } } diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index edbbcb5005c..1f3ed408810 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -2330,15 +2330,17 @@ pub enum CardNetwork { strum::EnumIter, strum::EnumString, utoipa::ToSchema, - Copy, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] pub enum RegulatedName { #[serde(rename = "GOVERNMENT NON-EXEMPT INTERCHANGE FEE (WITH FRAUD)")] + #[strum(serialize = "GOVERNMENT NON-EXEMPT INTERCHANGE FEE (WITH FRAUD)")] NonExemptWithFraud, - #[serde(rename = "GOVERNMENT EXEMPT INTERCHANGE FEE")] - ExemptFraud, + + #[serde(untagged)] + #[strum(default)] + Unknown(String), } #[derive( @@ -2378,8 +2380,8 @@ pub enum PanOrToken { Copy, )] #[router_derive::diesel_enum(storage_type = "db_enum")] +#[strum(serialize_all = "UPPERCASE")] #[serde(rename_all = "snake_case")] -#[strum(serialize_all = "lowercase")] pub enum CardType { Credit, Debit, @@ -2413,6 +2415,23 @@ impl CardNetwork { | Self::Maestro => true, } } + + pub fn is_us_local_network(&self) -> bool { + match self { + Self::Star | Self::Pulse | Self::Accel | Self::Nyce => true, + Self::Interac + | Self::CartesBancaires + | Self::Visa + | Self::Mastercard + | Self::AmericanExpress + | Self::JCB + | Self::DinersClub + | Self::Discover + | Self::UnionPay + | Self::RuPay + | Self::Maestro => false, + } + } } /// Stage of the dispute diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 2d386d0f002..6ecbf665c50 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -77,6 +77,14 @@ impl PaymentMethodData { pub fn is_network_token_payment_method_data(&self) -> bool { matches!(self, Self::NetworkToken(_)) } + + pub fn get_co_badged_card_data(&self) -> Option<&payment_methods::CoBadgedCardData> { + if let Self::Card(card) = self { + card.co_badged_card_data.as_ref() + } else { + None + } + } } #[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)] @@ -92,6 +100,7 @@ pub struct Card { pub bank_code: Option<String>, pub nick_name: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, + pub co_badged_card_data: Option<payment_methods::CoBadgedCardData>, } #[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)] @@ -120,6 +129,7 @@ pub struct CardDetail { pub bank_code: Option<String>, pub nick_name: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, + pub co_badged_card_data: Option<payment_methods::CoBadgedCardData>, } impl CardDetailsForNetworkTransactionId { @@ -162,6 +172,7 @@ impl From<&Card> for CardDetail { bank_code: item.bank_code.to_owned(), nick_name: item.nick_name.to_owned(), card_holder_name: item.card_holder_name.to_owned(), + co_badged_card_data: item.co_badged_card_data.to_owned(), } } } @@ -723,6 +734,7 @@ impl TryFrom<payment_methods::PaymentMethodCreateData> for PaymentMethodData { bank_code: None, nick_name, card_holder_name, + co_badged_card_data: None, })), } } @@ -732,7 +744,7 @@ impl From<api_models::payments::PaymentMethodData> for PaymentMethodData { fn from(api_model_payment_method_data: api_models::payments::PaymentMethodData) -> Self { match api_model_payment_method_data { api_models::payments::PaymentMethodData::Card(card_data) => { - Self::Card(Card::from(card_data)) + Self::Card(Card::from((card_data, None))) } api_models::payments::PaymentMethodData::CardRedirect(card_redirect) => { Self::CardRedirect(From::from(card_redirect)) @@ -782,8 +794,18 @@ impl From<api_models::payments::PaymentMethodData> for PaymentMethodData { } } -impl From<api_models::payments::Card> for Card { - fn from(value: api_models::payments::Card) -> Self { +impl + From<( + api_models::payments::Card, + Option<payment_methods::CoBadgedCardData>, + )> for Card +{ + fn from( + (value, co_badged_card_data_optional): ( + api_models::payments::Card, + Option<payment_methods::CoBadgedCardData>, + ), + ) -> Self { let api_models::payments::Card { card_number, card_exp_month, @@ -810,6 +832,7 @@ impl From<api_models::payments::Card> for Card { bank_code, nick_name, card_holder_name, + co_badged_card_data: co_badged_card_data_optional, } } } @@ -1875,6 +1898,16 @@ pub enum PaymentMethodsData { NetworkToken(NetworkTokenDetailsPaymentMethod), } +impl PaymentMethodsData { + pub fn get_co_badged_card_data(&self) -> Option<payment_methods::CoBadgedCardData> { + if let Self::Card(card) = self { + card.co_badged_card_data.clone() + } else { + None + } + } +} + #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct NetworkTokenDetailsPaymentMethod { pub last4_digits: Option<String>, @@ -1909,6 +1942,7 @@ pub struct CardDetailsPaymentMethod { pub card_type: Option<String>, #[serde(default = "saved_in_locker_default")] pub saved_to_locker: bool, + pub co_badged_card_data: Option<payment_methods::CoBadgedCardData>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] @@ -1926,6 +1960,7 @@ impl From<payment_methods::CardDetail> for CardDetailsPaymentMethod { card_network: item.card_network, card_type: item.card_type.map(|card| card.to_string()), saved_to_locker: true, + co_badged_card_data: None, } } } diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rs index 955d01c94df..de7d9641449 100644 --- a/crates/hyperswitch_domain_models/src/payment_methods.rs +++ b/crates/hyperswitch_domain_models/src/payment_methods.rs @@ -12,7 +12,11 @@ use common_utils::{ }; use diesel_models::{enums as storage_enums, PaymentMethodUpdate}; use error_stack::ResultExt; +#[cfg(feature = "v1")] +use masking::ExposeInterface; use masking::{PeekInterface, Secret}; +#[cfg(feature = "v1")] +use router_env::logger; #[cfg(feature = "v2")] use rustc_hash::FxHashMap; #[cfg(feature = "v2")] @@ -20,13 +24,11 @@ use serde_json::Value; use time::PrimitiveDateTime; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -use crate::{ - address::Address, payment_method_data as domain_payment_method_data, - type_encryption::OptionalEncryptableJsonType, -}; +use crate::{address::Address, type_encryption::OptionalEncryptableJsonType}; use crate::{ mandates::{self, CommonMandateReference}, merchant_key_store::MerchantKeyStore, + payment_method_data as domain_payment_method_data, type_encryption::{crypto_operation, AsyncLift, CryptoOperation}, }; @@ -131,6 +133,25 @@ impl PaymentMethod { &self.payment_method_id } + #[cfg(feature = "v1")] + pub fn get_payment_methods_data( + &self, + ) -> Option<domain_payment_method_data::PaymentMethodsData> { + self.payment_method_data + .clone() + .map(|value| value.into_inner().expose()) + .and_then(|value| { + serde_json::from_value::<domain_payment_method_data::PaymentMethodsData>(value) + .map_err(|error| { + logger::warn!( + ?error, + "Failed to parse payment method data in payment method info" + ); + }) + .ok() + }) + } + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub fn get_id(&self) -> &id_type::GlobalPaymentMethodId { &self.id diff --git a/crates/router/src/core/debit_routing.rs b/crates/router/src/core/debit_routing.rs index d704c47a521..4b1a7d03990 100644 --- a/crates/router/src/core/debit_routing.rs +++ b/crates/router/src/core/debit_routing.rs @@ -28,7 +28,7 @@ pub async fn perform_debit_routing<F, Req, D>( operation: &BoxedOperation<'_, F, Req, D>, state: &SessionState, business_profile: &domain::Profile, - payment_data: &D, + payment_data: &mut D, connector: Option<ConnectorCallType>, ) -> (Option<ConnectorCallType>, bool) where @@ -210,7 +210,7 @@ async fn handle_pre_determined_connector<F, D>( debit_routing_config: &settings::DebitRoutingConfig, debit_routing_supported_connectors: HashSet<api_enums::Connector>, connector_data: &api::ConnectorRoutingData, - payment_data: &D, + payment_data: &mut D, acquirer_country: enums::CountryAlpha2, ) -> Option<ConnectorCallType> where @@ -236,45 +236,123 @@ where None } -pub async fn get_sorted_co_badged_networks_by_fee<F: Clone, D: OperationSessionGetters<F>>( +pub async fn get_sorted_co_badged_networks_by_fee< + F: Clone, + D: OperationSessionGetters<F> + OperationSessionSetters<F>, +>( state: &SessionState, - payment_data: &D, + payment_data: &mut D, acquirer_country: enums::CountryAlpha2, ) -> Option<Vec<enums::CardNetwork>> { logger::debug!("Fetching sorted card networks"); - - let payment_method_data_optional = payment_data.get_payment_method_data(); let payment_attempt = payment_data.get_payment_attempt(); - let co_badged_card_request = api_models::open_router::CoBadgedCardRequest { - merchant_category_code: enums::MerchantCategoryCode::Mcc0001, - acquirer_country, - // we need to populate this in case of save card flows - // this should we populated by checking for the payment method info - // payment method info is some then we will have to send the card isin as null - co_badged_card_data: None, + let (saved_co_badged_card_data, saved_card_type, card_isin) = + extract_saved_card_info(payment_data); + + let debit_routing_output_optional = match ( + saved_co_badged_card_data + .clone() + .zip(saved_card_type.clone()), + card_isin.clone(), + ) { + (None, None) => { + logger::debug!("Neither co-badged data nor ISIN found; skipping routing"); + None + } + _ => { + let co_badged_card_data = saved_co_badged_card_data + .zip(saved_card_type) + .and_then(|(co_badged, card_type)| { + api_models::open_router::DebitRoutingRequestData::try_from(( + co_badged, card_type, + )) + .map(Some) + .map_err(|error| { + logger::warn!("Failed to convert co-badged card data: {:?}", error); + }) + .ok() + }) + .flatten(); + + if co_badged_card_data.is_none() && card_isin.is_none() { + logger::debug!("Neither co-badged data nor ISIN found; skipping routing"); + return None; + } + + let co_badged_card_request = api_models::open_router::CoBadgedCardRequest { + merchant_category_code: enums::MerchantCategoryCode::Mcc0001, + acquirer_country, + co_badged_card_data, + }; + + routing::perform_open_routing_for_debit_routing( + state, + payment_attempt, + co_badged_card_request, + card_isin, + ) + .await + .map_err(|error| { + logger::warn!(?error, "Debit routing call to open router failed"); + }) + .ok() + } }; - if let Some(hyperswitch_domain_models::payment_method_data::PaymentMethodData::Card(card)) = - payment_method_data_optional - { - // perform_open_routing_for_debit_routing - let debit_routing_output_optional = routing::perform_open_routing_for_debit_routing( - state, - payment_attempt, - co_badged_card_request, - Some(Secret::new(card.card_number.get_card_isin())), - ) - .await - .map_err(|error| { - logger::warn!(?error, "Failed to calculate total fees per network"); - }) - .ok() - .map(|data| data.co_badged_card_networks); + debit_routing_output_optional + .as_ref() + .map(|debit_routing_output| payment_data.set_co_badged_card_data(debit_routing_output)); + + debit_routing_output_optional.map(|data| { + logger::info!( + "Co-badged card networks: {:?}", + data.co_badged_card_networks + ); + data.co_badged_card_networks + }) +} - return debit_routing_output_optional; +fn extract_saved_card_info<F, D>( + payment_data: &D, +) -> ( + Option<api_models::payment_methods::CoBadgedCardData>, + Option<String>, + Option<Secret<String>>, +) +where + D: OperationSessionGetters<F>, +{ + let payment_method_data_optional = payment_data.get_payment_method_data(); + match payment_data + .get_payment_method_info() + .and_then(|info| info.get_payment_methods_data()) + { + Some(hyperswitch_domain_models::payment_method_data::PaymentMethodsData::Card(card)) => { + match (&card.co_badged_card_data, &card.card_isin) { + (Some(co_badged), _) => { + logger::debug!("Co-badged card data found in saved payment method"); + (Some(co_badged.clone()), card.card_type, None) + } + (None, Some(card_isin)) => { + logger::debug!("No co-badged data; using saved card ISIN"); + (None, None, Some(Secret::new(card_isin.clone()))) + } + _ => (None, None, None), + } + } + _ => match payment_method_data_optional { + Some(hyperswitch_domain_models::payment_method_data::PaymentMethodData::Card(card)) => { + logger::debug!("Using card data from payment request"); + ( + None, + None, + Some(Secret::new(card.card_number.get_card_isin())), + ) + } + _ => (None, None, None), + }, } - None } fn check_connector_support_for_network( @@ -317,7 +395,7 @@ async fn handle_retryable_connector<F, D>( debit_routing_config: &settings::DebitRoutingConfig, debit_routing_supported_connectors: HashSet<api_enums::Connector>, connector_data_list: Vec<api::ConnectorRoutingData>, - payment_data: &D, + payment_data: &mut D, acquirer_country: enums::CountryAlpha2, ) -> Option<ConnectorCallType> where diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 990071b37e4..95924f06308 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -783,6 +783,11 @@ pub(crate) async fn get_payment_method_create_request( Some(pm_data) => match payment_method { Some(payment_method) => match pm_data { domain::PaymentMethodData::Card(card) => { + let card_network = get_card_network_with_us_local_debit_network_override( + card.card_network.clone(), + card.co_badged_card_data.as_ref(), + ); + let card_detail = payment_methods::CardDetail { card_number: card.card_number.clone(), card_exp_month: card.card_exp_month.clone(), @@ -790,7 +795,7 @@ pub(crate) async fn get_payment_method_create_request( card_holder_name: billing_name, nick_name: card.nick_name.clone(), card_issuing_country: card.card_issuing_country.clone(), - card_network: card.card_network.clone(), + card_network: card_network.clone(), card_issuer: card.card_issuer.clone(), card_type: card.card_type.clone(), }; @@ -806,8 +811,8 @@ pub(crate) async fn get_payment_method_create_request( card: Some(card_detail), metadata: None, customer_id: customer_id.clone(), - card_network: card - .card_network + card_network: card_network + .clone() .as_ref() .map(|card_network| card_network.to_string()), client_secret: None, @@ -855,6 +860,32 @@ pub(crate) async fn get_payment_method_create_request( } } +/// Determines the appropriate card network to to be stored. +/// +/// If the provided card network is a US local network, this function attempts to +/// override it with the first global network from the co-badged card data, if available. +/// Otherwise, it returns the original card network as-is. +/// +fn get_card_network_with_us_local_debit_network_override( + card_network: Option<common_enums::CardNetwork>, + co_badged_card_data: Option<&payment_methods::CoBadgedCardData>, +) -> Option<common_enums::CardNetwork> { + // logger::debug!("get_card_network_with_us_local_debit_network_override",); + if let Some(true) = card_network + .as_ref() + .map(|network| network.is_us_local_network()) + { + co_badged_card_data.and_then(|data| { + data.co_badged_card_networks + .iter() + .find(|network| network.is_global_network()) + .cloned() + }) + } else { + card_network + } +} + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[instrument(skip_all)] pub async fn create_payment_method( diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index c228975faac..d65cb2ffb87 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -774,7 +774,7 @@ pub async fn skip_locker_call_and_migrate_payment_method( .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; let payment_method_card_details = - PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone())); + PaymentMethodsData::Card(CardDetailsPaymentMethod::from((card.clone(), None))); let payment_method_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = Some( create_encrypted_data( @@ -932,10 +932,9 @@ pub async fn save_network_token_and_update_payment_method( Ok(resp) => { logger::debug!("Network token added to locker"); let (token_pm_resp, _duplication_check) = resp; - let pm_token_details = token_pm_resp - .card - .as_ref() - .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))); + let pm_token_details = token_pm_resp.card.as_ref().map(|card| { + PaymentMethodsData::Card(CardDetailsPaymentMethod::from((card.clone(), None))) + }); let pm_network_token_data_encrypted = pm_token_details .async_map(|pm_card| { create_encrypted_data( @@ -1382,6 +1381,7 @@ pub async fn add_payment_method_data( card_issuer: card_info.as_ref().and_then(|ci| ci.card_issuer.clone()), card_type: card_info.as_ref().and_then(|ci| ci.card_type.clone()), saved_to_locker: true, + co_badged_card_data: None, }; let pm_data_encrypted: Encryptable<Secret<serde_json::Value>> = create_encrypted_data( @@ -1647,7 +1647,10 @@ pub async fn add_payment_method( }); let updated_pmd = updated_card.as_ref().map(|card| { - PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone())) + PaymentMethodsData::Card(CardDetailsPaymentMethod::from(( + card.clone(), + None, + ))) }); let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = updated_pmd @@ -1911,7 +1914,10 @@ pub async fn save_migration_payment_method( }); let updated_pmd = updated_card.as_ref().map(|card| { - PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone())) + PaymentMethodsData::Card(CardDetailsPaymentMethod::from(( + card.clone(), + None, + ))) }); let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = updated_pmd @@ -2024,7 +2030,7 @@ pub async fn insert_payment_method( let pm_card_details = resp .card .clone() - .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))); + .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from((card.clone(), None)))); let key_manager_state = state.into(); let pm_data_encrypted: crypto::OptionalEncryptableValue = pm_card_details .clone() @@ -2247,9 +2253,9 @@ pub async fn update_customer_payment_method( saved_to_locker: true, }); - let updated_pmd = updated_card - .as_ref() - .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))); + let updated_pmd = updated_card.as_ref().map(|card| { + PaymentMethodsData::Card(CardDetailsPaymentMethod::from((card.clone(), None))) + }); let key_manager_state = (&state).into(); let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = updated_pmd .async_map(|updated_pmd| { diff --git a/crates/router/src/core/payment_methods/tokenize.rs b/crates/router/src/core/payment_methods/tokenize.rs index 21e2ed4feef..cce741d2c40 100644 --- a/crates/router/src/core/payment_methods/tokenize.rs +++ b/crates/router/src/core/payment_methods/tokenize.rs @@ -273,6 +273,7 @@ where card_network: card_details.card_network.clone(), card_type: card_details.card_type.clone(), saved_to_locker, + co_badged_card_data: card_details.co_badged_card_data.clone(), }); create_encrypted_data(&self.state.into(), self.key_store, pm_data) .await @@ -298,6 +299,7 @@ where card_network: card_details.card_network.clone(), card_type: card_details.card_type.clone(), saved_to_locker, + co_badged_card_data: None, }); create_encrypted_data(&self.state.into(), self.key_store, token_data) .await diff --git a/crates/router/src/core/payment_methods/tokenize/card_executor.rs b/crates/router/src/core/payment_methods/tokenize/card_executor.rs index eb9d3d6b6c6..e04e688933d 100644 --- a/crates/router/src/core/payment_methods/tokenize/card_executor.rs +++ b/crates/router/src/core/payment_methods/tokenize/card_executor.rs @@ -131,6 +131,7 @@ impl<'a> NetworkTokenizationBuilder<'a, CardRequestValidated> { .map_or(card_req.card_issuing_country.clone(), |card_info| { card_info.card_issuing_country.clone() }), + co_badged_card_data: None, }; NetworkTokenizationBuilder { state: std::marker::PhantomData, diff --git a/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs b/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs index 2249434b107..a55896b36c5 100644 --- a/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs +++ b/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs @@ -151,6 +151,7 @@ impl<'a> NetworkTokenizationBuilder<'a, PmValidated> { card_issuing_country: optional_card_info .as_ref() .and_then(|card_info| card_info.card_issuing_country.clone()), + co_badged_card_data: None, }; NetworkTokenizationBuilder { state: std::marker::PhantomData, diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index 2231f7d89f6..af60d07a466 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -121,6 +121,7 @@ impl Vaultable for domain::Card { card_type: None, nick_name: value1.nickname.map(masking::Secret::new), card_holder_name: value1.card_holder_name, + co_badged_card_data: None, }; let supp_data = SupplementaryVaultData { diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 56988beec87..789a4f581b3 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -360,7 +360,7 @@ where &operation, state, &business_profile, - &payment_data, + &mut payment_data, connector, ) .await; @@ -615,8 +615,8 @@ where (business_profile.is_debit_routing_enabled && is_debit_routing_performed) .then(|| find_connector_with_networks(&mut connectors)) .flatten() - .map(|(connector_data, local_network)| { - payment_data.set_local_network(local_network); + .map(|(connector_data, network)| { + payment_data.set_card_network(network); connector_data }) { connector_from_network @@ -8076,7 +8076,11 @@ pub trait OperationSessionSetters<F> { &mut self, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, ); - fn set_local_network(&mut self, local_network: enums::CardNetwork); + fn set_card_network(&mut self, card_network: enums::CardNetwork); + fn set_co_badged_card_data( + &mut self, + debit_routing_ouput: &api_models::open_router::DebitRoutingOutput, + ); #[cfg(feature = "v1")] fn set_capture_method_in_attempt(&mut self, capture_method: enums::CaptureMethod); fn set_frm_message(&mut self, frm_message: FraudCheck); @@ -8306,9 +8310,37 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentData<F> { self.payment_attempt.merchant_connector_id = merchant_connector_id; } - fn set_local_network(&mut self, local_network: enums::CardNetwork) { + fn set_card_network(&mut self, card_network: enums::CardNetwork) { + if let Some(domain::PaymentMethodData::Card(card)) = &mut self.payment_method_data { + card.card_network = Some(card_network); + }; + } + + fn set_co_badged_card_data( + &mut self, + debit_routing_ouput: &api_models::open_router::DebitRoutingOutput, + ) { + let co_badged_card_data = + api_models::payment_methods::CoBadgedCardData::from(debit_routing_ouput); + let card_type = debit_routing_ouput + .card_type + .clone() + .to_string() + .to_uppercase(); + logger::debug!("set co-badged card data"); if let Some(domain::PaymentMethodData::Card(card)) = &mut self.payment_method_data { - card.card_network = Some(local_network); + card.co_badged_card_data = Some(co_badged_card_data); + card.card_type = Some(card_type); + logger::debug!("set co-badged card data in payment method data"); + } else if let Some( + hyperswitch_domain_models::payment_method_data::PaymentMethodsData::Card(card), + ) = &mut self + .get_payment_method_info() + .and_then(|payment_method_info| payment_method_info.get_payment_methods_data()) + { + card.co_badged_card_data = Some(co_badged_card_data); + card.card_type = Some(card_type); + logger::debug!("set co-badged card data in payment method info"); }; } @@ -8534,7 +8566,14 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentIntentData<F> { todo!() } - fn set_local_network(&mut self, local_network: enums::CardNetwork) { + fn set_card_network(&mut self, card_network: enums::CardNetwork) { + todo!() + } + + fn set_co_badged_card_data( + &mut self, + debit_routing_ouput: &api_models::open_router::DebitRoutingOutput, + ) { todo!() } @@ -8775,7 +8814,14 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentConfirmData<F> { todo!() } - fn set_local_network(&mut self, local_network: enums::CardNetwork) { + fn set_card_network(&mut self, card_network: enums::CardNetwork) { + todo!() + } + + fn set_co_badged_card_data( + &mut self, + debit_routing_ouput: &api_models::open_router::DebitRoutingOutput, + ) { todo!() } @@ -8988,7 +9034,14 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentStatusData<F> { todo!() } - fn set_local_network(&mut self, local_network: enums::CardNetwork) { + fn set_card_network(&mut self, card_network: enums::CardNetwork) { + todo!() + } + + fn set_co_badged_card_data( + &mut self, + debit_routing_ouput: &api_models::open_router::DebitRoutingOutput, + ) { todo!() } @@ -9211,7 +9264,14 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentCaptureData<F> { todo!() } - fn set_local_network(&mut self, local_network: enums::CardNetwork) { + fn set_card_network(&mut self, card_network: enums::CardNetwork) { + todo!() + } + + fn set_co_badged_card_data( + &mut self, + debit_routing_ouput: &api_models::open_router::DebitRoutingOutput, + ) { todo!() } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 8bd2c0d3b73..6b6d23951d4 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -2116,6 +2116,11 @@ pub async fn retrieve_payment_method_data_with_permanent_token( .network_token_requestor_reference_id .clone(), ); + + let co_badged_card_data = payment_method_info + .get_payment_methods_data() + .and_then(|payment_methods_data| payment_methods_data.get_co_badged_card_data()); + match vault_fetch_action { VaultFetchAction::FetchCardDetailsFromLocker => { let card = vault_data @@ -2128,6 +2133,7 @@ pub async fn retrieve_payment_method_data_with_permanent_token( &payment_intent.merchant_id, locker_id, card_token_data, + co_badged_card_data, ) .await }) @@ -2178,6 +2184,7 @@ pub async fn retrieve_payment_method_data_with_permanent_token( &payment_intent.merchant_id, locker_id, card_token_data, + co_badged_card_data, ) .await }) @@ -2242,6 +2249,7 @@ pub async fn retrieve_card_with_permanent_token_for_external_authentication( &payment_intent.merchant_id, locker_id, card_token_data, + None, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -2259,7 +2267,9 @@ pub async fn fetch_card_details_from_locker( merchant_id: &id_type::MerchantId, locker_id: &str, card_token_data: Option<&domain::CardToken>, + co_badged_card_data: Option<api_models::payment_methods::CoBadgedCardData>, ) -> RouterResult<domain::Card> { + logger::debug!("Fetching card details from locker"); let card = cards::get_card_from_locker(state, customer_id, merchant_id, locker_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -2304,7 +2314,7 @@ pub async fn fetch_card_details_from_locker( card_issuing_country: None, bank_code: None, }; - Ok(api_card.into()) + Ok(domain::Card::from((api_card, co_badged_card_data))) } #[cfg(all( @@ -4737,15 +4747,26 @@ pub async fn get_additional_payment_data( _ => None, }; - let card_network = match card_data + // Added an additional check for card_data.co_badged_card_data.is_some() + // because is_cobadged_card() only returns true if the card number matches a specific regex. + // However, this regex does not cover all possible co-badged networks. + // The co_badged_card_data field is populated based on a co-badged BIN lookup + // and helps identify co-badged cards that may not match the regex alone. + // Determine the card network based on cobadge detection and co-badged BIN data + let is_cobadged_based_on_regex = card_data .card_number .is_cobadged_card() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Card cobadge check failed due to an invalid card network regex", - )? { - true => card_data.card_network.clone(), - false => None, + )?; + + let card_network = match ( + is_cobadged_based_on_regex, + card_data.co_badged_card_data.is_some(), + ) { + (false, false) => None, + _ => card_data.card_network.clone(), }; let last4 = Some(card_data.card_number.get_last4()); diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 40cd4c81612..1817c05e648 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -195,6 +195,11 @@ where payment_method_billing_address, ) .await?; + let payment_methods_data = + &save_payment_method_data.request.get_payment_method_data(); + + let co_badged_card_data = payment_methods_data.get_co_badged_card_data(); + let customer_id = customer_id.to_owned().get_required_value("customer_id")?; let merchant_id = merchant_context.get_merchant_account().get_id(); let is_network_tokenization_enabled = @@ -263,7 +268,7 @@ where save_payment_method_data.request.get_payment_method_data(), ) { (Some(card), _) => Some(PaymentMethodsData::Card( - CardDetailsPaymentMethod::from(card.clone()), + CardDetailsPaymentMethod::from((card.clone(), co_badged_card_data)), )), ( _, @@ -294,7 +299,10 @@ where > = match network_token_resp { Some(token_resp) => { let pm_token_details = token_resp.card.as_ref().map(|card| { - PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone())) + PaymentMethodsData::Card(CardDetailsPaymentMethod::from(( + card.clone(), + None, + ))) }); pm_token_details @@ -641,9 +649,10 @@ where }); let updated_pmd = updated_card.as_ref().map(|card| { - PaymentMethodsData::Card(CardDetailsPaymentMethod::from( + PaymentMethodsData::Card(CardDetailsPaymentMethod::from(( card.clone(), - )) + None, + ))) }); let pm_data_encrypted: Option< Encryptable<Secret<serde_json::Value>>, diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 2cbb532bc35..8b71c02349b 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -494,6 +494,7 @@ pub async fn save_payout_data_to_locker( card_network: card_info.card_network, card_type: card_info.card_type, saved_to_locker: true, + co_badged_card_data: None, }, ) }) @@ -514,6 +515,7 @@ pub async fn save_payout_data_to_locker( card_network: None, card_type: None, saved_to_locker: true, + co_badged_card_data: None, }, ) }); diff --git a/crates/router/src/utils/verify_connector.rs b/crates/router/src/utils/verify_connector.rs index b13ba70e6fb..0f5d9e6b318 100644 --- a/crates/router/src/utils/verify_connector.rs +++ b/crates/router/src/utils/verify_connector.rs @@ -24,6 +24,7 @@ pub fn generate_card_from_details( card_issuing_country: None, bank_code: None, card_holder_name: None, + co_badged_card_data: None, }) } diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index 8b3372d7dec..3497a048a8a 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -52,6 +52,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { bank_code: None, nick_name: Some(Secret::new("nick_name".into())), card_holder_name: Some(Secret::new("card holder name".into())), + co_badged_card_data: None, }), confirm: true, statement_descriptor_suffix: None, @@ -302,6 +303,7 @@ async fn payments_create_failure() { bank_code: None, nick_name: Some(Secret::new("nick_name".into())), card_holder_name: Some(Secret::new("card holder name".into())), + co_badged_card_data: None, }); let response = services::api::execute_connector_processing_step( diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rs index c7ad3b69a32..d7017d3d44e 100644 --- a/crates/router/tests/connectors/adyen.rs +++ b/crates/router/tests/connectors/adyen.rs @@ -154,6 +154,7 @@ impl AdyenTest { bank_code: None, nick_name: Some(Secret::new("nick_name".into())), card_holder_name: Some(Secret::new("card holder name".into())), + co_badged_card_data: None, }), confirm: true, statement_descriptor_suffix: None, diff --git a/crates/router/tests/connectors/airwallex.rs b/crates/router/tests/connectors/airwallex.rs index 0e538818d50..bf5a06f157a 100644 --- a/crates/router/tests/connectors/airwallex.rs +++ b/crates/router/tests/connectors/airwallex.rs @@ -83,6 +83,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { bank_code: None, nick_name: Some(Secret::new("nick_name".into())), card_holder_name: Some(Secret::new("card holder name".into())), + co_badged_card_data: None, }), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), router_return_url: Some("https://google.com".to_string()), diff --git a/crates/router/tests/connectors/fiserv.rs b/crates/router/tests/connectors/fiserv.rs index 78235278ed9..77ab8223145 100644 --- a/crates/router/tests/connectors/fiserv.rs +++ b/crates/router/tests/connectors/fiserv.rs @@ -54,6 +54,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { bank_code: None, nick_name: Some(Secret::new("nick_name".into())), card_holder_name: Some(Secret::new("card holder name".into())), + co_badged_card_data: None, }), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 diff --git a/crates/router/tests/connectors/rapyd.rs b/crates/router/tests/connectors/rapyd.rs index ee6ac303e88..e173f4753d6 100644 --- a/crates/router/tests/connectors/rapyd.rs +++ b/crates/router/tests/connectors/rapyd.rs @@ -54,6 +54,7 @@ async fn should_only_authorize_payment() { bank_code: None, nick_name: Some(Secret::new("nick_name".into())), card_holder_name: Some(Secret::new("card holder name".into())), + co_badged_card_data: None, }), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 @@ -82,6 +83,7 @@ async fn should_authorize_and_capture_payment() { bank_code: None, nick_name: Some(Secret::new("nick_name".into())), card_holder_name: Some(Secret::new("card holder name".into())), + co_badged_card_data: None, }), ..utils::PaymentAuthorizeType::default().0 }), diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index ede3aeb17db..d6925ae1667 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -941,6 +941,7 @@ impl Default for CCardType { bank_code: None, nick_name: Some(Secret::new("nick_name".into())), card_holder_name: Some(Secret::new("card holder name".into())), + co_badged_card_data: None, }) } } diff --git a/crates/router/tests/connectors/worldline.rs b/crates/router/tests/connectors/worldline.rs index 793a1cc15f4..22fd198bd0a 100644 --- a/crates/router/tests/connectors/worldline.rs +++ b/crates/router/tests/connectors/worldline.rs @@ -84,6 +84,7 @@ impl WorldlineTest { bank_code: None, nick_name: Some(Secret::new("nick_name".into())), card_holder_name: Some(Secret::new("card holder name".into())), + co_badged_card_data: None, }), confirm: true, statement_descriptor_suffix: None,
2025-04-29T07:15:49Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Once debit routing is performed for a card and the card is saved in the payment, we can also store the debit routing output. This allows us to reuse the saved data in future saved card flows instead of re-running the debit routing process. Changes: In this PR, support for co-badged card data has been introduced. This data will be stored in the payment_method_data column of the payment_methods table and will contain the debit routing output. In the saved card flow, we check if the co-badged card data is present in the payment_method_data of the payment method. If it is present, the same data will be sent to the open router for debit routing. If the co-badged card data is not available, then the card_isin, which contains the card BIN, will be used to call the open router. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> add debit routing support for saved card flow ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Tested locally by creating dummy co-badged card bin dump -> Create a merchant account and business profile -> Enable debit routing and provide merchant business country for the business profile ``` curl --location 'http://localhost:8080/account/merchant_1745690754/business_profile/pro_OiJkBiFuCYbYAkCG9X02' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: ' \ --data '{ "is_debit_routing_enabled": true, "merchant_business_country": "US" }' ``` -> Create a payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-tenant-id: hyperswitch' \ --header 'api-key: dev_t6MGc7fYh7s9QLODlx0Pvl5QaGQtKhHFq0eUOJm6hNBfrWK2FqqWZ4tDXpqMUzfZ' \ --data-raw '{ "amount": 100, "amount_to_capture": 100, "currency": "USD", "confirm": true, "capture_method": "automatic", "setup_future_usage": "on_session", "capture_on": "2022-09-10T10:11:12Z", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "customer_id": "cu_1745917372", "return_url": "http://127.0.0.1:4040", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4400002000000004", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "737" } }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX", "last_name": "ss" }, "email": "[email protected]" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ``` { "payment_id": "pay_p70wBAMKn2Cwih0biDX0", "merchant_id": "merchant_1745690754", "status": "succeeded", "amount": 100, "net_amount": 100, "shipping_cost": null, "amount_capturable": 0, "amount_received": 100, "connector": "adyen", "client_secret": "pay_p70wBAMKn2Cwih0biDX0_secret_n9DPdVNK5DMvaPoYj3y2", "created": "2025-04-29T09:02:58.609Z", "currency": "USD", "customer_id": "cu_1745917372", "customer": { "id": "cu_1745917372", "name": "John Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0004", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "440000", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": "ss" }, "phone": null, "email": "[email protected]" }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "http://127.0.0.1:4040/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1745917372", "created_at": 1745917378, "expires": 1745920978, "secret": "epk_248a7b7506aa4a60b28db8ddf75d38ad" }, "manual_retry_allowed": false, "connector_transaction_id": "B6WPZCJ7DLDD9J75", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_p70wBAMKn2Cwih0biDX0_1", "payment_link": null, "profile_id": "pro_OiJkBiFuCYbYAkCG9X02", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_VyX6BwB09KJrmeR1ODFD", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-29T09:17:58.609Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "125.0.0.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-29T09:03:00.705Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` -> Connector request indicating the card brand as star ![image](https://github.com/user-attachments/assets/42033c7c-cdf2-449e-8164-544c747a2f2a) -> Create a payment for the same customer ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_t6MGc7fYh7s9QLODlx0Pvl5QaGQtKhHFq0eUOJm6hNBfrWK2FqqWZ4tDXpqMUzfZ' \ --data-raw '{ "amount": 6100, "currency": "USD", "confirm": false, "business_country": "US", "business_label": "default", "amount_to_capture": 6100, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "return_url": "https://google.com", "email": "[email protected]", "setup_future_usage": "on_session", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "customer_id": "cu_1745917372", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } } }' ``` ``` { "payment_id": "pay_icPaUi7x7A2gK2F43q56", "merchant_id": "merchant_1745690754", "status": "requires_payment_method", "amount": 6100, "net_amount": 6100, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_icPaUi7x7A2gK2F43q56_secret_gKv1GroVoPf0i000siHK", "created": "2025-04-29T09:06:25.436Z", "currency": "USD", "customer_id": "cu_1745917372", "customer": { "id": "cu_1745917372", "name": "Joseph Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": "[email protected]", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": null, "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1745917372", "created_at": 1745917585, "expires": 1745921185, "secret": "epk_03223a8293164e14a0b1dc07cc86404a" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_OiJkBiFuCYbYAkCG9X02", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-29T09:21:25.436Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-04-29T09:06:25.462Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": null, "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null } ``` -> list payment methods for the same customer ``` curl --location 'http://localhost:8080/customers/cu_1745917372/payment_methods' \ --header 'Accept: application/json' \ --header 'api-key: dev_t6MGc7fYh7s9QLODlx0Pvl5QaGQtKhHFq0eUOJm6hNBfrWK2FqqWZ4tDXpqMUzfZ' ``` ``` { "customer_payment_methods": [ { "payment_token": "token_mzQEW3GchjpQQDxWqQ7G", "payment_method_id": "pm_KNynHcJOxmcco1GrzdWm", "customer_id": "cu_1745917372", "payment_method": "card", "payment_method_type": "debit", "payment_method_issuer": null, "payment_method_issuer_code": null, "recurring_enabled": false, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "card": { "scheme": "Star", "issuer_country": null, "last4_digits": "0004", "expiry_month": "03", "expiry_year": "2030", "card_token": null, "card_holder_name": "joseph Doe", "card_fingerprint": null, "nick_name": null, "card_network": "Star", "card_isin": "440000", "card_issuer": null, "card_type": null, "saved_to_locker": true }, "metadata": null, "created": "2025-04-29T09:03:00.719Z", "bank": null, "surcharge_details": null, "requires_cvv": true, "last_used_at": "2025-04-29T09:03:00.719Z", "default_payment_method_set": true, "billing": { "address": { "city": "San", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": "[email protected]" } } ], "is_guest_customer": null } ``` -> Confirm the a payment with the payment token ``` curl --location 'http://localhost:8080/payments/pay_icPaUi7x7A2gK2F43q56/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_f3e0703c217345e3ace5d6c6cd2046ad' \ --data '{ "payment_token": "token_mzQEW3GchjpQQDxWqQ7G", "payment_method_type": "debit", "payment_method": "card", "browser_info": { "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36", "accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "125.0.0.1" }, "client_secret": "pay_icPaUi7x7A2gK2F43q56_secret_gKv1GroVoPf0i000siHK", "setup_future_usage": "on_session", "payment_method_data": { "card_token": { "card_cvc": "123" } } }' ``` ``` { "payment_id": "pay_icPaUi7x7A2gK2F43q56", "merchant_id": "merchant_1745690754", "status": "failed", "amount": 6100, "net_amount": 6100, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "adyen", "client_secret": "pay_icPaUi7x7A2gK2F43q56_secret_gKv1GroVoPf0i000siHK", "created": "2025-04-29T09:06:25.436Z", "currency": "USD", "customer_id": "cu_1745917372", "customer": { "id": "cu_1745917372", "name": "Joseph Doe", "email": "[email protected]", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0004", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "440000", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": "token_mzQEW3GchjpQQDxWqQ7G", "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": "[email protected]", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "next_action": null, "cancellation_reason": null, "error_code": "24", "error_message": "CVC Declined", "unified_code": "UE_9000", "unified_message": "Something went wrong", "payment_experience": null, "payment_method_type": "debit", "connector_label": "adyen_US_default", "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": true, "connector_transaction_id": "C87D7CD547P6TNV5", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_OiJkBiFuCYbYAkCG9X02", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_VyX6BwB09KJrmeR1ODFD", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-04-29T09:21:25.436Z", "fingerprint": null, "browser_info": { "os_type": null, "language": "nl-NL", "time_zone": 0, "ip_address": "125.0.0.1", "os_version": null, "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "color_depth": 24, "device_model": null, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "accept_language": "en", "java_script_enabled": true }, "payment_method_id": "pm_KNynHcJOxmcco1GrzdWm", "payment_method_status": "active", "updated": "2025-04-29T09:10:38.933Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "saved_card", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": "DECLINED CVC Incorrect" } ``` -> Logs showing the debit routing flow was triggered with the previously saved co-badged card data ![image](https://github.com/user-attachments/assets/f348a89a-8279-403c-a847-18ccc948d9e8) -> Logs showing the card brand was set star in the connector request ![image](https://github.com/user-attachments/assets/01663089-f8f7-4d3a-807e-57bb97c74968) ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
v1.114.0
b0ad3ef5cde30078aa5f51258b9ff6e190079417
b0ad3ef5cde30078aa5f51258b9ff6e190079417